node-v0.10.25~dfsg2/0000755000000000000000000000000012270121457012615 5ustar rootrootnode-v0.10.25~dfsg2/doc/0000755000000000000000000000000012271410374013362 5ustar rootrootnode-v0.10.25~dfsg2/doc/v0.4_announcement.html0000644000000000000000000001030312270121457017506 0ustar rootroot node v0.4 announcement

Second Stable Branch of Node released

Wiki page detailing API changes between v0.4 and v0.2

Major changes since v0.2:

node-v0.10.25~dfsg2/doc/full-white-stripe.jpg0000644000000000000000000001043712270121457017455 0ustar rootrootJFIFC       C 8" = U!1Q "Aa27u#BCRbqr-a!R1QA"2 ?m=W߭9m=W߭R#зGm^M ~Sw-G-JD4-Won\\~\\~H;j2 Mܶ랫랫)зGm^F[a)sp]#sp]%"l77rۮz [rۮz [ĤCBym[uUwx[uUwxh[#-ߔn.on.o tvem=W߭9m=W߭R!nڼ~Sw-G-JD4-Won\\~\\~H;j2 Mܶ랫랫)зGm^F[a)sp]#sp]%"l77rۮz [rۮz [ĤCBym[uUwx[uUwxh[#-ߔn.on.o tvem=W߭9m=W߭R!nڼ~Sw-G-JD4-Won\\~\\~H;j2 Mܶ랫랫)зGm^F[a)sp]#sp]%"l77rۮz [rۮz [ĤCBym[uUwx[uUwxh[#-ߔn.on.o tvem=W߭9m=W߭R!nڼ~Sw-G-JD4-Won\\~\\~H;j2 Mܶ랫랫)зGm^F[a)sp]#sp]%"l77rۮz [rۮz [ĤCBym[uUwx[uUwxh[#-ߐb8ZڋY ,>:7^$c3M!]Ok3_!FZMnfg!D)Zd-i_X]Q,'ZIeчcsohӆUdUTQUSB&b#eoބOŵ 4+IJ,?xj7oVJ4&h}|/޺&}5UN/}TgsZkܵ3#ga-K{JRJo$7#k_ a%}:,5e>~Ue*$} gu&^3ֹ-:rCodY41'솻gd-qӥoeRۿ_K}CG6k*9,] K!Rz!RIcfaeb~@e1{: p5JY`!hnYx9.RkiN5e֬'}o=뵢©n)igJFzsQB#e-W]cVj_N6CCw̱։z2,A5zX+̵{u<}+Z+xOgBy$y/Wlކr#T6 ihϒI,+O,}3noCǥ]՞`q_t&|#%a-&(|՚0/#x[mdy-lO)>V捼..$ij34!7!7߻X=̉o9^WYQmiRR5{jW¤wF?y ^8ze[;;kwu~XT]F1/Ͽof梺=?1~|3[^&(l1(162VJWuy(K-Io,hL`]ctv7q ղTda//pY (i'km&jN ,KuR_a/aF/\aKKZ\M/ naBO}o6hTSVLD,node-v0.10.25~dfsg2/doc/api_assets/0000755000000000000000000000000012270121457015515 5ustar rootrootnode-v0.10.25~dfsg2/doc/api_assets/sh.css0000644000000000000000000000055512270121457016646 0ustar rootroot.sh_sourceCode { font-weight: normal; font-style: normal; } .sh_sourceCode .sh_symbol, .sh_sourceCode .sh_cbracket { color: #333; } .sh_sourceCode .sh_keyword { color: #c96; } .sh_sourceCode .sh_string, .sh_sourceCode .sh_regexp, .sh_sourceCode .sh_number, .sh_sourceCode .sh_specialchar { color: #690; } .sh_sourceCode .sh_comment { color: #666; } node-v0.10.25~dfsg2/doc/api_assets/style.css0000644000000000000000000002517112270121457017375 0ustar rootroot/*--------------------- Layout and Typography ----------------------------*/ html { -webkit-font-smoothing: antialiased; } body { font-family: "Lucida Grande", "Lucida Sans Unicode", "Lucida Sans", Verdana, Tahoma, sans-serif; font-size: 14px; line-height: 180%; color: black; background-color: white; margin: 0; padding: 49px 0 0 0; border-top: 6px #8CC84B solid; } a { color: #480; text-decoration: underline; } a:visited { color: #46483e; text-decoration: underline; } a:hover, a:focus { text-decoration: none; } code a:hover { background: none; color: #b950b7; } #changelog #gtoc { display: none; } #gtoc p { margin: 0; font-size: 18px; line-height: 30px; } #gtoc a { font-family: Georgia, FreeSerif, Times, serif; text-decoration: none; color: #46483e; } #gtoc a:hover { color: #669900; text-decoration: underline; } .notice { display: block; padding: 1em; margin: 1.4667em 0 2.9334em; background: #FFF6BF; color: #514721; border: 1px solid #FFD324; } .notice p { margin: 0; } .api_stability_0 { border-color: #D60027; } .api_stability_1 { border-color: #EC5315; } .api_stability_2 { border-color: #FFD700; } .api_stability_3 { border-color: #AEC516; } .api_stability_4 { border-color: #009431; } .api_stability_5 { border-color: #0084B6; } ul.plain { list-style: none; } abbr { border-bottom: 1px dotted #454545; } p { margin: 0 0 1.4667em 0; position: relative; text-rendering: optimizeLegibility; } table { border-collapse: collapse; margin: 0 0 1.4667em 0; } th, td { border: 1px solid #aaa; } table p { margin: 0 1ex; } th { text-align:left; } .apidoc #apicontent p, .apidoc #apicontent li { font-size: 15px; line-height: 22px; color: #000; font-family: Georgia, FreeSerif, Times, serif; } ol, ul, dl { margin: 0 0 1em 0; padding: 0; } ol ul, ol ol, ol dl, ul ul, ul ol, ul dl, dl ul, dl ol, dl dl { margin-bottom: 0; } ol p:first-child, ul p:first-child, dl p:first-child { margin-bottom: 0; } ul, ol { margin-left: 2em; } dl dt { position: relative; margin: 1.5em 0 0; } dl dd { position: relative; margin: 0 1em 0; } dd + dt.pre { margin-top: 1.6em; } h1, h2, h3, h4, h5, h6 { font-family: Helvetica, Arial, sans-serif; color: #000; text-rendering: optimizeLegibility; position: relative; } header h1 { font-family: Georgia, FreeSerif, Times, serif; font-size: 30px; font-weight: normal; line-height: 36px; color: #480; margin: 15px 0 11px; } h1 { font-size: 29px; line-height: 33px; margin: 2em 0 15px; } #toc + h1 { margin-top: 1em; padding-top: 0; } h2 { font-size: 1.4em; line-height: 1.0909em; margin: 1.5em 0 0.5em; } h2 + h2 { margin: 0 0 0.5em; } h3 { font-size: 1.3em; line-height: 1.1282em; margin: 2.2em 0 0.5em; } h3 + h3 { margin: 0 0 0.5em; } h2, h3, h4 { position: relative; padding-right: 40px; } h1 span, h2 span, h3 span, h4 span { font-size: 25px; position: absolute; display: block; top: 0; right: 0; opacity: 0.3; } h1 span:hover, h2 span:hover, h3 span:hover, h4 span:hover { opacity: 1; } h1 span a, h2 span a, h3 span a, h4 span a { font-size: 0.8em; color: #000; text-decoration: none; font-family: Helvetica, Arial, sans-serif; font-weight: bold; } h1 span a.top, h2 span a.top, h3 span a.top, h4 span a.top { /* XXX Get an image and clean up these two links * so that they look nice next to one another. * http://www.chrisglass.com/work/nodejs/website/v05/docs.html * -isaacs */ display: none; } h5 { font-size: 1.125em; line-height: 1.4em; } h6 { font-size: 1em; line-height: 1.4667em; } pre, tt, code { font-size: 14px; line-height: 1.5438em; font-family: Monaco, Consolas, "Lucida Console", monospace; margin: 0; padding: 0; } .pre { font-family: Monaco, Consolas, "Lucida Console", monospace; line-height: 1.5438em; font-size: 0.95em; } pre { padding: 1em 1.6em 1em 1.2em; vertical-align: top; background: #f8f8f8; border: 1px solid #e8e8e8; border-width: 1px 1px 1px 6px; margin: -0.5em 0 1.1em; overflow-x: auto; } pre + h3 { margin-top: 2.225em; } code.pre { white-space: pre; } #intro { width: 775px; margin: 0 auto; text-align: center; color: #d2d8ba; /* preload platform-icons.png */ background-image: url(http://nodejs.org/images/platform-icons.png); background-repeat: no-repeat; background-position: -999em -999em; } #intro.interior #logo { margin-left: -298px; border: 0; } hr { background: none; border: medium none; border-bottom: 1px solid #ccc; margin: 1em 0; } #toc { font-size: 15px; line-height: 1.5em; line-height: 22px; padding-top: 4px; } #toc h2 { font-size: 15px; line-height: 21px; margin: 0 0 0.5em; } #toc h2 a { float: right; } #toc hr { margin: 1em 0 2em; } #toc ul, #api-section-index #apicontent ul li, #api-section-index #apicontent ul { font-family: Georgia, FreeSerif, Times, serif; color: #666 !important; } #toc ul a { text-decoration: none; border-bottom: 1px dotted #480; } #toc ul a:hover, #toc ul a:focus { border-bottom: 1px dotted #fff; color: #000; } p tt, p code, span.type { background: #f8f8ff; border: 1px solid #dedede; padding: 0 0.2em; } #content { width: 953px; margin: 0 auto; overflow: visible; clear: both; display: block; } #column1.interior { width: 749px; float: right; padding-top: 7px; padding-top: 11px; font-size: 18px; } #column2.interior { width: 140px; float: left; margin-top: -55px; overflow: visible; } #column2.interior ul { margin-left: 0; } #column2.interior li { list-style-type: none; } #column2.interior li a { display: block; padding: 0 0 0 35px; color: #878b78; text-transform: uppercase; text-decoration: none; font-size: 11px; line-height: 23px; } #column2.interior li a.home { background: url(http://nodejs.org/images/icons-interior.png) no-repeat -156px 3px; } #column2.interior li a.download { background: url(http://nodejs.org/images/icons-interior.png) no-repeat -156px -21px; } #column2.interior li a.about { background: url(http://nodejs.org/images/icons-interior.png) no-repeat -156px -45px; } #column2.interior li a.npm { background: url(http://nodejs.org/images/icons-interior.png) no-repeat -156px -69px; } #column2.interior li a.docs { background: url(http://nodejs.org/images/icons-interior.png) no-repeat -156px -93px; } #column2.interior li a.blog { background: url(http://nodejs.org/images/icons-interior.png) no-repeat -156px -117px; } #column2.interior li a.community { background: url(http://nodejs.org/images/icons-interior.png) no-repeat -156px -141px; } #column2.interior li a.logos { background: url(http://nodejs.org/images/icons-interior.png) no-repeat -156px -165px; } #column2.interior li a.jobs { background: url(http://nodejs.org/images/icons-interior.png) no-repeat -156px -189px; } #column2.interior li a.home.current { background-position: 2px 3px; } #column2.interior li a.download.current { background-position: 2px -21px; } #column2.interior li a.about.current { background-position: 2px -45px; } #column2.interior li a.npm.current { background-position: 2px -69px; } #column2.interior li a.docs.current { background-position: 2px -93px; } #column2.interior li a.blog.current { background-position: 2px -117px; } #column2.interior li a.community.current { background-position: 2px -141px; } #column2.interior li a.logos.current { background-position: 2px -165px; } #column2.interior li a.jobs.current { background-position: 2px -189px; } #column2.interior li a.home:hover { background-position: -331px 3px; } #column2.interior li a.download:hover { background-position: -331px -21px; } #column2.interior li a.about:hover { background-position: -331px -45px; } #column2.interior li a.npm:hover { background-position: -331px -69px; } #column2.interior li a.docs:hover { background-position: -331px -93px; } #column2.interior li a.blog:hover { background-position: -331px -117px; } #column2.interior li a.community:hover { background-position: -331px -141px; } #column2.interior li a.logos:hover { background-position: -331px -165px; } #column2.interior li a.jobs:hover { background-position: -331px -189px; } #column2.interior li a.current { color: #8cc84b; font-weight: bold; } #column2.interior li a:hover { color: #000000; text-decoration: none; } #column2.interior li + li { border-top: 1px solid #c1c7ac; } #column2.interior p.twitter { padding-top: 20px; } #column2.interior p.twitter a { background: url(http://nodejs.org/images/twitter-bird.png) no-repeat 0 4px; padding-left: 37px; text-decoration: none; } #column2.interior p.twitter a:hover { text-decoration: underline; } a.totop { font-family: "Lucida Grande", "Lucida Sans Unicode", "Lucida Sans", Verdana, Tahoma, sans-serif; font-weight: bold; text-indent: -9999999px; background: url(http://nodejs.org/images/anchor.png) no-repeat top left; margin-right: 7px; display: block; width: 13px; border-bottom: 1px solid #cccccc; } a.anchor { font-family: "Lucida Grande", "Lucida Sans Unicode", "Lucida Sans", Verdana, Tahoma, sans-serif; font-weight: bold; text-indent: -9999999px; background: url(http://nodejs.org/images/anchor.png) no-repeat top right; display: block; width: 13px; border-bottom: 1px solid #cccccc; } #footer { width: 942px; margin: 150px auto 55px auto; padding: 0; } #footer .joyent-logo { display:block; position:absolute; overflow:hidden; text-indent:-999em; height:100px; width:190px; z-index:999; } #footer p { font-size: 11px; line-height: 1em; padding: 0 0 0 195px; color: #666; } #footer p, #footer li { font-family: "Lucida Grande", "Lucida Sans Unicode", "Lucida Sans", Verdana, Tahoma, sans-serif; } #footer a { text-decoration: none; border: none; color: #480; } #footer a:hover { color: #000; } #footer p a { border-bottom: 1px dotted #480; color: #878b78; } #footer ul { background: url(http://nodejs.org/images/footer-logo-alt.png) left 17px no-repeat; padding: 23px 0 0 195px; height: 26px; margin-left: -1px; border-top: 1px solid #626557; } #footer ul li { list-style-type: none; float: left; font-size: 12px; margin: 0 !important; padding: 0; height: 12px; } #footer ul li a { margin: 0; padding: 0 6px 0 0; display: block; height: 12px; line-height: 12px; } #footer ul li + li { margin-left: 3px; } #footer ul li + li a { padding: 0 6px 0 6px; border-left: 1px solid #878b78; } #footer ul li a.twitter { background: url(http://nodejs.org/images/twitter-bird.png) no-repeat 5px 0px; padding-left: 25px; } /* simpler clearfix */ .clearfix:after { content: "."; display: block; height: 0; clear: both; visibility: hidden; } node-v0.10.25~dfsg2/doc/sh.css0000644000000000000000000000055512270121457014513 0ustar rootroot.sh_sourceCode { font-weight: normal; font-style: normal; } .sh_sourceCode .sh_symbol, .sh_sourceCode .sh_cbracket { color: #333; } .sh_sourceCode .sh_keyword { color: #c96; } .sh_sourceCode .sh_string, .sh_sourceCode .sh_regexp, .sh_sourceCode .sh_number, .sh_sourceCode .sh_specialchar { color: #690; } .sh_sourceCode .sh_comment { color: #666; } node-v0.10.25~dfsg2/doc/mac_osx_nodejs_installer_logo.png0000644000000000000000000005542512270121457022173 0ustar rootrootPNG  IHDR&~/tEXtSoftwareAdobe ImageReadyqe<ZIDATx} $Uu9Ya6EEYE""*QQhԨWcQF"jQ( lo{?vݪ_737s_wWWUWݺm b !z1C1C1C1C1C1C1C1C1C1C1C1C1C1C1C1C1C1C1C1C1C1C1C1C1C1C1C1C1C1C1C1C1C1C1C1C1C1C1C1C1C1C1C1C1C1C1C1C1C1C1C1C1C1C1C1C1C1C1C1C1C1C1C1C1C1C1C1C1C1C1C1C1C1C1C1C1C1C1C1C1C1C&y@bW)8{Tq%KN^S [f~86yu5&>mGyE-o:B qu .BQǰwssWϴz3w9Ƿh8]/NokOh_¦q(Qvs8F3ax-ׅh]ȭ?uT1=F|.^vw\gh!C$Q2u%dkLׇR"wE'% -KA3f&`hRlnuWYU08;gSC&)9m;V(Y|nnza`dlQ0U4 ec$3ZjB{釧臿pk݅ JL"%tȣL:.mIEͪUlb*"tj3I,blŘ$|~ ivJ=p\*SD~J_ *e-OYF66t%nSbi{n9__m@ ӓB+Y@;ڰfZJ ,wRumovF[zL{f P{reU_i;@ D:\BY+i3CB"WZ }o@h{yh# @ -ZGP@ ]Vh?:/%TH|'Ay.!JB;Ek\.SWYb@- НҔyJxq%AbzsU& |Y2eAf>  a-%rBE%C7D C! g%Br&q-@ `@X_vč;D-jأ75CfA(rD- l= wҢdrx@ `+ʮ(a;&Ԓ#"țVIF&/!527Ŀͫ)=8L9RU0 b P€fd)@ `E`jC$̥ߡAY{ (>T|TTe$!5锔ͽG,0K ]XEXЉ0NbBʖ C ɒ"鐲DRˆk.1`ˈz]|aɩDUwe^!,E4j(g SWJoB 0Harmcؒ$Soэ!+ž  `gI?@,rs@ `>;*6H)ڪ=` \؟@ ȓib$% 'qQJb, 7ZO\E-zΣ^6҉ 0BݤZU*V3w R!b`^v]G;Tm'm?6،$@_Š=^ vԶTە.v:_{? uo3cxVxWyc|ն 3kN;]OО<@ƦKq.dA4$Opc\-\*|W_WEw7QTB_bp7m} ë` ؎6d!cN4dmbgMAzm_uӝ7=dF,WRa-JMjŹzOϘos?mzt/h{?Aŗ_ 9C8mU~e2K]RAJE~U{ 7¤sd[$o;گk_zRǻ4IyզSsb61426vHSw=I$}7d|O]  axzOl;3XYJp|~}Έׇ.%ÄkK6Qm1R>z{l phô+HΔ "9z/tѺz1~3&f{/PMxz9(eO;NtkDB.{x7&ÅU2}t}$('o!LE8+u/$܎ٞ70ւ3OJ&0/[~1s:kD>XHK-@V7ҍE3,TYTd%D/կlp/A[.QoM鵾[}|&詋|9.*%.x.>OQu[đ)y;3w5rs8tm ͫL 94uom/*ұ>g Kzr>#]yuͭO{:Up\8;inw힧Pѧ)7^ R(t*5)7V9 .JSɉ Qt̉ڏkc;C^9|Ŵi^!h#bb=.!z(#c휯 *u&620 ѡ- W$+$tIBThͣ;bQ&FU:.+`w-82fU'JI0=IG,a3⚍{,Kqzj9[ק魟锎tRр[aŌc(C-A\Gk{)y`Ԥ$qm%;ߞ>su+{8t(֪KvIJGGacGti=W'kTS(1=] 7I-]3m?m /Мcv.Sazm`gʅtU~}N6N}Ip߱ 4ZuB(l@ 󨨿0%r ˅뾒>/];%SpX4av8F;꾺7W Joi%L_)aKV3];gWިg_S7;{`ӈ'Ϫ8_0j]<7&Jd˰;؉%`eKYB].vm{F f?_-Ÿ2W|B @1#XM< xu ,,܂"'i?۩&z97]B^Lә;V!jqM&*Pǁxd{O((jN6orDt*3oA%mo-u6PH^< @jCu?Xϥ҆hN!{m 1HSWi{q #cKMpOVJR_F/ ܆[{TZcgyԕcX:A2r51*ւ- Y;P~,k˥^>߾]B4NaY\?XvD8_%"p @1GH8YCh1ϩc)qI^%^*;k&IT 5k3E 5N=r`/vJo`7&D.,4RL㑻|O?d4#H_w.O6UYWb%8PH-#F$#V=Kotkl XӾHzK j*Ē\2"qaH/ak!PJ|=SXis"hH%]qV'nX)$ҴpOe0_aʻZ_0d¬c²;}&yg[-7$&BRufS{gꭏG#7ϬSP\LIC79Q|Z-}KYLHmC-/䷵=d68` aGf0"d-AHD: >(.Q2/߃ȥzu1%`yn}5qв_c.{5k86 5]qdRHn{ScRs:IagBǵ[4i֌8Dr6oCxD ITkh$Qzb !ßhRw.1OCJ?z9#gOh:ηI&%叅ӷiJ:.}d7Hi-< K^Lq=*f x<&NC_m,]C |ٸ\a%4lziXKv>C@S'Rkc6_NsET ٥E"U?-8uPdaR"v%j Ϝzisz_)fGQн{&z.SR8Lj2fK{R̃h;i_Lp5v%XS_=U@9Rs8RKGɺ6jR}ZTs]ʧ8C=esU!ݓfsAhP)%6X5&r6W)3ĒSco֚|& zsH1jPm Sm35Ki&FMGZqޞyMPd8#nKuHbf~N^TqwN-w60W"t9V|أ9ІBG j#L4jυ0@_j%oZM$sڄ儎Ҷ#+듌=$iN"9f+b7Z'&1QWs/3%q¹P+9#GԤR[ ֛495<@ҬCʃt~Ѻ%GoxT8M)vv+$R_un{YʯJ]+|$lO=u)iˁ= bh+1!Q:%ܔ!v1F#ѫ?[PrcbM )Q9Dny{qJ'l|XPʅb ㌸1V۫'” gokR{ }5o4O-.f;s BG9,,tZUTC{_bݶ -=˧&;}Ӄ.s@ d +S1gD4q94D #%Ѳ/>>K7A2T H^  j 9J1R]+4WoIn_>k:hlDRoHIp2$oLeC*xa2YI&uI`4CPIˡP's\xEN#10jzHAσ*E˛zW$=Y$'Qg{xDղ%5db4yU=Rypٿ[f'ϸܯ`i|irKxו qe`vKBgH21 ZR MqUI.4gdD')u'OM Ai,#B'5m3'@ zof\ҷ(I-&NXE̴M{.ފ:I%c߸KSn&}UdoAP'uYˑo?I~EI*%My&*6*jhɖub%(ٴHؾ`//pٓ۶X)xJ!|ns?ü58XTl^OW$Ch4BbglsVC06JJ}+.8p:C2B=\R J]pbshR z'E1$ITLfdPV4g;k5)LO<=T[$y m 6p*;DT藸q+$#)rEC)z=DߟDUoHW^D M?m}ƍ  s#vb`fAQ1e`&ўWQY@8$n'wD\,,8|5iHxr/=J$8_Ңr߽Fsty&Iz* y,FX+$lgS:=Fy*,na,܎f9\9r"Gj&ó5Ao.l)BRƩZi$Oַ|k9o)ڷLؓ2 ~NE~|]6=9ȗc-X˰; I5yV'NM\%5D2>[zwbd^<;gkS@N7zܘ>4@m"0toRnL)+[DvG m?Sê2-cь;ʮROsUC)KErxSFne*ۘKp?3~,aw"Bm(+W.7IlclM_eFDԆ&6Hy.׈A[_ӣ+K;89nFE0wrRn$9@~ւ*Z^ۓ{Tpc}=oj\~M{dӽ6m7OoĢ9ypSd8QVtf1xI}jl0VYLuETSq;$%=Hߜw[-o7Ʈ =0Tb( g¡3Mz?IW=Fu_O%~Kr˙,)rnOf] ''lq֘ԋ7 ĩ-R"W9 1c' HAT:]:$̑DLehY*Ωǝosz>}G[DCɨl}za BOq&c(I-BM6hlLWcp-Y9NՎ۴o=S)3D)tlOYeJ\n2m${+b*BG"^7sVY9D;rY_XAC%y<԰Z.f n3'.y+]8l=.g- LȠ夔0 \S+?[k< % 7D 65 O|C!\NKVz6soeϷv>ds4[4S`8LŹ&#U ]!tD[͹(ݴTҥ/},wBuY~tͲB;{zİJwIg` l,6vz72JT%Ki>E/n_Im.]mJiAyr)[$cDt4lP_|.(8)JV|Zpk4rjotH&>0SLB˸'MD<Ϣ2a fÕ$&?>I!`=#iݠ7y귇*\8tbZ|& g돟.Df裻k㨿\I?ؚ7.gB JvKȔ˯ܗt}c~F4dM̠lL-g2Jl*)OE)&EfPͼK'wm ~%Ѫn3qLWV ,e\T7 REeՔ_{/ m]ir~ލRƺHK~/eOɜapa$薞F ଳI؝?1foȵ/M62OT$|_44x)hJ*!\786G$.j&v=XyԒ?[O>uM1s͂1Da,ks.wp?tKTއCg*x ܴt{YSf=ޒ9e)0do(Lh$V8=rvİ3_SO{Hm@vld;ÁㆄU(Mqyw!YjqN+AIaqfX2Ĺ-s}=\*bv( [SԻ{tRׅهOܞ=c'g{. &>J{_3])Z/En !Wγ\X8dҧ"Fn?F/ejE$]~gR셻i394sӜ,31WD-v ްxnZx9IC(ѵh_JhHۘF ] sR s1* dFf60mEÕi[L^*6ދƚ2ɳwJZ)%?s'Ƣdܛ,*^|ѓ嬵Lo[39}'iB ֠TAv3  ~~̦X9N4~8iO~9DFۭz#k;mjWl[GpoFʗg'1:W{.oHFm v^B M?o0\O ԑu(j5)/^a֦T.|eY6?ܪg pv"ڰffʃڻdR<٭S6tuNS#Mme+$  }:n>P $mيAvs3} <ҘI& R:Q`;ЉKX'LT&CN{60~St!D]_}l-XÐ 5I!t5`40ԜՙlqA4>n>lF,^Ewq-&ݸBtFOy *wpsAUy.Sl_:iH0tYr2$\4 /I`bw BO\"fD)$?ĦR=Ē3i$.ɒ7\_f)8_^<؍$3U\hT7ScJR";|2 c8$4x#Rb /V$雛RŌz AO2iqp@Ưj,Pzꌫ$/>8PvŅbF2f%̢,D$U'0dpȉ{&G%)7u.6.${\qRZ&RH|2Oez gC*-J yE^[] 'o|,ڱ8;(ggd=Tj>ͺ'+]Zs%x~v=tUimyigSw>Hw{*TE̫ /9mq^z=zY?i賍 [|ExiP9:;4x9LGlH-- $_5xܸduh0VOrn8.0~}%ړglWuY$% ZL?lO s=/P_'YS``jprXŐsF <ϫTVƙ\. iplq1W.}BA3[,!yT|If5 yiG Jqf&ˇs~~U.Ғ G5i{n;"-2 '7\$R4qFbא 2H !K sIM`*/{y;}Uj̩:vտUjf>xJ6"FC29_U*Jk79EWx!s".kf98_r$p`j}2n>v)I+ ' M:>n~39T;l~;99ZHYqӊS=\_{#ey> }7j)KУ˰-[2勲t[ĂkΤܶo 9Oqz 'dn'LR4A9$Y67 2zXb/Xm5k4D$n+?$BpD(eЄŲ(as߉co,+42S q/*%*$THױozu ߒ~M[E% Ԇ^}A1Ӯu`}t#8B5%toguƠ'ȥd aCCrǦzLS[:ϴ/[Kl_V!bTFX y&IR$gǒw⾙~r_Yב<Qjo9rjc"/u4JA9%AJLe6Ւ@,Fߏ2f(N{"-23 =*]/F]uxv RǑG*}(}wqO?mIBXz>5kf?i{:ΙY9أDGWRG@Vi"0FS%i#CD!̷EwsLTm4 㡵IsnCOsj &Qf T$hjCBf/pu!_ɩK&vh*L"Mh\&4le9*n 'XP@b:8x-E\'yH7ʐ"ߚJ1V$kjHBN#ax aHFIf]7MwV:;la_="{F֜?,Ii Kde\uC*vL*14/wu7O29ڗi&ONhޝJPXj7Amvƚxysu75)G S>\m4Ã܈fl)U%nkjK-Gjp0%Bx,G)ͷ]s {˳4` iHtҪ&I{W%!hۇ*C,yۭ`0n(oI䈈b%pˍכSJtWҮ\ wLd1iOa9#+XHw<5{]rϖdbf*' +i03zVCj&9Mw.۬_cIRKX2 fP /4d5 ]S(%Eb#EՓ{ rP>Chi3gG.Y5~ɭx ?XiC&%S$hbT ׯ]ER~@ӋJ~C>w%|EEҡ9HgG ܸSɦTwRp- y7~Gxg n)"tfHxyR"M:UW`s΢l 4j@m#՟ITH;ė9CĬ"$A.3 (""K0 ǩqnet;I./ǥ"S? *15Uٖܵ{*X sV+Qxd_ѷV}Ǿ̏a+F'Uhjr yHDIT U^}cvkuYάV5R"ӷ#;9szCl#&HHQ4=DhD'YK!WMfă]@b A\@HŤIQI8,T!g(a;BlBm8xi!!wP|-|™TeIpY^ wq~'-v| ԯ"N{v!U~Id8)"|^}*MkwwߙriŞ hӺ.eu>!Tx0Jf91NMnKsdZF ǹp~vP+r:]s|'P9 $"y-4z6V{ҩ~v},\ɕR ,{řWlֹK,^p9nXdު/CwD%u@zN@#fK=u#Èt?˾?Xy+I E'1%&8ПqP゚~NT߶͡JcV$_uBӶfȾT.J2}X@<^cB2rFP8V7 ƐDetm8YS{Kl.pcLIP+zucmF-X2F{mtNҸǭ~hQd:^jE!u4{)zIS !RX7tR8,47u|~@X=B%o-8yf,XtGaӒ8_#%xDѦ+-mW cN7#$^IU c)1RV7Hr┡bcؾ4}uھKq]M"J+!OT5}|?I9#8rk\e#Z>/SB)WS!VSSni G'hB "mHePpWB]]3M,v8}Rz'{sv1"if&sWbүESM"%Ukh |*nOX3V kJ 9Rq %Gĸ}@%e z|+}\'U=]CN~oJyoNv +Xy-M ,Q~R_M+(w)E9omܡ%] Kx1JR0VF񵘭h3]t=|9wy15zSw2ǚ3u}#[z9-@kzSҾM|.Bf|11H =Rh2/rDCө+-ui=G۪h^dcIY3Zowgu^YnZ8aX!9='J\g;ZB}9} gկcuˣ‰ 8,nG,_3>ؗ; L'~,g=KJBD^ơ+v`0S 7 s V.].R+pm[7v\SBT#y`fr)-OQ\h`\B(#N9R]])qUH&;l4|%7vvq?^\v/8Z~[ŭ}ZEtWЎ/g%ź|~|UH—!zg*D2uԸ5j-$R{8{GC {~g6Ј0Њ}LU&״}I0s0\$fmK69CkYbaa'֕jBjJ 37N`ʺ'WEf 岛e'VZӅZ!"w.s~T0B;b‰U?f.,'ȋ#rVC4diL]-Dj\C:p%3J4IՖaK-R:e̙0"7gNUΥ[zmVQҡJ=ҤΠ<1y[߯@ 9 c<_R1U{r/HJn !ݕG)/_*oҧ틜ZK\ҽF3qjZ2$ ~Ra :ѸVΩ<#i rkER wGsY dՖkJG2CG/F:f9NPlTME.Y1_7bۑ[HG~ؓ(?Y* ׊I}HO}Q#dH]x]٥4y~sm+(J07U[Myî4vVY. Lz\bqT3g92Q6oKf6J6 5GN31wz;~{z7$YN" TnG$^r/׹s\~ln1&ޯ[>:7ڴ"I|^'WJWߥ[2ϻi]{ޑ\[e1 cc54t2U?D2l<$*j!|>M?Qr=OVKRbSLY"c,-N'͒w9*$8f6RڔKg-syj}l~e՚Ju  3%rtmT56EwtFщ/߅&Uwx`}o/lg+S_cДu 3-#i`~|s2n&=D*L#"jRDV-xVx#2R2AڹG!ήjRO5W0͋5I\:47fK+i'Pb^wiDnpީI)wcU P:[pL Ԧmq[??^9˃ (Qf -JZx7&^frS:U̷JVD*=ݾ =Bouz Uk!̤JQ֔(/0_s2;D#^Jc<V/Uc,n#(@ 7ҧWBtP_I/S dP10NI4MM8kYӬLE\_$efs5c ۧ_Ecƶe,W#"']b2K[9 4c: ~XƭZM:2,4a*>z5WJq|$"uNfjݏb`SfJ&LʐN8YQGrKh?}h8ɶӑl;Nv)Kasu;2[i8UN k,JT1E:6[yY&cx[i,v]5V ڙή̻:~)S$׷Qa2+b4ewᶍ]5?Y|5G)UƎ}Q6*  ZbIm׹E '}/(//ƞ^+tw; B cLL2O^{XRړ}_1fC@Ye"|~ŲZ=,!\1Ƈ /,nZ6P A SCY ud?,+RԂKngэ6En= &I68鏹*tg߹c6FRzP1Ћ)ʴ >2 3k"c獙Hoʭmq^ +]~[a(Z]4m]aNU)3ߎ~/cul 'i+== ȾP^Ke}j׌;i89b'}ۚaDvz @b`3}CwD"Y9&F/AǕ<ߦ Ƿ̲rG&m)c ͮC%q?*BBESF 3|IzxA7HCL;8!0+%,cit[W+S'e4^.cY_.#g>~y¿]3k8zFIENDB`node-v0.10.25~dfsg2/doc/sh_main.js0000644000000000000000000003675312270121457015354 0ustar rootroot/* SHJS - Syntax Highlighting in JavaScript Copyright (C) 2007, 2008 gnombat@users.sourceforge.net License: http://shjs.sourceforge.net/doc/gplv3.html */ if (! this.sh_languages) { this.sh_languages = {}; } var sh_requests = {}; function sh_isEmailAddress(url) { if (/^mailto:/.test(url)) { return false; } return url.indexOf('@') !== -1; } function sh_setHref(tags, numTags, inputString) { var url = inputString.substring(tags[numTags - 2].pos, tags[numTags - 1].pos); if (url.length >= 2 && url.charAt(0) === '<' && url.charAt(url.length - 1) === '>') { url = url.substr(1, url.length - 2); } if (sh_isEmailAddress(url)) { url = 'mailto:' + url; } tags[numTags - 2].node.href = url; } /* Konqueror has a bug where the regular expression /$/g will not match at the end of a line more than once: var regex = /$/g; var match; var line = '1234567890'; regex.lastIndex = 10; match = regex.exec(line); var line2 = 'abcde'; regex.lastIndex = 5; match = regex.exec(line2); // fails */ function sh_konquerorExec(s) { var result = ['']; result.index = s.length; result.input = s; return result; } /** Highlights all elements containing source code in a text string. The return value is an array of objects, each representing an HTML start or end tag. Each object has a property named pos, which is an integer representing the text offset of the tag. Every start tag also has a property named node, which is the DOM element started by the tag. End tags do not have this property. @param inputString a text string @param language a language definition object @return an array of tag objects */ function sh_highlightString(inputString, language) { if (/Konqueror/.test(navigator.userAgent)) { if (! language.konquered) { for (var s = 0; s < language.length; s++) { for (var p = 0; p < language[s].length; p++) { var r = language[s][p][0]; if (r.source === '$') { r.exec = sh_konquerorExec; } } } language.konquered = true; } } var a = document.createElement('a'); var span = document.createElement('span'); // the result var tags = []; var numTags = 0; // each element is a pattern object from language var patternStack = []; // the current position within inputString var pos = 0; // the name of the current style, or null if there is no current style var currentStyle = null; var output = function(s, style) { var length = s.length; // this is more than just an optimization - we don't want to output empty elements if (length === 0) { return; } if (! style) { var stackLength = patternStack.length; if (stackLength !== 0) { var pattern = patternStack[stackLength - 1]; // check whether this is a state or an environment if (! pattern[3]) { // it's not a state - it's an environment; use the style for this environment style = pattern[1]; } } } if (currentStyle !== style) { if (currentStyle) { tags[numTags++] = {pos: pos}; if (currentStyle === 'sh_url') { sh_setHref(tags, numTags, inputString); } } if (style) { var clone; if (style === 'sh_url') { clone = a.cloneNode(false); } else { clone = span.cloneNode(false); } clone.className = style; tags[numTags++] = {node: clone, pos: pos}; } } pos += length; currentStyle = style; }; var endOfLinePattern = /\r\n|\r|\n/g; endOfLinePattern.lastIndex = 0; var inputStringLength = inputString.length; while (pos < inputStringLength) { var start = pos; var end; var startOfNextLine; var endOfLineMatch = endOfLinePattern.exec(inputString); if (endOfLineMatch === null) { end = inputStringLength; startOfNextLine = inputStringLength; } else { end = endOfLineMatch.index; startOfNextLine = endOfLinePattern.lastIndex; } var line = inputString.substring(start, end); var matchCache = []; for (;;) { var posWithinLine = pos - start; var stateIndex; var stackLength = patternStack.length; if (stackLength === 0) { stateIndex = 0; } else { // get the next state stateIndex = patternStack[stackLength - 1][2]; } var state = language[stateIndex]; var numPatterns = state.length; var mc = matchCache[stateIndex]; if (! mc) { mc = matchCache[stateIndex] = []; } var bestMatch = null; var bestPatternIndex = -1; for (var i = 0; i < numPatterns; i++) { var match; if (i < mc.length && (mc[i] === null || posWithinLine <= mc[i].index)) { match = mc[i]; } else { var regex = state[i][0]; regex.lastIndex = posWithinLine; match = regex.exec(line); mc[i] = match; } if (match !== null && (bestMatch === null || match.index < bestMatch.index)) { bestMatch = match; bestPatternIndex = i; if (match.index === posWithinLine) { break; } } } if (bestMatch === null) { output(line.substring(posWithinLine), null); break; } else { // got a match if (bestMatch.index > posWithinLine) { output(line.substring(posWithinLine, bestMatch.index), null); } var pattern = state[bestPatternIndex]; var newStyle = pattern[1]; var matchedString; if (newStyle instanceof Array) { for (var subexpression = 0; subexpression < newStyle.length; subexpression++) { matchedString = bestMatch[subexpression + 1]; output(matchedString, newStyle[subexpression]); } } else { matchedString = bestMatch[0]; output(matchedString, newStyle); } switch (pattern[2]) { case -1: // do nothing break; case -2: // exit patternStack.pop(); break; case -3: // exitall patternStack.length = 0; break; default: // this was the start of a delimited pattern or a state/environment patternStack.push(pattern); break; } } } // end of the line if (currentStyle) { tags[numTags++] = {pos: pos}; if (currentStyle === 'sh_url') { sh_setHref(tags, numTags, inputString); } currentStyle = null; } pos = startOfNextLine; } return tags; } //////////////////////////////////////////////////////////////////////////////// // DOM-dependent functions function sh_getClasses(element) { var result = []; var htmlClass = element.className; if (htmlClass && htmlClass.length > 0) { var htmlClasses = htmlClass.split(' '); for (var i = 0; i < htmlClasses.length; i++) { if (htmlClasses[i].length > 0) { result.push(htmlClasses[i]); } } } return result; } function sh_addClass(element, name) { var htmlClasses = sh_getClasses(element); for (var i = 0; i < htmlClasses.length; i++) { if (name.toLowerCase() === htmlClasses[i].toLowerCase()) { return; } } htmlClasses.push(name); element.className = htmlClasses.join(' '); } /** Extracts the tags from an HTML DOM NodeList. @param nodeList a DOM NodeList @param result an object with text, tags and pos properties */ function sh_extractTagsFromNodeList(nodeList, result) { var length = nodeList.length; for (var i = 0; i < length; i++) { var node = nodeList.item(i); switch (node.nodeType) { case 1: if (node.nodeName.toLowerCase() === 'br') { var terminator; if (/MSIE/.test(navigator.userAgent)) { terminator = '\r'; } else { terminator = '\n'; } result.text.push(terminator); result.pos++; } else { result.tags.push({node: node.cloneNode(false), pos: result.pos}); sh_extractTagsFromNodeList(node.childNodes, result); result.tags.push({pos: result.pos}); } break; case 3: case 4: result.text.push(node.data); result.pos += node.length; break; } } } /** Extracts the tags from the text of an HTML element. The extracted tags will be returned as an array of tag objects. See sh_highlightString for the format of the tag objects. @param element a DOM element @param tags an empty array; the extracted tag objects will be returned in it @return the text of the element @see sh_highlightString */ function sh_extractTags(element, tags) { var result = {}; result.text = []; result.tags = tags; result.pos = 0; sh_extractTagsFromNodeList(element.childNodes, result); return result.text.join(''); } /** Merges the original tags from an element with the tags produced by highlighting. @param originalTags an array containing the original tags @param highlightTags an array containing the highlighting tags - these must not overlap @result an array containing the merged tags */ function sh_mergeTags(originalTags, highlightTags) { var numOriginalTags = originalTags.length; if (numOriginalTags === 0) { return highlightTags; } var numHighlightTags = highlightTags.length; if (numHighlightTags === 0) { return originalTags; } var result = []; var originalIndex = 0; var highlightIndex = 0; while (originalIndex < numOriginalTags && highlightIndex < numHighlightTags) { var originalTag = originalTags[originalIndex]; var highlightTag = highlightTags[highlightIndex]; if (originalTag.pos <= highlightTag.pos) { result.push(originalTag); originalIndex++; } else { result.push(highlightTag); if (highlightTags[highlightIndex + 1].pos <= originalTag.pos) { highlightIndex++; result.push(highlightTags[highlightIndex]); highlightIndex++; } else { // new end tag result.push({pos: originalTag.pos}); // new start tag highlightTags[highlightIndex] = {node: highlightTag.node.cloneNode(false), pos: originalTag.pos}; } } } while (originalIndex < numOriginalTags) { result.push(originalTags[originalIndex]); originalIndex++; } while (highlightIndex < numHighlightTags) { result.push(highlightTags[highlightIndex]); highlightIndex++; } return result; } /** Inserts tags into text. @param tags an array of tag objects @param text a string representing the text @return a DOM DocumentFragment representing the resulting HTML */ function sh_insertTags(tags, text) { var doc = document; var result = document.createDocumentFragment(); var tagIndex = 0; var numTags = tags.length; var textPos = 0; var textLength = text.length; var currentNode = result; // output one tag or text node every iteration while (textPos < textLength || tagIndex < numTags) { var tag; var tagPos; if (tagIndex < numTags) { tag = tags[tagIndex]; tagPos = tag.pos; } else { tagPos = textLength; } if (tagPos <= textPos) { // output the tag if (tag.node) { // start tag var newNode = tag.node; currentNode.appendChild(newNode); currentNode = newNode; } else { // end tag currentNode = currentNode.parentNode; } tagIndex++; } else { // output text currentNode.appendChild(doc.createTextNode(text.substring(textPos, tagPos))); textPos = tagPos; } } return result; } /** Highlights an element containing source code. Upon completion of this function, the element will have been placed in the "sh_sourceCode" class. @param element a DOM
 element containing the source code to be highlighted
@param  language  a language definition object
*/
function sh_highlightElement(element, language) {
  sh_addClass(element, 'sh_sourceCode');
  var originalTags = [];
  var inputString = sh_extractTags(element, originalTags);
  var highlightTags = sh_highlightString(inputString, language);
  var tags = sh_mergeTags(originalTags, highlightTags);
  var documentFragment = sh_insertTags(tags, inputString);
  while (element.hasChildNodes()) {
    element.removeChild(element.firstChild);
  }
  element.appendChild(documentFragment);
}

function sh_getXMLHttpRequest() {
  if (window.ActiveXObject) {
    return new ActiveXObject('Msxml2.XMLHTTP');
  }
  else if (window.XMLHttpRequest) {
    return new XMLHttpRequest();
  }
  throw 'No XMLHttpRequest implementation available';
}

function sh_load(language, element, prefix, suffix) {
  if (language in sh_requests) {
    sh_requests[language].push(element);
    return;
  }
  sh_requests[language] = [element];
  var request = sh_getXMLHttpRequest();
  var url = prefix + 'sh_' + language + suffix;
  request.open('GET', url, true);
  request.onreadystatechange = function () {
    if (request.readyState === 4) {
      try {
        if (! request.status || request.status === 200) {
          eval(request.responseText);
          var elements = sh_requests[language];
          for (var i = 0; i < elements.length; i++) {
            sh_highlightElement(elements[i], sh_languages[language]);
          }
        }
        else {
          throw 'HTTP error: status ' + request.status;
        }
      }
      finally {
        request = null;
      }
    }
  };
  request.send(null);
}

/**
Highlights all elements containing source code on the current page. Elements
containing source code must be "pre" elements with a "class" attribute of
"sh_LANGUAGE", where LANGUAGE is a valid language identifier; e.g., "sh_java"
identifies the element as containing "java" language source code.
*/
function highlight(prefix, suffix, tag) {
  var nodeList = document.getElementsByTagName(tag);
  for (var i = 0; i < nodeList.length; i++) {
    var element = nodeList.item(i);
    var htmlClasses = sh_getClasses(element);
    var highlighted = false;
    var donthighlight = false;
    for (var j = 0; j < htmlClasses.length; j++) {
      var htmlClass = htmlClasses[j].toLowerCase();
      if (htmlClass === 'sh_none') {
        donthighlight = true
        continue;
      }
      if (htmlClass.substr(0, 3) === 'sh_') {
        var language = htmlClass.substring(3);
        if (language in sh_languages) {
          sh_highlightElement(element, sh_languages[language]);
          highlighted = true;
        }
        else if (typeof(prefix) === 'string' && typeof(suffix) === 'string') {
          sh_load(language, element, prefix, suffix);
        }
        else {
          throw 'Found <' + tag + '> element with class="' + htmlClass + '", but no such language exists';
        }
        break;
      }
    }
    if (highlighted === false && donthighlight == false) {
      sh_highlightElement(element, sh_languages["javascript"]);
    }
  }
}



function sh_highlightDocument(prefix, suffix) {
  highlight(prefix, suffix, 'tt');
  highlight(prefix, suffix, 'code');
  highlight(prefix, suffix, 'pre');
}
node-v0.10.25~dfsg2/doc/template.html0000644000000000000000000000675112270121457016074 0ustar  rootroot


  
  __SECTION__ Node.js __VERSION__ Manual & Documentation
  
  
  


    
    

Node.js __VERSION__ Manual & Documentation


Table of Contents

__TOC__
__CONTENT__
node-v0.10.25~dfsg2/doc/robots.txt0000644000000000000000000000016012270121457015430 0ustar rootrootUser-Agent: * Disallow: /dist/ Disallow: /docs/ Allow: /dist/latest/ Allow: /dist/latest/docs/api/ Allow: /api/ node-v0.10.25~dfsg2/doc/favicon.ico0000644000000000000000000000217612270121457015511 0ustar rootroot h(  \W:oѢNǍNǍuӦ2ڴNǍNǍNǍNǍNǍNǍܸăSȐNǍNǍNǍNǍNǍNǍNǍNǍVɒw{NǍNǍNǍNǍNǍNǍNǍNǍNǍNǍNǍNǍo~NǍNǍNǍNǍNǍNǍNǍNǍNǍNǍNǍNǍ~~NǍNǍNǍNǍNǍNǍNǍNǍNǍNǍNǍNǍ~~NǍNǍNǍNǍNǍNǍNǍNǍNǍNǍNǍNǍ~~NǍNǍNǍNǍNǍNǍNǍNǍNǍNǍNǍNǍ~~NǍNǍNǍNǍNǍNǍNǍNǍNǍNǍNǍNǍ~~NǍNǍNǍNǍNǍNǍNǍNǍNǍNǍNǍNǍ~`NǍNǍNǍNǍNǍNǍNǍNǍNǍNǍNǍPǎS7rҤNǍNǍNǍNǍNǍNǍNǍNǍzթ/`^̗NǍNǍNǍNǍdΛW ‡SȐSȐ{?node-v0.10.25~dfsg2/doc/trademark-policy.pdf0000644000000000000000000033257412270121457017342 0ustar rootroot%PDF-1.3 % 4 0 obj << /Length 5 0 R /Filter /FlateDecode >> stream x[ےܶ}WĭZӼ-+I٩r$~#JkF9IA`xmKnt7w{Neju|~P{w2.M/6ڔe[.H{K*SW*VWjFy7S6I*?bԍ zvw(zO]~T +a8.U$cWs??^ M};-}&*byk3oż6rdb9YRD svʪ:Ii6i$"VeVkAݳ"M6YVio/I9wW ww{\ґDɛV{G۽;{͈,1 IvX /(C~Y6Y7} Q굊(>d!;ym>T$q7j`D^sI%%%^E=N}Mu'\mbQwg<$'70uc'nڲh[`#.h}+D# )-ضJ`iL >7."!(CZ]l['E^J a2GR8E%-yaw?nPy" ypi?7\]9q@ Fw{ɕD/)rFWG܅v=pEAʘ"o9XUXbrx{sBƑ8MԵdY-]UV%-l f&_1%50{"MA?uD5F b! qn%0Q`L}8zwD (>_/`I2Sr9rYQJ^F./q %xEAET3#dL6pǎQ(F83y?. pM"utIxF.f{9⎘3į$eI51S8]'jg=HR[OEHAㆯtV, S;p5JKA7AG-# AA i\;㙸N%A@)jeQ 1d u-Yqƀbϊu3Єg`XQJ0XhR txD I9 WG2]0AiE,:AMp0δ1(a}med 2\PQi2`!SD}C9pod+\:Z-+y(73IwpiCzða=%hJFcZcl(Iǥ/k 53ㄤܮ=R6Uu;TXk9zp $lM<$b~A.A!3oAsl(>t*TiSZe|䷸RvZe~cBG#@#ř@c0=5=aIŷnl EofOc:`\עH Dj^Zq:~ 3}A$og< fGu!uPU-_ވ3Ǖw#QkL E+ʭ ̦BcA(ϢX-V  v("vd#ջ=b$)0%\g8W1靹*4fyF -̢*^WV68%-N ||va"gUYJboV⣻ajM#Ϡ cH ÔJ5C8;5#ͬJqp0_].0O k =8Du6sv]Z48;O>U׺%0 \ N չ;M_P=qW A*NJ1֭7\1bS8ޤu0dr!yȏ(!i &0e/&]Um.B^}~zkH1m1 uf@ 'xxǔe^& ˺\z]4S~F3 ssR 9̨Υڇ87LD`EbX{*C/Q߾s2(l@n-SV\lu+%Mfcc =J@`a>EY^wt2: ~ E]RϝgW1;GӝxН].{s rm1 uw<ȁ!ģxq;$m յmgXWoE3`cbJ| RTb-K\xgu>aZM1=BG':[\>y\BQ>)B[;A<:ƟC)NSnzVV[ endstream endobj 5 0 obj 3511 endobj 2 0 obj << /Type /Page /Parent 3 0 R /Resources 6 0 R /Contents 4 0 R /MediaBox [0 0 612 792] >> endobj 6 0 obj << /ProcSet [ /PDF /Text ] /ColorSpace << /Cs1 7 0 R >> /Font << /F2.0 9 0 R /F1.0 8 0 R /F3.0 10 0 R >> >> endobj 11 0 obj << /Length 12 0 R /N 3 /Alternate /DeviceRGB /Filter /FlateDecode >> stream xwTSϽ7" %z ;HQIP&vDF)VdTG"cE b PQDE݌k 5ޚYg}׺PtX4X\XffGD=HƳ.d,P&s"7C$ E6<~&S2)212 "įl+ɘ&Y4Pޚ%ᣌ\%g|eTI(L0_&l2E9r9hxgIbטifSb1+MxL 0oE%YmhYh~S=zU&ϞAYl/$ZUm@O ޜl^ ' lsk.+7oʿ9V;?#I3eE妧KD d9i,UQ h A1vjpԁzN6p\W p G@ K0ށiABZyCAP8C@&*CP=#t] 4}a ٰ;GDxJ>,_“@FXDBX$!k"EHqaYbVabJ0՘cVL6f3bձX'?v 6-V``[a;p~\2n5׌ &x*sb|! ߏƿ' Zk! $l$T4QOt"y\b)AI&NI$R$)TIj"]&=&!:dGrY@^O$ _%?P(&OJEBN9J@y@yCR nXZOD}J}/G3ɭk{%Oחw_.'_!JQ@SVF=IEbbbb5Q%O@%!BӥyҸM:e0G7ӓ e%e[(R0`3R46i^)*n*|"fLUo՝mO0j&jajj.ϧwϝ_4갺zj=U45nɚ4ǴhZ ZZ^0Tf%9->ݫ=cXgN].[7A\SwBOK/X/_Q>QG[ `Aaac#*Z;8cq>[&IIMST`ϴ kh&45ǢYYF֠9<|y+ =X_,,S-,Y)YXmĚk]c}džjcΦ浭-v};]N"&1=xtv(}'{'IߝY) Σ -rqr.d._xpUەZM׍vm=+KGǔ ^WWbj>:>>>v}/avO8 FV> 2 u/_$\BCv< 5 ]s.,4&yUx~xw-bEDCĻHGKwFGEGME{EEKX,YFZ ={$vrK .3\rϮ_Yq*©L_wד+]eD]cIIIOAu_䩔)3ѩiB%a+]3='/40CiU@ёL(sYfLH$%Y jgGeQn~5f5wugv5k֮\۹Nw]m mHFˍenQQ`hBBQ-[lllfjۗ"^bO%ܒY}WwvwXbY^Ю]WVa[q`id2JjGէ{׿m>PkAma꺿g_DHGGu;776ƱqoC{P38!9 ҝˁ^r۽Ug9];}}_~imp㭎}]/}.{^=}^?z8hc' O*?f`ϳgC/Oϩ+FFGGόzˌㅿ)ѫ~wgbk?Jި9mdwi獵ޫ?cǑOO?w| x&mf endstream endobj 12 0 obj 2612 endobj 7 0 obj [ /ICCBased 11 0 R ] endobj 14 0 obj << /Length 15 0 R /Filter /FlateDecode >> stream x\n$}`0%Ďxa,b %#7I%nAwĩ41H:W+q4zjrFң%cՂJҭ$pH=Vs0~GOWlIm7zuFeBn:'{~M喦TV\*dccO;o(eFmU'67L5efRS:b$;0 EV ACe#35Ў­;.|)b|n {XCG?P?@ X8o+knH ZJJn$v@CW:zuFLJ ,.cw.8-.Y\p BLKsC; J\-ּ><r {pZqrpxH҈Y=mqF&ʚqJ/P34ίv`mӡRn18'Nld O;~!(S2~q L7Jhp^pȲ, -mR>JݴCO[NRčqE׋3ȥ"c$$FYO:N:&޽;H Ƶw9d3 !p-ZnC;T60eMw/|vMp 2zoKR/"2<pHD)nѿsUe\2[NLoudyY~H\>7Rѻ^(M!Ezp!ioKlAJAQ_,vQY9Ө!H 痴]8S")@HYqr.pS5m.ǭH@d +F:*9K-\""{\\gN Ξ'_T{^$ƨ;׳`!i?8qY0kW2M3wl;/c:L"ŝnx*xsݶk`Э1'=M{mbzﴢP1l}أU'IKl`O( Er#F@S=syV"I/IgDJAQ_,Uַ+Љ &7FhJ&cAK x(Un6 UgɄ㡯IT{IEVo\d? G ,V͘Ճƾ I^ި4JQ@-0G.?챽'^j7g,&Iu[ٸ! MQB endstream endobj 15 0 obj 4393 endobj 13 0 obj << /Type /Page /Parent 3 0 R /Resources 16 0 R /Contents 14 0 R /MediaBox [0 0 612 792] >> endobj 16 0 obj << /ProcSet [ /PDF /Text ] /ColorSpace << /Cs1 7 0 R >> /Font << /F5.0 18 0 R /F6.0 19 0 R /F3.0 10 0 R /F2.0 9 0 R /F1.0 8 0 R /F4.0 17 0 R >> >> endobj 21 0 obj << /Length 22 0 R /Filter /FlateDecode >> stream x\ےSt&ڪg\ *ʓps.vVZdO^}#[Z.VjO?oO*/pP栆շS}6WުWn]_ mԫ{1Jx>,v*WT87SWyH>kN6{u|r+w*}oRiy%w3}=o5~=1wWSGX>ֻU<7}f^\8QkHNydcbZ}6TQ4z*XDUgyɊm[Y[$[d.U\]K21Q!;<ބ3h^voU>Z1PI]V6֠Մ0Bb?8%gՄ%:@D^@+0NMJ=oһ{T[Q읾*}o Xzgxc_~? ~yӟAcG_- bf:2Myb;e‹k)_bް^*Ƃ\Xȳ۬"O-fj j&%חB0e8x 0JhI^B-~@tF}Naˬ)+4 d|u>z-䝊FdU&Є]Nu ?GIX23XԝȍQA I'$K<}iTAsx4 .۬*+$,ʈl yVmm"}>mx.@b$4 ]9%<+v+&T IjrAI^ e+}]󎸓dbvr~Cx@?O8\c$\"/|᏶d@菉$̲Jֶㇹ133 m$VKoadA::^Z)K/H]KajѴ`$dK;V:!;ϸpAGDxn;aݕ}m?Y~a,t%,M_p@:Z9y5cJ᪴õh}؛"* 0kWLR(%D+&^-.oir)@8O@{Zc9|%]?PdE݊~l }i~"4a+" Aw bXViDHNr<"X_p>%V.S}rГ vԦ i "<ޘ2v2 %X.`xma4v ¹j(H9Lw.tn+ywіle!*"N)2nN1_*5b z8ԟxs;ʨ} ôeNkTR+x6~+L}ܫMR1F^> 6ui Yl Zg13\;;Pj)*O\d1Rm2-䃧tnYvaI&@D yg~$r!z"Hĥ 'qrFsnAL bgSdDjGe;*Mt> >k}{(8vDڔ WzcaNDyhRu„)#`v5^p,0mJ*^f2P!,;}nJ28}%eI_G7 ՄA85$R&3\ <<vm X(l[ EىE$y殁"s 9׮eQD1K08kt8xƼ[a' (%6ULGnQɧ!nLZ]<ԭ+ejc`:.rtdcA&!% bfG~6*>g.M8xA*9 t{G9+9 PXL B>̩MK!r cEPQTJlZ(]xEhx|F=' Gm@e 0y ᒐ-r7FOT GI#U<+{(g/we Oϟ|A gbU{墮l"Zdf#p^/mĠh<mtm36_bn\[Equ ̈́#xq2@SKN,uء~4; & (IM#<ۮ6%caĎydƿ0©.KilFDhYlӠgFipE~v8b ƬS1vsʷxaĶ[VY'ZJn#?A{p3L 1քi &ӝ1 0M/q1[C$.q‹-6إ뉦em^Ӻxzϣ]LQ9}\Y;P ai:ENF2_b[ wTa?X(lK*v]ԍё.JCPkREr:hz<@qK> endobj 23 0 obj << /ProcSet [ /PDF /Text ] /ColorSpace << /Cs1 7 0 R >> /Font << /F5.0 18 0 R /F6.0 19 0 R /F3.0 10 0 R /F2.0 9 0 R /F1.0 8 0 R /F4.0 17 0 R >> >> endobj 25 0 obj << /Length 26 0 R /Filter /FlateDecode >> stream x[ێ}W,yDlF,bI"GG9?f9ûb6u9u%|0if+{e~6OSI?}Ioe}Que^7E?ޛqbRs̍{k8?N)A)%Bڛ&{G].fû_n"Y?+n[/?ݘ M}?-}**,6<굹Ѽ6bb9򰦈]&)-8bHzIx'FVtJ`LDSIGefPUu]4,$=v qs,Y'#Js-xT5e/ԔaXY,-чРHyPdů{,tGEJ !vZ% zQlОg>`s8oK `  [HzQ:JJ"*pD;0LF~t]% $g!Rjyaʭ$DP9Ӻ+ڶy ~i>l*q+1B7,(vvNS'R2gc?,C^_$L;޾`h臁toh}AdV@씡Vt,CTt>{Ab{]xx?[tewXiGa] KMi*ro7y5-n&az|\qj0ХS/@u4nOT>"b0; ~ Vu/xU2JB,긮t;51\uCÜ0=|铕 I%@Hwp6>a>g|;8j%aJ5Sslq~U!܆ךTs${+N]Xr>؇Pt8| XzOB *\4i\d\Xـ<]5P5`ff0''L^_p%PJ,Rr դ`5V8= B XH:"-\fT0`*4h_n{,=U5ӃY{hLpBQ7nZo`LPż*lMs' HA*#:h'd]zv5!4jzqz׷hi 垖 ~CGhhP-ʚ_/\|}Dh/_;ElU~HCDpKaU9e0nC@bM\\<_³b3Uc7lp^_vGRlo`lŐQ=:!A78ᢰ/JZT :",b߂zJƏ̔Qtry4ש ,XyV~5?BlLOYUrwg, c5BөKȔ * бFDBo?tFzxpG `1'/%/ Y1B\tT_&||K1 YFpnr0<^ʖOٚvP |xqo .p@/2 1*h;rнti2b˒0oRbLceى:$/DCӢvA6eX] i=grFYX~ Wх[B^ː-~#WA VɣLf_Hu })7&$EA#/6K:'MKNԀ1! (>)祈\zItݢ,4` XA> .,Ҵz@܀T,gL|(+>ُʗWn_{bϐ|yFmVDw;wnlyMXjj+gZ|qBZi2ROk11NY]댄Ҙ]VJxvu1pH38F#_FGOaV-Pi_k9Ze0O2C+ nƽ*KS;)Ⱦ4Gq1Y-0jGoޱaim> endobj 27 0 obj << /ProcSet [ /PDF /Text ] /ColorSpace << /Cs1 7 0 R >> /Font << /F2.0 9 0 R /F1.0 8 0 R /F3.0 10 0 R >> >> endobj 29 0 obj << /Length 30 0 R /Filter /FlateDecode >> stream xWMo0 Wjɶl_7lz+la5ǖnChYIHTz$䉮艴–7Z|M].Q&"Tei(-lEJHb7}9pR%c)--R¸ٜE\t}W08pq^{};xt;M~?q  fog?}H[WHJ6[Hf9Դ4K '˅,F,? l+Sc}b"V ňO#⩅VH [EY,Μi<{> endobj 31 0 obj << /ProcSet [ /PDF /Text ] /ColorSpace << /Cs1 7 0 R >> /Font << /F2.0 9 0 R /F1.0 8 0 R >> >> endobj 3 0 obj << /Type /Pages /MediaBox [0 0 612 792] /Count 5 /Kids [ 2 0 R 13 0 R 20 0 R 24 0 R 28 0 R ] >> endobj 32 0 obj << /Type /Catalog /Pages 3 0 R >> endobj 33 0 obj << /Length 34 0 R /Length1 6780 /Filter /FlateDecode >> stream xY |T?7K62 uyÐA2 L `@A&$ URK\Vy ,QVSu~jEO[o߻s9nw}KQ2HeQsWG`9-˗zJyb Qnsmͭ:}v(bu6 |h7[.nsڼ$u͋ڤSiQ;w.5#cI[ܟ,m#6<1Ȝt/Y ٨$R ui761sRi͕ zapܫ<YQM0,WPMHr=(.vg9$'#HUBE%UA{BsD>6@f"PiU.$`yQa"mTIg-s.lIb`5p8 +2#Fb^Ԩ6ǪMjU㵓bnbn#FԗVO/( ĔҾ Ef`?OIT Wwu:(b FV%rtr阅Vr~O|?9h% 8f~}JQ P v3jʌ1+ww@Sېo}HCGA\̍ QZ(742jB4R pDEVd|GحzW]Əp8F>N*0 ޠpp?2P+tV~,ah]P&"~ 2/~wPU66px <^" f~:~:g#]k$qK^J޲ $6A}H.$u$Iܳ@=HeSejU*_(@V J+H+do9ǻ#Ngx#BXh: =Bm,ְx<,dg|~61ދcY,tdNrP e!yg*qg/+r'"D;'= F 'uH9;_!݅JWMn!:(AF!t Z 3=jTfc:g0NA+?2ɝ7ڣ'7ը"A>qK%Q+4Q֫=1'k`qlǵv3\݉71=1:s~c|klqp1+pfY{,-~T/,"Yr-Vu5ٚhZVʭdOz=7lHhF!۰0̀gVN6Pլ^k W%6LjS}c6Sӵ2Of+c[j|}Q?tZ{s%d@2WfUW4ZϏW֏'˓m hRogM;aK oԋ@>ʮ4He?+^ҏTk~og̯7T2%$PW`)Luuv OJOgz'#D !Up !bg91.å$c$# I9y'$|.۪=]hi|A jgiUܖvɛ۴Vkqժ]FUEMFW6R-k*h 5gƚ&;%ǚ`Xe\+Zzab6Xn9]R/ŔB9N: qQK]BB?sԈN7-΀9YC,/R%;uMÐ)!,.KX,sõCs!9םG Fzz)1=Jي |"y|i]4$OOAzE=C{IjZIw:fAe{e^^E2X)uZK)4h-lr+d:XH[ma$ʡ#gR1Zv -ib<%SV>O3p A)tqzoY[)jC?/;ͦvIl4&}~20 uEhJY,eSMzҫOq3!Ji,,:\Yؔl*5yM7ihk exQӫ񑷖~#M/,J>/%dň#PZi>}zi'! ;s^I}{Y>5|w*)Yim'kư+Vu7l;ŽOxo3]\/QQf(ʭM͟Rvj@>Gae=tB9A%(*sfUl3{f;>+KǛy.?Kp¼Ï߈L1Dxh1^bji񁒣UtĹԴݴ˴9YsxǿC?~?߫@q'x̾evdz%#v9UɈ]n@$oc;ܟb79ۍ9_Gj>jƯal Hb(l&vW{J|+C2A,SS>V>65^6Üh^d5SMe2۲ղrDvO;)xJ6>a^E>ϡV1#Sn弜]Ag7b"ſb g3hP%@̙b']'d|%³=TǏbo|.`YOpg*L)I3Rߤ } v4֏0DG#]zzOP`Ԯ/t=kXƧKE[|a+Ea୙X孬qcǔ5te%y _2]05ĩ:9Y LOHINJLZ&EpFE>W]PAMq&N,uW3( U>*5td6u'kVX(SR{9VEˣY~44Ķ90w: \TP?VWinn%8[ )-s̓.d^=K5_-c}2-fXoˀ"n%m`_rsaϹO֔nZJC:D3Y`?6/CO46mEKFl9'p8"R-6IqLJSh&cD W"d4)2ԁx"x.Eu3:ZzhK=9\Ç.8QwcV)qx<8Uw./[?c?qxM:56J5\jRB p% VPabN1jvΏCt^C''F !=nCW2y RERbBBLsW^}{MJwa8šQz|d$&{o^8dz endstream endobj 34 0 obj 4534 endobj 35 0 obj << /Type /FontDescriptor /Ascent 905 /CapHeight 728 /Descent -212 /Flags 32 /FontBBox [-665 -325 2000 1006] /FontName /IXKJIL+ArialMT /ItalicAngle 0 /StemV 0 /AvgWidth 441 /Leading 33 /MaxWidth 2000 /XHeight 530 /FontFile2 33 0 R >> endobj 36 0 obj [ 278 ] endobj 18 0 obj << /Type /Font /Subtype /TrueType /BaseFont /IXKJIL+ArialMT /FontDescriptor 35 0 R /Widths 36 0 R /FirstChar 32 /LastChar 32 /Encoding /MacRomanEncoding >> endobj 37 0 obj << /Length 38 0 R /Length1 20952 /Filter /FlateDecode >> stream x|x3;w7ig{-vF͖,M-ٖ-;`MǢ`LC%Ȧ9CTHGH@CHv߹+c}oGwm3srOvF*HXi$ \yWDw͖eIZqךb1׭^XF֬bmqEl}敥v ʝ_Qz> ].ߴS[6oQ*۲mu?GH1Ql:kt= q(#ļG#ʤ]z뻱;?_m\f#@ ~p?:/]qHr?iXw-TdK5GqYK.GP~! $)_HcU" '{ @B:mH Bp!QKD9bvW25uh2=>DcI*^5J|֢ x E!<*^E'u#Y^bGG 9@F7~ SHH ώ^U ?waAfvKnZCp[Flkcӣk`{vR }#NSGF*BFM3>LϦmK/AHD!mKG0 g#\3beٿ=BM"k1cS#9 Y, /:Т(ԸQ<׊g`O7Rꁔ/L+RPJQiBjAxx#+KKK}K˥R/w.u7:F9.Oh5 SkB]G¡>I8q@Q:y_7{/9Yl>Tl>6yխK;9Geu @3I=S~)95fkkA*':!zZ)*V*[*[H3i@d yAt\ tyIG.2>oΝ۷ΝpA;8wQ@#gjvX׷&u"pQ3e;r\}{T.YI;uQJ? `ұ2q=MZguGIo'n{K4ȊPw>&)?p^8tt>PJGϢ;]ZzJ'я%h %Q hr4 BNd)Z>>yh%zqPz5"]TnF F,BOw )Q'6z7^z -DW؂#_0++4ɏԃf>ԏ֢cP`WAG6xR? sJԂkhr,݄A_*HW3'i9:5،=È-ގE >*FIif56sW |0Z8WsA^{@waNx!IL^sH c֡Kn(G_b˰S5̣Knjٺ݂n$\!;/( 6RR?{A=B[a?k G^X{1#G:3߆z9s^#H G(Gfp:ꂱ\LEoߠak-x߉{o͠OK?b0`6Hn| .ߛ og{n`W-nxq^}bz<_}1Im6S[hL^:Ha濘_Iܖ Uڨjqñ \ m0Gˀ~9 F؄8;XKr__(RjuVz?=J3R[2{X7|^]>#{s22)o̿T/\Vx#ӄQA9}*n4-_MзxaCg ~ Gcwwb/zK oW~~k41)%~KJOUKSөt`0#Tz~s]w07 x?e270HB0O$$T)Ҩ Ǭ iv-Aw^{0J:㷨f|%Jh}D;@] su<$a䧌 ?͠Ao>S_xз ܍ORdPn>O{o%TDfۂ]EUEVP(&!^j/up?[LP^)gq<P@>މjw]oL5M9ԗ؍=?Q@MuGLEq+GywxƇ"Y |$:D৒ѿazZTyV+*+QJ,-G ґ= ^1gfK6cܜ{"VzWb&>&'m˱c\s66ъ÷qhPTʻjёE9˕֯psPQoA"oqѵ7ӆoLak GO^Rfh+'z o|؇sh..,|~;,o/;jDv-G9]q6jJ}qf5tM̉I{ޅdD.Pjs.I^Vסu0pUna}N64eI=L%I59{'͚FB+hrh.!t"aMb9]Yq1s`1BnbمV8F#"-ZLI˞ y|v)' \rfCǺl^o7v}Tl' m\O;(Bڐ dх.PW?IEJ^5ʀ욖:]bEcU"k@ᩆ>3Twߢa7ڦuM^>Vس'A oSXmܴU,-Zzs E'ẵTPQtk P7Jdb㤀/#V늝cT T"\+':nPAӒ2>Sj;P @bP,TC17B~~`%]"tyaHdw -!z%EB߯hpa'(:?#pNS*a]D9Gխ.WJjԭ`&̳,5l /`. ^i>F/F0 %,%F6T%eQN/&fqz&P3punNA]s^jKY@РZA84.Dkh xBJs]>sǑMW(ܻgrVPsexjjkj XAW Q_Dn8tmEsm˿x=?KC /2 r~ _7EO11*Q3׶Il֓&'8xtX6 Z=HY)e20_+CraW凿3jQsk)$[#R%rqM+x-ZHjE"zrDD/1{{ ZrH14JRJ(#lD4(,exSHJh!\Cgcc 9 6L>91dnUY5ܙ AؙdRWЏ~&=K_1a ?qMh KB4LX"5J$RFia!a;]!RR Sfcc1c ~*#~1_I6pV}v>dgP~izҪ3\f=foXW+}?TVPrEQ^i42 5 z~7MaR@Tyh `2s8fQ-k6 [`bc|@|rTvAi&̤P!ӣʔ}"ltyyyYb6"7X9=# PM8<18O#f˦$J.1#xGT[_1kR(:PGMX `€Gģq /KMWuT/Qh8rV*%3zG0շ+Ώ%APZHC%'j B\^0en,7蕺rr8,%X(S˸9/no-8P*vnwD FD_? =!NLD*Bo. J=~~N(b(֞gL;Y"׏ X2} |QohJ{h ɆWr E% S= n2s12 'i/`/z1dPLPG/`J%U}V<;%3n_ ~n. Ì ߥ7$r̝7#K*D:[T'OVS5.J履UO(!m4[f[Y8V PT I{4 `RX"73զdy`>:Y 6h M@ A䌍Un甦PĩU6Ā8&"aMA3M]& U{FzӦWeQ9DU*UNZ@M,*OԘ,EE"0~RhN\4 TQ-AZ"BC|rA.|r.JD927b5!ZgtC[ qg@m#aR<* k(]JA A'X~h0 &X̄tj-Ң*T[ jki@3n 3~L+d*)鸻)5nt̮ ߾qsM{{'-V9+_l])}z׆x>aƶ[g?͟ C5@ b)0+J^*cd˜))jEC渥Ǫn;f!(,V^1ϙqV=n)jH"Aobvh 4`RÃ"4J xRwԟi?W[~-̔~2މ"~zsgC5@PJa4 ƥ,5Cf]zXwǽ mG;'{V͸Xvj=חK qFV XBT*p4XjBM8+i 6nns G}씝IA>$) vf ӥE`c`H 6c>'N 7Ǚi%:kb A1uzzтDKpJY:[LY>&IOKߑJptw|2811`͢pgaaqC 8v8 sSbd DB&_‰Zڱgy0v߶ic,̇1v8trqkS'4*J8\޳Xz=Q։Y SI)4䤴)HB1N9vzzo+ͦ٦eIE4 m w=Af@Ĥ@:"DFwA"bA*$b_$%`jH?[9gn} P*P,inj̵O[-&UCN^m2:^8m_Kݤѱ¬Ыݳ 5ZNrV?`͕S!y_'wv].ybl!7߿6a9dil9\&8Lnra S4厘v8^JWVkM0akPӬF5Xc DAV}Ll0Jf% $w ;ŵZbDͲd Hy3Xa-pY)F5g9E7`a kZ~g˙{*]C+~u6u/1lׅk舤70?> ކלD4 gQe3M0?,,- bB(z͛B:;3$+$ tQTnh^m/!i@q>\ h[![vE%;789~ aq 0n|Je0\3g4gnpg4 `Q-D20_zOp@48)T.jvS`RDՙ;WrCkE-g0m 1SZs0Şp%K}i׌,iI~*!l[ ڊOt\Rv֜hK;:魭o-yfKؚKVGD=jiu`ٸL*B8D;cB O=?= v|) ݻ]v?-i| cS p\`@fX6F'G*~U>V3vR1F4U^|6B'-yXn d^D/ Ä0P w8|獙iJO@%'8N0*"Ppn|^%W1R]QMk$8,1 JUV6qFE :ˊ(_(,B=hQ-ưe6=J䎫DVͽvPe@K+CyކO{{c=ݽ&vڵJW3uTcޭ=Aa/ZTcs8]YzVd<:ӿ5ڴ'8ͬ , R95xI.?K/qn r^*(E4 HShE2k:UWxp`CNM_YeV3leªtԆ\J8lUvT!Qdy葚V~GA% \Z DIPgӟVJ[Riq*7Y~Jpz'N n[$h]ЋZ1;3`r\4RتTA cSK.9F5C x]KȄe@' eWZtJ.S{v-cf>`5]($wOc֥2^]1ː]W\6zbA>$fYOZ.ͦ͗eOG#56/6[EP<ܣB[cÂ]ņTZUX;FP:#! Ǵ-j Ocbx)8Nl}J<9`)b`0}Ni8-Έ.Kk0̷IVh)x: ,ٸX_۶)V n ThRPX{${\ڢ(e_7\O7?dlFZkdKڛ).ap}}8ol\ee4Dӗ˔G'Ө& pG8OZ.<uE({;Bx*VVռ?`1ա\';z{sKܬi(Zwԭ֩mT%u,cnPY Qx2 Wy֦҂)BPY6_6""_ ]Шq b0}a4ING*i8p=hSa o8xށBF?%k(G%⒬ȦöT"=bxP3>> ''fq GB$z,FqL. {S;ʸC5D_#)ADcX Kp7RʲL[z̢`f!)vfǷTWy+J|\ѽ)ڵ1:K޻iG!^9^P_٧?-¥+%,0- ˁd-yɨכJ3ds_w>AEHOSNޢw*.2$>Ӣ'@E=Ҩ\5xMPZуǻ^U ԂDJǭ`R} 7O}X 13(J9aGnDؠ)E4<fq.S$]X,10L F]xs:Ї<>\ m/!h f6̟ΰ޼bjʊ+ҷUְ!C5=Nݑ̑?qDDuyh}(BU]-jETNRͲmfq`"뛌Mկ6vuu]YE.3&z菃%lIcT,>Yb<o^p69p7=_ ]"oɈ/QH,ڊHX,Tjsק]T/ltY}1)+Ĺs[}6;$a)(#.Rq DZK>hq+қN Z[$Qef!SX[$J21i>ʆ5 SbkH&o)2NoVJ{ S")_~aEl2ή_K [&^‹yV;;\fWR!^]/ι%$gqUٖͭU5k4nOĽo*,35[6 >]zUs_H?Sʒ+<\Re13rP3'څ|:du*\^"""hllpM 7MhiT- Ub0+^drDQM4V蔹QY %ඣV3 ]HFd5Neb`3 \A nsӳ zx%{nE;0C =?XZ\/PgnzK-W8Jn{U P@O{嵫)S[rU]Ơ,0ܔ V;ZW?Emj1 QÎ짐*' /XsG̯Z [>gk YtCml*T*O(WقݛbA0 K6;|>|H6$L#Gz [Q"]Om=r" xWA]1_Mу>O/;A͹7ܶ{awO>UpŽ,xQ GTϫ^VK2n4M3/]٩e.tRrd]晃h`{# ؗNh4lɏ|~FЄڱ=rعSVa<=.+ |z6a {hحDG911HI}OOB|= Q+?8QT;Jv\'a)f↋@^\qŖ|h043 U{mJƦ 6ѥAǦK'ezb7i]K֧6UޏcosY>?bu~?Skt8aFvہ3˧] ~F1*`sIw$&!rD$\$f ~! gkHnpTATJhÕC_عԭm+gpe;6욵h9,o|e{Ps]º=*~BmH/YBc@}0+`$//IɧWzc}i_y-ZW D9F ˢ2ʝV > 5fcz?z <%f<8-fեA`oF:j5`s( ƇJoj2w8r0-7,W{5KLf"`0eƉ#ѐؚd`a5@ʖMa"$ E P*Q!)9 M"Bg={2Ni [{Ke*\ܧEuϚ'G^Z͵hfh9/Oр6eY[ҧW5l02]i~/|~U_9mCLt j0QP8CL94;, X`+Ll$M @XLQ6ÿ814@HC#8 bX>Dt$`  X MB@wV tBwR5"%BRqx ­FbC`ߚx#<1J,Axa?"̂-X)EL=@0A(Q `; j*3&ګπ3_[8'b-R , xMTm-}慠Z :g&jЇ+.w 5Xhifro8Lo|&^o\Szf|gBuC8;W;j1mWn,{_JͰdsP2AJݴYm|`DL1Gӱ̱$rc#>TXTc(l1R%V FjGbYl▲=rc+ _zefUoT92^S6+i%KnTC۰z{t}2l2c#Cۢ U52 esS}_tMpP  ir"&lPJ^Y pTD$h/P1Gte#\$`Z r) H^fm Lh 7ߒ_Y^[ z) k7G:o⣍T[RGc"=z%. F4,Vɢ"6 h{mOEm$C!)b\n:<xS03ؚ=o{(Y55q OGׇ"SnoSMByiK-3a>@b4ˋH8A$zqtE~/~{ 4MTAE]ĥs > xP$*PZ֒kmpwUZMj|&0S v6m^^sZ^ژ yϮQb߶5I,3:-Nzo*{BNQhlr,u lR5C٬ :+Qn+\.pG0;3naj\mͦ6-lk=MNُӯ3?خr 8;h>IʣN{]ǐz2]-2BYpFFN-xO :AOiu҅T;-z1 5Dzǒ.KhKWZ\;vY-];F{5a5Y[M8~jzNjU1l4($ 5DM\B o'̙%0l%jD&~QH-I*EqǮhV;Z)㾊7})>0ejk4upeWߓ7v><9.N?㺄o|y!AA.$ όMԕKaw9C-*?_<|ƃ]Xs9u(*2 ·!@D~Rڢ}7>k6oZ~ʮ7_7T endstream endobj 38 0 obj 15463 endobj 39 0 obj << /Type /FontDescriptor /Ascent 891 /CapHeight 677 /Descent -216 /Flags 96 /FontBBox [-498 -307 1333 1023] /FontName /OLIHNC+TimesNewRomanPS-ItalicMT /ItalicAngle -8 /StemV 0 /AvgWidth 402 /Leading 42 /MaxWidth 1278 /XHeight 454 /FontFile2 37 0 R >> endobj 40 0 obj [ 250 0 0 0 0 0 0 214 333 333 0 0 0 0 250 0 0 0 0 0 0 0 0 0 0 0 0 0 675 0 675 0 0 0 0 0 0 0 0 0 0 333 0 0 0 0 667 0 0 0 0 0 556 0 0 0 0 0 0 0 0 0 0 0 0 500 500 444 500 444 278 500 500 278 278 444 278 722 500 500 500 500 389 389 278 500 0 667 444 444 ] endobj 19 0 obj << /Type /Font /Subtype /TrueType /BaseFont /OLIHNC+TimesNewRomanPS-ItalicMT /FontDescriptor 39 0 R /Widths 40 0 R /FirstChar 32 /LastChar 121 /Encoding /MacRomanEncoding >> endobj 41 0 obj << /Length 42 0 R /Length1 30136 /Filter /FlateDecode >> stream xy|[7>sJ]Wҕd[-ٖرN`q6 N K -@@iEa).{[ڸ-)!iI)h@@,s@h|?+Ϝg9g937\0ቼeCDyXicwG.>8tޅeB8-x^le!NN֭FB!N3n|SYp٥S? hم /0=Sq ^B y| !*Lv @RlMD8W~ѐRkg:N{3X}7 DWz<@=m8Eȗ7~qD(rN=UFU\zTe) 6Ae'po[ +>%ʞFPF~琚1}feG auzmz șarݬYH*j/$LV#EQ,' NH n$Jrv; aCjm>Aywx2bU|JYёpD2A4tu#JJ˪_&%DDI+)9$>k(FG XCq*Pk|X)ekQ&Cz818?#8ߛb{G j?!!a8O+HQ1k/9Mw$#)k"`5ĬP=緐2d?o%ՀWR9KJmQrzA j1,F*l|g_āRP%Z/")8&#zs6?Ŵ#%+:0)F!*|:Ǟ9k=R=֦DnfJo'F դ-Lp&=CH?Fccccc,ZGqI! ~Ux-9 Cݖ\ 9fBxsGzFvy^x[d:(rݳW5 M @K[J_T1٪]'8'p*[wXDy=#kY~RyvR#>«RfkVQ*W ~@?i>F'ri5]34ܡ6#pC-GZ>iu?w?y?Tq ^M_Jmt'U4E[Zʯ;yȧVՀq8lFcc21fcq:ӌkj>ը{4!ͰffF#jSVQ}I? Ǒa1J G I,'Qn.8YNw= qtTrB4H~ѣQ.rcmӸ(~0j?BpFR-c? 6{?B[9EKw')p딘r—{FJʱs_#o6+wMރ&YLke1\'+{wnzL9V] n# ߯R[*E訒3bX+sw7RVn).d35vq۟+F @[cc߯w(9o$+Qf(*}UeKAjYPXF+b~:b~"b=b^1/EXS$D\[]!ɐ!CCB澐yZ?HS݊_t,f́G%fސK^\8 sm\\\b}VDB4W!X\[sFqs ```3M94CR, sO[QBt?i1$ b?%08X.Q h.xK=^nvܓ+uw7)UڹxqۇnP;.] 6 5cytʦ$tYn0S/OJ%ViyfM HvMH'`2mV\"b-D`zasIrjZ+fn2h` Iē($.1Mj'-ʠl+%!H!Hs@@_ҳs?^.{!(}A(!qL|g0",OiR|)E-}V0rq⨖+(j'ޕH@6Ml_%^FD@*x~)%I!Ƌ:%nj+ L̉s7ݢd't kVWO\5 e1C. ?q*sQ>n3w%TTO&&_*9<%y|͠wܕ0YN&gTMD4Dkh=2:F8{7OnV*<\C%OCOo8f 5[i*!~ JVݩzRڦ~1Q:k'M'd+z۔>DK.}=@_?{{;č>woªU_jM/?4N&'k&wM7q ~#k-"!Ŝ' ź;O/ɃEDKh9K7v}'9™~ ->N^K/T[=~J6{I~MX"\cWm fV}X9{I5}Nڸx\ *&n?~~ǽx/%|UUmYT›RV/UPߤ~@}꟩'5kԌj>u7j>vRWԍїM)nR.:ɍmA<QVB{.]MS)5\ yCʩyw˸Cv:Iu p-#ۋ6Cu6Hs:{>ɽ չ&q(dVVzXw8zD;תqs4Ӏtk\@גw/Ϧi+p /d43U9gbQO5s t){wW1>j!{A" EFyCvgx's$*DnIpzɏȅd f74~!p>i t9]L:3'//'LޭS'/<$/{1w(tEo"#d h5Vq&."jDN`?A=堟6b >yAd<|s\Mn===S*%0(:_uhg.9 X<x AJ)$@g_P m6?gØ@TUNh'2z#=҈5*v:6j1NQԈ.i@(ȪҬY,.-C²!$fl[oQrJʅW%j&.)E"|KWJx6#B˽3Mwt tV}FCԱPQNʺ}Bꚶ#:3^1: U Z2۳Ugi iy0!:!J7YMGVtZېBv<*IJi%Y~ڒ3zuC\\qޱPv¬>\lf`j.Sܵ}Yz-Sު~}(6p~(ڥ;j;-+kyEhah4x!EIV<R4{TDG:W1#Z&0]i4NpĮZ#{+kF+AA_+Qi! )TBJ+Hd7mOR[!4UC}aCǦߛ[J 7٦٧]ϸ321*~3bdlcI)ίq1`s%vEDz'%J<:%=;)|<<_8=LZN«Jma[ ?vRV/qea wl v#^oyի?=W oz\d6aiaղN^;}G.Zw'x?z#[WI?N?`wqbÍVWu=Wl[|U3j%Sy0>elgȑ:V՝G*, Ԩl ب7Lt7bt')?S\ޜ.<3ŐyZl 8UF}ɠıl5Z? q qjklJ~ 6S"Zfj!i7jS tʙgoaϴA-ii_yƝTu+wG:/'n`kܖLx/QFOfk(-!}Z=un6TVT%3-ZfյE{'ўT$1c/hfihg_pR}kD @uBPtzog'[TJITUxrxDo0f@ &WW&Nߍ~ZZG5vϠ)&6p|O Rf&&uEX=P:J2mvo9ߩKS6ji :ze 8CsBx|c`|u"`UgnW"G)Z=ņݖ{1 c' dhzҿE&ű@Nީr{ڥ$))mj]}ÿݴ>Ӿw޿Jikїo۴okDgHDS5lEæ#Ijx1%w^jy{FK vWCEm(@"](`HJ|Dg[b Zڣ+ʧ?UXO $.Ĺx7qwaJ1iUbǓ~M))xE"NSZRV(5_8Mt;=N&K M0O+)3/d\@2b̐az]-DHa̹p~(f` (hj;+}S.ӯY,jYXȹ|u$־0?zh߿kRM~pQ}[EP<0/*:_>^PMffWcowӥb輼F6F]]۝4!GS« S~ġ6Q]h2\ІBw$\XU@Rҟp(Pf'bޥu+UedrqnFk.rvjjih5V:-ٛ|!ɥɥumɝ5BPb+׀[͢3C,)_o7ߐi7 o]/ STN~av!\ChDiqδ-b4VJBVh,-+d+OY^Jil:,F#(UT>If-xejfi>4+8 |30MJ)\}_W:)8c4X@4(jJoX`ז@MT1T]Zf7/8'1r<%_vv8:s& b1K٥ -e7$ ^e+уUOǟN:erj}Je9Z4z$bH梶Ts!ӏ'"D펨k6\dl-4e&!Sk/djgWѣ WOtwEw -ys~eGc76R8"ے/qu(A-(6f1b M1C9F!s;ѕ)6<&|&B+ [4Nyx/>l6 (V kcEK~qKyu]Uw&Au/2R -oWb7op:'bhNiMk\IZMts~} z",[ xC{$ hD2dҔk>b40gHG 4m C1j)< Y ӡXKp8f&|L0Ellm`*p2cmǧ/~FV#"_X'cM'ȟ&9q(-9V(Z>NbB7R(]>RG}ArAe oLAoٳŔR^zLJj (RԎK%WQ8|gjUd >E_ڷy3ΙwڼEpewC1bd\JIC%]Ү#QkD΋P(a8퉩c,¥7دw1){Q퉧K=%^9Eo>qb|DfГը Ⱦ&^`{Wk5lR0</ص&E¦0guE?=] Aho5>xYK7t4<u_G7́w |"`j8vHtQ!ڭEVSu/GfQET(PA 6RH]!#Z"Njⱀw. o ^m121rFo2 Će8KS,*Vrc\a. Fq1~ %7$6aې3ʤ e@M&aR&IJO[L8(q,dz.VҊȯI~q]X>\O=|N>m_j䐙jؽէmXǿL8ٵUQ12/>$V}ZnJ| (L8f?%ĄP~laS-UWLW)B/_/ *nɬ,%VZO6áduWhWx?6BpBUb%at\Q-#rݹTv=ݰ>O :Ez,EѩjZ]T飔 Zp: 紱ePXJ{<])\+zOs3&qQZ0n՚^rh]A:v?m&A\ZX]t-[nmŹM._"8J S\sN -x3):FV+аRy&ݺ;M͏p^S5}lTZF1s\~3Tٴɳ)z} SlŵZ/bK[)MZC\jr 3D~x!)]# 8LB,w1uu{9la|1! d3Yb"CqxUfDB}rدգ'dsMp⃜G4Glש.ҢQgZ.*~vm jVݯopWe uy]Wޫ^j_u>r^fZIo?jz4ELǗA^CIoj 1_bl\ݟ>OD 5@ h"4N*~MʮNCmۑg"o+$Ӏ3]C`Va +r%HzfcJ;ʂ]"h\Lb rQ0Zlռ6bf816ŭ׵db:|~h:C%lۺ}5`#p?Bm.8z 2A {/[nu[Y_ڙ[P U:uoos ϥxK:3rݯ̱`ӌȦBR!ImM'?B'2#4J#R]9 .X(`H' bc 1~C~Ƥ-"~E;Θ'-KWh;"^W( )Ų4:S]l&Auu1p 1B@r9Ôg:}!zb7}~l]ì+˟xӎ>Mw>}ٝ[|m_Ǹ'~Ts{`(n഍Bnt)5jJVXB- %uye7ݘx<3x&S6[v:{ RP@ 7/g式;˒V]jZFUɺ^Ƨ/[52Q%kx֩_Z e$͙&NbUg(m7s_M~xOyfhtOpf /duq{[/l;w{K<&BV瀺MAW7a2d`τ"2Hn,J#jOrHD X#_^`@z 'Xud2rB@bJuGpӐǽͻC]G&U34A܏Fl>z,!(*D)K)SN!+&afRtaS$ /]V11-W\=/ua~-B-c3<~3RIy܆HBLmi iRb_C'6AVuzJ-ji"p\ /h_ &qXXl4sc"T qr&,nMQ=d6.'EN"=:cX'AWdIfF¤) ()B!E¥1KӥHIY%FaRS”oiC롏*<`ݵa3is҂&OTAog3x3;p^lXxƉ6_\ٹX2t'ɥ1#K&TfnB*$4V͝jo[˷źlnFz4?]j[k߯jsfu!> t|r꞊TeE@םνi/У-]qO&~sڝ\eW'MFdyi<,/ky^U3抚[ja55!Xvn5nݯ{D:Q x]ǻq1SMݤ?rY2cuu{/GOܲEȸ9, \,O;:16qooӿW8@YY[[8eky \λ\S:飾$j,2 \siQUj􆳠CV]Ov_b}' 9㥰P'Si3~N8&WŊS" ? ͖ftC7n}2Z4dxl8f7-A[B lM  5D5LJRj ݰIdlc\1 ƛ!7l0`S+wbf?yC%%ֳ6qѵ,ًv,6li* {*w^`e)&K̺fws8sa]}#($'|A.RBV q .=>)Fe*qW@\$k2`37izlKe=eCe{ʲece2X=$lvYƄqpih".6P~`4{3('K$w44}GpHO֠\q8?Oܤd]8@ࡘPg-qrkd 98.r=Om7wܨ Ra$)CDA٧e/3,jx>E?Nc@i23VEodh÷5}rp*>AQ9A6NLxr5s_eAw1~ Գ9/ИrP3Uʺg^v'KLG2fϭ- mqcOMޔ>tVO]Oz A%Vu+RaQzӺvIgT- 5B>ܜ;L3i\"7 10"c狖LOj< Pft#;YST6.OeUʤI4K;^~ y^ ?I?/WDSI1)iqvi,HQ$bp -&Razw鍠Ԑyh(2ȦR!6&6i첊\;*2.'˟) [oqPi?3$u+o V&ZS4ȭ. @UB[RmIk+(U4/nEZݱIoJ_?gmKe*\|BG;ns?ٚi޵bo;DhGa1' ZWcwsvroqhcGq[_q;ٰ ~Y̜"mk,?pblt_*&tF(-iZxd3balC6%ào*Y$ *hUQ^A{e՘!czS`=h0d q1mǨ [6 ~$^Gqm u91yO9t)Cz.PcaRfE/Zּ!2otڳ'>bN)n=s{՞^:{%LE;CwIy"1Y5D+j*ĭ2Zv0`5EE+5Y!MW;ir~lH.K5%n6i/EdȮG*h)iw~7;^bPNUgBqÔ6 vp@eM&\'IЕ =<8[zBJ}䉟@^Z>mLHo=~ `/28}Q9aQ=;-\M-9uJT`FǾ4KI8BgOq m3=3]2 @ -wF/=qyWjؒo: t͸œ PRLro cZ^CeOse*?~i0k5|d[/Yͺkx(ϊeniڨ̜2)E7L ,_L;2ʫdHm2R/2(q{#Y;X0(0,:k{zj-G7ZbalgmMSkε ,jDxZv3i*֌2r8,gH-K2L`+Ys囻!.KL<P?ѿ$Vq%hty"\8d)!L8ۂR7^;0r1>lpp=V$$;a"0DqM= H2Q@aPYK|aV슐Ҧ"h6TLo_}U]9[Wuϙֳ"t`qo껐Һn*JUU+g{ ]W-~gEM9sN"u>Xu#>ڌzs/Z)5*c"\4 \cky<(*ZFwd[$*F>*%ã 4*K9O9qpb1t"9Z$wkiKVDauɂ-sZhP'"*XRCl&Zjً)5A%W*P8*IAKh>-q'gO(@ J)3%Q,PR-4(v}α(;͆dт3>0,+*6#fk=VxaA\ cozAXFNv`팱 ={EY|c'}ʭEMxV#v~OhTll w+=]4 ѱK 7_i\Z슶_`qEE;&#hc*Gwe2{5T#d z6#~tq/3 nUܴZFBRFE.ʩt&;]TQ] '{٠*l D`,x4 >ieh2>"Go^d\BBag(F`$:0,Nc2&yƱYnf )>o(>faI؋5Ft9~CITVc!ąz, E%ggv}f8eÆ8o _5s{ϲ+J@>#HV\myIՑS *<E^w.@"Rۮ `f/UAo&GܼaEF.En*H$bOZRڞ d~;5#>n&E{/ւt.E I-;%II BVT*-,gGOgk،5Evw:Lxw`[48Lw@w0!!``⼃I&;$R&[Ŋl@vgdwBfW ZS bPB7"eDII)B|cq\gBW x>=_ S;XމHI۸O$CxofFF9]C,h\)HV&+1&[ L7$x(E jjVTNc"kY{C,u 9%eUsq"<+螋×k cw: !ρiC3 E5/-1Q9:K܌O?\q^g *eFUrGm*&*`f*`qzQXǤq#, H,qapeK7>0&*M3x&=_RۀsvƐSOiZU;6A GaGE\L Q>{ʻ*SUPJ j 2M7RT&qNL3 /Ŧl-;H=;8vƼ޺犊Fc- N)K7D].{߽GN^_W]K\*毜Oz`uoT$0D_+njWVǮlɒ嵴+_]m.ibI;i44mB2BC S4Piap(L31L GBKEv h&~-![Gh@q)a(?ͦ龜K]'{79_ˊ[hxEUJ9e=hJY`x"u zvPL:%˖6u.3Ԑwi-g8l;*mwҸٳȕpwhT-f{k6j6sUcw}t(Ni,xCRm/S'0X6@ىRw+=l5f"=+Wl1o^>u_ھn!ѸQ*mg*A.ц/oKSnE*Gl-D:_(F9xJg2}X?c9ޙ+kʼn`H1^g  7&Aca_7K)r7liᰧhxZ1,GT[TL-ovEuP4Ҫc뀇RrڍO՞ /GPov@ jVGE'EZ:F"ѥ^D = i_ƓIϊ7|tT,I)6}gaKf۟njIH? J|:yG_l{ذtN;~xvʀCZjhAy%i0j ; '#vݓ@ma!o㹉H02c]H.QaodCTFXP\vf~fP/!;Kޢ\FXckkO(ߑI5wKƯ?s y{vD!V)TRI;0k; uU`l5Re֘.g˰ a? P ]#q_t$BtQR!mZ@:Ľ_{o^~[}ȯ!a-{TqŪ2W3sA#/ɉ2 j">ݩKS>pGS%IG.UHz5Q>R5Vn=]wQ >{uԇO!5y)~j;+Њq S0H Q >;W+jdfTBeŨfSZ'%t=;YZn y]xݺ{Ȯɇ\ aJ_> CrWDw.L!vy~6/OǤIoKx9 lm$nRʒluHtSfEG*. B^P`{}}t~}yFF12<<JVQD{m)v֏-ˑےٿ8Sm@2"#LT>f'akiLcJ`@ff]Ά7O֬pfh 2>3-&A RQc۷"`i$GG_!挑&RMvjXc{]ڞqvB?;D BCBK%ul}`mlAR)H -e nKwƲ kLiYo=2uj>K8=+ş>b$xxHfkU.&>[i^EVoe=^_L{ d;Y-XBѠ/..MM>Zݓړ];=~1tEQ 85΍K]]''RR%*R Pcj\)TڭyAwU09R/Ix66JH͔Z7V2mHG4pNM@1'^շz"~A嘉B0\Εj`np3^ ΛP}l,LwGn@K q3}Uö$l$ yyaH>  ̄U?bDeXUF_W^w W/odk?Kmdq},Ջ;{`IxƾӜXWXܐ>JQ@ԎZӇ/]`Z5Y=_j R>5PquW8^y)w2&CmI7ހ Qx3r܇1U,h$uˍMy7_yޫoXYy׬'79 endstream endobj 42 0 obj 22138 endobj 43 0 obj << /Type /FontDescriptor /Ascent 891 /CapHeight 677 /Descent -216 /Flags 32 /FontBBox [-558 -307 2000 1026] /FontName /XMKFTJ+TimesNewRomanPS-BoldMT /ItalicAngle 0 /StemV 0 /AvgWidth 427 /Leading 42 /MaxWidth 2000 /XHeight 470 /FontFile2 41 0 R >> endobj 44 0 obj [ 250 0 0 0 0 0 0 0 333 333 0 0 250 333 250 0 0 0 0 0 0 0 0 0 0 0 333 0 0 0 0 0 0 0 0 722 722 667 611 778 0 389 500 0 667 944 722 778 611 0 722 556 667 722 0 0 0 0 0 0 0 0 0 0 0 500 556 444 556 444 333 500 556 278 333 556 278 833 556 500 556 556 444 389 333 556 500 722 500 500 ] endobj 10 0 obj << /Type /Font /Subtype /TrueType /BaseFont /XMKFTJ+TimesNewRomanPS-BoldMT /FontDescriptor 43 0 R /Widths 44 0 R /FirstChar 32 /LastChar 121 /Encoding /MacRomanEncoding >> endobj 45 0 obj << /Length 46 0 R /Length1 8632 /Filter /FlateDecode >> stream x: XG֯焙a.Ǒ# rC(^hH@J 3j$kVTbb 0&ϭ5$_ |mW׫Uа9`uR/j!&Ԯhe=&ByeK5O[47\vS3;\0ͭCDL1T1\i%}tˋjXyq͢9a~O )K7'b/O*tae@0 ?BL(X!x109#x〙?c<-{9|i>g<#^8 _3ȶ!'ȩЃYJFg]d:̵m`|wypƙqQhkv>SK:&ebǸeL85Z©ax8wYyGp9uh<(840ZG!>O>ňd~7:|m>A34+ֻ fhЯ \Atc"_)vH# kJDI#D:ڳAbRr1KVJT¸2uѓZ,  \.\EMOnl!H2x].eҳX[֊2=.]JiүRPOڥ_ %JotBI+zHDRP PjR"-d9QZ(-5B&IJSK2Ke˵6s\ 85HqI6KYZLV4TZ& f|RZkcKaq);Z C^GbAUlY#[F-bK2Dl[|bKؒ :vU7z^TzG0tV1Kq, ZJYBDOa,Q\)-RHJՓP:KV/NqtU^ nu4(&yRUxCE!wU"V+$ǩN\՘XZ+n}-=r:q+:Di)XlaVt';KT'T,J,U"Ϩ$N$K*+:4r80ṴR\G,A>g|׿$P|N)_7F idD| 8| hBhb$p>K{燾e%님4<[Z10` +hG`9 V؏Z~x^! Ojbu8`Gh;@,N5Bߒ8(p#<)txNq8nDC\e0(eE!=7] z3Ͻ&L a/ؒ#rv<#FE'qn~O̓!FCnټoL%ss 9CGq XjXkQb{3ntu OGYĐDLƐ)d>y\"s~3'p)r}1c ?oLPi.z0\S)0ۜ7B  MZ{0 tBgS<+L"H&A \4>tBOq^n:/a[{zO"BWC߄zP<%0{^;`x >sޗ(9+qD!$䒉dNDn'w!*Aѧ1ENߣ90 䒸1Xnk䚸5!YS4N+5`,|&|U7R7QW.{_I\qV]<ϫ:pW|t< g9!2>Jv 7q PN_dYc\㔧(yFKJo|$! >Ln徠fFz2Bho#{C{|2 z.0"S~SI󩩩L/"\H("HsV`bV2xتn *0 I Asf)SeeJj/Qv+hUiuFꆫSxD}ZZ~U)LgE!/FUpq6hQQgLgBYOi젨GU0D.Qc°W)Ғ߫MChxꈫW ̕FCK˧77\KkuI|+ umSKVTp[ m^iRB6M^щ7HySyE;%m*:eE~,Y J jz;kN`k\G fB _eee:V$|0wfad`ڈcƻ0¸K-{y30`e\X 1> P,%=tX6i QMiuKD<%~Cd%~pXԭ;=2 p"m@AdQ"# %EKł2녂=Ǽ7Cxl["|Ido@O2} em#RQgn ݊R#wo\txnkn+!*+/Kļܼ%ӉnI:NOII*+Vn + >s֋ {萨<83$1LQ|oNe+;n7qFn-;o0E2Jf6[$SY91Y'8H1q~ClRTl HUUҪl(&*@p92r9Iށ:Î%6e3y?l?m1'dOȺ}{~M{}37Pa[N_ @ExgiMʀRJBcurZa&SoW TEq +fw@\ q6cu.iU(3зɹlujGl]٥]^:͹uJkmX[VU0gb_wo,y|^'Pz3"v)!Gڲ LNI 3y-q\t$ A2UFFcJ/r6CO'2b /Ŧ]|υ*+tٞ}sfw_BT8,1?҈vD&LWlxiRG7lO3MMӦ՟:'W-߷xN{jzfU#[,$A)ɣG-O_1_0 yf~vN'-',oZI:h ToLf,AR8f 3g1lO]4nRpuz <<> рgCf2Hn"ѓDў6wUϡ!}_V|)Ȇ&y\t-YF0uhs1] UK=Q{põ ,Zyq&mkO6ۈzy%5-OJl6԰_9f[5~{KTI(yd]N㡒heCHοQG6Z\{ش~K/H7i}>_Esb&_ثP雷r4qf}r"{7z糖75^pO]in_ws'[oY/W=6 ~zW<'J%5*96PF]gL4B%"i0cbbҝY\;%}U~ZL|Ucvf+OvX\d)&IF{ 19~Ԫd16ASUEg[>Wyl/v/R(MB힉 uy''O^4H_mZ76q=7Yp3\RIΛ5i˽9wIڍ[\uص=0y깷%0Sx_:4Q*;.5 y8C.u$f###HMEZLiuΜx' NBrNNcTP,ɩ}FY CWRcqN*ց)rxVx.>HtV&SR߅ >t gXY5v*HQybJsX`f+@ZOG䓍À, T,ڴtF0* |(斐턒 _Wqjz4ZYi^ S}ToOL<̞DjyOywӵ>=B0&U0WoN|UtNH%r.P ;7z5,_;^ endstream endobj 46 0 obj 6293 endobj 47 0 obj << /Type /FontDescriptor /Ascent 905 /CapHeight 728 /Descent -212 /Flags 96 /FontBBox [-517 -325 1359 997] /FontName /EEDHJZ+Arial-ItalicMT /ItalicAngle -6 /StemV 0 /AvgWidth 441 /Leading 33 /MaxWidth 1333 /XHeight 530 /FontFile2 45 0 R >> endobj 48 0 obj [ 278 0 0 0 0 0 0 0 0 0 0 0 278 333 0 0 556 556 556 556 556 556 556 0 556 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 667 0 0 667 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 500 ] endobj 9 0 obj << /Type /Font /Subtype /TrueType /BaseFont /EEDHJZ+Arial-ItalicMT /FontDescriptor 47 0 R /Widths 48 0 R /FirstChar 32 /LastChar 118 /Encoding /MacRomanEncoding >> endobj 49 0 obj << /Length 50 0 R /Length1 46276 /Filter /FlateDecode >> stream x |T?|ιwLdI2 %HQJ EZEI" >Z`VJfP9s~;圻v%H@EW-!/pk\ZE=ˮʥXr\:,r;˗,XKsk## _\ڟ+W--}ՂkFOtW-j;ҞUkC>ճzh}A%Wv7O!#!H$IQ#BuޓoiT*7ϾyŁ϶}vvh0Sܧ eZ\|'ܛxߔCdPhlNnCSx Fijp1ݡJya\ ŕx[S]2N xw'NԎEJ*O4wpsw +4A $@v $i8FdXΣ/Q eXA4pP80Zr`l$Mk;0&; wN$&pDbKµa܍-p‰'%= ƽ | ?PŸ t#c>4wDͿ!߃H:徵.a͠? 5QK ݃={"pRiJ<\m Emr*waH7b7b6b6u?_\2zԹuG1*)a ޷#% q_qi fv]c1Zub0-+K1ԲtuJ爸tHg -!.rr!j]dɃ_W '  %*-́MlIܤSvT$혁bH*71ݺ]NtA]J'uU&a ( pؠ |ja!m8f8nP'gԪ:nuOMKۦަa݆CA AC  j,,D7 | n1p9|@c>r) 8',ȵ ׂ\uRgx \Jx0<nj|!eBʄ sh?'(y'?_-F& Se2 t1ULSRól#w"vmh[mi6wH2'wH v[~tkWM4] &RJ]94Gw wN IFUp"?D}͇S'q>/e<'J@}!7X_4 $w>N8އ)sJ~I% > r߅{yppzT5a.p=pDa\$}lP**ͪ$f߮*~iϦf4S",Np= MLmM& !bb>H/QR9/d2d!ӏBސi|5<7pޫ?&ӘDwPLT|{O?yl!#Ҍ0#J@ Mal`lA%U4`@S>=KXS^ \Q@2p0iWI*?҅x냃H),= ފҕFyW 6t)d"e%G8O^E[K]t`Ao34Bڕ#J'}$4K"J=$fjQo"a%FnSOEO>o8;N>??AOt V:L9xp +֢h042z0tYɈR;RzgCYȼQ7>ÛAB砸tB`z0E܀@}ducԡaޔ`oEs ]'jjjhfhi4eƧj65kZVUkE-mpZZ ۔J\i 7ǨaB+k9muD&{izl5mNwv"f S2cfyfO64|Gg'mM[DZӟD?3UNRh`?xJfws(bN_֙'|J:[ ^qU-͇X:;kYo˥<^y T# <ՆHW#a:T< hni㕞Sy%JeJ%x/V;PIBՀY0#a#QQ^g(* D({.(Ňh'(TCaZ0M, th/jYi鎴,N߶~3ݷ0X^L p"KӋ#}R/4E-:K Z" ;4[»&m޵?lף}V^(W+W+ףʻZ/H[;db$C̠|:'H=1.HlicdbMYSY/Efd[F{F$d[#I8[h_fZ֭K_"IٚXo0_ W©JRy8kȚh$roMb-M Bp]HO#)2H]`(w @UwM'8/+!wN}=D2+';*?9{NRH <9J(XvrF3@_hFaO&"ed5yJޡ6<@j~ܒ=Zz29LWҙ+L"SX)F"Jfg_;ԏ{0;=ď | b ,ג1z=U7MWq-mEbA#AeOdBZO܂c\E$FƓK^GޢvZ!٢}|%Av$T2AhAN0#ׯTomd}d6ʶx9N[i'=FvRl^6?lp'y8KS7aaת*Gn@q+ Z]=);7'ڢ0 *|P}@Ab:|M|QuLnmLDP{&}4Hq^ZiK/et+ӷ[LBX**W?*UO*2 4{S62?p2H3{@gI-٢dsT 4e֣@AI? #_hgcoeCz?4P0nSc*s NzB 3eTOgW>CvkT=}į ܽM\Rho1)I^I%cDKcEt".)tMYaHAI;vAg} q6,HftA3H$,K/ɟKΗ\;<~ k8!im"[קixIuf2X{g[g}++qChnĀhZ] a#-WtOTCI<<(e?':YbTa=%wCwp K mhr}LV[3 @XyoM N_0[ JCBpm;ѕHāeƀLo9_[fu 2&uO(DYǡ 賒x.U<5biC2!}Jd(EІ)yJȣdJtC˓N84ctc8&n먗8ilO1YpȿLw:"+ [w=pwj.' T?#j0"kHϨ|yak|$Y=<}(<Ah}{Z;TdB8kF8m3 .q+uĊ}Mhb!x Έgk~G'qC>5aRk J.Dh.vm= o\lQj'ؔ8$~>!x+sk/)R9!p ȳ\&Ww$ p? .|O&c Ձ>h 8wR4Nrgf7BT/\֠^̰Xk >7bN[=jϼpz/~9+pg0:6RCo'-ɑʅ5kǜΆǿxUӎIL7 Chp!4 g.q9H5F齛1$YCmF8't)I/y nUZ7{V\ g]#9בF> ەӢT(FoC:k D.pL؇zw\ً2kKqEwfe fϿ;e6hyZ-wF>ӬpL9 \",i~4]hQ.+4(~]mHEʵaVfzA;#Zo2v1Tݗ7r®# t HNJbF"cj3v}K=D+?n%!UKZ̽/0h uraXr+a`ӣ/CA5[D45rV}և2}~΋CUKZޝo3Ы-+_mQނ3{vsrQ'tP ݮ.AGF-Z9hޒi ,ofq9B0_.䔭Zm:$( kFg2_W/i4-vⲭv.OW_U1yeOf>'r|k7 )amoǩ XMgJϛC3j+ @3VA6% :F'7ѝ:lChV~sL<) Sl *KeQ-E y٠;`v@ )[v 'p>^骁 vذEU('$TXlB&~sTO7UcMOΓ]ΓN8e'[5*(q-6o]YĈ~"ktZ#է6"[kRMm]rf5|b)>+VPj#>G?M$9eVY  |qN .˰zM(᯶g(U\pOI},E~\Q49N{AAA3UF-#~1yvu!Ï[_V-[Γ//'T|Wsjtv]ձ5qs]F$J h]4 :glQݰP%%{tw1a weF0OmUMv>L5]F$(BwpW]GPnb[QOCvCJGS |]u] $8Ps:zT)>!ꘔF.wH/`wuZnB5TTjMvtSk&TY[;F;IW/^{pSr]rd7Ue҉t7]π~$Nn F*PURpW=~,:d|tHы 3hM̭+*09QSJo76'qbOStY ^V-^_VUO{Fּ{X=Xhɢ'Ń 5~hbIWTOJUEI a Ue<|M:3B\ܐH\]5'kĚ3( %"Sٱ!8\ՇF VbSg9QG9OUHQ " I@[HKJr(TXk% 7,N8_McD J1#ʹF8jR/z]|'?_7]7V@+/]WSQ;Vyל[.Yڻ xcƶ+zy2ɻoxڹSVpn6! n|e\\L-Q,r>mY34 iה`r@0Ja67D744*&&rPHxQ^u#w+ОY${Bj_fFǞ/Fޮa9_-ZTo B}!!s`8{f @)N1 Nݣ_wa@)/gY)O<̢W08;y_ziH{ʤ)THf*a[njW.2yJA=Kch~,F c)<~Z:fh kiA!>M[~^&2=kxܭ/3|?}hw&uJ[/mwQi}Sg3') M ?T~稛Z2{ &73dJ ش.wfK/nhlx'^ =* }v.3,l?f,YO Z G=u(Z$6]5h">i26ny cl$_h-vmu{<^OC=PZ J8Xrn.ۡd+|d6Y xxee4̕fuWXI>q߲EbKA˃,_B[ޔ>| }Ka?D|~Wg{t^@4m5ϓ"%Jyh`5e+C| 6dVZNvnYg=lYPDz9(ĝ v1gnpi:`wFs<͖.s3RIT:i &T݄b0{ 9XQ_03{jcY5suF[Q F-˾~ U4*JS+Q7JeUYu$M kA6O tp]5w?u:`o 6ZZIUà^`ԕ4,4jiba!)'tltRڷJF+Njq vN.^JsIս |uts>e&=j#1C ʈ1֥*z &F"`W4pcj1 DU@`oy{oņ̙#Ɵ`k͓6Tv'3lݓw`?{:2I rc}_[I^ZEn?e˾%jM>Zuڨ xL# fsq0CmhQblA[&T;ڦF<\|0B{"\R"!ngFrPT$j%S0H@3LM3( w9|k]W`]|)[s;C=vלϥ^ {oU ^Eq3ŗ aԉU"=#Us EW8vnsu4Z3DDŽ+7KgyzdrfˆWZQY}#59ufvOݧ٪ݪEhl]:; Mu_}J%wᬔo)ʯ/Q"k3EH<4LNؘuH"<ݕ( |n-'!+.Չ:}:)lONxKMCCWWzF&Oէ k5z] SF(pbIG(PyNʣ6<?"Ҹ^kU ;k:FR9EC.JbJSrqOXM6 = _vʉYYY9))>6XfwKԀߺ;9A荜n Y$bspMO PrL(-jiܤ*FfŜ&}s\)nY@uUmZ43gYesFkx0R]  U!eFdN\BrZ`]\ xX( xl+ࡡ.ె"6+] +'V.-'V. z}ړZ!)m[+ ZW*# O{>e2/@9RPwH8:b C,kqW/;GyЫ!RQ]3rdtJS)R13&Ro s(Ш컂#!Zlt}~[ql6lNQ !*pzQ<֞G!&;oD>ǃG:oXKieVN~6QSW9O^W뎞 ~'*B' ;%0P],)D?+8x~ms(r1l>#78{+:'d+]`UГTSU ?{GWC+Pډ4M$3?kf+ DֱSj=?l^EMl) 2[m~ypI5d3P-۪ȖdeU.01J?kԵn'/UE> .Cְ*y(}W8}[|?"a3OL΂T,z?touP7[I~SD(rjfFh \ E닋cZ*b*mDs*TGEUllM&ginٗriҢPGB- u~:L2;[ XPV; 8-(eheWcŕVp}F;_s BzW㜎.YU֔X6IJp]Y`jpANu8?hm$ JRvȕ/&Xlˎ e 7@G$3XqaJ[/`lp*ֆcwV^`ŸIJ0Ҝ'9:d#Zgc8{Αʫ˙;f0@2/C0(}Ţ䑳h{*OA3b}ɹpɑcOuo Dyq_QߋJ\n}/W"o2f+6E>~};,Y6L fp<׈fm<-cR&Ee֦xm3֠dI@Ξ8 QOiG1$4?p8HCT Ӱ2cgP*9vр63e\9shNؒ) Wgk#l<*vA9B^3wt8J{A352aTGG:ʣo[y>ΎACs<|q )>~+"I x+)╇979.kbqD7~oj9`>*_*6Ԯ.b @@ d$2 Wgۣy\$~nlhIZSq~΍(8|ݍ5Ac>kb zG7\osԋc(6qz,QCFk 2A@7Qg+ ! u58y447eŁ27Ϋ~yѬʼy%%_Lݲ'L!+Mp= ( k "kk=k{lp>]x8{o]ERyw->jTu1?>WT!{]ާuFbGzJhLg 80@ @6 ,7̧#dVߦ|jT] PYᑠПxcW灺௷j.-oͳuu}ck<:xuj乆n9 'ՌɃNNHn S؋˄1gQtX'.)N^GckkD2@>{,[Lo/'eGL,[fOf8[Q_^ZZxER_ͿωS[ة eREe~|ߧ,~x*)L+`y:^8AA=s@KIfUI|" QO:l9d.iMU䗼5 R*L#ۛn}d/uv:7=Λkaɬ6j6>np,s;M;q蜒컢 T{,+l?,N,̀qRJ6ڱn#wwwU&֚֚[z=dOV [L[7[${$TmU}5jy%`<ќ0ŘN :;^!D@e$iD֣VvG'?['$[;gARjאHy<B+?C'cdfTD/g&#vFvUb9'_] .*ŽP”JuU‰&XE Dj1Dm ڤ<hx9r"R2iQ˩P$pS~NLY2I%!UZlLU~CX ~Q[׾˖ߒ᳷qՁt|0E;xטO~0+7uCzĉ-.4cBUƥW3:U#QU.-gW 1䴲&CAl67%]үMCm<{Tz4 R( h]%64̎vManYķ(uG\vku )$M9]QHRkw]Dz+ WC:Ck4X1 l͉ dl;_] #Sen7Rq(o,KXÖX6(8s-|d~z&&gUX?櫳Y@h {0IFt$ShPP Y긺^=]"F#ѢHeQKhwMD`1cq!)ZFx|f썀~Ƕ{8lm,N ڈo y5'3NSɦU*to]CMդ#o݇SfxI4ZSzd헫=&BcDju5iNCNS'1n=%Zu:uYj♥th;wGjVŚ+֋53^Ƴ{Mp]rx{Kԭwk7{?Lޓڣ}B '|%4CڧR?K}pep[uXJerЪoM)]ӮgTl0oqBSg8۸zOJ zlZuE6mhotȥ:W ߯);N9 0*lbN8`cŅv4/*ٿ 6OiqACʎ$x}\@ ܼ8"7L 8mFg ;i>BF1 (+s/c`ʉJ&UԸ i6L%2ߏC|0sU1eY3ލC].{1 VQR_Aljz4V#¢s?~5)|oDöNeniMWm O9 TX$ũ%z\}J[B'@)y=%:slm(qkڥrIkT{JR|l+ċ Tj2S3hf#ޞZ^Y_Sғ}57JR;KcWo}'S--qjO$,bAO=$@>0<#ws ő;cd\5E1* Q|{; ixDp^J4 f mEa}(ɱANeȉ 3p1!t*\do yX=5flq;28='6 `pi|4 =׈`,"o݋/m.-|Biy1Oo,;4&6vqeD^i?[X'uC&ѐdQrĀu:8k}rdL '>bM`*lQafaw5jA=%$w98Ǻ3SpάˇLPy\(vXjM U`kBV+GcUAUO;6K֖XG3gh,RJSL,w tihf \+9|Gu6bA^OJHıcL$^^=*fR[0P׸GwP/dcmj>[A(U-zVVoIx*mO5Li3~eͺ7, n*`[c eGp1{젮7ԡ[_HX_BP Ecfޛr9߹)$/{ <ǩ=OY mX,[EC2Z%U&PϮ:B-Vo0EEE9z&4*J#lP>I'~OB#iIChh;L0ٻzu N[(btnV9;{.fO2G#4ߝ\HՌFT1ck2kL]cg0yi82NU%cAZSmy%/5ի\DCr%m)hPH6v%jп*S`IFyp\7&hP Xx3P(zz: vArMiM||(|>cv_/~31E^2k;,1giE=jK㨮tVZU{wzߵel˛la-+`BHX6a Ě$`kd"'=_1!dqdC򆁗!0 H~2d쮺uss+mweM[2VuvW+ʷ/#K|f@>&•Z<YQw!aG pd!}IB 9G[ܚBka=DjxOb7_f81LYwPqLyNy } ~,H8c؄јCf؈i,$弁0x!sYΊ?GS;EbLIH5wtikҷ-5fo˽ P(h р iJ:č'GIS SaCL*юh =Zgl,U>4 aUsPYDńpfY4TE6EUB-<8wCΣ&o^ @nrH|u/ɢgKnǿ=-.5+9FA|k~amDIOG=Aέ Cz؟[ lQ~xr` d]Vdj _<$8RW7k(%y8f\,Z[ _/ʢ j{vUFr-0~|Xɖx垄w$*~ԒV$%[R Z'ӁR20/GMVM4L+k+bHX3R2GG )Hl9KQ, J gd%"N> @>C:Sy3ܸ7hL7.Ұß{ݼ2Rv0wՕ Ds5mvի5#{(|Kkbr|B\EK bB5` m_2&dOwPtK^Fu$ZqDFM'IS1ƠŚ@&dݖ$D~7TuGMa6Ű=bFηɌF:~})AvI7*[z&͓)~̏Ι!̎Ɖ dǺZ\cݘ,n^xb|rzH{9kr YMkzv4=7mx?760 XpK&=ˢh KmlW`o@@ Mdy"ERŝXl|70I9HTS:dN+sebeKs 02#|>h)(H凮M)$DD  H>|#&؟ܴAF~B0l]6?w@Z8շw-Yߒ|KsZ~Zê{Jjl^MrK02!Le;wj}F%|eϦK~\yod7/1Ͽտ-ӧ- bP-ѝryU*r: ,"cQ(2˭|b"''__L_kX{ɈwQ<<49ÕԍX%OV.H۶X=?qf <,[pK.<ټ/Cl6P y_&}=oa$#O+FrA9o%sn+O® hJ"ck¾Zhf SaWh fѼ,l 7Nci=<,l4<8B4" Hl2/fW*Kw ,ˆԮ%~}]j|mko4kf́ώ(ECA@C ͘1}6 sCI{+ݟ+txthf ٤54r]OvQwԌ&k0"MkrM[5$1u+?'ʮ^H/ps+ۮm̲k>j5#hx0[Peh;p]Lh|B7X!WrE:y u_~ٲI9X'dim4Kb'S222rŻZP_/K=S;Lnq/` Bے\hڧpuV /A^zP}Л]YWnopotT6Ѿɾ)j ֣[[ń2NSDc%*[áuFfd撧Y ـH# L-YNVLU{([nOM%wHpcjWj/p.I,i4L^hOPMI?0$3Hp| sdz8;|½1\]M"BK鴃®1tgx@u>P(~SgN 9qLMf23s͈-2$8;;__Q!Z-9 E>\MawD36I^ɣk!nwVn  MfPL\:>|8eSMIJa80pkA:(@׭j;|ĬXZTXp+kQ9g(,-Mrd`5L!pjvxT[d'[|Vr#țbмANxhQ -Ƽk)Uv3j9 A}j3~5 9JkSթhv3\*ڋTIUW #vPw.(<=>-ȧA{t*z=(6Ъ)ar&NW<s%c,DTubb7fI0PF*Y(Qx簵P(<?}[ߕ oSu<άH;٭'~ ܨ+=ڢr0_:7F;,gDQ@ ^4B LKkIRxv#t3]O@CxԡICNF5h!gah 9pmI0^3.<t'CY= g-%bj+ F$RK<鄫l3}{yM6f١pH^rJ'Z_JMֿu>&=zQ|uGeЍY}`sk|RKUs&"ٯKͪ!le[]+Rk?P_1h (x2J\2.#bΤi4h̸ٽk Drhh=TdHrg[Q`22ZvtKN\AhZx^misvq>G1`pHbPmL.PqƦk3(<.k&07,WtZ>;.Dt b^<4+=v{0,?cF<4 CEWwZo.fÎ=AG1<b<Ɗ S>(%M26? HcI٤}>c?h?g7ޡ̀T+z_&*kkg2)7os=D[CAjBA*sKǹ9}A7 *?G=q{U]^ԣh,-焲 Hn6,._OƟ5 $i6e~xcEDԫ$؆LG"zHK:G~s%:oFq5wZK fFƱ]c{QviMG([eԑ(GQ)e"m8m.nlH)UךPeK\ 8l4obuqsɭZFp{|kPmxNop944xۻ >^Goo7l8kimਇQ@"^VSǧ G#!#(6c@9N6"30boi-&:lm5mb Gb/Ǒbb5ڲX~dؐ;5`ήٲ^Lbmfh^lAy'ʨU6REfX+g{T^#[g6lH#3#0#|mK!N^cmL DE u#v;5.6S}Oז[Wߵ~T!,].IeC4 _бi3*{ K;#\ͻ,ӕ+qc.ܰE *i(TMksRuhJҞh&]2.|eQoɺ 99űtZ\4㙢V",^kq\;:=h9!ΙI(O/rZ+E Rxg]BL̀jY;e頲 >mߦY3L9RQb:w)+6R8'!q/.HT>СߕRӘs _xW3q_A?ƫ!b.6 x, QTCj4USilj5N7C 6 x+6K1NNjxȗ':bB?L:r9` cCBxf'[ϔ$.%q+|q[wQ|’ɐ KD0i|DHr 6' Dxb8<[n]yk2}nvx!>c6um{.8s qbPi@9je)G $Kj`tn J:EH$lWX{/BG"8&48},qr4v{$(aY°<~&j^fk[OX~5'Ά#f1O#d,WieAvIÔap`2L5,L cPӐ^|ĺuBB |HBDD"O|Qy1MH$2==,b6S8,`E+dFPTۂ6bABwzQ @@uhMȷ8o>t}̂@a{j@z^ 5 (09Q8'n_ljokHq|k·_;>1 . K兦֢KQ8ː7,RyWp{7>4t.-*!Jj6g܄u"^w=-rB-S B)$C eJD$88mᐳ#)<-/KK]xQU%*ԋSJȹ".)AEZ,9a襴zds\{aTY݁EGeJAQR: ǥl4=PHt_T`ЄyQg0'9Y$Ə]Ωo : j7D(˺oڹ˴mOoU]xݲu씮o9.|kWE>0P -Gr teK;&L^!}R4঳H YSq+IgCfvt4﷍9N:EKB%hh0$(r&HVCѪ!+UC{=5X+oTXZ['FSK"rEjWVewdobwjo'_p}.RwXFkoǾS>>oKju{?7yY ? seAGCDRJGn+|?f3I̗vVJJD,t\S_q$ee;IuA1Orvp p%;)x`pI/@ZeyA(5eIŠ5BLL >'PB/ ms|?jN:-Lwoe ڍEUXfξ yC)O1e]JGAw+PLwZ F=F+:B" $Wa ;8m~I:$gnh~97w| 4x,ܳo`aKQ.RGfZNñ{1 N2J9ts ֍&6nC[%$`]o{7)`&oNӥVb;J,I\ۋwT!A>Ua4]1CTKXIp#Tٴ:BިN9ąVa@|9, ;NxN\ KD`Jʝ^BeuuJ ܻ;^NJe maوɼJgxº y(o<4F e3A/8t!U72+e.#kY˧iD%J3lFrSqkk:Tm?w̜Ko*O?yb V&*SrHiS3_=PsP%M1xOӖy0@cGOt(T+vtTr^ً`IV'8+A.GH2”@_A.y< <_'B^@z2jCp8|:=X<E#!$fY0eGµ$d< l^1=b0AY82aPS@6Ȧ8|I3*kϼT RvZa9-Hz-{xy͛HM:Q^/s_#4wA 7䦈`8,7aiaYCW ԝSTH z*@) ZٱBIU02ѹPi(OE1En8;:9[wTX7 1x69p^"ND2gR/[EM~)БJžxŪZjt]OwW(\Iw]\uLs.gb<&8{}f1 mk8 |Ix/po*ވh)TpE[sHm2#7ܙbRЈ *bR.#|^o<+<s %V8pl(q~hxy6Gdѱþ<PApDbE2޺ZcL]t IǺ`_ezzP`0f|^6Yw{䝌}I4e@&0ŘsJ:dY|i&3:{8& 3yzƅ-idO=UH-sCm뽮,~ϫ;XʮWIY$Ƽ!+*>D06RԙM-"-}Hj`̝1jJP<4t[8lȓY4=ɦ:CxʼnTͰ0`'*<&QyJPf;f=eA6r꧴tbDsbjj R"2LjbɩTujW*=4t5ZXǟsrAQdUyn[o_]\#FBT AJ :w6h!X`.gS4 1;E5 ny$=OETBEzO;at{+|JHZ 鏓>o*꤀y e R{NMS@ ).RHx+ PG_?P*K..N3ٜn_0ab%wb[Hƞb`8Ο1hHZ%Jb|N Y l2H>fPksb(FK _Nǁ oF^p=HخG>M?{RMjU:[ȯ#4]xjxZltgjmGT싅7oaox4ٝՊ;{aՑVj9UrXزFa1ɬΏFwi'w,NU>C;gVNdO=}o kIy]5k[ b#RY5^bv@3??}gt-zGp_NrXٍʍnf6+P)AwBQө*+ %;d8Yǃ<~6M e3*Z͙bW,@ |$aNr6ɴ¾P(\̡]Pf/c%&M[n)(0UANQ]0HC YK5UpoaS=pdN>d0{$DYpOeчTWHOAHakr}Gi霈J/ޖ[an'Ħ b~hM 6JQ6sEsqzAk:KU‘sbwkl+ЙT)`'fJ#K\B=D4g9,XEu8@DAc]KiGsTڝ JX68Uvֹ&~_g>t9^p 8 m16KK:qi?K7Yjkq_SvC"ξ>K3;y%qCA:cq߃ItF{Nu UzcB5 2s|HܾlOmUCdǖh{믹.1ʠ/7XhvmT6W'6wk[[כ*{{{5*%Fr*I%NVr1X1=X f`Fn@Z;$C7k~J= (A%ӗsg廻2P4]P?pz'5£ճ{Qg@YQ<a4a9=Ϸw}]]v!=ؕφm}\H KIz^MRf@d5˘vj]o;jAQ‡υυ A8؃ÍZAcd#N40L(SĄuAG `SyD =hQ<ꡗ1-=cAVz2Zf2?$KQNZNnYb'EƔL7"%^_罠YcARك؀ AҪbf*C~<K8Xg8w̪.OvQsXubú/9x%r7?) _[W'WBИE.?'aK7{,fCq[4?sZ4,jn|NዠL-_="\{]\i R0g&CLybM|^ʝ-|ڶtvfh;>=T.:]:዗1łN=2⏃-|}R&s'Onwb&co<ֵ+vdy!v \,Ň1yJySf'ov@dS}M-ނiBPҷo|>D(8I؅@G!hGP !|A@YV&ط,(zk=1nVDe_$gx2nz<{ ;re=,77o| zSe?|pϕNw) \J2zJgKYp$^}ءR.sž\! [*XiX-?*Ҝ|=݌!d-z@f(X:%hJVz [/?l:8ŁV VJ#3&j83<ׄ=߂̟)^g&W4xYYΘD\ox`yTej5)Vfl!d /|lmO5 rbMfCTX vNbca>;C(|onsR ϊ&kibb"ZP}S{,a0u~p` 2GzGGϨEՃNr%g ]斥[`R0 Dюl8A4bp]..5ICW,'ȭ:#rf@dIA;(@avlzX\&8QkVXmUuvRX#R7Yl4j1/"  G83HXFL|`d5Sdk5NN2'tOkVpy `qh+  4 5F~Ô3PA# hx Y#30q#,toR+]f{i|]ި`{E׬*6^}F*ӝ ٷLWԫ)VE|UR1;u6Q"t][jw>ZX׫ߨWVR6ZL'[d.WJO&k #mKOXAt H{4'W@'W'W𞁓+jm+l\adUaGJ8S{\Z5黻0h;.-;9{ҪBhEht+V`jA}'`,!0rEcK1M8.4E[ RJa6L_~ hRQw`SӢORL X-uA:rAndzT%kAt"S"~ԿLls_7Q8%>hǮ\_X ;F]mw37`_֓[gIѻpJ] /wϸkW? Ah*_" ^@**c%/$H* hmt 5HBUV@ C(& m 51 *IJ+I4>~5LSJ|ryD ex M0;\ebNܱv5Ο_| L 3&"5d@g6jqkjQc'p`28M+T/JDk8Q^DJB7^:ٝ6O]X,|Ftցjg,{ m.6 sԅkKB/M8~y{ ǀ2R=tel1fu GUM"U+>=G~?Fnx˥z}jE=*NwBeCǮ:"#=tU ]{Rsb)^2Pn_g5͔W-I;˲r)a/KC$ |T;PkHX%-EuaaA.BݟQbaY[m¸p] %?!  ?ׇAqgk׭]f_uEWxɮoF7l ] endstream endobj 50 0 obj 33917 endobj 51 0 obj << /Type /FontDescriptor /Ascent 891 /CapHeight 677 /Descent -216 /Flags 32 /FontBBox [-568 -307 2000 1006] /FontName /HIHBGD+TimesNewRomanPSMT /ItalicAngle 0 /StemV 0 /AvgWidth 401 /Leading 42 /MaxWidth 2000 /XHeight 460 /FontFile2 49 0 R >> endobj 52 0 obj [ 250 333 408 0 0 0 0 180 333 333 0 0 250 333 250 278 0 500 500 500 500 500 0 0 500 0 278 278 0 0 0 0 921 722 0 667 722 611 556 0 0 333 389 722 611 889 722 722 556 0 667 556 611 722 0 944 0 722 0 333 0 333 0 0 0 444 500 444 500 444 333 500 500 278 278 500 278 778 500 500 500 500 333 389 278 500 500 722 500 500 444 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 980 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 444 444 0 333 ] endobj 8 0 obj << /Type /Font /Subtype /TrueType /BaseFont /HIHBGD+TimesNewRomanPSMT /FontDescriptor 51 0 R /Widths 52 0 R /FirstChar 32 /LastChar 213 /Encoding /MacRomanEncoding >> endobj 53 0 obj << /Length 54 0 R /Length1 3704 /Filter /FlateDecode >> stream xyxTsI"$EPǔcX$`B [%H)A\JKSRZqZZ^:$4t3j̉QWZUQʖGJ.\PX*RpQi<Пj}9bV'T3>c~9Cft霨GV[s#v\mHloW>`^jǜڶSyNnw6'XIّlDX]l'oxQOCwo}9iVvqV_3{_;)ߋOoQqqޔM>!85#abH~U<$_Q+"R/B|Y/>ֵ/E^.'Kf-.~<wt;vi2n7Ӻ[q4 59lϣKYKڑǥfGzwOg+v GC,[b*o FS>WEzOm]$7m[ʰQoOi'}Wb6^kZuZaykdXwjq>rQÙ3\X;EjyV٪ f=.igxYKڧkb#6*ikq\eR]_E(`ʘ!,?$B,[KmD/YO8W,3b+t~LcmfeaTq8Y(HO/~IW,ǵ~Aʒgncbfđq8LY흒\qA 9[%fb%}Лwǻή]Ve vtyx!كB?'K[}pff}zL|u:]y}JvSBtȒ,v;7Ibɢ=ٲ;{KfgZd њYQc4&䧽d?lfӝ ˏT2itCfp,;1 ) *aaj(dIyp( \K#aaEx2e_eP`UVy@(,6P$¨knלš)s"RWgsN uu:^G\oBu yqClDA.b26顀5C3b'9}+ E|GQ6ٷUW> endobj 56 0 obj [ 460 ] endobj 17 0 obj << /Type /Font /Subtype /TrueType /BaseFont /XQYQUV+Symbol /FontDescriptor 55 0 R /Widths 56 0 R /FirstChar 165 /LastChar 165 /Encoding /MacRomanEncoding >> endobj 57 0 obj (Joyent-Nodejs-TrademarkPolicy-20110708) endobj 58 0 obj (Mac OS X 10.6.7 Quartz PDFContext) endobj 59 0 obj (Emily Tanaka-Delgado) endobj 60 0 obj () endobj 61 0 obj (Microsoft Word) endobj 62 0 obj (D:20110709005519Z00'00') endobj 63 0 obj () endobj 64 0 obj [ () ] endobj 1 0 obj << /Title 57 0 R /Author 59 0 R /Subject 60 0 R /Producer 58 0 R /Creator 61 0 R /CreationDate 62 0 R /ModDate 62 0 R /Keywords 63 0 R /AAPL:Keywords 64 0 R >> endobj xref 0 65 0000000000 65535 f 0000110362 00000 n 0000003627 00000 n 0000020864 00000 n 0000000022 00000 n 0000003607 00000 n 0000003731 00000 n 0000006590 00000 n 0000107289 00000 n 0000072297 00000 n 0000065227 00000 n 0000003854 00000 n 0000006569 00000 n 0000011116 00000 n 0000006626 00000 n 0000011095 00000 n 0000011223 00000 n 0000109905 00000 n 0000025943 00000 n 0000042226 00000 n 0000015683 00000 n 0000011386 00000 n 0000015662 00000 n 0000015790 00000 n 0000019451 00000 n 0000015953 00000 n 0000019430 00000 n 0000019558 00000 n 0000020646 00000 n 0000019682 00000 n 0000020626 00000 n 0000020753 00000 n 0000020975 00000 n 0000021025 00000 n 0000025649 00000 n 0000025670 00000 n 0000025919 00000 n 0000026115 00000 n 0000041669 00000 n 0000041691 00000 n 0000041958 00000 n 0000042416 00000 n 0000064645 00000 n 0000064667 00000 n 0000064931 00000 n 0000065415 00000 n 0000071798 00000 n 0000071819 00000 n 0000072075 00000 n 0000072476 00000 n 0000106484 00000 n 0000106506 00000 n 0000106765 00000 n 0000107471 00000 n 0000109613 00000 n 0000109634 00000 n 0000109881 00000 n 0000110078 00000 n 0000110135 00000 n 0000110187 00000 n 0000110226 00000 n 0000110245 00000 n 0000110278 00000 n 0000110320 00000 n 0000110339 00000 n trailer << /Size 65 /Root 32 0 R /Info 1 0 R /ID [ <775bf79af8b396aed2c008286f782e67> <775bf79af8b396aed2c008286f782e67> ] >> startxref 110537 %%EOF node-v0.10.25~dfsg2/doc/blog/0000755000000000000000000000000012270121457014305 5ustar rootrootnode-v0.10.25~dfsg2/doc/blog/vulnerability/0000755000000000000000000000000012270121457017176 5ustar rootrootnode-v0.10.25~dfsg2/doc/blog/vulnerability/http-server-pipeline-flood-dos.md0000644000000000000000000000314512270121457025475 0ustar rootroottitle: DoS Vulnerability (fixed in Node v0.8.26 and v0.10.21) date: Tue Oct 22 10:42:10 PDT 2013 slug: cve-2013-4450-http-server-pipeline-flood-dos category: vulnerability Node.js is vulnerable to a denial of service attack when a client sends many pipelined HTTP requests on a single connection, and the client does not read the responses from the connection. We recommend that anyone using Node.js v0.8 or v0.10 to run HTTP servers in production please update as soon as possible. * v0.10.21 * v0.8.26 This is fixed in Node.js by pausing both the socket and the HTTP parser whenever the downstream writable side of the socket is awaiting a drain event. In the attack scenario, the socket will eventually time out, and be destroyed by the server. If the "attacker" is not malicious, but merely sends a lot of requests and reacts to them slowly, then the throughput on that connection will be reduced to what the client can handle. There is no change to program semantics, and except in the pathological cases described, no changes to behavior. If upgrading is not possible, then putting an HTTP proxy in front of the Node.js server can mitigate the vulnerability, but only if the proxy parses HTTP and is not itself vulnerable to a pipeline flood DoS. For example, nginx will prevent the attack (since it closes connections after 100 pipelined requests by default), but HAProxy in raw TCP mode will not (since it proxies the TCP connection without regard for HTTP semantics). This addresses CVE-2013-4450. ././@LongLink0000644000000000000000000000015212271410374011641 Lustar rootrootnode-v0.10.25~dfsg2/doc/blog/vulnerability/http-server-security-vulnerability-please-upgrade-to-0-6-17.mdnode-v0.10.25~dfsg2/doc/blog/vulnerability/http-server-security-vulnerability-please-upgrade-to-0-6-0000644000000000000000000001046312270121457032035 0ustar rootroottitle: HTTP Server Security Vulnerability: Please upgrade to 0.6.17 author: Isaac Schlueter date: Mon May 07 2012 10:02:01 GMT-0700 (PDT) status: publish category: vulnerability slug: http-server-security-vulnerability-please-upgrade-to-0-6-17

tl;dr

  • A carefully crafted attack request can cause the contents of the HTTP parser's buffer to be appended to the attacking request's header, making it appear to come from the attacker. Since it is generally safe to echo back contents of a request, this can allow an attacker to get an otherwise correctly designed server to divulge information about other requests. It is theoretically possible that it could enable header-spoofing attacks, though such an attack has not been demonstrated.

  • Versions affected: All versions of the 0.5/0.6 branch prior to 0.6.17, and all versions of the 0.7 branch prior to 0.7.8. Versions in the 0.4 branch are not affected.
  • Fix: Upgrade to v0.6.17, or apply the fix in c9a231d to your system.

Details

A few weeks ago, Matthew Daley found a security vulnerability in Node's HTTP implementation, and thankfully did the responsible thing and reported it to us via email. He explained it quite well, so I'll quote him here:

There is a vulnerability in node's `http_parser` binding which allows information disclosure to a remote attacker:

In node::StringPtr::Update, an attempt is made at an optimization on certain inputs (`node_http_parser.cc`, line 151). The intent is that if the current string pointer plus the current string size is equal to the incoming string pointer, the current string size is just increased to match, as the incoming string lies just beyond the current string pointer. However, the check to see whether or not this can be done is incorrect; "size" is used whereas "size_" should be used. Therefore, an attacker can call Update with a string of certain length and cause the current string to have other data appended to it. In the case of HTTP being parsed out of incoming socket data, this can be incoming data from other sockets.

Normally node::StringPtr::Save, which is called after each execution of `http_parser`, would stop this from being exploitable as it converts strings to non-optimizable heap-based strings. However, this is not done to 0-length strings. An attacker can therefore exploit the mistake by making Update set a 0-length string, and then Update past its boundary, so long as it is done in one `http_parser` execution. This can be done with an HTTP header with empty value, followed by a continuation with a value of certain length.

The attached files demonstrate the issue:

$ ./node ~/stringptr-update-poc-server.js &
[1] 11801
$ ~/stringptr-update-poc-client.py
HTTP/1.1 200 OK
Content-Type: text/plain
Date: Wed, 18 Apr 2012 00:05:11 GMT
Connection: close
Transfer-Encoding: chunked

64
X header:
 This is private data, perhaps an HTTP request with a Cookie in it.
0

The fix landed on 7b3fb22 and c9a231d, for master and v0.6, respectively. The innocuous commit message does not give away the security implications, precisely because we wanted to get a fix out before making a big deal about it.

The first releases with the fix are v0.7.8 and 0.6.17. So now is a good time to make a big deal about it.

If you are using node version 0.6 in production, please upgrade to at least v0.6.17, or at least apply the fix in c9a231d to your system. (Version 0.6.17 also fixes some other important bugs, and is without doubt the most stable release of Node 0.6 to date, so it's a good idea to upgrade anyway.)

I'm extremely grateful that Matthew took the time to report the problem to us with such an elegant explanation, and in such a way that we had a reasonable amount of time to fix the issue before making it public.

node-v0.10.25~dfsg2/doc/blog/v0.9.9.md0000644000000000000000000000542212270121457015475 0ustar rootrootdate: Thu Feb 7 10:32:17 PST 2013 title: Node v0.9.9 (Unstable) version: 0.9.9 category: release slug: node-v0-9-9-unstable 2013.02.07, Version 0.9.9 (Unstable) * tls: port CryptoStream to streams2 (Fedor Indutny) * typed arrays: only share ArrayBuffer backing store (Ben Noordhuis) * stream: make Writable#end() accept a callback function (Nathan Rajlich) * buffer: optimize 'hex' handling (Ben Noordhuis) * dns, cares: don't filter NOTIMP, REFUSED, SERVFAIL (Ben Noordhuis) * readline: treat bare \r as a line ending (isaacs) * readline: make \r\n emit one 'line' event (Ben Noordhuis) * cluster: support datagram sockets (Bert Belder) * stream: Correct Transform class backpressure (isaacs) * addon: Pass module object to NODE_MODULE init function (isaacs, Rod Vagg) * buffer: slow buffer copy compatibility fix (Trevor Norris) * Add bytesWritten to tls.CryptoStream (Andy Burke) Source Code: http://nodejs.org/dist/v0.9.9/node-v0.9.9.tar.gz Macintosh Installer (Universal): http://nodejs.org/dist/v0.9.9/node-v0.9.9.pkg Windows Installer: http://nodejs.org/dist/v0.9.9/node-v0.9.9-x86.msi Windows x64 Installer: http://nodejs.org/dist/v0.9.9/x64/node-v0.9.9-x64.msi Windows x64 Files: http://nodejs.org/dist/v0.9.9/x64/ Linux 32-bit Binary: http://nodejs.org/dist/v0.9.9/node-v0.9.9-linux-x86.tar.gz Linux 64-bit Binary: http://nodejs.org/dist/v0.9.9/node-v0.9.9-linux-x64.tar.gz Solaris 32-bit Binary: http://nodejs.org/dist/v0.9.9/node-v0.9.9-sunos-x86.tar.gz Solaris 64-bit Binary: http://nodejs.org/dist/v0.9.9/node-v0.9.9-sunos-x64.tar.gz Other release files: http://nodejs.org/dist/v0.9.9/ Website: http://nodejs.org/docs/v0.9.9/ Documentation: http://nodejs.org/docs/v0.9.9/api/ Shasums: ``` 643c26c2fc0c9ddeee99d346af86a022e6b470bc node-v0.9.9-darwin-x64.tar.gz f3ffeb08ceab15fd24a33c8d1974be952177b623 node-v0.9.9-darwin-x86.tar.gz 63d6ce5e4333a0cd203753a3153998076baa23a7 node-v0.9.9-linux-x64.tar.gz f1008b823b6010bd3ed3fd4f422eac3af5bd61da node-v0.9.9-linux-x86.tar.gz 679b09328f1a0c3225286a891bb5b4de131777d6 node-v0.9.9-sunos-x64.tar.gz 4253f2e976a05ee6ea6ecc3b583e942b812d0b86 node-v0.9.9-sunos-x86.tar.gz 0436ee0e57d12d5fc53914f9157521427d016629 node-v0.9.9-x86.msi 8a98bc39e9c99a1a1dad6f38a47f56eeb9ad6ecd node-v0.9.9.pkg af1deb80c79f256b319a727f8593740ff99cdbc8 node-v0.9.9.tar.gz ab3db4d6ffab88bb1babdddd96ca8d2c6caf4625 node.exe 56f5a3c72992463435f6649b31da81fd679e91ae node.exp e77f0097ce66317fc255b8e1642eaa675c190267 node.lib 5ff7b6d7f1001383b4bd97e1315c67e7b223477d node.pdb 5b4dcf545eace51a4cae58e9c42b73604f6eb0f9 x64/node-v0.9.9-x64.msi 43fd59cf0df5bdf21690a43a68a8f16160e28ec6 x64/node.exe b4845d2318dd5b1030eeca02703d7f19ebf2ef15 x64/node.exp 2726441e5ff354bc51a841fa9a5a193d39831ac0 x64/node.lib df9083c37cf13109326df30df01e9692238ac381 x64/node.pdb ``` node-v0.10.25~dfsg2/doc/blog/release/0000755000000000000000000000000012270121457015725 5ustar rootrootnode-v0.10.25~dfsg2/doc/blog/release/v0.10.5.md0000644000000000000000000000511512270121457017160 0ustar rootrootdate: Tue Apr 23 14:05:49 PDT 2013 version: 0.10.5 category: release title: Node v0.10.5 (Stable) slug: node-v0-10-5-stable 2013.04.23, Version 0.10.5 (Stable) * uv: Upgrade to 0.10.5 (isaacs) * build: added support for Visual Studio 2012 (Miroslav Bajtoš) * http: Don't try to destroy nonexistent sockets (isaacs) * crypto: LazyTransform on properties, not methods (isaacs) * assert: put info in err.message, not err.name (Ryan Doenges) * dgram: fix no address bind() (Ben Noordhuis) * handle_wrap: fix NULL pointer dereference (Ben Noordhuis) * os: fix unlikely buffer overflow in os.type() (Ben Noordhuis) * stream: Fix unshift() race conditions (isaacs) Source Code: http://nodejs.org/dist/v0.10.5/node-v0.10.5.tar.gz Macintosh Installer (Universal): http://nodejs.org/dist/v0.10.5/node-v0.10.5.pkg Windows Installer: http://nodejs.org/dist/v0.10.5/node-v0.10.5-x86.msi Windows x64 Installer: http://nodejs.org/dist/v0.10.5/x64/node-v0.10.5-x64.msi Windows x64 Files: http://nodejs.org/dist/v0.10.5/x64/ Linux 32-bit Binary: http://nodejs.org/dist/v0.10.5/node-v0.10.5-linux-x86.tar.gz Linux 64-bit Binary: http://nodejs.org/dist/v0.10.5/node-v0.10.5-linux-x64.tar.gz Solaris 32-bit Binary: http://nodejs.org/dist/v0.10.5/node-v0.10.5-sunos-x86.tar.gz Solaris 64-bit Binary: http://nodejs.org/dist/v0.10.5/node-v0.10.5-sunos-x64.tar.gz Other release files: http://nodejs.org/dist/v0.10.5/ Website: http://nodejs.org/docs/v0.10.5/ Documentation: http://nodejs.org/docs/v0.10.5/api/ Shasums: ``` b3a5122fdfa67a7b69c4c80e5cca4c8d700c9461 node-v0.10.5-darwin-x64.tar.gz c95d027af3d774c8650be634b9fe2555c3381c88 node-v0.10.5-darwin-x86.tar.gz 6bdc5d48368a4425f289c3babe457bb427cb2476 node-v0.10.5-linux-x64.tar.gz 99643f86f6441436822a0feebd397a3c515d03f9 node-v0.10.5-linux-x86.tar.gz 72a41a467dcfd96b4244ef8089cf03cf68fa0788 node-v0.10.5-sunos-x64.tar.gz 6388c920ce5500f6523b718c864ccee2f3c4e72e node-v0.10.5-sunos-x86.tar.gz 1dc49f8689c90c84fd335d8023d7c9f01b0183ab node-v0.10.5-x86.msi 4a7c59c37afa8ac7b6f2d1d83b34de30f24642ae node-v0.10.5.pkg 99b92864f4a277debecb4c872ea7202c9aa6996f node-v0.10.5.tar.gz 6f094dd0ce62bcdbf6f36cc67413b1b194d98616 node.exe 9b1b33512631bc58f6480db5587832c79851afc5 node.exp 01788dd89217706b9ca8e7ef9f9136d06236a191 node.lib 1890ff369a65222539ddfd705a40699ca37d476a node.pdb 368e7b7b56cb2c05dc818449cf7962a36b1a9cb7 x64/node-v0.10.5-x64.msi 8624e85306a27079bf4cc3ff25c6914fd59a4e29 x64/node.exe c9c0c0b45eebdfaf93b5e6bda38b23052308dab3 x64/node.exp 0fb687c156204c59e26dff2302f8f9fab73cc3f2 x64/node.lib afdecf9ffdce0c28815ae5fc24d6e0defa71ed32 x64/node.pdb ``` node-v0.10.25~dfsg2/doc/blog/release/v0.8.11.md0000644000000000000000000000454012270121457017165 0ustar rootrootcategory: release version: v0.8.11 date: Thu Sep 27 10:13:12 PDT 2012 slug: node-v0.8.11 title: Node v0.8.11 (Stable) This is just a minor bugfix release to correct the regression in [v0.8.10](http://blog.nodejs.org/2012/09/25/node-v0-8-10-stable/). If you haven't yet upgraded to v0.8.10, then please use this release instead. 2012.09.27, Version 0.8.11 (Stable) * fs: Fix stat() size reporting for large files (Ben Noordhuis) Source Code: http://nodejs.org/dist/v0.8.11/node-v0.8.11.tar.gz Macintosh Installer (Universal): http://nodejs.org/dist/v0.8.11/node-v0.8.11.pkg Windows Installer: http://nodejs.org/dist/v0.8.11/node-v0.8.11-x86.msi Windows x64 Installer: http://nodejs.org/dist/v0.8.11/x64/node-v0.8.11-x64.msi Windows x64 Files: http://nodejs.org/dist/v0.8.11/x64/ Linux 32-bit Binary: http://nodejs.org/dist/v0.8.11/node-v0.8.11-linux-x86.tar.gz Linux 64-bit Binary: http://nodejs.org/dist/v0.8.11/node-v0.8.11-linux-x64.tar.gz Solaris 32-bit Binary: http://nodejs.org/dist/v0.8.11/node-v0.8.11-sunos-x86.tar.gz Solaris 64-bit Binary: http://nodejs.org/dist/v0.8.11/node-v0.8.11-sunos-x64.tar.gz Other release files: http://nodejs.org/dist/v0.8.11/ Website: http://nodejs.org/docs/v0.8.11/ Documentation: http://nodejs.org/docs/v0.8.11/api/ Shasums: ``` 3677fdcce837233d4d3d5cdfb8685123ef38fcc2 node-v0.8.11-darwin-x64.tar.gz 24213b076d5c95a1ee7598c540a454a4d6b1d899 node-v0.8.11-darwin-x86.tar.gz 380e533b7953767ec3a43109d37615238296d15c node-v0.8.11-linux-x64.tar.gz 0d9c1bd3a97aa7a5adf6274271f4a8e7745ff704 node-v0.8.11-linux-x86.tar.gz d4dbb70ca6a3e06c763b7be5fffaae1c7630bd69 node-v0.8.11-sunos-x64.tar.gz d8fcd334118576a744a57eb1f3565c242810f4f1 node-v0.8.11-sunos-x86.tar.gz 80a14ed82672d3c5c14f60f41ba3f03d65dde13f node-v0.8.11-x86.msi 8a096cdaf7c3e76ee82373214b51a7c7f306de47 node-v0.8.11.pkg e9dd36cbbe03c632ee7e9c52e06122fa022981c8 node-v0.8.11.tar.gz 5bf31a7e2518d06df1dd05f135617db8c32d8a2e node.exe 79a21c6de2d8e38937865c4cd36306b92e37c832 node.exp 31862938d8cd95efe0e6121764c7797a1487fe51 node.lib 2bbcad390e7fc122be74cb1a116f5420057e9600 node.pdb 30798c0b6d69b13ba94c3501b222f88212f77149 x64/node-v0.8.11-x64.msi 1e69c413252121ab475420795023f9799823d3f7 x64/node.exe 470683d233c9d0295f45f5635203560b242d6f7c x64/node.exp 2134bf022d719da1e455585792af8782ffe81d33 x64/node.lib 1c2a22d0ce3c902f5dae7fde15d32bd9393a2153 x64/node.pdb ``` node-v0.10.25~dfsg2/doc/blog/release/v0.8.3.md0000644000000000000000000000416412270121457017110 0ustar rootrootcategory: release date: 2012-07-19T17:09:26.413Z version: 0.8.3 title: Version 0.8.3 (Stable) slug: node-v0-8-3-stable 2012.07.19, Version 0.8.3 (Stable) * V8: upgrade to 3.11.10.15 * npm: Upgrade to 1.1.43 * net: fix net.Server.listen({fd:x}) error reporting (Ben Noordhuis) * net: fix bogus errno reporting (Ben Noordhuis) * build: Move npm shebang logic into an npm script (isaacs) * build: fix add-on loading on freebsd (Ben Noordhuis) * build: disable unsafe optimizations (Ben Noordhuis) * build: fix spurious mksnapshot crashes for good (Ben Noordhuis) * build: speed up genv8constants (Dave Pacheco) * fs: make unwatchFile() remove a specific listener (Ben Noordhuis) * domain: Remove first arg from intercepted fn (Toshihiro Nakamura) * domain: Fix memory leak on error (isaacs) * events: Fix memory leak from removeAllListeners (Nathan Rajlich) * zlib: Fix memory leak in Unzip class. (isaacs) * crypto: Fix memory leak in DecipherUpdate() (Ben Noordhuis) Source Code: http://nodejs.org/dist/v0.8.3/node-v0.8.3.tar.gz Macintosh Installer (Universal): http://nodejs.org/dist/v0.8.3/node-v0.8.3.pkg Windows Installer: http://nodejs.org/dist/v0.8.3/node-v0.8.3-x86.msi Windows x64 Installer: http://nodejs.org/dist/v0.8.3/x64/node-v0.8.3-x64.msi Windows x64 Files: http://nodejs.org/dist/v0.8.3/x64/ Other release files: http://nodejs.org/dist/v0.8.3/ Website: http://nodejs.org/docs/v0.8.3/ Documentation: http://nodejs.org/docs/v0.8.3/api/ Shasums: ``` 10d478f3a084bf5e705be3f232c41f3e3d56e57f node-v0.8.3-x86.msi a6b9168eaa817692914d0de6c0d04702d7615681 node-v0.8.3.pkg f699d3788e242ed87a9037bae1aa0fa9335e45a9 node-v0.8.3.tar.gz 60294792588e000d846a4c416617f127d5ba6163 node.exe efc7f597745bcf201a7996ecf9f9b94d9112b89f node.exp 4c5ea551d88fe21465f7d2e4c6f3d39ee02f2209 node.lib fd2c3873bed6872fd36e5906b65dfb4f1cec32fb node.pdb 64c6ec7db3f7f24e70ccecdada6f7b966c73134c x64/node-v0.8.3-x64.msi 94cd3f41004f1e9b8efd8d4a337b6154c1d5fee2 x64/node.exe a6ed8354a14577b9200c780b129e2b66f7b85e39 x64/node.exp 3427a95bf9b14f56eec3f59aed80077fbde8f67f x64/node.lib 9af962968551daad044259641a615697f6588616 x64/node.pdb ``` node-v0.10.25~dfsg2/doc/blog/release/v0.8.5.md0000644000000000000000000000510112270121457017102 0ustar rootrootversion: 0.8.5 title: Version 0.8.5 (stable) category: release slug: node-v0-8-5-stable date: Thu Aug 02 2012 15:00:45 GMT-0700 (PDT) 2012.08.02, Version 0.8.5 (Stable) * node: tag Encode and friends NODE_EXTERN (Ben Noordhuis) * fs: fix ReadStream / WriteStream missing callback (Gil Pedersen) * fs: fix readFileSync("/proc/cpuinfo") regression (Ben Noordhuis) * installer: don't assume bash is installed (Ben Noordhuis) * Report errors properly from --eval and stdin (isaacs) * assert: fix throws() throws an error without message property (koichik) * cluster: fix libuv assert in net.listen() (Ben Noordhuis) * build: always link sunos builds with libumem (Trent Mick) * build: improve armv7 / hard-float detection (Adam Malcontenti-Wilson) * https: Use host header as effective servername (isaacs) * sunos: work around OS bug to prevent fs.watch() from spinning (Bryan Cantrill) * linux: fix 'two watchers, one path' segfault (Ben Noordhuis) * windows: fix memory leaks in many fs functions (Bert Belder) * windows: don't allow directories to be opened for writing/appending (Bert Belder) * windows: make fork() work even when not all stdio handles are valid (Bert Belder) * windows: make unlink() not remove mount points, and improve performance (Bert Belder) * build: Sign pkg installer for OS X (isaacs) Source Code: http://nodejs.org/dist/v0.8.5/node-v0.8.5.tar.gz Macintosh Installer (Universal): http://nodejs.org/dist/v0.8.5/node-v0.8.5.pkg Windows Installer: http://nodejs.org/dist/v0.8.5/node-v0.8.5-x86.msi Windows x64 Installer: http://nodejs.org/dist/v0.8.5/x64/node-v0.8.5-x64.msi Windows x64 Files: http://nodejs.org/dist/v0.8.5/x64/ Other release files: http://nodejs.org/dist/v0.8.5/ Website: http://nodejs.org/docs/v0.8.5/ Documentation: http://nodejs.org/docs/v0.8.5/api/ Shasums: ``` 74b470d04c3dac9f5838d4ed61e2fb50e394114a node-v0.8.5-x86.msi 28280575b717306b34440c83aace720dccc3047f node-v0.8.5.pkg 835ba5ca429e56f65aeb1a5d9730fff105e86337 node-v0.8.5.tar.gz c8ce66eefd6d75b44cdf29bb49aeffe4ea534b7f node.exe d3832fb5a7a45d739c9d3faa7e13115bdaaa9cc7 node.exp 5dee595f12dbfdee14b6e8aebc07a77ee96e5e45 node.lib ac62ec2d2508dfcd0c2f5cfcf725286ad876fb7a node.pdb 12876d80668b066b460833d096998525d8eceec7 npm-1.1.46.tgz 4e820e5a99512e194ec30878ede08488211c8391 npm-1.1.46.zip 95882b6aeab74725197b10d31ff4ee3a0723574c x64/node-v0.8.5-x64.msi 9d9c0652e57e05708b59bba78a55bc1237fcfb73 x64/node.exe f13f377c432c5a8fb4661abaae3a07c46ac74a66 x64/node.exp a17e3e8742ac084e1f7f99f721470e9d6182e75f x64/node.lib 4026170fed5a55fad6ee569daa9666cbb9d5ae3d x64/node.pdb ``` node-v0.10.25~dfsg2/doc/blog/release/version-0-7-6-unstable.md0000644000000000000000000000473112270121457022220 0ustar rootrootversion: 0.7.6 title: Version 0.7.6 (unstable) author: Isaac Schlueter date: Tue Mar 13 2012 14:12:30 GMT-0700 (PDT) status: publish category: release slug: version-0-7-6-unstable

2012.03.13, Version 0.7.6 (unstable)

  • Upgrade v8 to 3.9.17

  • Upgrade npm to 1.1.8

    - Add support for os/cpu fields in package.json (Adam Blackburn)
    - Automatically node-gyp packages containing a binding.gyp
    - Fix failures unpacking in UNC shares
    - Never create un-listable directories
    - Handle cases where an optionalDependency fails to build

  • events: newListener emit correct fn when using 'once' (Roly Fentanes)

  • url: Ignore empty port component (Łukasz Walukiewicz)

  • module: replace 'children' array (isaacs)

  • tls: parse multiple values of a key in ssl certificate (Sambasiva Suda)

  • cluster: support passing of named pipes (Ben Noordhuis)

  • Windows: include syscall in fs errors (Bert Belder)

  • http: #2888 Emit end event only once (Igor Zinkovsky)

  • readline: add multiline support (Rlidwka)

  • process: add process.hrtime() (Nathan Rajlich)

  • net, http, https: add localAddress option (Dmitry Nizovtsev)

  • addon improvements (Nathan Rajlich)

  • build improvements (Ben Noordhuis, Sadique Ali, T.C. Hollingsworth, Nathan Rajlich)

  • add support for "SEARCH" request methods (Nathan Rajlich)

  • expose the zlib and http_parser version in process.versions (Nathan Rajlich)

Source Code: http://nodejs.org/dist/v0.7.6/node-v0.7.6.tar.gz

Windows Installer: http://nodejs.org/dist/v0.7.6/node-v0.7.6.msi

Windows x64 Files: http://nodejs.org/dist/v0.7.6/x64/

Macintosh Installer (Universal): http://nodejs.org/dist/v0.7.6/node-v0.7.6.pkg

Other release files: http://nodejs.org/dist/v0.7.6/

Website: http://nodejs.org/docs/v0.7.6/

Documentation: http://nodejs.org/docs/v0.7.6/api/

node-v0.10.25~dfsg2/doc/blog/release/node-v0-4-9.md0000644000000000000000000000253412270121457020032 0ustar rootrootversion: 0.4.9 title: Node v0.4.9 author: ryandahl date: Wed Jun 29 2011 11:41:05 GMT-0700 (PDT) status: publish category: release slug: node-v0-4-9 2011.06.29, Version 0.4.9 (stable)
  • Improve documentation
  • #1095 error handling bug in stream.pipe() (Felix Geisendörfer)
  • #1097 Fix a few leaks in node_crypto.cc (Ben Noordhuis)
  • #562 #1078 Parse file:// urls properly (Ryan Petrello)
  • #880 Option to disable SSLv2 (Jérémy Lal)
  • #1087 Disabling SSL compression disabled with early OpenSSLs.
  • #1144 debugger: don't allow users to input non-valid commands (Siddharth Mahendraker)
  • Perf improvement for util.inherits
  • #1166 Support for signature verification with RSA/DSA public keys (Mark Cavage)
  • #1177 Remove node_modules lookup optimization to better support nested project structures (Mathias Buus)
  • #1203 Add missing scope.Close to fs.sendfileSync
  • #1187 Support multiple 'link' headers
  • #1196 Fix -e/--eval can't load module from node_modules (Koichi Kobayashi)
  • Upgrade V8 to 3.1.8.25, upgrade http-parser.
Download: http://nodejs.org/dist/node-v0.4.9.tar.gz Website: http://nodejs.org/docs/v0.4.9 Documentation: http://nodejs.org/docs/v0.4.9/api node-v0.10.25~dfsg2/doc/blog/release/v0.8.19.md0000644000000000000000000000512112270121457017171 0ustar rootrootcategory: release date: Wed Feb 6 09:47:18 PST 2013 version: 0.8.19 title: Node v0.8.19 (Stable) slug: node-v0-8-19-stable 2013.02.06, Version 0.8.19 (Stable) * npm: Upgrade to v1.2.10 * zlib: pass object size hint to V8 (Ben Noordhuis) * zlib: reduce memory consumption, release early (Ben Noordhuis) * buffer: slow buffer copy compatibility fix (Trevor Norris) * zlib: don't assert on malformed dictionary (Ben Noordhuis) * zlib: don't assert on missing dictionary (Ben Noordhuis) * windows: better ipv6 support (Bert Belder) * windows: add error mappings related to unsupported protocols (Bert Belder) * windows: map ERROR_DIRECTORY to UV_ENOENT (Bert Belder) Source Code: http://nodejs.org/dist/v0.8.19/node-v0.8.19.tar.gz Macintosh Installer (Universal): http://nodejs.org/dist/v0.8.19/node-v0.8.19.pkg Windows Installer: http://nodejs.org/dist/v0.8.19/node-v0.8.19-x86.msi Windows x64 Installer: http://nodejs.org/dist/v0.8.19/x64/node-v0.8.19-x64.msi Windows x64 Files: http://nodejs.org/dist/v0.8.19/x64/ Linux 32-bit Binary: http://nodejs.org/dist/v0.8.19/node-v0.8.19-linux-x86.tar.gz Linux 64-bit Binary: http://nodejs.org/dist/v0.8.19/node-v0.8.19-linux-x64.tar.gz Solaris 32-bit Binary: http://nodejs.org/dist/v0.8.19/node-v0.8.19-sunos-x86.tar.gz Solaris 64-bit Binary: http://nodejs.org/dist/v0.8.19/node-v0.8.19-sunos-x64.tar.gz Other release files: http://nodejs.org/dist/v0.8.19/ Website: http://nodejs.org/docs/v0.8.19/ Documentation: http://nodejs.org/docs/v0.8.19/api/ Shasums: ``` b97ded53b15196764afd1cc456c5b05a40d8bb2f node-v0.8.19-darwin-x64.tar.gz 685a21891320f3bfc1b878247d64c9912f83eb19 node-v0.8.19-darwin-x86.tar.gz b66b2bb829f627e3cf05bc19ba8b15092b1deb4d node-v0.8.19-linux-x64.tar.gz dcc0be09cf9d9ab863c720f7470a05baea2f7a18 node-v0.8.19-linux-x86.tar.gz 67fe40e63cbf0a0a079d8214687fb9848b67bbe2 node-v0.8.19-sunos-x64.tar.gz c949abebb61bfbe21d4f51337d2b4c76965bc467 node-v0.8.19-sunos-x86.tar.gz 0e41157ca1cbc43aafc3ac65bdde5564e2e13de6 node-v0.8.19-x86.msi a77d2ac238aba0003144ab2d04fc6d1356c18cc5 node-v0.8.19.pkg f4fdbb642055be65579e11cb52c823573efabcf2 node-v0.8.19.tar.gz 7bafe93904e9741592bc9a593169cabec9cca0dd node.exe 0785e45ade6642b4fee320e950795110ef1ca94c node.exp f623019194ff2e9cf975fe007032ece07adb4e49 node.lib 3ba7c54527b8f15521f9e667867e485ef46ffda4 node.pdb d44bff1c52b24d385edd69db14507739e53a654a x64/node-v0.8.19-x64.msi ec60e8b2e68529d3256a94193df62088a986a826 x64/node.exe daf65fd50219588877637b414be36e78a859d4e6 x64/node.exp c154205667ad7c9063cebeeb98af39f203c8c16e x64/node.lib f4a494678c0da4bad787f25001bb209f37f82722 x64/node.pdb ``` node-v0.10.25~dfsg2/doc/blog/release/node-v0-4-3.md0000644000000000000000000000206612270121457020024 0ustar rootrootversion: 0.4.3 title: Node v0.4.3 author: ryandahl date: Fri Mar 18 2011 22:17:59 GMT-0700 (PDT) status: publish category: release slug: node-v0-4-3 2011.03.18, Version 0.4.3 (stable)
  • Don't decrease server connection counter again if destroy() is called more than once GH-431 (Andreas Reich, Anders Conbere)
  • Documentation improvements (koichik)
  • Fix bug with setMaxListeners GH-682
  • Start up memory footprint improvement. (Tom Hughes)
  • Solaris improvements.
  • Buffer::Length(Buffer*) should not invoke itself recursively GH-759 (Ben Noordhuis)
  • TLS: Advertise support for client certs GH-774 (Theo Schlossnagle)
  • HTTP Agent bugs: GH-787, GH-784, GH-803.
  • Don't call GetMemoryUsage every 5 seconds.
  • Upgrade V8 to 3.1.8.3
Download: http://nodejs.org/dist/node-v0.4.3.tar.gz Website: http://nodejs.org/docs/v0.4.3/ Documentation: http://nodejs.org/docs/v0.4.3/api Announcement commit node-v0.10.25~dfsg2/doc/blog/release/node-v0-5-6.md0000644000000000000000000000627512270121457020036 0ustar rootrootversion: 0.5.6 title: Node v0.5.6 (unstable) author: piscisaureus date: Fri Sep 09 2011 16:30:39 GMT-0700 (PDT) status: publish category: release slug: node-v0-5-6 2011.09.08, Version 0.5.6 (unstable)
  • #345, #1635, #1648 Documentation improvements (Thomas Shinnick, Abimanyu Raja, AJ ONeal, Koichi Kobayashi, Michael Jackson, Logan Smyth, Ben Noordhuis)
  • #650 Improve path parsing on windows (Bert Belder)
  • #752 Remove headers sent check in OutgoingMessage.getHeader() (Peter Lyons)
  • #1236, #1438, #1506, #1513, #1621, #1640, #1647 Libuv-related bugs fixed (Jorge Chamorro Bieling, Peter Bright, Luis Lavena, Igor Zinkovsky)
  • #1296, #1612 crypto: Fix BIO's usage. (Koichi Kobayashi)
  • #1345 Correctly set socket.remoteAddress with libuv backend (Bert Belder)
  • #1429 Don't clobber quick edit mode on windows (Peter Bright)
  • #1503 Make libuv backend default on unix, override with `node --use-legacy`
  • #1565 Fix fs.stat for paths ending with \ on windows (Igor Zinkovsky)
  • #1568 Fix x509 certificate subject parsing (Koichi Kobayashi)
  • #1586 Make socket write encoding case-insensitive (Koichi Kobayashi)
  • #1591, #1656, #1657 Implement fs in libuv, remove libeio and pthread-win32 dependency on windows (Igor Zinkovsky, Ben Noordhuis, Ryan Dahl, Isaac Schlueter)
  • #1592 Don't load-time link against CreateSymbolicLink on windows (Peter Bright)
  • #1601 Improve API consistency when dealing with the socket underlying a HTTP client request (Mikeal Rogers)
  • #1610 Remove DigiNotar CA from trusted list (Isaac Schlueter)
  • #1617 Added some win32 os functions (Karl Skomski)
  • #1624 avoid buffer overrun with 'binary' encoding (Koichi Kobayashi)
  • #1633 make Buffer.write() always set _charsWritten (Koichi Kobayashi)
  • #1644 Windows: set executables to be console programs (Peter Bright)
  • #1651 improve inspection for sparse array (Koichi Kobayashi)
  • #1672 set .code='ECONNRESET' on socket hang up errors (Ben Noordhuis)
  • Add test case for foaf+ssl client certificate (Niclas Hoyer)
  • Added RPATH environment variable to override run-time library paths (Ashok Mudukutore)
  • Added TLS client-side session resumption support (Sean Cunningham)
  • Added additional properties to getPeerCertificate (Nathan Rixham, Niclas Hoyer)
  • Don't eval repl command twice when an error is thrown (Nathan Rajlich)
  • Improve util.isDate() (Nathan Rajlich)
  • Improvements in libuv backend and bindings, upgrade libuv to bd6066cb349a9b3a1b0d87b146ddaee06db31d10
  • Show warning when using lib/sys.js (Maciej Malecki)
  • Support plus sign in url protocol (Maciej Malecki)
  • Upgrade V8 to 3.6.2
Download: http://nodejs.org/dist/v0.5.6/node-v0.5.6.tar.gz Windows Executable: http://nodejs.org/dist/v0.5.6/node.exe Website: http://nodejs.org/docs/v0.5.6/ Documentation: http://nodejs.org/docs/v0.5.6/api/ node-v0.10.25~dfsg2/doc/blog/release/node-v0-6-7.md0000644000000000000000000000422112270121457020025 0ustar rootrootversion: 0.6.7 title: Node v0.6.7 author: Isaac Schlueter date: Fri Jan 06 2012 17:54:49 GMT-0800 (PST) status: publish category: release slug: node-v0-6-7

2012.01.06, Version 0.6.7 (stable)

  • V8 hash collision fix (Breaks MIPS) (Bert Belder, Erik Corry)

  • Upgrade V8 to 3.6.6.15

  • Upgrade npm to 1.1.0-beta-10 (isaacs)

  • many doc updates (Ben Noordhuis, Jeremy Martin, koichik, Dave Irvine, Seong-Rak Choi, Shannen, Adam Malcontenti-Wilson, koichik)

  • Fix segfault in node_http_parser.cc

  • dgram, timers: fix memory leaks (Ben Noordhuis, Yoshihiro Kikuchi)

  • repl: fix repl.start not passing the ignoreUndefined arg (Damon Oehlman)

  • #1980: Socket.pause null reference when called on a closed Stream (koichik)

  • #2263: XMLHttpRequest piped in a writable file stream hang (koichik)

  • #2069: http resource leak (koichik)

  • buffer.readInt global pollution fix (Phil Sung)

  • timers: fix performance regression (Ben Noordhuis)

  • #2308, #2246: node swallows openssl error on request (koichik)

  • #2114: timers: remove _idleTimeout from item in .unenroll() (James Hartig)

  • #2379: debugger: Request backtrace w/o refs (Fedor Indutny)

  • simple DTrace ustack helper (Dave Pacheco)

  • crypto: rewrite HexDecode without snprintf (Roman Shtylman)

  • crypto: don’t ignore DH init errors (Ben Noordhuis)

Source Code: http://nodejs.org/dist/v0.6.7/node-v0.6.7.tar.gz

Windows Installer: http://nodejs.org/dist/v0.6.7/node-v0.6.7.msi

Macintosh Installer: http://nodejs.org/dist/v0.6.7/node-v0.6.7.pkg

Website: http://nodejs.org/docs/v0.6.7/

Documentation: http://nodejs.org/docs/v0.6.7/api/

node-v0.10.25~dfsg2/doc/blog/release/v0.10.6.md0000644000000000000000000000454412270121457017166 0ustar rootrootdate: Tue May 14 14:32:31 PDT 2013 version: 0.10.6 category: release title: Node v0.10.6 (Stable) slug: node-v0-10-6-stable 2013.05.14, Version 0.10.6 (Stable) * module: Deprecate require.extensions (isaacs) * stream: make Readable.wrap support objectMode, empty streams (Daniel Moore) * child_process: fix handle delivery (Ben Noordhuis) * crypto: Fix performance regression (isaacs) * src: DRY string encoding/decoding (isaacs) Source Code: http://nodejs.org/dist/v0.10.6/node-v0.10.6.tar.gz Macintosh Installer (Universal): http://nodejs.org/dist/v0.10.6/node-v0.10.6.pkg Windows Installer: http://nodejs.org/dist/v0.10.6/node-v0.10.6-x86.msi Windows x64 Installer: http://nodejs.org/dist/v0.10.6/x64/node-v0.10.6-x64.msi Windows x64 Files: http://nodejs.org/dist/v0.10.6/x64/ Linux 32-bit Binary: http://nodejs.org/dist/v0.10.6/node-v0.10.6-linux-x86.tar.gz Linux 64-bit Binary: http://nodejs.org/dist/v0.10.6/node-v0.10.6-linux-x64.tar.gz Solaris 32-bit Binary: http://nodejs.org/dist/v0.10.6/node-v0.10.6-sunos-x86.tar.gz Solaris 64-bit Binary: http://nodejs.org/dist/v0.10.6/node-v0.10.6-sunos-x64.tar.gz Other release files: http://nodejs.org/dist/v0.10.6/ Website: http://nodejs.org/docs/v0.10.6/ Documentation: http://nodejs.org/docs/v0.10.6/api/ Shasums: ``` 24982edc3b6aafd019273fa5e8a2031353314b56 node-v0.10.6-darwin-x64.tar.gz e208c5dc83864a7f35f9df60ee35642bc7dd689c node-v0.10.6-darwin-x86.tar.gz ab2ad473f5aa0f1c5adb50b9ea47fd05010bca2c node-v0.10.6-linux-x64.tar.gz 29cdac417449f088e6e6fa67d57c9205d8bff6c5 node-v0.10.6-linux-x86.tar.gz 66e3a9e53af6d8f27c690a77c329a2bd108965ac node-v0.10.6-sunos-x64.tar.gz 05bda089f4f702deddb8e593653676ede5f0e10b node-v0.10.6-sunos-x86.tar.gz 6ceb80be28c63f2c57e8479755d206400b205c46 node-v0.10.6-x86.msi cd0acf9b332c30aba6a72979d3373e342fad6b95 node-v0.10.6.pkg fa06101af8890eeaf997bd2620d7742b71a7223c node-v0.10.6.tar.gz a2a2befa62b3cd2da9c2e51204df017e0f0c0cae node.exe 8401647a2f8fb3486fa08d7e603822ae12cf6dee node.exp 8ab923eb23584310874a4f63d71244cca5bfc0f8 node.lib b9042fec324b202853f7f1d8b1d26ea49d944913 node.pdb 647a2ea899113e14d8f0894aa969ffd3a5d407c6 x64/node-v0.10.6-x64.msi 021048aa29fce5ce200b22896fd5f1b053f0d40c x64/node.exe adbdc6112b3172c259a3fa9e07b7d456a0c65beb x64/node.exp 226af9033a41c96c68ade96cecedcf1289414424 x64/node.lib cca201bfe38713ffde4a0cad70cb3a5325097257 x64/node.pdb ``` node-v0.10.25~dfsg2/doc/blog/release/node-v0-6-10.md0000644000000000000000000000277512270121457020113 0ustar rootrootversion: 0.6.10 title: Node v0.6.10 author: Isaac Schlueter date: Thu Feb 02 2012 17:22:03 GMT-0800 (PST) status: publish category: release slug: node-v0-6-10

2012.02.02, Version 0.6.10 (stable)

  • Update V8 to 3.6.6.20

  • Add npm msysgit bash shim to msi installer (isaacs)

  • buffers: fix intermittent out of bounds error (Ben Noordhuis)

  • buffers: honor length argument in base64 decoder (Ben Noordhuis)

  • windows: Fix path.exists regression (Bert Belder)

  • Make QueryString.parse run faster (Philip Tellis)

  • http: avoid freeing http-parser objects too early (koichik)

  • timers: add v0.4 compatibility hack (Ben Noordhuis)

  • Proper EPERM error code support (Igor Zinkovsky, Brandon Philips)

  • dgram: Implement udp multicast methods on windows (Bert Belder)

Source Code: http://nodejs.org/dist/v0.6.10/node-v0.6.10.tar.gz

Windows Installer: http://nodejs.org/dist/v0.6.10/node-v0.6.10.msi

Macintosh Installer: http://nodejs.org/dist/v0.6.10/node-v0.6.10.pkg

Website: http://nodejs.org/docs/v0.6.10/

Documentation: http://nodejs.org/docs/v0.6.10/api/

node-v0.10.25~dfsg2/doc/blog/release/v0.8.9.md0000644000000000000000000000644012270121457017115 0ustar rootrootdate: Tue Sep 11 2012 11:50:17 GMT-0700 (PDT) category: release version: 0.8.9 title: Version 0.8.9 (Stable) slug: node-v0-8-9-stable 2012.09.11, Version 0.8.9 (Stable) * v8: upgrade to 3.11.10.22 * GYP: upgrade to r1477 * npm: Upgrade to 1.1.61 * npm: Don't create world-writable files (isaacs) * windows: fix single-accept mode for shared server sockets (Bert Belder) * windows: fix uninitialized memory access in uv_update_time() (Bert Belder) * windows: don't throw when a signal handler is attached (Bert Belder) * unix: fix memory leak in udp (Ben Noordhuis) * unix: map errno ESPIPE (Ben Noordhuis) * unix, windows: fix memory corruption in fs-poll.c (Ben Noordhuis) * sunos: fix os.cpus() on x86_64 (Ben Noordhuis) * child process: fix processes with IPC channel don't emit 'close' (Bert Belder) * build: add a "--dest-os" option to force a gyp "flavor" (Nathan Rajlich) * build: set `process.platform` to "sunos" on SunOS (Nathan Rajlich) * build: fix `make -j` fails after `make clean` (Bearice Ren) * build: fix openssl configuration for "arm" builds (Nathan Rajlich) * tls: support unix domain socket/named pipe in tls.connect (Shigeki Ohtsu) * https: make https.get() accept a URL (koichik) * http: respect HTTP/1.0 TE header (Ben Noordhuis) * crypto, tls: Domainify setSNICallback, pbkdf2, randomBytes (Ben Noordhuis) * stream.pipe: Don't call destroy() unless it's a function (isaacs) Source Code: http://nodejs.org/dist/v0.8.9/node-v0.8.9.tar.gz Macintosh Installer (Universal): http://nodejs.org/dist/v0.8.9/node-v0.8.9.pkg Windows Installer: http://nodejs.org/dist/v0.8.9/node-v0.8.9-x86.msi Windows x64 Installer: http://nodejs.org/dist/v0.8.9/x64/node-v0.8.9-x64.msi Windows x64 Files: http://nodejs.org/dist/v0.8.9/x64/ Linux 32-bit Binary: http://nodejs.org/dist/v0.8.9/node-v0.8.9-linux-x86.tar.gz Linux 64-bit Binary: http://nodejs.org/dist/v0.8.9/node-v0.8.9-linux-x64.tar.gz Solaris 32-bit Binary: http://nodejs.org/dist/v0.8.9/node-v0.8.9-sunos-x86.tar.gz Solaris 64-bit Binary: http://nodejs.org/dist/v0.8.9/node-v0.8.9-sunos-x64.tar.gz Other release files: http://nodejs.org/dist/v0.8.9/ Website: http://nodejs.org/docs/v0.8.9/ Documentation: http://nodejs.org/docs/v0.8.9/api/ Shasums: ``` 68aa7341807fb114f334151b7a1c8859e96b83d4 node-v0.8.9-darwin-x64.tar.gz 9e4a9422c1fd71750e9c46235d58aedaac3ba002 node-v0.8.9-darwin-x86.tar.gz 6236f781632555abf69d77f4bdfeb1e4e83779f3 node-v0.8.9-linux-x64.tar.gz 7f46084541d4909f44cfef2bb95f1e4f7435629e node-v0.8.9-linux-x86.tar.gz 33b0fe68f63519f3c8e6dc4d2aa51c96f62d2a56 node-v0.8.9-sunos-x64.tar.gz e05863cb3a7d4add340ad434228f57da04a03b3d node-v0.8.9-sunos-x86.tar.gz 104f325d5289c51c6eb6a0634691dcdb39abb1db node-v0.8.9-x86.msi 1dd2cf48fb9b1f3e11e6e6750084ad4b2a2b0a85 node-v0.8.9.pkg 2d3234adceedc2dc87284af88609ede6ecd71734 node-v0.8.9.tar.gz 2997e2075cd04cf693453ce5664fa37615faa9a7 node.exe d2834bd8ed3569b7880211dfe31a4f21cd475ab8 node.exp 41eac45ae350324de321a85787897bd8aa6b371c node.lib ab6666144b23b2594521d27a95fb36b0904d48a2 node.pdb f29db0a61a7bb32a7198ab059eca25b1283b9d6d x64/node-v0.8.9-x64.msi 2a7e69cef1bf7bc88109e007406e6feeaaa007b2 x64/node.exe 0423cd6602684c24e65358b9caa51740af67677b x64/node.exp 92155062a70100bfb5cf1389dd93e8851e7f3d0b x64/node.lib cbbee351b84d7da0a91f56d6bbf6805e7b85cc8f x64/node.pdb ``` node-v0.10.25~dfsg2/doc/blog/release/node-v0-5-5.md0000644000000000000000000000434512270121457020031 0ustar rootrootversion: 0.5.5 title: Node v0.5.5 author: bennoordhuis date: Fri Aug 26 2011 23:20:10 GMT-0700 (PDT) status: publish category: release slug: node-v0-5-5

2011.08.26, Version 0.5.5 (unstable)

  • typed arrays, implementation from Plesk
  • fix IP multicast on SunOS
  • fix DNS lookup order: IPv4 first, IPv6 second (--use-uv only)
  • remove support for UNIX datagram sockets (--use-uv only)
  • UDP support for Windows (Bert Belder)
  • #1572 improve tab completion for objects in the REPL (Nathan Rajlich)
  • #1563 fix buffer overflow in child_process module (reported by Dean McNamee)
  • #1546 fix performance regression in http module (reported by Brian Geffon)
  • #1491 add PBKDF2 crypto support (Glen Low)
  • #1447 remove deprecated http.cat() function (Mikeal Rogers)
  • #1140 fix incorrect dispatch of vm.runInContext's filename argument
    (Antranig Basman)

  • #1140 document vm.runInContext() and vm.createContext() (Antranig Basman)
  • #1428 fix os.freemem() on 64 bits freebsd (Artem Zaytsev)
  • #1164 make all DNS lookups async, fixes uncatchable exceptions
    (Koichi Kobayashi)

  • fix incorrect ssl shutdown check (Tom Hughes)
  • various cmake fixes (Tom Hughes)
  • improved documentation (Koichi Kobayashi, Logan Smyth, Fedor Indutny,
    Mikeal Rogers, Maciej Małecki, Antranig Basman, Mickaël Delahaye)

  • upgrade libuv to commit 835782a
  • upgrade V8 to 3.5.8

Download: http://nodejs.org/dist/node-v0.5.5.tar.gz

Windows Executable: http://nodejs.org/dist/v0.5.5/node.exe

Website: http://nodejs.org/docs/v0.5.5/

Documentation: http://nodejs.org/docs/v0.5.5/api/



Update: The .exe has a bug that results in incompatibility with Windows XP and Server 2003. This has been reported in issue #1592 and fixed. A new binary was made that is compatibile with the older Windows: http://nodejs.org/dist/v0.5.5/node-186364e.exe. node-v0.10.25~dfsg2/doc/blog/release/version-0-6-13-stable.md0000644000000000000000000000337112270121457021731 0ustar rootrootversion: 0.6.13 title: Version 0.6.13 (stable) author: Isaac Schlueter date: Thu Mar 15 2012 10:37:02 GMT-0700 (PDT) status: publish category: release slug: version-0-6-13-stable

2012.03.15 Version 0.6.13 (stable)

  • Windows: Many libuv test fixes (Bert Belder)

  • Windows: avoid uv_guess_handle crash in when fd < 0 (Bert Belder)

  • Map EBUSY and ENOTEMPTY errors (Bert Belder)

  • Windows: include syscall in fs errors (Bert Belder)

  • Fix fs.watch ENOSYS on Linux kernel version mismatch (Ben Noordhuis)

  • Update npm to 1.1.9

    - upgrade node-gyp to 0.3.5 (Nathan Rajlich)
    - Fix isaacs/npm#2249 Add cache-max and cache-min configs
    - Properly redirect across https/http registry requests
    - log config usage if undefined key in set function (Kris Windham)
    - Add support for os/cpu fields in package.json (Adam Blackburn)
    - Automatically node-gyp packages containing a binding.gyp
    - Fix failures unpacking in UNC shares
    - Never create un-listable directories
    - Handle cases where an optionalDependency fails to build

Source Code: http://nodejs.org/dist/v0.6.13/node-v0.6.13.tar.gz

Windows Installer: http://nodejs.org/dist/v0.6.13/node-v0.6.13.msi

Macintosh Installer: http://nodejs.org/dist/v0.6.13/node-v0.6.13.pkg

Website: http://nodejs.org/docs/v0.6.13/

Documentation: http://nodejs.org/docs/v0.6.13/api/

node-v0.10.25~dfsg2/doc/blog/release/version-0-6-14-stable.md0000644000000000000000000000357012270121457021733 0ustar rootrootversion: 0.6.14 title: Version 0.6.14 (stable) author: Isaac Schlueter date: Fri Mar 23 2012 11:22:22 GMT-0700 (PDT) status: publish category: release slug: version-0-6-14-stable

2012.03.22 Version 0.6.14 (stable)

  • net: don't crash when queued write fails (Igor Zinkovsky)

  • sunos: fix EMFILE on process.memoryUsage() (Bryan Cantrill)

  • crypto: fix compile-time error with openssl 0.9.7e (Ben Noordhuis)

  • unix: ignore ECONNABORTED errors from accept() (Ben Noordhuis)

  • Add UV_ENOSPC and mappings to it (Bert Belder)

  • http-parser: Fix response body is not read (koichik)

  • Upgrade npm to 1.1.12

    - upgrade node-gyp to 0.3.7
    - work around AV-locked directories on Windows
    - Fix isaacs/npm#2293 Don't try to 'uninstall' /
    - Exclude symbolic links from packages.
    - Fix isaacs/npm#2275 Spurious 'unresolvable cycle' error.
    - Exclude/include dot files as if they were normal files

Source Code: http://nodejs.org/dist/v0.6.14/node-v0.6.14.tar.gz

Windows Installer: http://nodejs.org/dist/v0.6.14/node-v0.6.14.msi

Windows x64 Files: http://nodejs.org/dist/v0.6.14/x64/

Macintosh Installer (Universal): http://nodejs.org/dist/v0.6.14/node-v0.6.14.pkg

Other release files: http://nodejs.org/dist/v0.6.14/

Website: http://nodejs.org/docs/v0.6.14/

Documentation: http://nodejs.org/docs/v0.6.14/api/

node-v0.10.25~dfsg2/doc/blog/release/v0.11.4.md0000644000000000000000000000614412270121457017163 0ustar rootrootdate: Fri Jul 12 14:34:13 PDT 2013 version: 0.11.4 category: release title: Node v0.11.4 (Unstable) slug: node-v0-11-4-unstable 2013.07.12, Version 0.11.4 (Unstable) * npm: Upgrade to 1.3.4 * v8: Upgrade to v3.20.2 * c-ares: Upgrade to piscisaureus/cares@805d153 * timers: setImmediate process full queue each turn (Ben Noordhuis) * http: Add agent.get/request methods (isaacs) * http: Proper KeepAlive behavior (isaacs) * configure: fix the --without-ssl option (Nathan Rajlich) * buffer: propagate originating parent (Trevor Norris) * tls_wrap: return Error not throw for missing cert (Timothy J Fontaine) * src: enable native v8 typed arrays (Ben Noordhuis) * stream: objectMode transform should allow falsey values (Jeff Barczewski) * slab_allocator: remove SlabAllocator (Trevor Norris) * crypto: fix memory leak in LoadPKCS12 (Fedor Indutny) * tls: export TLSSocket (Fedor Indutny) * zlib: allow changing of level and strategy (Brian White) * zlib: allow custom flush type for flush() (Brian White) Source Code: http://nodejs.org/dist/v0.11.4/node-v0.11.4.tar.gz Macintosh Installer (Universal): http://nodejs.org/dist/v0.11.4/node-v0.11.4.pkg Windows Installer: http://nodejs.org/dist/v0.11.4/node-v0.11.4-x86.msi Windows x64 Installer: http://nodejs.org/dist/v0.11.4/x64/node-v0.11.4-x64.msi Windows x64 Files: http://nodejs.org/dist/v0.11.4/x64/ Linux 32-bit Binary: http://nodejs.org/dist/v0.11.4/node-v0.11.4-linux-x86.tar.gz Linux 64-bit Binary: http://nodejs.org/dist/v0.11.4/node-v0.11.4-linux-x64.tar.gz Solaris 32-bit Binary: http://nodejs.org/dist/v0.11.4/node-v0.11.4-sunos-x86.tar.gz Solaris 64-bit Binary: http://nodejs.org/dist/v0.11.4/node-v0.11.4-sunos-x64.tar.gz Other release files: http://nodejs.org/dist/v0.11.4/ Website: http://nodejs.org/docs/v0.11.4/ Documentation: http://nodejs.org/docs/v0.11.4/api/ Shasums: ``` 0035d18e2dcf9aad669b1c7c07319e17abfe3762 ./node-v0.11.4.tar.gz a7be873e87c6f4721892791a047331018f851986 ./node-v0.11.4.pkg fbfcf8a599c765ba924ddbe1ba8c143053b5342e ./node-v0.11.4-linux-x64.tar.gz 7df3de8dfb8547ba11e8dec16380ac1ca9978e82 ./node-v0.11.4-linux-x86.tar.gz f272e7d87ab9b0baa41b10561d34b3aeadfcd0fa ./node-v0.11.4-darwin-x86.tar.gz 7f56d5a7e6b73e22950610ae6c1dd00edd4940bc ./node-v0.11.4-darwin-x64.tar.gz 0b919bae82fa7ab9a17bf694fa44080b2612a0d4 ./node-v0.11.4-sunos-x86.tar.gz 5283e2c1f8a9e51fa864957d1ed28bb1549a7ab9 ./node-v0.11.4-sunos-x64.tar.gz 50374dcf0932465ce0ac8d124df8ecd34eeea6a1 ./node-v0.11.4-x86.msi 42a9430e7500d8e4b0a78428594082f5deeab4d6 ./node.pdb 4eda314346e201890fde54fc55f8db7896cb9288 ./node.exp 8c1631b168d855fc93a952a8a1a91946d2596278 ./node.exe bb76a0d00c3c8c10f8c49c46e7d684b8850ac90a ./node.lib 2f2bf4bc58da9be63e9840b113b4d665a6019bad ./x64/node-v0.11.4-x64.msi 31273870a763aa55d611a366ade2ca6c39bac2f5 ./x64/node.exp a90905f911e2f741c34699c62f28ffab48565559 ./x64/node.pdb d325667dcbdf50c92fc8c3034df3808f734179fa ./x64/node.exe 9a9a0fc005cf4c09154f3171be74b4153579c6fe ./x64/node.lib 0d3f96506def112ff1344f87d7271122412ff899 ./pkgsrc/nodejs-x64-0.11.4.tgz 28b1eb61fe7b9901a809a137424c4e05bd8f6fa6 ./pkgsrc/nodejs-ia32-0.11.4.tgz ``` node-v0.10.25~dfsg2/doc/blog/release/node-v0-7-3.md0000644000000000000000000000233312270121457020024 0ustar rootrootversion: 0.7.3 title: Node v0.7.3 (unstable) author: Isaac Schlueter date: Tue Feb 07 2012 17:08:27 GMT-0800 (PST) status: publish category: release slug: node-v0-7-3

2012.02.07, Version 0.7.3 (unstable)

  • Upgrade V8 to 3.9.2

  • Revert support for isolates. (Ben Noordhuis)

  • cluster: Cleanup docs, event handling, and process.disconnect (Andreas Madsen)

  • gyp_addon: link with node.lib on Windows (Nathan Rajlich)

  • http: fix case where http-parser is freed twice (koichik)

  • Windows: disable RTTI and exceptions (Bert Belder)

Source Code: http://nodejs.org/dist/v0.7.3/node-v0.7.3.tar.gz

Windows Installer: http://nodejs.org/dist/v0.7.3/node-v0.7.3.msi

Macintosh Installer: http://nodejs.org/dist/v0.7.3/node-v0.7.3.pkg

Website: http://nodejs.org/docs/v0.7.3/

Documentation: http://nodejs.org/docs/v0.7.3/api/

node-v0.10.25~dfsg2/doc/blog/release/v0.9.8.md0000644000000000000000000000527212270121457017117 0ustar rootrootcategory: release date: Thu Jan 24 10:28:53 PST 2013 version: 0.9.8 title: Node v0.9.8 (Unstable) slug: node-v0-9-8-unstable 2013.01.24, Version 0.9.8 (Unstable) * npm: Upgrade to v1.2.3 * V8: Upgrade to 3.15.11.10 * streams: Support objects other than Buffers (Jake Verbaten) * buffer: remove float write range checks (Trevor Norris) * http: close connection on 304/204 responses with chunked encoding (Ben Noordhuis) * build: fix build with dtrace support on FreeBSD (Fedor Indutny) * console: Support formatting options in trace() (isaacs) * domain: empty stack on all exceptions (Dave Olszewski) * unix, windows: make uv_*_bind() error codes consistent (Andrius Bentkus) * linux: add futimes() fallback (Ben Noordhuis) Source Code: http://nodejs.org/dist/v0.9.8/node-v0.9.8.tar.gz Macintosh Installer (Universal): http://nodejs.org/dist/v0.9.8/node-v0.9.8.pkg Windows Installer: http://nodejs.org/dist/v0.9.8/node-v0.9.8-x86.msi Windows x64 Installer: http://nodejs.org/dist/v0.9.8/x64/node-v0.9.8-x64.msi Windows x64 Files: http://nodejs.org/dist/v0.9.8/x64/ Linux 32-bit Binary: http://nodejs.org/dist/v0.9.8/node-v0.9.8-linux-x86.tar.gz Linux 64-bit Binary: http://nodejs.org/dist/v0.9.8/node-v0.9.8-linux-x64.tar.gz Solaris 32-bit Binary: http://nodejs.org/dist/v0.9.8/node-v0.9.8-sunos-x86.tar.gz Solaris 64-bit Binary: http://nodejs.org/dist/v0.9.8/node-v0.9.8-sunos-x64.tar.gz Other release files: http://nodejs.org/dist/v0.9.8/ Website: http://nodejs.org/docs/v0.9.8/ Documentation: http://nodejs.org/docs/v0.9.8/api/ Shasums: ``` 30bbd1df69be189afca34d808932f5417986d966 node-v0.9.8-darwin-x64.tar.gz e9e2e9477836e22a2e8242ddbc73400a2a5fac43 node-v0.9.8-darwin-x86.tar.gz fddaef3c084121f21d466a29f1117a844761a4a6 node-v0.9.8-linux-arm-pi.tar.gz 0ec573b26722c45abf8db1c865f8169d49244877 node-v0.9.8-linux-x64.tar.gz b5227fb14eaad8f0c3c4fbc97b30292dcc34046b node-v0.9.8-linux-x86.tar.gz 1d846eba7dc3c02c19d82915bfccba4efb77d54c node-v0.9.8-sunos-x64.tar.gz e06c6b965d44084ef355d80b10d99f23005bdac7 node-v0.9.8-sunos-x86.tar.gz 4ba7fcefbd0d9cc83427500f4d71fa5ed0e82bb8 node-v0.9.8-x86.msi c92303e41c45aef6959b6a70285cdd6be30ef0b4 node-v0.9.8.pkg ce337f1f7baca56954412fbeaa25b4f9ea4c8528 node-v0.9.8.tar.gz 474b4afd7b8696edaf240f1710084c3c7e48a00c node.exe 22044cb9cf46570d9a41cc830eda962e57331da7 node.exp 3b612ca0692f8764dd722092d0ae6e5e2c6ae5fd node.lib 7b6e50f83202781bf827b554957d097f4ae66c46 node.pdb c67b8047392e591434169c5d367ff2356ae640fd x64/node-v0.9.8-x64.msi 474b4afd7b8696edaf240f1710084c3c7e48a00c x64/node.exe 22044cb9cf46570d9a41cc830eda962e57331da7 x64/node.exp 3b612ca0692f8764dd722092d0ae6e5e2c6ae5fd x64/node.lib 7b6e50f83202781bf827b554957d097f4ae66c46 x64/node.pdb ``` node-v0.10.25~dfsg2/doc/blog/release/v0.9.6.md0000644000000000000000000000575212270121457017120 0ustar rootroottitle: Node v0.9.6 (Unstable) slug: node-v0-9-6-unstable version: 0.9.6 category: release date: Fri Jan 11 11:23:56 PST 2013 2013.01.11, Version 0.9.6 (Unstable) * V8: update to 3.15.11.5 * node: remove ev-emul.h (Ben Noordhuis) * path: make basename and extname ignore trailing slashes (Bert Belder) * typed arrays: fix sunos signed/unsigned char issue (Ben Noordhuis) * child_process: Fix {stdio:'inherit'} regression (Ben Noordhuis) * child_process: Fix pipe() from child stdio streams (Maciej Małecki) * child_process: make fork() execPath configurable (Bradley Meck) * stream: Add readable.push(chunk) method (isaacs) * dtrace: x64 ustack helper (Fedor Indutny) * repl: fix floating point number parsing (Nirk Niggler) * repl: allow overriding builtins (Ben Noordhuis) * net: add localAddress and localPort to Socket (James Hight) * fs: make pool size coincide with ReadStream bufferSize (Shigeki Ohtsu) * typed arrays: implement load and store swizzling (Dean McNamee) * windows: fix perfctr crash on XP and 2003 (Scott Blomquist) * dgram: fix double implicit bind error (Ben Noordhuis) Source Code: http://nodejs.org/dist/v0.9.6/node-v0.9.6.tar.gz Macintosh Installer (Universal): http://nodejs.org/dist/v0.9.6/node-v0.9.6.pkg Windows Installer: http://nodejs.org/dist/v0.9.6/node-v0.9.6-x86.msi Windows x64 Installer: http://nodejs.org/dist/v0.9.6/x64/node-v0.9.6-x64.msi Windows x64 Files: http://nodejs.org/dist/v0.9.6/x64/ Linux 32-bit Binary: http://nodejs.org/dist/v0.9.6/node-v0.9.6-linux-x86.tar.gz Linux 64-bit Binary: http://nodejs.org/dist/v0.9.6/node-v0.9.6-linux-x64.tar.gz Solaris 32-bit Binary: http://nodejs.org/dist/v0.9.6/node-v0.9.6-sunos-x86.tar.gz Solaris 64-bit Binary: http://nodejs.org/dist/v0.9.6/node-v0.9.6-sunos-x64.tar.gz Other release files: http://nodejs.org/dist/v0.9.6/ Website: http://nodejs.org/docs/v0.9.6/ Documentation: http://nodejs.org/docs/v0.9.6/api/ Shasums: ``` 31ef1e0d875232c85ecde0bc84ddf19cf6cd63f7 node-v0.9.6-darwin-x64.tar.gz 62d5f6f2b39e87eb1f86da0423b6ec45180cd986 node-v0.9.6-darwin-x86.tar.gz e3cb0989c8262349659424ea2f534c8afe12f93c node-v0.9.6-linux-x64.tar.gz ff4b68f274a52038fbd04a4ef143e1076ae71db9 node-v0.9.6-linux-x86.tar.gz 59ebb5e5c02c9e40a7a3cc2d8f554f2d722048eb node-v0.9.6-sunos-x64.tar.gz 714b88c5f34bb0adad2d73b6d76fa423d14c29b8 node-v0.9.6-sunos-x86.tar.gz 3ecc617efcae5274c3a1e3452e8fb0646a3e6afc node-v0.9.6-x86.msi d865d044cc1e9379998aa6c3d34dbe2824e41b5e node-v0.9.6.pkg 650d7c50e29ce7ab428de0617ad315063a53ea1a node-v0.9.6.tar.gz 94b10c6945ec78af6d9b90fc083f97adfa44473f node.exe 0b0eceee083ca9cfdc8c24fbdfe92f7ee25938c2 node.exp 9af3ceee0be869e866b2f516dc2b17690e442739 node.lib 7dfbdf0ac378e67cfa5aff550f057c31f8f92d38 node.pdb 02f27f503a16850a66f7e6fe8732bfa5fcbe311f x64/node-v0.9.6-x64.msi 3f5990602e7268413602dd54a4d019b3330630ae x64/node.exe 836a7be49bd7ed5f1794775d0c20e75f327b067d x64/node.exp e5e3abed1da31d94525f8731e2d67f0e19b20304 x64/node.lib b61c1a7a5786a38864943bb3d4c78859d0430d7a x64/node.pdb ``` node-v0.10.25~dfsg2/doc/blog/release/version-0-7-4-unstable.md0000644000000000000000000000305112270121457022210 0ustar rootrootversion: 0.7.4 title: Node v0.7.4 (unstable) author: Isaac Schlueter date: Wed Feb 15 2012 11:38:35 GMT-0800 (PST) status: publish category: release slug: version-0-7-4-unstable

2012.02.14, Version 0.7.4 (unstable)

  • Upgrade V8 to 3.9.5

  • Upgrade npm to 1.1.1

  • build: Detect host_arch better (Karl Skomski)

  • debugger: export debug_port to process (Fedor Indutny)

  • api docs: CSS bug fixes (isaacs)

  • build: use -fPIC for native addons on UNIX (Nathan Rajlich)

  • Re-add top-level v8::Locker (Marcel Laverdet)

  • Move images out of the dist tarballs (isaacs)

  • libuv: Remove uv_export and uv_import (Ben Noordhuis)

  • build: Support x64 build on Windows (Igor Zinkovsky)

Source Code: http://nodejs.org/dist/v0.7.4/node-v0.7.4.tar.gz

Windows Installer: http://nodejs.org/dist/v0.7.4/node-v0.7.4.msi

Macintosh Installer: http://nodejs.org/dist/v0.7.4/node-v0.7.4.pkg

Other release files: http://nodejs.org/dist/v0.7.4/

Website: http://nodejs.org/docs/v0.7.4/

Documentation: http://nodejs.org/docs/v0.7.4/api/

node-v0.10.25~dfsg2/doc/blog/release/v0.10.14.md0000644000000000000000000000522012270121457017235 0ustar rootrootdate: Thu Jul 25 13:35:41 PDT 2013 version: 0.10.14 category: release title: Node v0.10.14 (Stable) slug: node-v0-10-14-stable 2013.07.25, Version 0.10.14 (Stable) * uv: Upgrade to v0.10.13 * npm: Upgrade to v1.3.5 * os: Don't report negative times in cpu info (Ben Noordhuis) * fs: Handle large UID and GID (Ben Noordhuis) * url: Fix edge-case when protocol is non-lowercase (Shuan Wang) * doc: Streams API Doc Rewrite (isaacs) * node: call MakeDomainCallback in all domain cases (Trevor Norris) * crypto: fix memory leak in LoadPKCS12 (Fedor Indutny) Source Code: http://nodejs.org/dist/v0.10.14/node-v0.10.14.tar.gz Macintosh Installer (Universal): http://nodejs.org/dist/v0.10.14/node-v0.10.14.pkg Windows Installer: http://nodejs.org/dist/v0.10.14/node-v0.10.14-x86.msi Windows x64 Installer: http://nodejs.org/dist/v0.10.14/x64/node-v0.10.14-x64.msi Windows x64 Files: http://nodejs.org/dist/v0.10.14/x64/ Linux 32-bit Binary: http://nodejs.org/dist/v0.10.14/node-v0.10.14-linux-x86.tar.gz Linux 64-bit Binary: http://nodejs.org/dist/v0.10.14/node-v0.10.14-linux-x64.tar.gz Solaris 32-bit Binary: http://nodejs.org/dist/v0.10.14/node-v0.10.14-sunos-x86.tar.gz Solaris 64-bit Binary: http://nodejs.org/dist/v0.10.14/node-v0.10.14-sunos-x64.tar.gz Other release files: http://nodejs.org/dist/v0.10.14/ Website: http://nodejs.org/docs/v0.10.14/ Documentation: http://nodejs.org/docs/v0.10.14/api/ Shasums: ``` f6a13dc93f677e9d71f15570ea3db2244c09b26e node-v0.10.14-darwin-x64.tar.gz c7a456bb7bd7a3d46e4d4ed65b19458e8c937431 node-v0.10.14-darwin-x86.tar.gz 9797f93df6085796ccad0f84a65fcdee46aaeedf node-v0.10.14-linux-x64.tar.gz f40ade7d212be254a67994f86f598b1c1c0b7b4c node-v0.10.14-linux-x86.tar.gz c187f1385224e8d4bc2b465d9677c060b399e268 node-v0.10.14-sunos-x64.tar.gz bd8edd17eff8928ccd0adedbe63ddf3631324148 node-v0.10.14-sunos-x86.tar.gz 7654aacdcdc832387e479b2c3de731b3b6ca3d01 node-v0.10.14-x86.msi 90892d5672a75baa761afd2f238c06d4fa58cfef node-v0.10.14.pkg b5d27b36d25bd7d45e1bb52ce0e0fdfb49dde370 node-v0.10.14.tar.gz f2de9c77ed3914fd9139668581f970f8df698687 node.exe b2a767985060c0719569d8fcfe7ad7e5548d952c node.exp fa035fd44672547f8424df4a461f0a48c4cfdb97 node.lib aaaf7b82f826dd2a0358223ea7f1a70ccf93bc77 node.pdb 9758a6374055ebfb5a2d788e1f95ebb267a5c20b pkgsrc/nodejs-ia32-0.10.14.tgz d8ca87abc993a042030d63bcae08e85a30eef4b8 pkgsrc/nodejs-x64-0.10.14.tgz b372293ff300dacae79c44603e878726e282b3a2 x64/node-v0.10.14-x64.msi 293a240db1cd280907a16956d4d6bb72ad9ef02a x64/node.exe 9d03fa6d751359e174586190e757efbf61869d50 x64/node.exp 8b4e097f17d4efe13a05bff7534bb23738821a9d x64/node.lib 0323632950aa90ed4bb083774b487f6287dae7a5 x64/node.pdb ``` node-v0.10.25~dfsg2/doc/blog/release/v0.10.19.md0000644000000000000000000000520712270121457017247 0ustar rootrootdate: Tue Sep 24 15:09:23 PDT 2013 version: 0.10.19 category: release title: Node v0.10.19 (Stable) slug: node-v0-10-19-stable 2013.09.24, Version 0.10.19 (Stable) * uv: Upgrade to v0.10.17 * npm: upgrade to 1.3.11 * readline: handle input starting with control chars (Eric Schrock) * configure: add mips-float-abi (soft, hard) option (Andrei Sedoi) * stream: objectMode transforms allow falsey values (isaacs) * tls: prevent duplicate values returned from read (Nathan Rajlich) * tls: NPN protocols are now local to connections (Fedor Indutny) Source Code: http://nodejs.org/dist/v0.10.19/node-v0.10.19.tar.gz Macintosh Installer (Universal): http://nodejs.org/dist/v0.10.19/node-v0.10.19.pkg Windows Installer: http://nodejs.org/dist/v0.10.19/node-v0.10.19-x86.msi Windows x64 Installer: http://nodejs.org/dist/v0.10.19/x64/node-v0.10.19-x64.msi Windows x64 Files: http://nodejs.org/dist/v0.10.19/x64/ Linux 32-bit Binary: http://nodejs.org/dist/v0.10.19/node-v0.10.19-linux-x86.tar.gz Linux 64-bit Binary: http://nodejs.org/dist/v0.10.19/node-v0.10.19-linux-x64.tar.gz Solaris 32-bit Binary: http://nodejs.org/dist/v0.10.19/node-v0.10.19-sunos-x86.tar.gz Solaris 64-bit Binary: http://nodejs.org/dist/v0.10.19/node-v0.10.19-sunos-x64.tar.gz Other release files: http://nodejs.org/dist/v0.10.19/ Website: http://nodejs.org/docs/v0.10.19/ Documentation: http://nodejs.org/docs/v0.10.19/api/ Shasums: ``` 74f1db96742fcc0128d1c14d3cb808ef5c847749 node-v0.10.19-darwin-x64.tar.gz 71ef9bd63d3926a2b78a43a5d077838c43e7e2ea node-v0.10.19-darwin-x86.tar.gz ebc6dc67276f7461dbd45496924b36949c75e7e0 node-v0.10.19-linux-x64.tar.gz 226b507f554fa5cc07296c30f08db76f5eaeb157 node-v0.10.19-linux-x86.tar.gz 3b324613b79d1c4ab3b9414b0644a3a559c2aec9 node-v0.10.19-sunos-x64.tar.gz 83cb3e58e9ac925ea22c8533cabc712625faa3f7 node-v0.10.19-sunos-x86.tar.gz dcbe7db6d0c93f83f539f38807cd3c1923969721 node-v0.10.19-x86.msi e6397e1df4e74864e3f0e5fc7bd24178828497f4 node-v0.10.19.pkg 39478caf7024af6d992007457540f8941104c5d9 node-v0.10.19.tar.gz 0fe9364b443e76f7364f8694751da15479417bdf node.exe 63555cdb67c2fd63411726dc691b08af520b27f6 node.exp c4d33b56cff97c47b12df3ad237977a57d4c798d node.lib 19a603db8f8c30b1736124740a6a1c856f2d21d8 node.pdb ca32da0335ecb09ab7316b6e18f23461e298768e pkgsrc/nodejs-ia32-0.10.19.tgz b0b05a7f74d980720677a3232e82e23df211c122 pkgsrc/nodejs-x64-0.10.19.tgz 45aed04478346035e8dc7933d120ab636d56eac4 x64/node-v0.10.19-x64.msi b81788c17fec167b77883dcbaf8c629ad7560c4d x64/node.exe 086761bf6ff4622714d24d7979548a37aaaea57e x64/node.exp cc554a431039952207adfcb3997a7366ad7182e8 x64/node.lib 02d18f042f3d25663ea4d979dff8120435982079 x64/node.pdb ``` node-v0.10.25~dfsg2/doc/blog/release/node-v0-6-6.md0000644000000000000000000000246012270121457020027 0ustar rootrootversion: 0.6.6 title: Node v0.6.6 author: Isaac Schlueter date: Thu Dec 15 2011 11:07:57 GMT-0800 (PST) status: publish category: release slug: node-v0-6-6 2011.12.14, Version 0.6.6 (stable)
  • npm update to 1.1.0-beta-4 (Isaac Z. Schlueter)
  • cli: fix output of --help (Ben Noordhuis)
  • new website
  • pause/resume semantics for stdin (Isaac Z. Schlueter)
  • Travis CI integration (Maciej Małecki)
  • child_process: Fix bug regarding closed stdin (Ben Noordhuis)
  • Enable upgrades in MSI. (Igor Zinkovsky)
  • net: Fixes memory leak (Ben Noordhuis)
  • fs: handle fractional or NaN ReadStream buffer size (Ben Noordhuis)
  • crypto: fix memory leaks in PBKDF2 error path (Ben Noordhuis)
Source Code: http://nodejs.org/dist/v0.6.6/node-v0.6.6.tar.gz Windows Installer: http://nodejs.org/dist/v0.6.6/node-v0.6.6.msi Macintosh Installer: http://nodejs.org/dist/v0.6.6/node-v0.6.6.pkg Website: http://nodejs.org/docs/v0.6.6/ Documentation: http://nodejs.org/docs/v0.6.6/api/ node-v0.10.25~dfsg2/doc/blog/release/v0.10.2.md0000644000000000000000000000603112270121457017153 0ustar rootrootdate: Thu Mar 28 13:00:39 PDT 2013 version: 0.10.2 category: release title: Node v0.10.2 (Stable) slug: node-v0-10-2-stable 2013.03.28, Version 0.10.2 (Stable) * npm: Upgrade to 1.2.15 * uv: Upgrade to 0.10.3 * tls: handle SSL_ERROR_ZERO_RETURN (Fedor Indutny) * tls: handle errors before calling C++ methods (Fedor Indutny) * tls: remove harmful unnecessary bounds checking (Marcel Laverdet) * crypto: make getCiphers() return non-SSL ciphers (Ben Noordhuis) * crypto: check randomBytes() size argument (Ben Noordhuis) * timers: do not calculate Timeout._when property (Alexey Kupershtokh) * timers: fix off-by-one ms error (Alexey Kupershtokh) * timers: handle signed int32 overflow in enroll() (Fedor Indutny) * stream: Fix stall in Transform under very specific conditions (Gil Pedersen) * stream: Handle late 'readable' event listeners (isaacs) * stream: Fix early end in Writables on zero-length writes (isaacs) * domain: fix domain callback from MakeCallback (Trevor Norris) * child_process: don't emit same handle twice (Ben Noordhuis) * child_process: fix sending utf-8 to child process (Ben Noordhuis) Source Code: http://nodejs.org/dist/v0.10.2/node-v0.10.2.tar.gz Macintosh Installer (Universal): http://nodejs.org/dist/v0.10.2/node-v0.10.2.pkg Windows Installer: http://nodejs.org/dist/v0.10.2/node-v0.10.2-x86.msi Windows x64 Installer: http://nodejs.org/dist/v0.10.2/x64/node-v0.10.2-x64.msi Windows x64 Files: http://nodejs.org/dist/v0.10.2/x64/ Linux 32-bit Binary: http://nodejs.org/dist/v0.10.2/node-v0.10.2-linux-x86.tar.gz Linux 64-bit Binary: http://nodejs.org/dist/v0.10.2/node-v0.10.2-linux-x64.tar.gz Solaris 32-bit Binary: http://nodejs.org/dist/v0.10.2/node-v0.10.2-sunos-x86.tar.gz Solaris 64-bit Binary: http://nodejs.org/dist/v0.10.2/node-v0.10.2-sunos-x64.tar.gz Other release files: http://nodejs.org/dist/v0.10.2/ Website: http://nodejs.org/docs/v0.10.2/ Documentation: http://nodejs.org/docs/v0.10.2/api/ Shasums: ``` 860ed25d3e77d4676b5512f87f3f98b6783ee258 node-v0.10.2-darwin-x64.tar.gz 811eb3b66651dfffeaf928496e8eecab5c9304fb node-v0.10.2-darwin-x86.tar.gz 2914731bdbe809483ed9da2578ce19121494e437 node-v0.10.2-linux-x64.tar.gz dbf039ee15e423738db4ffc9c498d6b0ad54da07 node-v0.10.2-linux-x86.tar.gz 17bc5bf26af7da790e6b0c4cbb2b73ea1c9f2ed5 node-v0.10.2-sunos-x64.tar.gz 5e02e35cc15ae56953921ad4c8e45b849c736e20 node-v0.10.2-sunos-x86.tar.gz 2adb1bf5919fb8adeaf96edd8a8ed16d71a3f8f8 node-v0.10.2-x86.msi 73ff97a4d2d3bb1f468db2654b5b59a28f868cce node-v0.10.2.pkg 759a05eff48ff0b54e55748012c5c45502f7cecd node-v0.10.2.tar.gz 6c1336a61395747fed20a12c8977a2b2ecf23354 node.exe f0775d4f649ee9c3d5614fdb26e64bc7d000cd5d node.exp 9860c6eb9062fbdc50b515f4ccab179f74dd3ec8 node.lib d41d99a3921022533c1760e15447ce3acf050a7d node.pdb 1dbd11a5278831356daca035fe5bbbe1062798b4 x64/node-v0.10.2-x64.msi d36abd4ecf02c522e8c75fce24eab1ce800d6458 x64/node.exe 295a950fe3c1c3ceb04249474388b891bf2a39ed x64/node.exp b64eabafc3f9498552b3ea97bd0d922db1f90f75 x64/node.lib 1f31d6c0079e9f2c9a6de3d956649d83ca6e7a25 x64/node.pdb ``` node-v0.10.25~dfsg2/doc/blog/release/node-v0-5-0-unstable.md0000644000000000000000000000350712270121457021636 0ustar rootrootversion: 0.5.0 title: Node v0.5.0 (Unstable) author: ryandahl date: Wed Jul 06 2011 02:23:17 GMT-0700 (PDT) status: publish category: release slug: node-v0-5-0-unstable 2011.07.05, Version 0.5.0 (unstable)
  • New non-default libuv backend to support IOCP on Windows. Use --use-uv to enable.
  • deprecate http.cat
  • docs improved.
  • add child_process.fork
  • add fs.utimes() and fs.futimes() support (Ben Noordhuis)
  • add process.uptime() (Tom Huges)
  • add path.relative (Tony Huang)
  • add os.getNetworkInterfaces()
  • add remoteAddress and remotePort for client TCP connections (Brian White)
  • add secureOptions flag, setting ciphers, SSL_OP_CRYPTOPRO_TLSEXT_BUG to TLS (Theo Schlossnagle)
  • add process.arch (Nathan Rajlich)
  • add reading/writing of floats and doubles from/to buffers (Brian White)
  • Allow script to be read from stdin
  • #477 add Buffer::fill method to do memset (Konstantin Käfer)
  • #573 Diffie-Hellman support to crypto module (Håvard Stranden)
  • #695 add 'hex' encoding to buffer (isaacs)
  • #851 Update how REPLServer uses contexts (Ben Weaver)
  • #853 add fs.lchow, fs.lchmod, fs.fchmod, fs.fchown (isaacs)
  • #889 Allow to remove all EventEmitter listeners at once (Felix Geisendörfer)
  • #926 OpenSSL NPN support (Fedor Indutny)
  • #955 Change ^C handling in REPL (isaacs)
  • #979 add support for Unix Domain Sockets to HTTP (Mark Cavage)
  • #1173 #1170 add AMD, asynchronous module definition (isaacs)
  • DTrace probes: support X-Forwarded-For (Dave Pacheco) Download: http://nodejs.org/dist/node-v0.5.0.tar.gz Website: http://nodejs.org/docs/v0.5.0/ Documentation: http://nodejs.org/docs/v0.5.0/api/ node-v0.10.25~dfsg2/doc/blog/release/v0.8.2.md0000644000000000000000000000440612270121457017106 0ustar rootrootversion: 0.8.2 title: Version 0.8.2 (stable) category: release slug: node-v0-8-2-stable date: 2012.07.09 2012.07.09, Version 0.8.2 (Stable) * npm: Upgrade to 1.1.36 * readline: don't use Function#call() (Nathan Rajlich) * Code cleanup to pass 'use strict' (Jonas Westerlund) * module: add filename to require() json errors (TJ Holowaychuk) * readline: fix for unicode prompts (Tim Macfarlane) * timers: fix handling of large timeouts (Ben Noordhuis) * repl: fix passing an empty line inserting "undefined" into the buffer (Nathan Rajlich) * repl: fix crashes when buffering command (Maciej Małecki) * build: rename strict_aliasing to node_no_strict_aliasing (Ben Noordhuis) * build: disable -fstrict-aliasing for any gcc < 4.6.0 (Ben Noordhuis) * build: detect cc version with -dumpversion (Ben Noordhuis) * build: handle output of localized gcc or clang (Ben Noordhuis) * unix: fix memory corruption in freebsd.c (Ben Noordhuis) * unix: fix 'zero handles, one request' busy loop (Ben Noordhuis) * unix: fix busy loop on unexpected tcp message (Ben Noordhuis) * unix: fix EINPROGRESS busy loop (Ben Noordhuis) Source Code: http://nodejs.org/dist/v0.8.2/node-v0.8.2.tar.gz Macintosh Installer (Universal): http://nodejs.org/dist/v0.8.2/node-v0.8.2.pkg Windows Installer: http://nodejs.org/dist/v0.8.2/node-v0.8.2-x86.msi Windows x64 Installer: http://nodejs.org/dist/v0.8.2/x64/node-v0.8.2-x64.msi Windows x64 Files: http://nodejs.org/dist/v0.8.2/x64/ Other release files: http://nodejs.org/dist/v0.8.2/ Website: http://nodejs.org/docs/v0.8.2/ Documentation: http://nodejs.org/docs/v0.8.2/api/ Shasums: ``` 6571b7aad17ed4860d9ecb7946098dcd569e3eb0 node-v0.8.2-x86.msi 8436e940b8c3b1dff73bf4d1eee98fd3b1fc6295 node-v0.8.2.pkg 0e743d21b487151e67950f09198def058db19a1e node-v0.8.2.tar.gz dcc45bee9d4a6b38ccef0f00e4a6028864f07278 node.exe 5417f98a533c90f2b72ed3a2a002c2c36a65cb75 node.exp 57700a9555d16ebf5401898c179669654f045c5f node.lib 5bf7e8777d715d5d6b40c21ea3969c4244c20879 node.pdb 6a5fe7efb56c3e17de357e9b9adc8f1c54db895a x64/node-v0.8.2-x64.msi 72f04cb5bb25bd568cb7bc42eb5e1365e614b672 x64/node.exe 6b402ca44a45a3bc1393854d92247bf79eb3df2b x64/node.exp ad39add3918fb31aef25e3a4acfe1da499900143 x64/node.lib fa981c97e0c474ede8e7c28904d710cc3ee3390c x64/node.pdb ``` node-v0.10.25~dfsg2/doc/blog/release/v0.9.3.md0000644000000000000000000000604112270121457017105 0ustar rootrootcategory: release version: v0.9.3 date: Wed Oct 24 10:04:08 PDT 2012 slug: node-v0.9.3 title: Node v0.9.3 (Unstable) 2012.10.24, Version 0.9.3 (Unstable) * V8: Upgrade to 3.13.7.4 * crypto: Default to buffers instead of binary strings (isaacs, Fedor Indutny) * crypto: add getHashes() and getCiphers() (Ben Noordhuis) * unix: add custom thread pool, remove libeio (Ben Noordhuis) * util: make `inspect()` accept an "options" argument (Nathan Rajlich) * https: fix renegotation attack protection (Ben Noordhuis) * cluster: make 'listening' handler see actual port (Aaditya Bhatia) * windows: use USERPROFILE to get the user's home dir (Bert Belder) * path: add platform specific path delimiter (Paul Serby) * http: add response.headersSent property (Pavel Lang) * child_process: make .fork()'d child auto-exit (Ben Noordhuis) * events: add 'removeListener' event (Ben Noordhuis) * string_decoder: Add 'end' method, do base64 properly (isaacs) * buffer: include encoding value in exception when invalid (Ricky Ng-Adam) * http: make http.ServerResponse no longer emit 'end' (isaacs) * streams: fix pipe is destructed by 'end' from destination (koichik) Source Code: http://nodejs.org/dist/v0.9.3/node-v0.9.3.tar.gz Macintosh Installer (Universal): http://nodejs.org/dist/v0.9.3/node-v0.9.3.pkg Windows Installer: http://nodejs.org/dist/v0.9.3/node-v0.9.3-x86.msi Windows x64 Installer: http://nodejs.org/dist/v0.9.3/x64/node-v0.9.3-x64.msi Windows x64 Files: http://nodejs.org/dist/v0.9.3/x64/ Linux 32-bit Binary: http://nodejs.org/dist/v0.9.3/node-v0.9.3-linux-x86.tar.gz Linux 64-bit Binary: http://nodejs.org/dist/v0.9.3/node-v0.9.3-linux-x64.tar.gz Solaris 32-bit Binary: http://nodejs.org/dist/v0.9.3/node-v0.9.3-sunos-x86.tar.gz Solaris 64-bit Binary: http://nodejs.org/dist/v0.9.3/node-v0.9.3-sunos-x64.tar.gz Other release files: http://nodejs.org/dist/v0.9.3/ Website: http://nodejs.org/docs/v0.9.3/ Documentation: http://nodejs.org/docs/v0.9.3/api/ Shasums: ``` 188b3ffacdc4342dc3c34e7ea8374acc3e186df0 node-v0.9.3-darwin-x64.tar.gz 94ae90f06a5bf72bb6efa8053c0beefde21f8bd7 node-v0.9.3-darwin-x86.tar.gz ccb065fe242f15ffe35ecd7b22db33d11d6a5951 node-v0.9.3-linux-x64.tar.gz 0febfb1c37a3560b0140f7f952042aa4b4712974 node-v0.9.3-linux-x86.tar.gz 4362fdfefa0ed2985045883cea51ab802555c24c node-v0.9.3-sunos-x64.tar.gz f43b6ce2a5da3bb384f6c115826cd2fea5f4bc2c node-v0.9.3-sunos-x86.tar.gz ff6a7f8ff1a6d1af299a2702e09eec2cdfef474a node-v0.9.3-x86.msi d47f953ee97047e1202350db2b11fb880ce2809b node-v0.9.3.pkg 34b7406e1da49bf0f0967e5a084157fdf8735078 node-v0.9.3.tar.gz d0829f57b8460807cf58b2154b16176ef68189b1 node.exe 76007380d1f5cefd772b5890cd64f409ba85893e node.exp fbe95014f9f4e2c5a38bc67b75511683f4a17fa9 node.lib 8c405af98ce922bf9bd82d29723aa343f3ca5488 node.pdb 04c1dce1188f4c52adfda0bc8219c478ed6553a8 x64/node-v0.9.3-x64.msi fe6af3bd1405ecdef826a31a7c1333819aab4f3b x64/node.exe abc9afb5ac40276346072f85601bd1a9e5135856 x64/node.exp 41622dce275f0f0f740485cca8d86ba3e63c884e x64/node.lib 8c34040ba4aa916d13c8313514cf93f99f5e3e34 x64/node.pdb ``` node-v0.10.25~dfsg2/doc/blog/release/v0.8.20.md0000644000000000000000000000445212270121457017167 0ustar rootroottitle: Node v0.8.20 (Stable) slug: node-v0-8-20-stable category: release date: Fri Feb 15 11:21:42 PST 2013 version: 0.8.20 2013.02.15, Version 0.8.20 (Stable) * npm: Upgrade to v1.2.11 * http: Do not let Agent hand out destroyed sockets (isaacs) * http: Raise hangup error on destroyed socket write (isaacs) * http: protect against response splitting attacks (Bert Belder) Source Code: http://nodejs.org/dist/v0.8.20/node-v0.8.20.tar.gz Macintosh Installer (Universal): http://nodejs.org/dist/v0.8.20/node-v0.8.20.pkg Windows Installer: http://nodejs.org/dist/v0.8.20/node-v0.8.20-x86.msi Windows x64 Installer: http://nodejs.org/dist/v0.8.20/x64/node-v0.8.20-x64.msi Windows x64 Files: http://nodejs.org/dist/v0.8.20/x64/ Linux 32-bit Binary: http://nodejs.org/dist/v0.8.20/node-v0.8.20-linux-x86.tar.gz Linux 64-bit Binary: http://nodejs.org/dist/v0.8.20/node-v0.8.20-linux-x64.tar.gz Solaris 32-bit Binary: http://nodejs.org/dist/v0.8.20/node-v0.8.20-sunos-x86.tar.gz Solaris 64-bit Binary: http://nodejs.org/dist/v0.8.20/node-v0.8.20-sunos-x64.tar.gz Other release files: http://nodejs.org/dist/v0.8.20/ Website: http://nodejs.org/docs/v0.8.20/ Documentation: http://nodejs.org/docs/v0.8.20/api/ Shasums: ``` 2b87bf077022b8fa1cbcec10ea3866574fed2b75 node-v0.8.20-darwin-x64.tar.gz 42023ffbdbf36ef69250bd750f112e684eb97008 node-v0.8.20-darwin-x86.tar.gz 93480cbc67f2c757879228434bce1fd765db7df8 node-v0.8.20-linux-x64.tar.gz 7fedae5ce4b366d5dcaa7f2e770b3ff739648a51 node-v0.8.20-linux-x86.tar.gz fd66ea1bfbe5c8fe8df5ba8cc79cd3fab6e753ac node-v0.8.20-sunos-x64.tar.gz ca6ad9aa92330358f6201191347451ab42fe12cf node-v0.8.20-sunos-x86.tar.gz 200ff5e5083df2a6bb4552e673d81b498e9812f0 node-v0.8.20-x86.msi 54440b1f525da0126b434440ee6433c2b96959ae node-v0.8.20.pkg b780f58f0e3bc43d2380d4a935f2b45350783b37 node-v0.8.20.tar.gz 8e13b125c3572a1cb46364b3241405cdf7af1a82 node.exe f67ea64d6686207dbacb9bb8feacce3ac8899ec8 node.exp c338212caf48d945e8e8049c2a0c30e38e8730d6 node.lib 019b24c60cdb03f9d8209290e7af90e8565999e7 node.pdb 67fff498c5271033073a3ca9fc01178b5f5c309a x64/node-v0.8.20-x64.msi 6ecab177a47ff5c74397799b329c2359b40c7d1f x64/node.exe bcd51345c05a28be5db3553fc578aa3dd52fc97e x64/node.exp 825f2ba0bb9d7bd170adef89009b84ee147754e5 x64/node.lib 50c4cc483cc4b675966c7ec524afacb59ff99164 x64/node.pdb ``` node-v0.10.25~dfsg2/doc/blog/release/v0.8.16.md0000644000000000000000000000456312270121457017177 0ustar rootrootcategory: release version: 0.8.16 date: Thu Dec 13 08:47:52 PST 2012 title: Node v0.8.16 (Stable) slug: node-v0-8-16 2012.12.13, Version 0.8.16 (Stable) * npm: Upgrade to 1.1.69 * fs: fix WriteStream/ReadStream fd leaks (Ben Noordhuis) * crypto: fix leak in GetPeerCertificate (Fedor Indutny) * buffer: Don't double-negate numeric buffer arg (Trevor Norris) * net: More accurate IP address validation and IPv6 dotted notation. (Joshua Erickson) Source Code: http://nodejs.org/dist/v0.8.16/node-v0.8.16.tar.gz Macintosh Installer (Universal): http://nodejs.org/dist/v0.8.16/node-v0.8.16.pkg Windows Installer: http://nodejs.org/dist/v0.8.16/node-v0.8.16-x86.msi Windows x64 Installer: http://nodejs.org/dist/v0.8.16/x64/node-v0.8.16-x64.msi Windows x64 Files: http://nodejs.org/dist/v0.8.16/x64/ Linux 32-bit Binary: http://nodejs.org/dist/v0.8.16/node-v0.8.16-linux-x86.tar.gz Linux 64-bit Binary: http://nodejs.org/dist/v0.8.16/node-v0.8.16-linux-x64.tar.gz Solaris 32-bit Binary: http://nodejs.org/dist/v0.8.16/node-v0.8.16-sunos-x86.tar.gz Solaris 64-bit Binary: http://nodejs.org/dist/v0.8.16/node-v0.8.16-sunos-x64.tar.gz Other release files: http://nodejs.org/dist/v0.8.16/ Website: http://nodejs.org/docs/v0.8.16/ Documentation: http://nodejs.org/docs/v0.8.16/api/ Shasums: ``` 8ad2323e7909abaaa1e1f6eefa93a31e253acb20 node-v0.8.16-darwin-x64.tar.gz 760401fbb405f27a6f4379a999fa2408f30af9fb node-v0.8.16-darwin-x86.tar.gz 04d67913ea1ba12fbdf7460342f3b801b12cbf78 node-v0.8.16-linux-x64.tar.gz 5c5bbd485f4fd8682948e31237d7d59be708e64a node-v0.8.16-linux-x86.tar.gz 08b870e5b91b94a8b1b1564367e231b20f2ca2b9 node-v0.8.16-sunos-x64.tar.gz 72a564cab3dccb0569cbab9888f5746acb3b70f9 node-v0.8.16-sunos-x86.tar.gz b3daebf61a421aa05dff9d19e8108def951366dc node-v0.8.16-x86.msi 2a37219d45a9a2bfa63ce7a57a0c550996b52833 node-v0.8.16.pkg 6479366bfbc2b4392f7f496dec55b5ab719308c0 node-v0.8.16.tar.gz 8998022ec5d46e0d083ff3230baa638fa0c40603 node.exe 8cf330b21d8ad5c1245d6b4e668ca5fe78875c2d node.exp 107feafbbf61f7173e97be29b29f33dc96b33d4b node.lib caa002d5f0896d44a9e976d7c2f97d0e5f0fe366 node.pdb 5914d679d71a687323ff7b9232767f9df0e9d9aa x64/node-v0.8.16-x64.msi ec1debf6dfbf6051635ca9743981e35357b2af9f x64/node.exe 21216676af7d407bc70d44c35c966992b7eaab34 x64/node.exp ad443c0bf1bbf3a4d0b0a54f4f8ae7c1c235ee49 x64/node.lib fb3651dcf2c871d1fdb8b96d11d5f5db137b654c x64/node.pdb ``` node-v0.10.25~dfsg2/doc/blog/release/v0.8.15.md0000644000000000000000000000502012270121457017163 0ustar rootrootdate: Mon Nov 26 09:14:49 PST 2012 title: Node v0.8.15 (Stable) slug: node-v0-8-15 version: v0.8.15 category: release 2012.11.26, Version 0.8.15 (Stable) * npm: Upgrade to 1.1.66 (isaacs) * linux: use /proc/cpuinfo for CPU frequency (Ben Noordhuis) * windows: map WSAESHUTDOWN to UV_EPIPE (Ben Noordhuis) * windows: map ERROR_GEN_FAILURE to UV_EIO (Bert Belder) * unix: do not set environ unless one is provided (Charlie McConnell) * domains: don't crash if domain is set to null (Bert Belder) * windows: fix the x64 debug build (Bert Belder) * net, tls: fix connect() resource leak (Ben Noordhuis) Source Code: http://nodejs.org/dist/v0.8.15/node-v0.8.15.tar.gz Macintosh Installer (Universal): http://nodejs.org/dist/v0.8.15/node-v0.8.15.pkg Windows Installer: http://nodejs.org/dist/v0.8.15/node-v0.8.15-x86.msi Windows x64 Installer: http://nodejs.org/dist/v0.8.15/x64/node-v0.8.15-x64.msi Windows x64 Files: http://nodejs.org/dist/v0.8.15/x64/ Linux 32-bit Binary: http://nodejs.org/dist/v0.8.15/node-v0.8.15-linux-x86.tar.gz Linux 64-bit Binary: http://nodejs.org/dist/v0.8.15/node-v0.8.15-linux-x64.tar.gz Solaris 32-bit Binary: http://nodejs.org/dist/v0.8.15/node-v0.8.15-sunos-x86.tar.gz Solaris 64-bit Binary: http://nodejs.org/dist/v0.8.15/node-v0.8.15-sunos-x64.tar.gz Other release files: http://nodejs.org/dist/v0.8.15/ Website: http://nodejs.org/docs/v0.8.15/ Documentation: http://nodejs.org/docs/v0.8.15/api/ Shasums: ``` 084f5132d8f2ad704086285a600790c4de323e59 node-v0.8.15-darwin-x64.tar.gz 8a17c611d96aba9427de21125c2d1696e937245e node-v0.8.15-darwin-x86.tar.gz cbd126c613eb42438a63a789b380b840793b2c83 node-v0.8.15-linux-x64.tar.gz 73431db2519d4520c6f8ac7303ec6170e6eb17c6 node-v0.8.15-linux-x86.tar.gz 1ed591003d0f502131540aadbabd95c22d2d936a node-v0.8.15-sunos-x64.tar.gz 0c5908f857a65d5f6e8cfc17e4d8114aa4d9f521 node-v0.8.15-sunos-x86.tar.gz 5c5447b6ef451cfa4762db00aabd740425ea112d node-v0.8.15-x86.msi 1e06dc52609dd106fd3553f4a9d12e66bcac1f45 node-v0.8.15.pkg a7874cde1a87497992f1f8ea0fdaa760f617a94f node-v0.8.15.tar.gz 9251cc51eaa856bdf7c1a92d49419731e6dec830 node.exe e4230b867122b42a16cc27eccadde3996cfdf266 node.exp f4f7ca1d11877bcb1e50f0a139a0b7438ea406cb node.lib 02bc3e986eebb77fcabde4e492d858e14096ac34 node.pdb 9c1020cc2c7443238093f0cde3875097788e5c7f x64/node-v0.8.15-x64.msi 8a76699adbee52ee704408e6708ff5b5b6ebc02f x64/node.exe b9fba72a0da7d2b25dcdcbcf514b877f1cb6399a x64/node.exp 81511b51ef403214f0ba97ed29cb5d45ff6a21f7 x64/node.lib 1519acd77acd41e03238f6ed9a006d97ade4a055 x64/node.pdb ``` node-v0.10.25~dfsg2/doc/blog/release/node-v0-4-11.md0000644000000000000000000000277212270121457020107 0ustar rootrootversion: 0.4.11 title: Node v0.4.11 author: ryandahl date: Thu Aug 18 2011 01:44:42 GMT-0700 (PDT) status: publish category: release slug: node-v0-4-11 2011.08.17, Version 0.4.11 (stable)
    • #738 Fix crypto encryption/decryption with Base64. (SAWADA Tadashi)
    • #1202 net.createConnection defer DNS lookup error events to next tick (Ben Noordhuis)
    • #1374 fix setting ServerResponse.statusCode in writeHead (Trent Mick)
    • #1417 Fix http.ClientRequest crashes if end() was called twice
    • #1497 querystring: Replace 'in' test with 'hasOwnProperty' (isaacs)
    • #1546 http perf improvement
    • fix memleak in libeio (Tom Hughes)
    • cmake improvements (Tom Hughes)
    • node_net.cc: fix incorrect sizeof() (Tom Hughes)
    • Windows/cygwin: no more GetConsoleTitleW errors on XP (Bert Belder)
    • Doc improvements (koichik, Logan Smyth, Ben Noordhuis, Arnout Kazemier)
    Download: http://nodejs.org/dist/node-v0.4.11.tar.gz Website: http://nodejs.org/docs/v0.4.11/ Documentation: http://nodejs.org/docs/v0.4.11/api/ node-v0.10.25~dfsg2/doc/blog/release/version-0-6-12-stable.md0000644000000000000000000000430312270121457021724 0ustar rootrootversion: 0.6.12 title: Version 0.6.12 (stable) author: Isaac Schlueter date: Fri Mar 02 2012 13:22:49 GMT-0800 (PST) status: publish category: release slug: version-0-6-12-stable

    2012.03.02 Version 0.6.12 (stable)

    • Upgrade V8 to 3.6.6.24

    • dtrace ustack helper improvements (Dave Pacheco)

    • API Documentation refactor (isaacs)

    • #2827 net: fix race write() before and after connect() (koichik)

    • #2554 #2567 throw if fs args for 'start' or 'end' are strings (AJ ONeal)

    • punycode: Update to v1.0.0 (Mathias Bynens)

    • Make a fat binary for the OS X pkg (isaacs)

    • Fix hang on accessing process.stdin (isaacs)

    • repl: make tab completion work on non-objects (Nathan Rajlich)

    • Fix fs.watch on OS X (Ben Noordhuis)

    • Fix #2515 nested setTimeouts cause premature process exit (Ben Noordhuis)

    • windows: fix time conversion in stat (Igor Zinkovsky)

    • windows: fs: handle EOF in read (Brandon Philips)

    • windows: avoid IOCP short-circuit on non-ifs lsps (Igor Zinkovsky)

    • Upgrade npm to 1.1.4 (isaacs)

      - windows fixes
      - Bundle nested bundleDependencies properly
      - install: support --save with url install targets
      - shrinkwrap: behave properly with url-installed modules
      - support installing uncompressed tars or single file modules from urls etc.
      - don't run make clean on rebuild
      - support HTTPS-over-HTTP proxy tunneling

    Source Code: http://nodejs.org/dist/v0.6.12/node-v0.6.12.tar.gz

    Windows Installer: http://nodejs.org/dist/v0.6.12/node-v0.6.12.msi

    Macintosh Installer: http://nodejs.org/dist/v0.6.12/node-v0.6.12.pkg

    Website: http://nodejs.org/docs/v0.6.12/

    Documentation: http://nodejs.org/docs/v0.6.12/api/

    node-v0.10.25~dfsg2/doc/blog/release/version-0-6-11-stable.md0000644000000000000000000000452312270121457021727 0ustar rootrootversion: 0.6.11 title: Version 0.6.11 (stable) author: Isaac Schlueter date: Fri Feb 17 2012 13:32:55 GMT-0800 (PST) status: publish category: release slug: version-0-6-11-stable

    2012.02.17 Version 0.6.11 (stable)

    • http: allow multiple WebSocket RFC6455 headers (Einar Otto Stangvik)

    • http: allow multiple WWW-Authenticate headers (Ben Noordhuis)

    • windows: support unicode argv and environment variables (Bert Belder)

    • tls: mitigate session renegotiation attacks (Ben Noordhuis)

    • tcp, pipe: don't assert on uv_accept() errors (Ben Noordhuis)

    • tls: Allow establishing secure connection on the existing socket (koichik)

    • dgram: handle close of dgram socket before DNS lookup completes (Seth Fitzsimmons)

    • windows: Support half-duplex pipes (Igor Zinkovsky)

    • build: disable omit-frame-pointer on solaris systems (Dave Pacheco)

    • debugger: fix --debug-brk (Ben Noordhuis)

    • net: fix large file downloads failing (koichik)

    • fs: fix ReadStream failure to read from existing fd (Christopher Jeffrey)

    • net: destroy socket on DNS error (Stefan Rusu)

    • dtrace: add missing translator (Dave Pacheco)

    • unix: don't flush tty on switch to raw mode (Ben Noordhuis)

    • windows: reset brightness when reverting to default text color (Bert Belder)

    • npm: update to 1.1.1

      - Update which, fstream, mkdirp, request, and rimraf
      - Fix #2123 Set path properly for lifecycle scripts on windows
      - Mark the root as seen, so we don't recurse into it. Fixes #1838. (Martin Cooper)

    Source Code: http://nodejs.org/dist/v0.6.11/node-v0.6.11.tar.gz

    Windows Installer: http://nodejs.org/dist/v0.6.11/node-v0.6.11.msi

    Macintosh Installer: http://nodejs.org/dist/v0.6.11/node-v0.6.11.pkg

    Website: http://nodejs.org/docs/v0.6.11/

    Documentation: http://nodejs.org/docs/v0.6.11/api/

    node-v0.10.25~dfsg2/doc/blog/release/node-v0-4-7.md0000644000000000000000000000157112270121457020030 0ustar rootrootversion: 0.4.7 title: Node v0.4.7 author: ryandahl date: Sat Apr 23 2011 00:47:55 GMT-0700 (PDT) status: publish category: release slug: node-v0-4-7 2011.04.22, Version 0.4.7 (stable)
    • Don't emit error on ECONNRESET from read() #670
    • Fix: Multiple pipes to the same stream were broken #929 (Felix Geisendörfer)
    • URL parsing/formatting corrections #954 (isaacs)
    • make it possible to do repl.start('', stream) (Wade Simmons)
    • Add os.loadavg for SunOS (Robert Mustacchi)
    • Fix timeouts with floating point numbers #897 (Jorge Chamorro Bieling)
    • Improve docs.
    Download: http://nodejs.org/dist/node-v0.4.7.tar.gz Website: http://nodejs.org/docs/v0.4.7/ Documentation: http://nodejs.org/docs/v0.4.7/api node-v0.10.25~dfsg2/doc/blog/release/v0.8.17.md0000644000000000000000000000574212270121457017200 0ustar rootrootdate: Wed Jan 9 17:06:36 PST 2013 title: Node v0.8.17 (Stable) slug: node-v0-8-17-stable category: release version: 0.8.17 This release addresses a potential security vulnerability. If you do not use TypedArrays, then you're fine (but should still upgrade for other reasons, like better performance and npm peerDependencies.) If you use TypedArrays, you should upgrade to v0.8.17 as soon as possible. If user input can affect the size parameter in a TypedArray, an integer overflow vulnerability could allow an attacker to write to areas of memory outside the intended buffer. Please upgrade ASAP. 2013.01.09, Version 0.8.17 (Stable) * npm: Upgrade to v1.2.0 - peerDependencies (Domenic Denicola) - node-gyp v0.8.2 (Nathan Rajlich) - Faster installs from github user/project shorthands (Nathan Zadoks) * typed arrays: fix 32 bit size/index overflow (Ben Noordhuis) * http: Improve performance of single-packet responses (Ben Noordhuis) * install: fix openbsd man page location (Ben Noordhuis) * http: bubble up parser errors to ClientRequest (Brian White) Source Code: http://nodejs.org/dist/v0.8.17/node-v0.8.17.tar.gz Macintosh Installer (Universal): http://nodejs.org/dist/v0.8.17/node-v0.8.17.pkg Windows Installer: http://nodejs.org/dist/v0.8.17/node-v0.8.17-x86.msi Windows x64 Installer: http://nodejs.org/dist/v0.8.17/x64/node-v0.8.17-x64.msi Windows x64 Files: http://nodejs.org/dist/v0.8.17/x64/ Linux 32-bit Binary: http://nodejs.org/dist/v0.8.17/node-v0.8.17-linux-x86.tar.gz Linux 64-bit Binary: http://nodejs.org/dist/v0.8.17/node-v0.8.17-linux-x64.tar.gz Solaris 32-bit Binary: http://nodejs.org/dist/v0.8.17/node-v0.8.17-sunos-x86.tar.gz Solaris 64-bit Binary: http://nodejs.org/dist/v0.8.17/node-v0.8.17-sunos-x64.tar.gz Other release files: http://nodejs.org/dist/v0.8.17/ Website: http://nodejs.org/docs/v0.8.17/ Documentation: http://nodejs.org/docs/v0.8.17/api/ Shasums: ``` 1efb55f154e6079c7f2a8991ed73b5069307576a node-v0.8.17-darwin-x64.tar.gz d9e3f502b9121b14743fedc7d48ed15cbda3a3da node-v0.8.17-darwin-x86.tar.gz de5d5d32ef97081b57b652289e097a332e9cc8af node-v0.8.17-linux-x64.tar.gz 44824481dbb3ed278e613f805f597e8d14f68d11 node-v0.8.17-linux-x86.tar.gz 6f3ee5e3a3515f79478c18ad61666bdaf73f8485 node-v0.8.17-sunos-x64.tar.gz 3bcd62169201e8c6223eeef09633998901692da1 node-v0.8.17-sunos-x86.tar.gz befea571ebdf67fa47ef84826334599feb3ed7a3 node-v0.8.17-x86.msi 71b598cd3a418b8ce78a2158d8ae29a6c7e66be6 node-v0.8.17.pkg 65d22e4e183cee8888c797300d8fdbb5c530c740 node-v0.8.17.tar.gz 8bf4e9699d41bcc0fcf822af095c2a944aea3e95 node.exe 2b659a6864682d6613a94a8c187618a3893401bc node.exp 082995b6fc667af51aae11b612390800c8e9636c node.lib bbbab14038a29fa67dfcabfd27802c39428e8f8e node.pdb a220542df0610d848ead007673e19cb24c1e0ac5 x64/node-v0.8.17-x64.msi 636ab1f211624588d3c5073232f30aa5f93eed10 x64/node.exe 8540c7b6cfb62b51b52c72813ca30d42b936e656 x64/node.exp 1e0d70fcf5efa6e4c23c1d8ec768c5a8e6c36874 x64/node.lib 2b13ba57dbdd942b3198b441fea936f8b8154c29 x64/node.pdb ``` node-v0.10.25~dfsg2/doc/blog/release/v0.10.17.md0000644000000000000000000000756712270121457017260 0ustar rootrootdate: Wed Aug 21 16:37:31 PDT 2013 version: 0.10.17 category: release title: Node v0.10.17 (Stable) slug: node-v0-10-17-stable 2013.08.21, Version 0.10.17 (Stable) * uv: Upgrade v0.10.14 * http_parser: Do not accept PUN/GEM methods as PUT/GET (Chris Dickinson) * tls: fix assertion when ssl is destroyed at read (Fedor Indutny) * stream: Throw on 'error' if listeners removed (isaacs) * dgram: fix assertion on bad send() arguments (Ben Noordhuis) * readline: pause stdin before turning off terminal raw mode (Daniel Chatfield) Source Code: http://nodejs.org/dist/v0.10.17/node-v0.10.17.tar.gz Macintosh Installer (Universal): http://nodejs.org/dist/v0.10.17/node-v0.10.17.pkg Windows Installer: http://nodejs.org/dist/v0.10.17/node-v0.10.17-x86.msi Windows x64 Installer: http://nodejs.org/dist/v0.10.17/x64/node-v0.10.17-x64.msi Windows x64 Files: http://nodejs.org/dist/v0.10.17/x64/ Linux 32-bit Binary: http://nodejs.org/dist/v0.10.17/node-v0.10.17-linux-x86.tar.gz Linux 64-bit Binary: http://nodejs.org/dist/v0.10.17/node-v0.10.17-linux-x64.tar.gz Solaris 32-bit Binary: http://nodejs.org/dist/v0.10.17/node-v0.10.17-sunos-x86.tar.gz Solaris 64-bit Binary: http://nodejs.org/dist/v0.10.17/node-v0.10.17-sunos-x64.tar.gz Other release files: http://nodejs.org/dist/v0.10.17/ Website: http://nodejs.org/docs/v0.10.17/ Documentation: http://nodejs.org/docs/v0.10.17/api/ Shasums: ``` 8502c5ec4878154b5896fca6a14ff6c83c3774a1 node-v0.10.17-darwin-x64.tar.gz 6d785ae86ea050159dfd85841a4faac830be8a2a node-v0.10.17-darwin-x86.tar.gz 244dc1a25dcd2cc252ae9315bb2da07b41381c5c node-v0.10.17-linux-x64.tar.gz 109c32b514fab374b73972dda4f4d27a33e20d5d node-v0.10.17-linux-x86.tar.gz 2e046a6e05520c7be941365830517db90b791999 node-v0.10.17-sunos-x64.tar.gz 907d73aa0e84717c342327265f0b665d09b50154 node-v0.10.17-sunos-x86.tar.gz ac8f653545b58d009e19522e3ead8886d151b59d node-v0.10.17-x86.msi 32f160364990489e1f79593e1cdcea9dfde28125 node-v0.10.17.pkg c9d31d5415d2cf7a09fd7abebf9f01259e9dd93b node-v0.10.17.tar.gz 33a5e3a86c391fc30080e796c46a74cefbd9104c node.exe 004ebfa938b3f14984b964dcaba061d10c32f12c node.exp 3dd092b26c742f20006fc2085b329a3e32d8e3d9 node.lib a8d997936e240626c56df8c6c8d55b659003a644 node.pdb 165fecaab04a09a4df6b731f0e4b264bdb281644 pkgsrc/nodejs-ia32-0.10.17.tgz 0c813098a93090823b513147de7f41f920dd8569 pkgsrc/nodejs-x64-0.10.17.tgz 3cf665ad6c8f7d3040c2bfea8791f77c40c8f2a0 x64/node-v0.10.17-x64.msi 95baf773a34f85014eb67d026b7b9cd0396f96f5 x64/node.exe ebdbcea161d44368c224fce448bf3d85e5a54f21 x64/node.exp 49d12cb3d5be6f6707b7f5c89952f81bddb69a68 x64/node.lib 0c0ef15eb6705c81137187c597cb0105bd2bc352 x64/node.pdb ``` Shasums: ``` 8502c5ec4878154b5896fca6a14ff6c83c3774a1 node-v0.10.17-darwin-x64.tar.gz 6d785ae86ea050159dfd85841a4faac830be8a2a node-v0.10.17-darwin-x86.tar.gz 244dc1a25dcd2cc252ae9315bb2da07b41381c5c node-v0.10.17-linux-x64.tar.gz 109c32b514fab374b73972dda4f4d27a33e20d5d node-v0.10.17-linux-x86.tar.gz 2e046a6e05520c7be941365830517db90b791999 node-v0.10.17-sunos-x64.tar.gz 907d73aa0e84717c342327265f0b665d09b50154 node-v0.10.17-sunos-x86.tar.gz ac8f653545b58d009e19522e3ead8886d151b59d node-v0.10.17-x86.msi 32f160364990489e1f79593e1cdcea9dfde28125 node-v0.10.17.pkg c9d31d5415d2cf7a09fd7abebf9f01259e9dd93b node-v0.10.17.tar.gz 33a5e3a86c391fc30080e796c46a74cefbd9104c node.exe 004ebfa938b3f14984b964dcaba061d10c32f12c node.exp 3dd092b26c742f20006fc2085b329a3e32d8e3d9 node.lib a8d997936e240626c56df8c6c8d55b659003a644 node.pdb 165fecaab04a09a4df6b731f0e4b264bdb281644 pkgsrc/nodejs-ia32-0.10.17.tgz 0c813098a93090823b513147de7f41f920dd8569 pkgsrc/nodejs-x64-0.10.17.tgz 3cf665ad6c8f7d3040c2bfea8791f77c40c8f2a0 x64/node-v0.10.17-x64.msi 95baf773a34f85014eb67d026b7b9cd0396f96f5 x64/node.exe ebdbcea161d44368c224fce448bf3d85e5a54f21 x64/node.exp 49d12cb3d5be6f6707b7f5c89952f81bddb69a68 x64/node.lib 0c0ef15eb6705c81137187c597cb0105bd2bc352 x64/node.pdb ``` node-v0.10.25~dfsg2/doc/blog/release/v0.8.8.md0000644000000000000000000000521312270121457017111 0ustar rootrootversion: 0.8.8 title: Version 0.8.8 (stable) category: release slug: node-v0-8-8-stable date: 2012-08-22T19:50:38.833Z 2012.08.22, Version 0.8.8 (Stable) * V8: upgrade to 3.11.10.19 * npm: upgrade to 1.1.59 * windows: fix uninitialized memory access in uv_update_time() (Bert Belder) * unix, windows: fix memory corruption in fs-poll.c (Ben Noordhuis) * unix: fix integer overflow in uv_hrtime (Tim Holy) * sunos: fix uv_cpu_info() on x86_64 (Ben Noordhuis) * tls: update default cipher list (Ben Noordhuis) * unix: Fix llvm and older gcc duplicate symbol warnings (Bert Belder) * fs: fix use after free in stat watcher (Ben Noordhuis) * build: Fix using manually compiled gcc on OS X (Nathan Rajlich) * windows: make junctions work again (Bert Belder) Source Code: http://nodejs.org/dist/v0.8.8/node-v0.8.8.tar.gz Macintosh Installer (Universal): http://nodejs.org/dist/v0.8.8/node-v0.8.8.pkg Windows Installer: http://nodejs.org/dist/v0.8.8/node-v0.8.8-x86.msi Windows x64 Installer: http://nodejs.org/dist/v0.8.8/x64/node-v0.8.8-x64.msi Windows x64 Files: http://nodejs.org/dist/v0.8.8/x64/ Linux 32-bit Binary: http://nodejs.org/dist/v0.8.8/node-v0.8.8-linux-x86.tar.gz Linux 64-bit Binary: http://nodejs.org/dist/v0.8.8/node-v0.8.8-linux-x64.tar.gz SunOS 32-bit Binary: http://nodejs.org/dist/v0.8.8/node-v0.8.8-sunos-x86.tar.gz SunOS 64-bit Binary: http://nodejs.org/dist/v0.8.8/node-v0.8.8-sunos-x64.tar.gz Other release files: http://nodejs.org/dist/v0.8.8/ Website: http://nodejs.org/docs/v0.8.8/ Documentation: http://nodejs.org/docs/v0.8.8/api/ Shasums: ``` ecf54d3aad371621446ee0432f7c182a4494a1a3 node-v0.8.8-darwin-x64.tar.gz d1aca7c797fd262e2f0c601fe5cc3815622ce801 node-v0.8.8-darwin-x86.tar.gz 603c36611c54651c149a26dc5bc6f833b0b846d0 node-v0.8.8-linux-x64.tar.gz 30c66fc26845b14ef99d3e043bb4dfcba605bd45 node-v0.8.8-linux-x86.tar.gz cd0d46d232d882dd4afe955bd8acd6c435c2f5fe node-v0.8.8-sunos-x64.tar.gz 857facbd156d4f7a49b9e1c5610b4a1f893bf534 node-v0.8.8-sunos-x86.tar.gz bb08591a6f973f3699085abb50f6bdc9586f01f9 node-v0.8.8-x86.msi 14239f6f379953405ca914b129c19b379718ba64 node-v0.8.8.pkg 5ddafc059d2f774e35e6375f5b61157879a46f0f node-v0.8.8.tar.gz 6cc8a0a363c1efa184f6b72970a5d1182b5b44aa node.exe 395c73c055886e2e981b46f3c363837613456d82 node.exp ca8a9560b3da13ecddbbc2fb15c1b3ab85d7371b node.lib b8e0e35b0ecc7c3514ad8ca4549c57dd8a221be4 node.pdb b604a56a236f632cdf55c366a882d3ecb2312fba x64/node-v0.8.8-x64.msi e80c1f4791e80243c5ddc7ea1e92ebd58fc4e10f x64/node.exe 8baf5b459e7f2074e0237d40c8c80e89b47660a3 x64/node.exp 4448fc2bfef66b7334016c0ab2e118c1cbc8544c x64/node.lib 0ddddf2c2fcd746827863b2454ddb4a8f6c3844e x64/node.pdb ``` node-v0.10.25~dfsg2/doc/blog/release/version-0-6-16-stable.md0000644000000000000000000000367112270121457021737 0ustar rootrootversion: 0.6.16 title: Version 0.6.16 (stable) author: Isaac Schlueter date: Mon Apr 30 2012 11:13:50 GMT-0700 (PDT) status: publish category: release slug: version-0-6-16-stable

    2012.04.30 Version 0.6.16 (stable)

    • Upgrade V8 to 3.6.6.25

    • Upgrade npm to 1.1.18

    • Windows: add mappings for UV_ENOENT (Bert Belder)

    • linux: add IN_MOVE_SELF to inotify event mask (Ben Noordhuis)

    • unix: call pipe handle connection cb on accept() error (Ben Noordhuis)

    • unix: handle EWOULDBLOCK (Ben Noordhuis)

    • map EWOULDBLOCK to UV_EAGAIN (Ben Noordhuis)

    • Map ENOMEM to UV_ENOMEM (isaacs)

    • Child process: support the gid and uid options (Bert Belder)

    • test: cluster: add worker death event test (Ben Noordhuis)

    • typo in node_http_parser (isaacs)

    • http_parser: Eat CRLF between requests, even on connection:close. (Ben Noordhuis)

    • don't check return value of unsetenv (Ben Noordhuis)

    Source Code: http://nodejs.org/dist/v0.6.16/node-v0.6.16.tar.gz

    Windows Installer: http://nodejs.org/dist/v0.6.16/node-v0.6.16.msi

    Windows x64 Files: http://nodejs.org/dist/v0.6.16/x64/

    Macintosh Installer (Universal): http://nodejs.org/dist/v0.6.16/node-v0.6.16.pkg

    Other release files: http://nodejs.org/dist/v0.6.16/

    Website: http://nodejs.org/docs/v0.6.16/

    Documentation: http://nodejs.org/docs/v0.6.16/api/

    node-v0.10.25~dfsg2/doc/blog/release/v0.10.16.md0000644000000000000000000000541012270121457017240 0ustar rootrootdate: Fri Aug 16 12:45:21 PDT 2013 version: 0.10.16 category: release title: Node v0.10.16 (Stable) slug: node-v0-10-16-stable 2013.08.16, Version 0.10.16 (Stable) * v8: back-port fix for CVE-2013-2882 * npm: Upgrade to 1.3.8 * crypto: fix assert() on malformed hex input (Ben Noordhuis) * crypto: fix memory leak in randomBytes() error path (Ben Noordhuis) * events: fix memory leak, don't leak event names (Ben Noordhuis) * http: Handle hex/base64 encodings properly (isaacs) * http: improve chunked res.write(buf) performance (Ben Noordhuis) * stream: Fix double pipe error emit (Eran Hammer) Source Code: http://nodejs.org/dist/v0.10.16/node-v0.10.16.tar.gz Macintosh Installer (Universal): http://nodejs.org/dist/v0.10.16/node-v0.10.16.pkg Windows Installer: http://nodejs.org/dist/v0.10.16/node-v0.10.16-x86.msi Windows x64 Installer: http://nodejs.org/dist/v0.10.16/x64/node-v0.10.16-x64.msi Windows x64 Files: http://nodejs.org/dist/v0.10.16/x64/ Linux 32-bit Binary: http://nodejs.org/dist/v0.10.16/node-v0.10.16-linux-x86.tar.gz Linux 64-bit Binary: http://nodejs.org/dist/v0.10.16/node-v0.10.16-linux-x64.tar.gz Solaris 32-bit Binary: http://nodejs.org/dist/v0.10.16/node-v0.10.16-sunos-x86.tar.gz Solaris 64-bit Binary: http://nodejs.org/dist/v0.10.16/node-v0.10.16-sunos-x64.tar.gz Other release files: http://nodejs.org/dist/v0.10.16/ Website: http://nodejs.org/docs/v0.10.16/ Documentation: http://nodejs.org/docs/v0.10.16/api/ Shasums: ``` c76d0cac292784dcff16642e5b8e9b6e50bd2d1f node-v0.10.16-darwin-x64.tar.gz 0405727606cc0bfd86fe16226235d6a17cf03524 node-v0.10.16-darwin-x86.tar.gz f651398c19cc56915c996660c8977a1da3c5cfaa node-v0.10.16-linux-arm-pi.tar.gz 784ac3b09eedc9ea2eda6d9bc8f7dd9760f40002 node-v0.10.16-linux-x64.tar.gz 8628a9679b0dd8b5521eb7009751f501b10db924 node-v0.10.16-linux-x86.tar.gz 49ebccdd4cf1b2433f64caf6430c0be050bf843c node-v0.10.16-sunos-x64.tar.gz caf9d90e133e02f041f50056fa2be6575c606923 node-v0.10.16-sunos-x86.tar.gz 85ed82a3f0ce7fbdc6875b7d7b35474ff52ae76a node-v0.10.16-x86.msi 9e993cf61047dd5c1c1736ce372c90d184b55616 node-v0.10.16.pkg 646fd7ce38091ec9bd0c5d080a9da522edaabff7 node-v0.10.16.tar.gz 2eab45f17ad076d73c699e0b7029ef2ccb902cd6 node.exe 7f9b2b152aeb31d99f9cb728475852dcf08e4e42 node.exp 17dabe6f59c2216170c37192ce709636d9458ce8 node.lib 1b0488a644f3c45010f1da2f0fbd6915f55c646e node.pdb c1535895c7f1b12e08432d9e7d760fa45d185013 pkgsrc/nodejs-ia32-0.10.16.tgz 68d9af8ea312603a483a15c057ccdffd39fe5ea4 pkgsrc/nodejs-x64-0.10.16.tgz de4511ff2319f2b2e72664f0fa5cdbb97a79ca51 x64/node-v0.10.16-x64.msi fd35dfd384a111dc52c8563125cdbe69577276b0 x64/node.exe 69b9866f0059fb7c6319d1f9bbea3886a27f29f5 x64/node.exp 6e19ddfb75eaeb41b4c18769b20ca6de997b5cd6 x64/node.lib 9e6b02883df774732ed1131c19e762cb309db917 x64/node.pdb ``` node-v0.10.25~dfsg2/doc/blog/release/v0.10.3.md0000644000000000000000000000532312270121457017157 0ustar rootrootdate: Wed Apr 3 11:24:08 PDT 2013 version: 0.10.3 category: release title: Node v0.10.3 (Stable) slug: node-v0-10-3-stable 2013.04.03, Version 0.10.3 (Stable) * npm: Upgrade to 1.2.17 * child_process: acknowledge sent handles (Fedor Indutny) * etw: update prototypes to match dtrace provider (Timothy J Fontaine) * dtrace: pass more arguments to probes (Dave Pacheco) * build: allow building with dtrace on osx (Dave Pacheco) * http: Remove legacy ECONNRESET workaround code (isaacs) * http: Ensure socket cleanup on client response end (isaacs) * tls: Destroy socket when encrypted side closes (isaacs) * repl: isSyntaxError() catches "strict mode" errors (Nathan Rajlich) * crypto: Pass options to ctor calls (isaacs) * src: tie process.versions.uv to uv_version_string() (Ben Noordhuis) Source Code: http://nodejs.org/dist/v0.10.3/node-v0.10.3.tar.gz Macintosh Installer (Universal): http://nodejs.org/dist/v0.10.3/node-v0.10.3.pkg Windows Installer: http://nodejs.org/dist/v0.10.3/node-v0.10.3-x86.msi Windows x64 Installer: http://nodejs.org/dist/v0.10.3/x64/node-v0.10.3-x64.msi Windows x64 Files: http://nodejs.org/dist/v0.10.3/x64/ Linux 32-bit Binary: http://nodejs.org/dist/v0.10.3/node-v0.10.3-linux-x86.tar.gz Linux 64-bit Binary: http://nodejs.org/dist/v0.10.3/node-v0.10.3-linux-x64.tar.gz Solaris 32-bit Binary: http://nodejs.org/dist/v0.10.3/node-v0.10.3-sunos-x86.tar.gz Solaris 64-bit Binary: http://nodejs.org/dist/v0.10.3/node-v0.10.3-sunos-x64.tar.gz Other release files: http://nodejs.org/dist/v0.10.3/ Website: http://nodejs.org/docs/v0.10.3/ Documentation: http://nodejs.org/docs/v0.10.3/api/ Shasums: ``` 9b2f0936ee60aa65f6a5053e82440508aa9be0a7 node-v0.10.3-darwin-x64.tar.gz f0392db831ca58c1f7b2d857d7e8cc601ea8b022 node-v0.10.3-darwin-x86.tar.gz 9a375e77f9994fbd4afd741bae64c548f2a43a64 node-v0.10.3-linux-x64.tar.gz 3323da517271e45a3850b169b10ef3d254a263a9 node-v0.10.3-linux-x86.tar.gz 0026e2453a3940ed16b9569b8187943ccf0aeb45 node-v0.10.3-sunos-x64.tar.gz af88ad2dc98368b36f1aafc7b79f8378169fc56e node-v0.10.3-sunos-x86.tar.gz e057c8841ddbe4dc8bc155a28b7e07dbe3d108d1 node-v0.10.3-x86.msi a37575d47de5696b8abb2e12dc3e9d0cdb5d17f6 node-v0.10.3.pkg 4a1feb4ac18ede9e7193921f59fc181c88b1c7ba node-v0.10.3.tar.gz 9d9266d1e69bfe24837c67ff755f055fd049cd48 node.exe 8762416a5e0d71e285215efde181c7242f3f2c6f node.exp 5c05f332070a77900010f15c1074c4e86e20fa0d node.lib a8dc61535f6ae5fd13bce9cdca989ffc113a4080 node.pdb b834751b2e9f18e6ef38cf9fe5331e6073e3cab2 x64/node-v0.10.3-x64.msi 932c30a53f546717f00de063ee09fc8ce603dd2a x64/node.exe a3e91038e027c91a555116d2c20742eea2e9378f x64/node.exp d60bb0f9026df9dcc17cff0267964032aaf46712 x64/node.lib f645a2d63179ae749defe13c653cf1777dd9021a x64/node.pdb ``` node-v0.10.25~dfsg2/doc/blog/release/v0.11.8.md0000644000000000000000000000642112270121457017165 0ustar rootrootdate: Wed Oct 30 08:54:47 PDT 2013 version: 0.11.8 category: release title: Node v0.11.8 (Unstable) slug: node-v0-11-8-unstable 2013.10.30, Version 0.11.8 (Unstable) * uv: Upgrade to v0.11.14 * v8: upgrade 3.21.18.3 * assert: indicate if exception message is generated (Glen Mailer) * buffer: add buf.toArrayBuffer() API (Trevor Norris) * cluster: fix premature 'disconnect' event (Ben Noordhuis) * crypto: add SPKAC support (Jason Gerfen) * debugger: count space for line numbers correctly (Alex Kocharin) * debugger: make busy loops SIGUSR1-interruptible (Ben Noordhuis) * debugger: repeat last command (Alex Kocharin) * debugger: show current line, fix for #6150 (Alex Kocharin) * dgram: send() can accept strings (Trevor Norris) * dns: rename domain to hostname (Ben Noordhuis) * dns: set hostname property on error object (Ben Noordhuis) * dtrace, mdb_v8: support more string, frame types (Dave Pacheco) * http: add statusMessage (Patrik Stutz) * http: expose supported methods (Ben Noordhuis) * http: provide backpressure for pipeline flood (isaacs) * process: Add exitCode property (isaacs) * tls: socket.renegotiate(options, callback) (Fedor Indutny) * util: format as Error if instanceof Error (Rod Vagg) Source Code: http://nodejs.org/dist/v0.11.8/node-v0.11.8.tar.gz Macintosh Installer (Universal): http://nodejs.org/dist/v0.11.8/node-v0.11.8.pkg Windows Installer: http://nodejs.org/dist/v0.11.8/node-v0.11.8-x86.msi Windows x64 Installer: http://nodejs.org/dist/v0.11.8/x64/node-v0.11.8-x64.msi Windows x64 Files: http://nodejs.org/dist/v0.11.8/x64/ Linux 32-bit Binary: http://nodejs.org/dist/v0.11.8/node-v0.11.8-linux-x86.tar.gz Linux 64-bit Binary: http://nodejs.org/dist/v0.11.8/node-v0.11.8-linux-x64.tar.gz Solaris 32-bit Binary: http://nodejs.org/dist/v0.11.8/node-v0.11.8-sunos-x86.tar.gz Solaris 64-bit Binary: http://nodejs.org/dist/v0.11.8/node-v0.11.8-sunos-x64.tar.gz Other release files: http://nodejs.org/dist/v0.11.8/ Website: http://nodejs.org/docs/v0.11.8/ Documentation: http://nodejs.org/docs/v0.11.8/api/ Shasums: ``` 1911bc1407fd116318edaa0cfd01bd664b2b352c node-v0.11.8-darwin-x64.tar.gz bac43c31e257e9f2deffb08c4154f522d5925825 node-v0.11.8-darwin-x86.tar.gz 1b2dac1788f3aad51ec643854ae57771792e6647 node-v0.11.8-linux-x64.tar.gz 1f674dd1ac15561dbf99ecf80d00e2cfcdc1a23b node-v0.11.8-linux-x86.tar.gz 51d29f3624b18e75cf5736eedd62a55931551251 node-v0.11.8-sunos-x64.tar.gz b995b05a3b14373c61faf4cd5c05157e06f410c8 node-v0.11.8-sunos-x86.tar.gz 5f6fd1f68d9f61c889c7a0148a6bfbb681a119b5 node-v0.11.8-x86.msi 95097ea074fa1b20c3bd46eae33a24935842149b node-v0.11.8.pkg 21d3927c78adaaf3fe7cc9602ffb0a85de7f6ea0 node-v0.11.8.tar.gz f735cf8b6404428087ba759dc21818b4d968e2ba node.exe c632e716ac2b303a4e2f3e0c81819b4020c9e0df node.exp dea16a4911693689c3981e19ae2fa77ea2884797 node.lib 0a5bfce12045512b1f4a0341d1381459e9731321 node.pdb 25b8d468c1ef53332834a46aaae0ee1820771871 pkgsrc/nodejs-ia32-0.11.8.tgz fb16a45a0a467aa7661048a3d00d4e81c35bbf56 pkgsrc/nodejs-x64-0.11.8.tgz b4b2c453404f5aa0d37fbce5d55ac1e030f3e7cc x64/node-v0.11.8-x64.msi 799da7eb400d91b7eec157d25da0e138630f27e4 x64/node.exe 6482cce41d8a98ba55daaccc581929df018f2edf x64/node.exp 7e2bb85b6ca45c4df487b9cca7d420e87170b272 x64/node.lib 1aa3a1f9d767e81dbdd1af1d13f221830c467d68 x64/node.pdb ``` node-v0.10.25~dfsg2/doc/blog/release/v0.8.23.md0000644000000000000000000000500512270121457017165 0ustar rootrootdate: Mon Apr 8 17:32:26 PDT 2013 version: 0.8.23 category: release title: Node v0.8.23 (Legacy) slug: node-v0-8-23-legacy 2013.04.09, Version 0.8.23 (Legacy) * npm: Upgrade to v1.2.18 * http: Avoid EE warning on ECONNREFUSED handling (isaacs) * tls: Re-enable check of CN-ID in cert verification (Tobias Müllerleile) * child_process: fix sending utf-8 to child process (Ben Noordhuis) * crypto: check key type in GetPeerCertificate() (Ben Noordhuis) * win/openssl: mark assembled object files as seh safe (Bert Belder) * windows/msi: fix msi build issue with WiX 3.7/3.8 (Raymond Feng) Source Code: http://nodejs.org/dist/v0.8.23/node-v0.8.23.tar.gz Macintosh Installer (Universal): http://nodejs.org/dist/v0.8.23/node-v0.8.23.pkg Windows Installer: http://nodejs.org/dist/v0.8.23/node-v0.8.23-x86.msi Windows x64 Installer: http://nodejs.org/dist/v0.8.23/x64/node-v0.8.23-x64.msi Windows x64 Files: http://nodejs.org/dist/v0.8.23/x64/ Linux 32-bit Binary: http://nodejs.org/dist/v0.8.23/node-v0.8.23-linux-x86.tar.gz Linux 64-bit Binary: http://nodejs.org/dist/v0.8.23/node-v0.8.23-linux-x64.tar.gz Solaris 32-bit Binary: http://nodejs.org/dist/v0.8.23/node-v0.8.23-sunos-x86.tar.gz Solaris 64-bit Binary: http://nodejs.org/dist/v0.8.23/node-v0.8.23-sunos-x64.tar.gz Other release files: http://nodejs.org/dist/v0.8.23/ Website: http://nodejs.org/docs/v0.8.23/ Documentation: http://nodejs.org/docs/v0.8.23/api/ Shasums: ``` 64cf0081e4d5d7ac528ce938007f9a7d3d952896 node-v0.8.23-darwin-x64.tar.gz 698b9dd9ece94cde200c25d881700a23a510883e node-v0.8.23-darwin-x86.tar.gz 94ea21cb5425d712b92289a82e0f48541d163fef node-v0.8.23-linux-x64.tar.gz c6880d51464904d782d6438bb451fdc85cb874eb node-v0.8.23-linux-x86.tar.gz 9da74301acd0e157a132392bc0e3dd9760400fbe node-v0.8.23-sunos-x64.tar.gz dffe26030f95c6f4c1b39ca9eae7d0882b1caacc node-v0.8.23-sunos-x86.tar.gz 0b8534504bc6a00215e21e03650228a37400b228 node-v0.8.23-x86.msi 033d01b7675f557b9cb49148a860d62f015c63fd node-v0.8.23.pkg 13772b9c1060aae5441f11cd3fdbe4e4791612b9 node-v0.8.23.tar.gz d0afaf05544c9fa8b4b6df5f1f03feb9167fb493 node.exe 13067ab2f18797536a38a76e5f8087ec54f45b6c node.exp 8a253e09bfa128b09ad0a0a507db8f7c96eba537 node.lib 51f36628dc6ec058966de7a9f3054617b0ddbb30 node.pdb 367967503a8963557f647bd9766a980f7c78ff93 x64/node-v0.8.23-x64.msi e86d6b984a937b27e1809db551d2159aea19c3d5 x64/node.exe 29abfe7952dafde326ff52094ec49445f41f5366 x64/node.exp d769b0e9af6975dcd860f3a57c3d3cc96c240e46 x64/node.lib e4268618e8dea66f2d1fa9bf8b817ae1e7106337 x64/node.pdb ``` node-v0.10.25~dfsg2/doc/blog/release/v0.10.11.md0000644000000000000000000000500012270121457017226 0ustar rootrootdate: Thu Jun 13 11:34:24 PDT 2013 version: 0.10.11 category: release title: Node v0.10.11 (Stable) slug: node-v0-10-11-stable 2013.06.13, Version 0.10.11 (Stable) * uv: upgrade to 0.10.11 * npm: Upgrade to 1.2.30 * openssl: add missing configuration pieces for MIPS (Andrei Sedoi) * Revert "http: remove bodyHead from 'upgrade' events" (isaacs) * v8: fix pointer arithmetic undefined behavior (Trevor Norris) * crypto: fix utf8/utf-8 encoding check (Ben Noordhuis) * net: Fix busy loop on POLLERR|POLLHUP on older linux kernels (Ben Noordhuis, isaacs) Source Code: http://nodejs.org/dist/v0.10.11/node-v0.10.11.tar.gz Macintosh Installer (Universal): http://nodejs.org/dist/v0.10.11/node-v0.10.11.pkg Windows Installer: http://nodejs.org/dist/v0.10.11/node-v0.10.11-x86.msi Windows x64 Installer: http://nodejs.org/dist/v0.10.11/x64/node-v0.10.11-x64.msi Windows x64 Files: http://nodejs.org/dist/v0.10.11/x64/ Linux 32-bit Binary: http://nodejs.org/dist/v0.10.11/node-v0.10.11-linux-x86.tar.gz Linux 64-bit Binary: http://nodejs.org/dist/v0.10.11/node-v0.10.11-linux-x64.tar.gz Solaris 32-bit Binary: http://nodejs.org/dist/v0.10.11/node-v0.10.11-sunos-x86.tar.gz Solaris 64-bit Binary: http://nodejs.org/dist/v0.10.11/node-v0.10.11-sunos-x64.tar.gz Other release files: http://nodejs.org/dist/v0.10.11/ Website: http://nodejs.org/docs/v0.10.11/ Documentation: http://nodejs.org/docs/v0.10.11/api/ Shasums: ``` c460678436e513ef5b8b8513abd74c75d8ebf7bb node-v0.10.11-darwin-x64.tar.gz edd321fc6d7525774a12433e943db3a7817a19b9 node-v0.10.11-darwin-x86.tar.gz 1388e8a2b6b4b2043db4fc382959d43e7c32e28e node-v0.10.11-linux-x64.tar.gz 2923e08deeb08a5ce1a29607c00f8b8e4fbd16c8 node-v0.10.11-linux-x86.tar.gz 4d12e60a9bf4c9c418d88951733a6a51201b789d node-v0.10.11-sunos-x64.tar.gz 842e283ea724a6d69a17e18426c32e6fd4b0734b node-v0.10.11-sunos-x86.tar.gz bbc874e7ad72d980a19ee76dc1d9012d801f1d8f node-v0.10.11-x86.msi 05d0a697a183f809a949832a0fd98e1e30d53e72 node-v0.10.11.pkg 4f646bb3418d1c177ce28cdbc61e71de35b38aea node-v0.10.11.tar.gz e2eec3e170e1d26622231ee3f0b632485756a5f0 node.exe 8957dd0c31c115819f9387250f038a1e6259cfa9 node.exp 930ba687c31f09dd199c0cfb2ac492f57c0f640f node.lib 6bd963cff4baba07cb05d7e6aa566aebe8db5519 node.pdb 016356e656ac8091900637e3fb64ddc3dd53cfb5 x64/node-v0.10.11-x64.msi a845f30c9f0100b6f4d79080c72068ff497c5c23 x64/node.exe 00719da33432ae9a264407c89239ce5a76e21df0 x64/node.exp 1f96e883134197c27aada23847b049491dd46b13 x64/node.lib 83989e612f56b0a8e90e4fad8cb1a7d8b0bdfcd0 x64/node.pdb ``` node-v0.10.25~dfsg2/doc/blog/release/node-v0-6-3.md0000644000000000000000000000304112270121457020020 0ustar rootrootversion: 0.6.3 title: Node v0.6.3 author: piscisaureus date: Fri Nov 25 2011 02:54:08 GMT-0800 (PST) status: publish category: release slug: node-v0-6-3 2011.11.25, Version 0.6.3 (stable)
    • #2083 Land NPM in Node. It is included in packages/installers and installed on `make install`.
    • #2076 Add logos to windows installer.
    • #1711 Correctly handle http requests without headers. (Ben Noordhuis, Felix Geisendörfer)
    • TLS: expose more openssl SSL context options and constants. (Ben Noordhuis)
    • #2177 Windows: don't kill UDP socket when a packet fails to reach its destination. (Bert Belder)
    • Windows: support paths longer than 260 characters. (Igor Zinkovsky)
    • Windows: correctly resolve drive-relative paths. (Bert Belder)
    • #2166 Don't leave file descriptor open after lchmod. (Isaac Schlueter)
    • #2084 Add OS X .pkg build script to make file.
    • #2160 Documentation improvements. (Ben Noordhuis)
    Source Code: http://nodejs.org/dist/v0.6.3/node-v0.6.3.tar.gz Windows Installer: http://nodejs.org/dist/v0.6.3/node-v0.6.3.msi Macintosh Installer: http://nodejs.org/dist/v0.6.3/node-v0.6.3.pkg Website: http://nodejs.org/docs/v0.6.3/ Documentation: http://nodejs.org/docs/v0.6.3/api/ node-v0.10.25~dfsg2/doc/blog/release/node-v0-4-8.md0000644000000000000000000000275612270121457020037 0ustar rootrootversion: 0.4.8 title: Node v0.4.8 author: ryandahl date: Sat May 21 2011 07:06:00 GMT-0700 (PDT) status: publish category: release slug: node-v0-4-8 2011.05.20, Version 0.4.8 (stable) * #974 Properly report traceless errors (isaacs) * #983 Better JSON.parse error detection in REPL (isaacs) * #836 Agent socket errors bubble up to req only if req exists * #1041 Fix event listener leak check timing (koichik) * #1038 Fix dns.resolve() with 'PTR' throws Error: Unknown type "PTR" (koichik) * #1073 Share SSL context between server connections (Fedor Indutny) * Disable compression with OpenSSL. Improves memory perf. * Implement os.totalmem() and os.freemem() for SunOS (Alexandre Marangone) * Fix a special characters in URL regression (isaacs) * Fix idle timeouts in HTTPS (Felix Geisendörfer) * SlowBuffer.write() with 'ucs2' throws ReferenceError. (koichik) * http.ServerRequest 'close' sometimes gets an error argument (Felix Geisendörfer) * Doc improvements * cleartextstream.destroy() should close(2) the socket. Previously was being mapped to a shutdown(2) syscall. * No longer compile out asserts and debug statements in normal build. * Debugger improvements. * Upgrade V8 to 3.1.8.16. Website: http://nodejs.org/docs/v0.4.8/ Download: http://nodejs.org/dist/node-v0.4.8.tar.gz Documentation: http://nodejs.org/docs/v0.4.8/api/ node-v0.10.25~dfsg2/doc/blog/release/node-v0-6-2.md0000644000000000000000000000273512270121457020030 0ustar rootrootversion: 0.6.2 title: Node v0.6.2 author: bennoordhuis date: Fri Nov 18 2011 15:35:32 GMT-0800 (PST) status: publish category: release slug: node-v0-6-2

    2011.11.18, Version 0.6.2 (stable)

    • doc improvements (Artur Adib, Trevor Burnham, Ryan Emery, Trent Mick)
    • timers: remember extra setTimeout() arguments when timeout==0
    • punycode: use Mathias Bynens's punycode library, it's more compliant
    • repl: improved tab completion (Ryan Emery)
    • buffer: fix range checks in .writeInt() functions (Lukasz Walukiewicz)
    • tls: make cipher list configurable
    • addons: make Buffer and ObjectWrap visible to Windows add-ons (Bert Belder)
    • crypto: add PKCS#1 a.k.a RSA public key verification support
    • windows: fix stdout writes when redirected to nul
    • sunos: fix build on Solaris and Illumos
    • Upgrade V8 to 3.6.6.8

    Source Code: http://nodejs.org/dist/v0.6.2/node-v0.6.2.tar.gz

    Windows Installer: http://nodejs.org/dist/v0.6.2/node-v0.6.2.msi

    Macintosh Installer: http://nodejs.org/dist/v0.6.2/node-v0.6.2.pkg

    Website: http://nodejs.org/docs/v0.6.2/

    Documentation: http://nodejs.org/docs/v0.6.2/api/

    node-v0.10.25~dfsg2/doc/blog/release/node-v0-7-1.md0000644000000000000000000000247712270121457020033 0ustar rootrootversion: 0.7.1 title: Node v0.7.1 author: Isaac Schlueter date: Mon Jan 23 2012 17:35:59 GMT-0800 (PST) status: publish category: release slug: node-v0-7-1

    2012.01.23, Version 0.7.1 (unstable)

    • Update V8 to 3.8.8

    • Install node-waf by default (Fedor Indutny)

    • crypto: Add ability to turn off PKCS padding (Ingmar Runge)

    • v8: implement VirtualMemory class on SunOS (Ben Noordhuis)

    • Add cluster.setupMaster (Andreas Madsen)

    • move path.exists* to fs.exists* (Maciej Małecki)

    • typed arrays: set class name (Ben Noordhuis)

    • libuv bug fixes (Igor Zinkovsky, Ben Noordhuis, Dan VerWeire)

    Source: http://nodejs.org/dist/v0.7.1/node-v0.7.1.tar.gz

    Windows Installer: http://nodejs.org/dist/v0.7.1/node-v0.7.1.msi

    Macintosh Installer: http://nodejs.org/dist/v0.7.1/node-v0.7.1.pkg

    Website: http://nodejs.org/docs/v0.7.1/

    Documentation: http://nodejs.org/docs/v0.7.1/api/

    node-v0.10.25~dfsg2/doc/blog/release/v0.10.0.md0000644000000000000000000007277712270121457017175 0ustar rootroottitle: Node v0.10.0 (Stable) category: release version: 0.10.0 date: 2013-03-11T16:00:00.000Z slug: node-v0-10-0-stable author: Isaac Z. Schlueter I am pleased to announce a new stable version of Node. This branch brings significant improvements to many areas, with a focus on API polish, ease of use, and backwards compatibility. For a very brief overview of the relevant API changes since v0.8, please see [the API changes wiki page](https://github.com/joyent/node/wiki/Api-changes-between-v0.8-and-v0.10). ## Streams2 In a [previous post](http://blog.nodejs.org/2012/12/20/streams2/), we introduced the "[Streams2](http://blog.nodejs.org/2012/12/20/streams2/)" API changes. If you haven't reviewed the changes, please go read that now (at least the tl;dr section). The changes to the stream interface have been a long time in the making. Even from the earliest days of Node, we've all sort of known that this whole "data events come right away" and "pause() is advisory" stuff was unnecessarily awful. In v0.10, we finally bit the bullet and committed to making drastic changes in order to make these things better. More importantly, all streams in Node-core are built using the same set of easily-extended base classes, so their behavior is much more consistent, and it's easier than ever to create streaming interfaces in your own userland programs. In fact, the Streams2 API was developed while using it for modules in the npm registry. At the time of this writing, [37 published Node modules](https://npmjs.org/browse/depended/readable-stream) already are using the [readable-stream](https://npmjs.org/package/readable-stream) library as a dependency. The readable-stream npm package allows you to use the new Stream interface in your legacy v0.8 codebase. ## Domains and Error Handling The `domain` module has been elevated from "Experimental" to "Unstable" status. It's been given more of a first-class treatment internally, making it easier to handle some of the edge cases that we found using Domains for error handling in v0.8. Specifically, domain error handler no longer relies on `process.on('uncaughtException')` being raised, and the C++ code in Node is domain-aware. If you're not already using Domains to catch errors in your programs, and you've found yourself wishing that you could get better debugging information when errors are thrown (especially in the midst of lots of requests and asynchronous calls), then definitely check it out. ## Faster process.nextTick In v0.8 (and before), the `process.nextTick()` function scheduled its callback using a spinner on the event loop. This *usually* caused the callback to be fired before any other I/O. However, it was not guaranteed. As a result, a lot of programs (including some parts of Node's internals) began using `process.nextTick` as a "do later, but before any actual I/O is performed" interface. Since it usually works that way, it seemed fine. However, under load, it's possible for a server to have a lot of I/O scheduled, to the point where the `nextTick` gets preempted for something else. This led to some odd errors and race conditions, which could not be fixed without changing the semantics of nextTick. So, that's what we did. In v0.10, `nextTick` handlers are run right after each call from C++ into JavaScript. That means that, if your JavaScript code calls `process.nextTick`, then the callback will fire as soon as the code runs to completion, but *before* going back to the event loop. The race is over, and all is good. However, there are programs out in the wild that use recursive calls to `process.nextTick` to avoid pre-empting the I/O event loop for long-running jobs. In order to avoid breaking horribly right away, Node will now print a deprecation warning, and ask you to use `setImmediate` for these kinds of tasks instead. ## Latency and Idle Garbage Collection One of the toughest things to get right in a garbage collected language is garbage collection. In order to try to avoid excessive memory usage, Node used to try to tell V8 to collect some garbage whenever the event loop was idle. However, knowing exactly when to do this is extremely difficult. There are different degrees of "idleness", and if you get it wrong, you can easily end up spending massive amounts of time collecting garbage when you'd least expect. In practice, disabling the `IdleNotification` call yields better performance without any excessive memory usage, because V8 is pretty good at knowing when it's the best time to run GC. So, in v0.10, we just ripped that feature out. (According to another point of view, we fixed the bug that it was ever there in the first place.) As a result, latency is much more predictable and stable. You won't see a difference in the benchmarks as a result of this, but you'll probably find that your app's response times are more reliable. ## Performance and Benchmarks When the Streams2 feature first landed in master, it disrupted a lot of things. We focused first on correctness rather than speed, and as a result of that, we got a correct implementation that was significantly slower. We have a consistent rule in Node, that it cannot be allowed to get slower for our main use cases. It took a lot of work, but over the last few months, we've managed to get v0.10 to an appropriate level of performance, without sacrificing the API goals that we had in mind. Benchmarks are complicated beasts. Until this release, we've gotten by with a pretty ad-hoc approach to running benchmarks. However, as we started actually having to track down regressions, the need for a more comprehensive approach was obvious. Work is underway to figure out the optimum way to get statistically significant benchmark results in an automated way. As it is, we're still seeing significant jitter in some of the data, so take the red and green colors with a grain of salt. The benchmarks below were run on an Apple 13-inch, Late 2011 MacBook Pro with a 2.8 GHz Intel Core i7 processor, 8GB of 1333MHz DDR3 RAM, running OS X Lion 10.7.5 (11G63b). The numbers are slightly different on Linux and SmartOS, but the conclusions are the same. The [raw data is available](http://nodejs.org/benchmarks-v0.10-vs-v0.8/), as well. ## Benchmarks: http Node is for websites, and websites run over HTTP, so this is the one that people usually care the most about:
    http/cluster.js type=bytes length=4: v0.10: 16843 v0.8: 16202 ................. 3.96%
    http/cluster.js type=bytes length=1024: v0.10: 15505 v0.8: 15065 .............. 2.92%
    http/cluster.js type=bytes length=102400: v0.10: 1555.2 v0.8: 1566.3 ......... -0.71%
    http/cluster.js type=buffer length=4: v0.10: 15308 v0.8: 14763 ................ 3.69%
    http/cluster.js type=buffer length=1024: v0.10: 15039 v0.8: 14830 ............. 1.41%
    http/cluster.js type=buffer length=102400: v0.10: 7584.6 v0.8: 7433.6 ......... 2.03%
    http/simple.js type=bytes length=4: v0.10: 12343 v0.8: 11761 .................. 4.95%
    http/simple.js type=bytes length=1024: v0.10: 11051 v0.8: 10287 ............... 7.43%
    http/simple.js type=bytes length=102400: v0.10: 853.19 v0.8: 892.75 .......... -4.43%
    http/simple.js type=buffer length=4: v0.10: 11316 v0.8: 10728 ................. 5.48%
    http/simple.js type=buffer length=1024: v0.10: 11199 v0.8: 10429 .............. 7.38%
    http/simple.js type=buffer length=102400: v0.10: 4942.1 v0.8: 4822.9 .......... 2.47%
    
    What we see here is that, overall, HTTP is faster. It's just slightly slower (1-5%) when sending extremely large string messages (ie `type=bytes` rather than `type=buffer`). But otherwise, things are about the same, or slightly faster. ## Benchmarks: fs The fs.ReadStream throughput is massively improved, and less affected by the chunk size argument:
    fs/read-stream buf size=1024: v0.10: 1106.6 v0.8: 60.597 ................... 1726.12%
    fs/read-stream buf size=4096: v0.10: 1107.9 v0.8: 235.51 .................... 370.44%
    fs/read-stream buf size=65535: v0.10: 1108.2 v0.8: 966.84 .................... 14.62%
    fs/read-stream buf size=1048576: v0.10: 1103.3 v0.8: 959.66 .................. 14.97%
    fs/read-stream asc size=1024: v0.10: 1081.5 v0.8: 62.218 ................... 1638.21%
    fs/read-stream asc size=4096: v0.10: 1082.3 v0.8: 174.78 .................... 519.21%
    fs/read-stream asc size=65535: v0.10: 1083.9 v0.8: 627.91 .................... 72.62%
    fs/read-stream asc size=1048576: v0.10: 1083.2 v0.8: 627.49 .................. 72.62%
    fs/read-stream utf size=1024: v0.10: 46.553 v0.8: 16.944 .................... 174.74%
    fs/read-stream utf size=4096: v0.10: 46.585 v0.8: 32.933 ..................... 41.45%
    fs/read-stream utf size=65535: v0.10: 46.57 v0.8: 45.832 ...................... 1.61%
    fs/read-stream utf size=1048576: v0.10: 46.576 v0.8: 45.884 ................... 1.51%
    
    The fs.WriteStream throughput increases considerably, for most workloads. As the size of the chunk goes up, the speed is limited by the underlying system and the cost of string conversion, so v0.8 and v0.10 converge. But for smaller chunk sizes (like you'd be more likely to see in real applications), v0.10 is a significant improvement.
    fs/write-stream buf size=2: v0.10: 0.12434 v0.8: 0.10097 ..................... 23.15%
    fs/write-stream buf size=1024: v0.10: 59.926 v0.8: 49.822 .................... 20.28%
    fs/write-stream buf size=65535: v0.10: 180.41 v0.8: 179.26 .................... 0.64%
    fs/write-stream buf size=1048576: v0.10: 181.49 v0.8: 176.73 .................. 2.70%
    fs/write-stream asc size=2: v0.10: 0.11133 v0.8: 0.08123 ..................... 37.06%
    fs/write-stream asc size=1024: v0.10: 53.023 v0.8: 36.708 .................... 44.45%
    fs/write-stream asc size=65535: v0.10: 178.54 v0.8: 174.36 .................... 2.39%
    fs/write-stream asc size=1048576: v0.10: 185.27 v0.8: 183.65 .................. 0.88%
    fs/write-stream utf size=2: v0.10: 0.11165 v0.8: 0.080079 .................... 39.43%
    fs/write-stream utf size=1024: v0.10: 45.166 v0.8: 32.636 .................... 38.39%
    fs/write-stream utf size=65535: v0.10: 176.1 v0.8: 175.34 ..................... 0.43%
    fs/write-stream utf size=1048576: v0.10: 182.3 v0.8: 182.82 .................. -0.28%
    
    ## Benchmark: tls We switched to a newer version of OpenSSL, and the CryptoStream implementation was significantly changed to support the Stream2 interface. The throughput of TLS connections is massively improved:
    tls/throughput.js dur=5 type=buf size=2: v0.10: 0.90836 v0.8: 0.32381 ....... 180.52%
    tls/throughput.js dur=5 type=buf size=1024: v0.10: 222.84 v0.8: 116.75 ....... 90.87%
    tls/throughput.js dur=5 type=buf size=1048576: v0.10: 403.17 v0.8: 360.42 .... 11.86%
    tls/throughput.js dur=5 type=asc size=2: v0.10: 0.78323 v0.8: 0.28761 ....... 172.32%
    tls/throughput.js dur=5 type=asc size=1024: v0.10: 199.7 v0.8: 102.46 ........ 94.91%
    tls/throughput.js dur=5 type=asc size=1048576: v0.10: 375.85 v0.8: 317.81 .... 18.26%
    tls/throughput.js dur=5 type=utf size=2: v0.10: 0.78503 v0.8: 0.28834 ....... 172.26%
    tls/throughput.js dur=5 type=utf size=1024: v0.10: 182.43 v0.8: 100.3 ........ 81.88%
    tls/throughput.js dur=5 type=utf size=1048576: v0.10: 333.05 v0.8: 301.57 .... 10.44%
    
    However, the speed at which we can make connections is somewhat reduced:
    tls/tls-connect.js concurrency=1 dur=5: v0.10: 433.05 v0.8: 560.43 .......... -22.73%
    tls/tls-connect.js concurrency=10 dur=5: v0.10: 438.38 v0.8: 577.93 ......... -24.15%
    
    At this point, it seems like the connection speed is related to the new version of OpenSSL, but we'll be tracking that further. TLS still has more room for improvement, but this throughput increase is a huge step. ## Benchmark: net The net throughput tests tell an interesting story. When sending ascii messages, they're much faster.
    net/net-c2s.js len=102400 type=asc dur=5: v0.10: 3.6551 v0.8: 2.0478 ......... 78.49%
    net/net-c2s.js len=16777216 type=asc dur=5: v0.10: 3.2428 v0.8: 2.0503 ....... 58.16%
    net/net-pipe.js len=102400 type=asc dur=5: v0.10: 4.4638 v0.8: 3.0798 ........ 44.94%
    net/net-pipe.js len=16777216 type=asc dur=5: v0.10: 3.9449 v0.8: 2.8906 ...... 36.48%
    net/net-s2c.js len=102400 type=asc dur=5: v0.10: 3.6306 v0.8: 2.0415 ......... 77.84%
    net/net-s2c.js len=16777216 type=asc dur=5: v0.10: 3.2271 v0.8: 2.0636 ....... 56.38%
    
    When sending Buffer messages, they're just slightly slower. (This difference is less than the typical variability of the test, but they were run 20 times and outliers were factored out for this post.)
    net/net-c2s.js len=102400 type=buf dur=5: v0.10: 5.5597 v0.8: 5.6967 ......... -2.40%
    net/net-c2s.js len=16777216 type=buf dur=5: v0.10: 6.1843 v0.8: 6.4595 ....... -4.26%
    net/net-pipe.js len=102400 type=buf dur=5: v0.10: 5.6898 v0.8: 5.986 ......... -4.95%
    net/net-pipe.js len=16777216 type=buf dur=5: v0.10: 5.9643 v0.8: 5.9251 ....... 0.66%
    net/net-s2c.js len=102400 type=buf dur=5: v0.10: 5.473 v0.8: 5.6492 .......... -3.12%
    net/net-s2c.js len=16777216 type=buf dur=5: v0.10: 6.1986 v0.8: 6.3236 ....... -1.98%
    
    When sending utf-8 messages, they're a bit slower than that:
    net/net-c2s.js len=102400 type=utf dur=5: v0.10: 2.2671 v0.8: 2.4606 ......... -7.87%
    net/net-c2s.js len=16777216 type=utf dur=5: v0.10: 1.7434 v0.8: 1.8771 ....... -7.12%
    net/net-pipe.js len=102400 type=utf dur=5: v0.10: 3.1679 v0.8: 3.5401 ....... -10.51%
    net/net-pipe.js len=16777216 type=utf dur=5: v0.10: 2.5615 v0.8: 2.7002 ...... -5.14%
    net/net-s2c.js len=102400 type=utf dur=5: v0.10: 2.2495 v0.8: 2.4578 ......... -8.48%
    net/net-s2c.js len=16777216 type=utf dur=5: v0.10: 1.7733 v0.8: 1.8975 ....... -6.55%
    
    You might suspect that this is a result of the new Streams implementation. However, running the same benchmarks without using any of the code in Node's `lib/` folder, just calling into the C++ bindings directly, yields consistently similar results. This slight regression comes along with significant improvements in everything that sits on *top* of TCP (that is, TLS and HTTP). Keep an eye out for more work in this area. Fast is never fast enough! ## Continuous Integration To support a higher degree of stability, and hopefully catch issues sooner, we have a Jenkins instance running every commit through the test suite, on each operating system we support. You can watch the action at [the Node Jenkins web portal](http://jenkins.nodejs.org/). Coming soon, we'll have automatically generated nightly builds every day, and eventually, the entire release process will be automated. While we're pretty rigorous about running tests and benchmarks, it's easy for things to slip by, and our ad-hoc methods are not cutting it any longer. This promises a much lower incidence of the sort of regressions that delayed the release of v0.10 for several months. ## Growing Out A year ago, we said that the innovation in the Node universe would be happening in userland modules. Now, we've finally taken that to its logical conclusion, and moved our iteration on **core** modules into userland as well. Things like `readable-stream` and `tlsnappy` allow us to get much more user-testing, experimentation, and contributions to a feature. The userland module can live on as a compatibility layer so that libraries can use the new features, even if they need to support older versions of Node. This is a remarkably effective way to do node-core development. Future developments will continue to be iterated in userland modules. ## Growing Up The question comes up pretty often whether Node is "ready for prime time" yet. I usually answer that it depends on your requirements for "prime time", but Node has been powering some high profile sites, and the options for "real" companies using Node for The Business are better than ever. It would be out of scope to try to provide an exhaustive list of all the companies using Node, and all of the options for support and training. However, here are a few resources that are quickly expanding to fill the "Enterprise Node" space. For those looking for commercial support, [StrongLoop](http://strongloop.com/) (Ben Noordhuis & Bert Belder's company) has released a distribution containing node v0.10 that they will support on Windows, Mac, Red Hat/Fedora, Debian/Ubuntu and multiple cloud platforms. You can [download their Node distribution here](http://strongloop.com/products#downloads). [The Node Firm](http://thenodefirm.com) is a worldwide network of key Node contributors and community members that help organizations succeed with Node. Through corporate training, consulting, architectural guidance, and [ongoing consulting subscriptions](http://thenodefirm.com/nodejs-consulting-subscriptions), they have helped Skype, Qualcomm, and others quickly and effectively embrace Node. Node would not be what it is without [npm](https://npmjs.org/), and npm would not be what it is without the registry of published modules. However, relying on the public registry is problematic for many enterprise use-cases. [Iris npm](https://www.irisnpm.com/) is a fully managed private npm registry, from [Iris Couch](http://www.iriscouch.com), the team that runs the public npm registry in production. [Joyent](http://joyent.com), the company you probably know as the custodian of the Node project, provides high performance cloud infrastructure specializing in real-time web and mobile applications. Joyent uses Node extensively throughout their stack, and provides impressive [post-mortem debugging and real-time performance analysis tools](http://dtrace.org/blogs/dap/2012/05/31/debugging-node-js-in-production-fluent-slides/) for Node.js applications. They are also my employer, so I'd probably have to get a "real" job if they weren't sponsoring Node :) ## Next Up: v0.12 The focus of Node v0.12 will be to make HTTP better. Node's current HTTP implementation is pretty good, and clearly sufficient to do a lot of interesting things with. However: 1. The codebase is a mess. We share a lot of code between the Client and Server implementations, but do so in a way that makes it unnecessarily painful to read the code or fix bugs. It will be split up so that client and server are clearly separated, and have cleaner interfaces. 2. The socket pooling behavior is confusing and weird. We will be adding configurable socket pooling as a standalone utility. This will allow us to implement KeepAlive behavior in a more reasonable manner, as well as providing something that you can use in your own programs. There is some experimentation going on in the [tlsnappy](https://github.com/indutny/tlsnappy) module, which may make its way back into the core TLS implementation and speed things up considerably. ## 1.0 After 0.12, the next major stable release will be 1.0. At that point, very little will change in terms of the day-to-day operation of the project, but it will mark a significant milestone in terms of our stability and willingness to add new features. However, we've already gotten strict about maintaining backwards compatibility, so this won't really be so much of a shift. New versions will still come out, especially to pull in new versions of our dependencies, and bugs will continue to be fixed. There's been talk of pinning our release cycles to V8, and automating the release process in some interesting ways. The goal of Node has always been to eventually be "finished" with the core program. Of course, that's a rather lofty goal, perhaps even impossible. But as we take Node to more places, and use it in more ways, we're getting closer to the day when the relevant innovation happens outside of the core Node program. Stability in the platform enables growth on top of it. And now, the traditional release notes: ## 2013.03.11, Version 0.10.0 (Stable) * npm: Upgrade to 1.2.14 * core: Append filename properly in dlopen on windows (isaacs) * zlib: Manage flush flags appropriately (isaacs) * domains: Handle errors thrown in nested error handlers (isaacs) * buffer: Strip high bits when converting to ascii (Ben Noordhuis) * win/msi: Enable modify and repair (Bert Belder) * win/msi: Add feature selection for various Node parts (Bert Belder) * win/msi: use consistent registry key paths (Bert Belder) * child_process: support sending dgram socket (Andreas Madsen) * fs: Raise EISDIR on Windows when calling fs.read/write on a dir (isaacs) * unix: fix strict aliasing warnings, macro-ify functions (Ben Noordhuis) * unix: honor UV_THREADPOOL_SIZE environment var (Ben Noordhuis) * win/tty: fix typo in color attributes enumeration (Bert Belder) * win/tty: don't touch insert mode or quick edit mode (Bert Belder) Source Code: http://nodejs.org/dist/v0.10.0/node-v0.10.0.tar.gz Macintosh Installer (Universal): http://nodejs.org/dist/v0.10.0/node-v0.10.0.pkg Windows Installer: http://nodejs.org/dist/v0.10.0/node-v0.10.0-x86.msi Windows x64 Installer: http://nodejs.org/dist/v0.10.0/x64/node-v0.10.0-x64.msi Windows x64 Files: http://nodejs.org/dist/v0.10.0/x64/ Linux 32-bit Binary: http://nodejs.org/dist/v0.10.0/node-v0.10.0-linux-x86.tar.gz Linux 64-bit Binary: http://nodejs.org/dist/v0.10.0/node-v0.10.0-linux-x64.tar.gz Solaris 32-bit Binary: http://nodejs.org/dist/v0.10.0/node-v0.10.0-sunos-x86.tar.gz Solaris 64-bit Binary: http://nodejs.org/dist/v0.10.0/node-v0.10.0-sunos-x64.tar.gz Other release files: http://nodejs.org/dist/v0.10.0/ Website: http://nodejs.org/docs/v0.10.0/ Documentation: http://nodejs.org/docs/v0.10.0/api/ Shasums: ``` b9e9bca99cdb5563cad3d3f04baa262e317b827c node-v0.10.0-darwin-x64.tar.gz 0227c9bc3df5b62267b9d4e3b0a92b3a70732229 node-v0.10.0-darwin-x86.tar.gz 9f5f7350d6f889ea8e794516ecfea651e8e53d24 node-v0.10.0-linux-x64.tar.gz cc5f1cd6a2f2530bc400e761144bbaf8fcb66cc4 node-v0.10.0-linux-x86.tar.gz 42c14b7eab398976b1ac0a8e6e96989059616af5 node-v0.10.0-sunos-x64.tar.gz ddcadbac66d1acea48aa6c5462d0a0d7308ea823 node-v0.10.0-sunos-x86.tar.gz 70eacf2cca7abec79fac4ca502e8d99590a2108a node-v0.10.0-x86.msi c48c269b9b0f0a95e6e9234d4597d1c8a1c45c5a node-v0.10.0.pkg 7321266347dc1c47ed2186e7d61752795ce8a0ef node-v0.10.0.tar.gz f8c6f55469551243ea461f023cc57c024f57fef2 node.exe 253ae79e411fcfddcf28861559ececb4b335db64 node.exp acb8febb5ea714c065f201ced5423b0838fdf1b6 node.lib 0fdad1400036dd26d720070f783d3beeb3bb9c0a node.pdb abcaf8ef606655a05e73ee5d06715ffd022aad22 x64/node-v0.10.0-x64.msi e5d0c235629b26430b6e07c07ee2c7dcda82f35e x64/node.exe 43b3fb3a6aaf6a04f578ee607a9455c1e23acf08 x64/node.exp 87dd6eb6c8127a1af0dcca639961441fc303d75a x64/node.lib 50aca715777fa42b854e6cfc56b6199a54aabd3c x64/node.pdb ``` node-v0.10.25~dfsg2/doc/blog/release/v0.10.1.md0000644000000000000000000000563612270121457017164 0ustar rootrootdate: Thu Mar 21 09:09:59 PDT 2013 version: 0.10.1 category: release title: Node v0.10.1 (Stable) slug: node-v0-10-1-stable 2013.03.21, Version 0.10.1 (Stable) * npm: upgrade to 1.2.15 * crypto: Improve performance of non-stream APIs (Fedor Indutny) * tls: always reset this.ssl.error after handling (Fedor Indutny) * tls: Prevent mid-stream hangs (Fedor Indutny, isaacs) * net: improve arbitrary tcp socket support (Ben Noordhuis) * net: handle 'finish' event only after 'connect' (Fedor Indutny) * http: Don't hot-path end() for large buffers (isaacs) * fs: Missing cb errors are deprecated, not a throw (isaacs) * fs: make write/appendFileSync correctly set file mode (Raymond Feng) * stream: Return self from readable.wrap (isaacs) * stream: Never call decoder.end() multiple times (Gil Pedersen) * windows: enable watching signals with process.on('SIGXYZ') (Bert Belder) * node: revert removal of MakeCallback (Trevor Norris) * node: Unwrap without aborting in handle fd getter (isaacs) Source Code: http://nodejs.org/dist/v0.10.1/node-v0.10.1.tar.gz Macintosh Installer (Universal): http://nodejs.org/dist/v0.10.1/node-v0.10.1.pkg Windows Installer: http://nodejs.org/dist/v0.10.1/node-v0.10.1-x86.msi Windows x64 Installer: http://nodejs.org/dist/v0.10.1/x64/node-v0.10.1-x64.msi Windows x64 Files: http://nodejs.org/dist/v0.10.1/x64/ Linux 32-bit Binary: http://nodejs.org/dist/v0.10.1/node-v0.10.1-linux-x86.tar.gz Linux 64-bit Binary: http://nodejs.org/dist/v0.10.1/node-v0.10.1-linux-x64.tar.gz Solaris 32-bit Binary: http://nodejs.org/dist/v0.10.1/node-v0.10.1-sunos-x86.tar.gz Solaris 64-bit Binary: http://nodejs.org/dist/v0.10.1/node-v0.10.1-sunos-x64.tar.gz Other release files: http://nodejs.org/dist/v0.10.1/ Website: http://nodejs.org/docs/v0.10.1/ Documentation: http://nodejs.org/docs/v0.10.1/api/ Shasums: ``` e213170fe5ec7721b31149fba1a7a691c50b5379 node-v0.10.1-darwin-x64.tar.gz 5526d189fa3180e11731e1aebb0f22c1c2fb3d8d node-v0.10.1-darwin-x86.tar.gz ec0818d8f151d933ec79961374bf74d9855305a5 node-v0.10.1-linux-x64.tar.gz b6345e86bc52575f8cc275cda36b1295ed544139 node-v0.10.1-linux-x86.tar.gz e94cb3ab3ac5a8026564152798070e06f1ba3119 node-v0.10.1-sunos-x64.tar.gz a894eaca7f49077e48b1786071dbdf57a2ea704c node-v0.10.1-sunos-x86.tar.gz 3f64590730d8e24e57530192479fd39dafde13b5 node-v0.10.1-x86.msi b41c576c473a1ae44c3061fe4799362239f00d8f node-v0.10.1.pkg d4d9ef3b70452112246ea2043ef75943611e3537 node-v0.10.1.tar.gz c034695812148c3fafe8b208203355d16289d1a7 node.exe 9fac94cbe9431ca518fdb1eed1a1b240a58ac781 node.exp 3571d5d7f9940f48b75f9a9b1fac8c8661e8ace2 node.lib 74f9ea112e2da1c1837180422a20630bc92bd5c9 node.pdb 0958d68900b80419e2af7a5448c4a451af06d0b4 x64/node-v0.10.1-x64.msi cc074b6c99cb1df01707ea12e986cf5bb4dc3c05 x64/node.exe f2746fea78ffb346e8ea979ea09924dc4408bcb9 x64/node.exp 1f1d9d1ba0d9383ecc93e8d8a481b13db39dc5f8 x64/node.lib 39a0a5a699e4a8cba44e618f6be6bd79f36a370f x64/node.pdb ``` node-v0.10.25~dfsg2/doc/blog/release/v0.10.15.md0000644000000000000000000000447512270121457017251 0ustar rootrootdate: Thu Jul 25 16:57:47 PDT 2013 version: 0.10.15 category: release title: Node v0.10.15 (Stable) slug: node-v0-10-15-stable 2013.07.25, Version 0.10.15 (Stable) * src: fix process.getuid() return value (Ben Noordhuis) Source Code: http://nodejs.org/dist/v0.10.15/node-v0.10.15.tar.gz Macintosh Installer (Universal): http://nodejs.org/dist/v0.10.15/node-v0.10.15.pkg Windows Installer: http://nodejs.org/dist/v0.10.15/node-v0.10.15-x86.msi Windows x64 Installer: http://nodejs.org/dist/v0.10.15/x64/node-v0.10.15-x64.msi Windows x64 Files: http://nodejs.org/dist/v0.10.15/x64/ Linux 32-bit Binary: http://nodejs.org/dist/v0.10.15/node-v0.10.15-linux-x86.tar.gz Linux 64-bit Binary: http://nodejs.org/dist/v0.10.15/node-v0.10.15-linux-x64.tar.gz Solaris 32-bit Binary: http://nodejs.org/dist/v0.10.15/node-v0.10.15-sunos-x86.tar.gz Solaris 64-bit Binary: http://nodejs.org/dist/v0.10.15/node-v0.10.15-sunos-x64.tar.gz Other release files: http://nodejs.org/dist/v0.10.15/ Website: http://nodejs.org/docs/v0.10.15/ Documentation: http://nodejs.org/docs/v0.10.15/api/ Shasums: ``` b812ba5b966b89180d1391a9de5ccd075fc84c65 node-v0.10.15-darwin-x64.tar.gz f07bed2a59040d7adf3a647c953c3942b132da5c node-v0.10.15-darwin-x86.tar.gz d236ed82967eefa726ec144301728b6a32ab8d8d node-v0.10.15-linux-x64.tar.gz 5629f83b10dc95d899268c3387895085270bb9e1 node-v0.10.15-linux-x86.tar.gz 408e52074146cfed792f20ea54e9eca4419164af node-v0.10.15-sunos-x64.tar.gz 01ed71a5b019c6a2b51750c2e287613be1df0d92 node-v0.10.15-sunos-x86.tar.gz 18c72b9394a943136ad5446599c732bc5fd5af9a node-v0.10.15-x86.msi 9dba40ed9c511faa215586d0b0f535d4ae55016c node-v0.10.15.pkg 14174896de074c244b0ed2251a95d7163d5a5e87 node-v0.10.15.tar.gz fad9611a7f656b8097c97de7b2ed016f3f33c6f9 node.exe ee48f297215ce12ba87998ccc06760ab3e667573 node.exp 11f354ebcccfb88133a529e6e1337185a3b60550 node.lib 230fc683b097afd33583ede1ec1f41fe4dae414b node.pdb 9d349103a53f444d1f9835989e22ebf2c906e3c0 pkgsrc/nodejs-ia32-0.10.15.tgz bb1397b448bf2a58ce62fc3c51fb14633e840bbd pkgsrc/nodejs-x64-0.10.15.tgz 7c6fbdfe5c0154477f1dd8acd915c8c13766b9ae x64/node-v0.10.15-x64.msi f273ef837b2bc3b8cf5b1b7a363b510cb230a9be x64/node.exe 57fcec104d9fd3af53286f15353c7cd75e961382 x64/node.exp 86afa3785280a25d183ff46bfea3a845b6b506c0 x64/node.lib f6bc69a9c20c3965fd4969040cde9b43c7de50ff x64/node.pdb ``` node-v0.10.25~dfsg2/doc/blog/release/v0.10.20.md0000644000000000000000000000454712270121457017245 0ustar rootrootdate: Mon Sep 30 15:05:41 PDT 2013 version: 0.10.20 category: release title: Node v0.10.20 (Stable) slug: node-v0-10-20-stable 2013.09.30, Version 0.10.20 (Stable) * tls: fix sporadic hang and partial reads (Fedor Indutny) - fixes "npm ERR! cb() never called!" Source Code: http://nodejs.org/dist/v0.10.20/node-v0.10.20.tar.gz Macintosh Installer (Universal): http://nodejs.org/dist/v0.10.20/node-v0.10.20.pkg Windows Installer: http://nodejs.org/dist/v0.10.20/node-v0.10.20-x86.msi Windows x64 Installer: http://nodejs.org/dist/v0.10.20/x64/node-v0.10.20-x64.msi Windows x64 Files: http://nodejs.org/dist/v0.10.20/x64/ Linux 32-bit Binary: http://nodejs.org/dist/v0.10.20/node-v0.10.20-linux-x86.tar.gz Linux 64-bit Binary: http://nodejs.org/dist/v0.10.20/node-v0.10.20-linux-x64.tar.gz Solaris 32-bit Binary: http://nodejs.org/dist/v0.10.20/node-v0.10.20-sunos-x86.tar.gz Solaris 64-bit Binary: http://nodejs.org/dist/v0.10.20/node-v0.10.20-sunos-x64.tar.gz Other release files: http://nodejs.org/dist/v0.10.20/ Website: http://nodejs.org/docs/v0.10.20/ Documentation: http://nodejs.org/docs/v0.10.20/api/ Shasums: ``` 6f827b5bb1184160a58e0aac711791b610c30afd node-v0.10.20-darwin-x64.tar.gz 89869942f09351a5256f9ff68c3e1c363f108e7a node-v0.10.20-darwin-x86.tar.gz b7c0a79acddfaeda8af221acdd18640ef5c62e8a node-v0.10.20-linux-x64.tar.gz 709cd1a646447036abe3f57ea6e33bb1d411c229 node-v0.10.20-linux-x86.tar.gz dbe318556bc7a4d7ea47947600edcdb375a92d8e node-v0.10.20-sunos-x64.tar.gz b003527f645bfc8c65d890854e20c92edc1feb86 node-v0.10.20-sunos-x86.tar.gz 34015dac5e517492fec6584cacd2d9864056107e node-v0.10.20-x86.msi a0408be15afd0b5d34b8762edab6420339a8c4ff node-v0.10.20.pkg d8777ac318627c1413f01358ea5c455f0f86e4b5 node-v0.10.20.tar.gz 5f61f783345dc3663b03322d6387800d96560cd5 node.exe bb81cb60eae4c6be9238aa05b5245f29609b6f96 node.exp e06eab29b27de1908aa2cf624d438e15ee126640 node.lib 2495f7a88f0085df5206c0d0cb44131cf9715156 node.pdb 6036d6b1f2cf34a5055ed59b6519cb09cc6f86ff pkgsrc/nodejs-ia32-0.10.20.tgz 9b743d9a5d80758e8cd9d436e165c9569fa9d0fd pkgsrc/nodejs-x64-0.10.20.tgz 1b574ef4fe2ad61ce398415599f8f376b576e65d x64/node-v0.10.20-x64.msi 7137043329a25c36ad24d11d8e4ce6e5ff8a72b2 x64/node.exe 624c5bdb06ddd726457fa7b04197069ba021016b x64/node.exp f61da5166124895495bd72520d6b6f730acc1cbc x64/node.lib efa36de57eda469254fab252f24ef67c17f96f00 x64/node.pdb ``` node-v0.10.25~dfsg2/doc/blog/release/v0.8.10.md0000644000000000000000000000633612270121457017171 0ustar rootroottitle: Node v0.8.10 (Stable) date: Tue Sep 25 15:36:47 PDT 2012 slug: node-v0-8-10-stable category: release version: 0.8.10 2012.09.25, Version 0.8.10 (Stable) * npm: Upgrade to 1.1.62 * repl: make invalid RegExps throw in the REPL (Nathan Rajlich) * v8: loosen artificial mmap constraint (Bryan Cantrill) * process: fix setuid() and setgid() error reporting (Ben Noordhuis) * domain: Properly exit() on domain disposal (isaacs) * fs: fix watchFile() missing deletion events (Ben Noordhuis) * fs: fix assert in fs.watch() (Ben Noordhuis) * fs: don't segfault on deeply recursive stat() (Ben Noordhuis) * http: Remove timeout handler when data arrives (Frédéric Germain) * http: make the client "res" object gets the same domain as "req" (Nathan Rajlich) * windows: don't blow up when an invalid FD is used (Bert Belder) * unix: map EDQUOT to UV_ENOSPC (Charlie McConnell) * linux: improve /proc/cpuinfo parser (Ben Noordhuis) * win/tty: reset background brightness when color is set to default (Bert Belder) * unix: put child process stdio fds in blocking mode (Ben Noordhuis) * unix: fix EMFILE busy loop (Ben Noordhuis) * sunos: don't set TCP_KEEPALIVE (Ben Noordhuis) * tls: Use slab allocator for memory management (Fedor Indutny) * openssl: Use optimized assembly code for x86 and x64 (Bert Belder) Source Code: http://nodejs.org/dist/v0.8.10/node-v0.8.10.tar.gz Macintosh Installer (Universal): http://nodejs.org/dist/v0.8.10/node-v0.8.10.pkg Windows Installer: http://nodejs.org/dist/v0.8.10/node-v0.8.10-x86.msi Windows x64 Installer: http://nodejs.org/dist/v0.8.10/x64/node-v0.8.10-x64.msi Windows x64 Files: http://nodejs.org/dist/v0.8.10/x64/ Linux 32-bit Binary: http://nodejs.org/dist/v0.8.10/node-v0.8.10-linux-x86.tar.gz Linux 64-bit Binary: http://nodejs.org/dist/v0.8.10/node-v0.8.10-linux-x64.tar.gz Solaris 32-bit Binary: http://nodejs.org/dist/v0.8.10/node-v0.8.10-sunos-x86.tar.gz Solaris 64-bit Binary: http://nodejs.org/dist/v0.8.10/node-v0.8.10-sunos-x64.tar.gz Other release files: http://nodejs.org/dist/v0.8.10/ Website: http://nodejs.org/docs/v0.8.10/ Documentation: http://nodejs.org/docs/v0.8.10/api/ Shasums: ``` ae327ce5cc9f46e7d1bdd04f06ea299e44f9a0fc node-v0.8.10-darwin-x64.tar.gz 812405695e3522bfd998d67b6de2daff55ff0a7b node-v0.8.10-darwin-x86.tar.gz 8ef4e489817a79aaea75cffd09cc4b072c38fe2e node-v0.8.10-linux-x64.tar.gz 76f289b12ba41730c43b59d286de5cee571c9064 node-v0.8.10-linux-x86.tar.gz 61e40e8a5e911b26889ad33856029d783388778a node-v0.8.10-sunos-x64.tar.gz 2fd06dc2d145fdba6b2800186ffcaebb0fe3b109 node-v0.8.10-sunos-x86.tar.gz 3e49e1c958815d0144cafe5e43c2fa83e775dd1c node-v0.8.10-x86.msi 9605340dca27725110eebcb15fdf61599622e308 node-v0.8.10.pkg c596cce77726724441cf7fc98f42df3a5335ab8e node-v0.8.10.tar.gz f6d172e3452e2bf429dc75836a385eff22407c83 node.exe ccb8c0e0fa052d8da48ea421cc7a220bb89835f9 node.exp 7ea077e6ca1216d5e8f42e445f75f0542f7d85c4 node.lib d86ad55c37ac1a0975731ab444fc58c93a7bca47 node.pdb 90fc70b09f92f788fc68a116f589a86ca3309fdb x64/node-v0.8.10-x64.msi 4b62cedf4bbbff1ffb8df6d52c9a57255f383ad3 x64/node.exe 6b4b813c3b065154ce437b7f36a15beceeb76af0 x64/node.exp 9e7dd3ddca3ba37483ac2125c39a52e72035e1d0 x64/node.lib 28de8dd05af5e390f5bd63508bd27b7c683177de x64/node.pdb ``` node-v0.10.25~dfsg2/doc/blog/release/version-0-6-15-stable.md0000644000000000000000000000355512270121457021737 0ustar rootrootversion: 0.6.15 title: Version 0.6.15 (stable) author: Isaac Schlueter date: Mon Apr 09 2012 10:39:18 GMT-0700 (PDT) status: publish category: release slug: version-0-6-15-stable

    2012.04.09 Version 0.6.15 (stable)

    • Update npm to 1.1.16

    • Show licenses in binary installers.

    • unix: add uv_fs_read64, uv_fs_write64 and uv_fs_ftruncate64 (Ben Noordhuis)

    • add 64bit offset fs functions (Igor Zinkovsky)

    • windows: don't report ENOTSOCK when attempting to bind an udp handle twice (Bert Belder)

    • windows: backport pipe-connect-to-file fixes from master (Bert Belder)

    • windows: never call fs event callbacks after closing the watcher (Bert Belder)

    • fs.readFile: don't make the callback before the fd is closed (Bert Belder)

    • windows: use 64bit offsets for uv_fs apis (Igor Zinkovsky)

    • Fix #2061: segmentation fault on OS X due to stat size mismatch (Ben Noordhuis)

    Source Code: http://nodejs.org/dist/v0.6.15/node-v0.6.15.tar.gz

    Windows Installer: http://nodejs.org/dist/v0.6.15/node-v0.6.15.msi

    Windows x64 Files: http://nodejs.org/dist/v0.6.15/x64/

    Macintosh Installer (Universal): http://nodejs.org/dist/v0.6.15/node-v0.6.15.pkg

    Other release files: http://nodejs.org/dist/v0.6.15/

    Website: http://nodejs.org/docs/v0.6.15/

    Documentation: http://nodejs.org/docs/v0.6.15/api/

    node-v0.10.25~dfsg2/doc/blog/release/v0.11.0.md0000644000000000000000000000606212270121457017156 0ustar rootrootdate: Thu Mar 28 14:52:55 PDT 2013 version: 0.11.0 category: release title: Node v0.11.0 (Unstable) slug: node-v0-11-0-stable 2013.03.28, Version 0.11.0 (Unstable) * V8: update to 3.17.13 * os: use %SystemRoot% or %windir% in os.tmpdir() (Suwon Chae) * util: fix util.inspect() line width calculation (Marcin Kostrzewa) * buffer: remove _charsWritten (Trevor Norris) * fs: uv_[fl]stat now reports subsecond resolution (Timothy J Fontaine) * fs: Throw if error raised and missing callback (bnoordhuis) * tls: expose SSL_CTX_set_timeout via tls.createServer (Manav Rathi) * tls: remove harmful unnecessary bounds checking (Marcel Laverdet) * buffer: write ascii strings using WriteOneByte (Trevor Norris) * dtrace: fix generation of v8 constants on freebsd (Fedor Indutny) * dtrace: x64 ustack helper (Fedor Indutny) * readline: handle wide characters properly (Nao Iizuka) * repl: Use a domain to catch async errors safely (isaacs) * repl: emit 'reset' event when context is reset (Sami Samhuri) * util: custom `inspect()` method may return an Object (Nathan Rajlich) * console: `console.dir()` bypasses inspect() methods (Nathan Rajlich) Source Code: http://nodejs.org/dist/v0.11.0/node-v0.11.0.tar.gz Macintosh Installer (Universal): http://nodejs.org/dist/v0.11.0/node-v0.11.0.pkg Windows Installer: http://nodejs.org/dist/v0.11.0/node-v0.11.0-x86.msi Windows x64 Installer: http://nodejs.org/dist/v0.11.0/x64/node-v0.11.0-x64.msi Windows x64 Files: http://nodejs.org/dist/v0.11.0/x64/ Linux 32-bit Binary: http://nodejs.org/dist/v0.11.0/node-v0.11.0-linux-x86.tar.gz Linux 64-bit Binary: http://nodejs.org/dist/v0.11.0/node-v0.11.0-linux-x64.tar.gz Solaris 32-bit Binary: http://nodejs.org/dist/v0.11.0/node-v0.11.0-sunos-x86.tar.gz Solaris 64-bit Binary: http://nodejs.org/dist/v0.11.0/node-v0.11.0-sunos-x64.tar.gz Other release files: http://nodejs.org/dist/v0.11.0/ Website: http://nodejs.org/docs/v0.11.0/ Documentation: http://nodejs.org/docs/v0.11.0/api/ Shasums: ``` 4889d63a4a08d146d59cd057b1c8b341ceac07cf node-v0.11.0-darwin-x64.tar.gz 4ef64fa36c095edfa3c6da852ed1ec46c6f3cf23 node-v0.11.0-darwin-x86.tar.gz 04c4d1fb71f98dfc921d9558667a727ca1aa6586 node-v0.11.0-linux-x64.tar.gz b1507837292e23464e2d184007f2567db3db1483 node-v0.11.0-linux-x86.tar.gz cd195da08ea5208a6c08b95511fa888d750f4cd7 node-v0.11.0-sunos-x64.tar.gz 4698b9a6cb911cbea3deac38ea191cef3051b3ab node-v0.11.0-sunos-x86.tar.gz 829649fe65133459c7fc231b8d048f19ae870c7b node-v0.11.0-x86.msi 7958b8212aaa9787724c552197d37cf5602ff645 node-v0.11.0.pkg 0402aae18f847238409e9d1a5ddd806beb5fe678 node-v0.11.0.tar.gz 320778de3329437815daa4f86d1a89db33458126 node.exe 1f4f509a9dc48c519064ca7f2deddeaff2b6b15b node.exp 5f83864acae194c0652a61af71262bd1ba55a04c node.lib 0d100a18ba569e5e9bb9e216355959261c4cd77b node.pdb b55553c83e12f253f23dec4d998b05bd673db83b x64/node-v0.11.0-x64.msi 7100ef58f9a8428d2bdd9d4de8ffb679d0198b1e x64/node.exe 12bf810852e7097bde1bf4bff6cd7f802603cdb9 x64/node.exp 28f83178241353dc727ba6d8ff38f9b9177be79a x64/node.lib 6c0f43db501facc3d9ed542a090f9ba2e84bdc41 x64/node.pdb ``` node-v0.10.25~dfsg2/doc/blog/release/node-v0-5-2.md0000644000000000000000000000210512270121457020016 0ustar rootrootversion: 0.5.2 title: Node v0.5.2 author: ryandahl date: Fri Jul 22 2011 11:40:22 GMT-0700 (PDT) status: publish category: release slug: node-v0-5-2 2011.07.22, Version 0.5.2 (unstable)
    • libuv improvements; named pipe support
    • #1242 check for SSL_COMP_get_compression_methods() (Ben Noordhuis)
    • #1348 remove require.paths (isaacs)
    • #1349 Delimit NODE_PATH with ; on Windows (isaacs)
    • #1335 Remove EventEmitter from C++
    • #1357 Load json files with require() (isaacs)
    • #1374 fix setting ServerResponse.statusCode in writeHead (Trent Mick)
    • Fixed: GC was being run too often.
    • Upgrade V8 to 3.4.14
    • doc improvements
    Download: http://nodejs.org/dist/v0.5.2/node-v0.5.2.tar.gz Windows Executable: http://nodejs.org/dist/v0.5.2/node.exe Website: http://nodejs.org/dist/v0.5.2/docs/ Documentation: http://nodejs.org/dist/v0.5.2/docs/api node-v0.10.25~dfsg2/doc/blog/release/v0.6.20.md0000644000000000000000000000315112270121457017160 0ustar rootrootversion: 0.6.20 title: Version 0.6.20 (maintenance) category: release slug: node-v0-6-20-maintenance date: 2012.07.10 18:00 2012.07.10 Version 0.6.20 (maintenance) * npm: Upgrade to 1.1.37 (isaacs) * benchmark: Backport improvements made in master (isaacs) * build: always link with -lz (Trent Mick) * core: use proper #include directives (Ben Noordhuis) * cluster: don't silently drop messages when the write queue gets big (Bert Belder) * windows: don't print error when GetConsoleTitleW returns an empty string (Bert Belder) Source Code: http://nodejs.org/dist/v0.6.20/node-v0.6.20.tar.gz Windows Installer: http://nodejs.org/dist/v0.6.20/node-v0.6.20.msi Windows x64 Files: http://nodejs.org/dist/v0.6.20/x64/ Macintosh Installer (Universal): http://nodejs.org/dist/v0.6.20/node-v0.6.20.pkg Other release files: http://nodejs.org/dist/v0.6.20/ Website: http://nodejs.org/docs/v0.6.20/ Documentation: http://nodejs.org/docs/v0.6.20/api/ Shasums: ``` 5029f30e6af79e7a9a1d45396afbe20229059b47 node-v0.6.20.msi 370105015bae2a77e4da41564ad3df8fcd0acaec node-v0.6.20.pkg 91da1dde9badd5250f3d4829c47757de0caab84b node-v0.6.20.tar.gz efa29addd716c175d945ade5dfa2b9ebd7f6fed8 node.exe aab0e367adcc9fdee479dbe67a32c6b27ee35960 node.exp ce6c455937f96eb671f44dc731d628849fa8b350 node.lib a8db5c269de9c3059684f9aa3de5a4cdbd9b3d12 node.pdb 22f97ba2c678b4c8a1def251269920ee46c90bca x64/node-v0.6.20.msi 276136ae7f6e2e59d0ae26d434e4d6ab65769957 x64/node.exe af56811749aa4fe013a36f7bccecfb94587c0afd x64/node.exp a629af1b4f6f4b82e332c35695fff956bd555f3b x64/node.lib 3b2d22b20efeb06bf3d86378168d604dbe52eb08 x64/node.pdb ``` node-v0.10.25~dfsg2/doc/blog/release/node-v0-6-9.md0000644000000000000000000000253012270121457020030 0ustar rootrootversion: 0.6.9 title: Node v0.6.9 author: Isaac Schlueter date: Fri Jan 27 2012 16:58:18 GMT-0800 (PST) status: publish category: release slug: node-v0-6-9

    2012.01.27, Version 0.6.9 (stable)

    • dgram: Bring back missing functionality for Unix (Dan VerWeire, Roman Shtylman, Ben Noordhuis)

      - Note: Windows UDP support not yet complete.

    • http: Fix parser memory leak (koichik)

    • zlib: Fix #2365 crashes on invalid input (Nicolas LaCasse)

    • module: fix --debug-brk on symlinked scripts (Fedor Indutny)

    • Documentation Restyling (Matthew Fitzsimmons)

    • Update npm to 1.1.0-3 (isaacs)

    • Windows: fix regression in stat() calls to C:\ (Bert Belder)

    Source Code: http://nodejs.org/dist/v0.6.9/node-v0.6.9.tar.gz

    Windows Installer: http://nodejs.org/dist/v0.6.9/node-v0.6.9.msi

    Macintosh Installer: http://nodejs.org/dist/v0.6.9/node-v0.6.9.pkg

    Website: http://nodejs.org/docs/v0.6.9/

    Documentation: http://nodejs.org/docs/v0.6.9/api/

    node-v0.10.25~dfsg2/doc/blog/release/v0.10.10.md0000644000000000000000000000441312270121457017234 0ustar rootrootdate: Tue Jun 4 14:37:25 PDT 2013 version: 0.10.10 category: release title: Node v0.10.10 (Stable) slug: node-v0-10-10-stable 2013.06.04, Version 0.10.10 (Stable) * uv: Upgrade to 0.10.10 * npm: Upgrade to 1.2.25 * url: Properly parse certain oddly formed urls (isaacs) * stream: unshift('') is a noop (isaacs) Source Code: http://nodejs.org/dist/v0.10.10/node-v0.10.10.tar.gz Macintosh Installer (Universal): http://nodejs.org/dist/v0.10.10/node-v0.10.10.pkg Windows Installer: http://nodejs.org/dist/v0.10.10/node-v0.10.10-x86.msi Windows x64 Installer: http://nodejs.org/dist/v0.10.10/x64/node-v0.10.10-x64.msi Windows x64 Files: http://nodejs.org/dist/v0.10.10/x64/ Linux 32-bit Binary: http://nodejs.org/dist/v0.10.10/node-v0.10.10-linux-x86.tar.gz Linux 64-bit Binary: http://nodejs.org/dist/v0.10.10/node-v0.10.10-linux-x64.tar.gz Solaris 32-bit Binary: http://nodejs.org/dist/v0.10.10/node-v0.10.10-sunos-x86.tar.gz Solaris 64-bit Binary: http://nodejs.org/dist/v0.10.10/node-v0.10.10-sunos-x64.tar.gz Other release files: http://nodejs.org/dist/v0.10.10/ Website: http://nodejs.org/docs/v0.10.10/ Documentation: http://nodejs.org/docs/v0.10.10/api/ Shasums: ``` d632cad2adb5b4eef7a94bc9e549579586b381f5 node-v0.10.10-darwin-x64.tar.gz 6f74d0ca1a3bc810a4e73267451c0177be405874 node-v0.10.10-darwin-x86.tar.gz b8a1f1954027b88b9545f3a2161543635f2120e7 node-v0.10.10-linux-x64.tar.gz aae6893ee82cee09eec0351b770d4857e31e46b7 node-v0.10.10-linux-x86.tar.gz 0004745f5c0f96efc85f2bd9d9df24b1b706f77e node-v0.10.10-sunos-x64.tar.gz a4e623f6688fde7f30d720ac4b1228546da823db node-v0.10.10-sunos-x86.tar.gz 1f09e829c92274de13270a7519e9e1cd5788e0a8 node-v0.10.10-x86.msi 24f7573e92060565ba84b7700efc4d9cf566e5ba node-v0.10.10.pkg c21643a57b1ec9eca56e6deac22fe075616e0e9c node-v0.10.10.tar.gz 419fc85e5e16139260f7b2080ffbb66550fbe93f node.exe bb2782228bf4f8783f9e6a9d1171f8ff0835c9b9 node.exp 28ce8d1f8156e6a8bf38844738f4a76499e0d2ce node.lib eb58da2b123bc7aaceaa37a7a0bcc048d8d8dcc1 node.pdb 781f75fc1c7499edb8d7e247d774266d57514d21 x64/node-v0.10.10-x64.msi 14b75f31d14ca2e0fb90308e98a3567c6de0434e x64/node.exe c5723e00cc875543ae263121d34d204690561860 x64/node.exp df523e092ee9ff13b3acf4f4b574d043c0da6d9a x64/node.lib db2a8874a3bc7cd21b8b29bc7faa5f75c8af0414 x64/node.pdb ``` node-v0.10.25~dfsg2/doc/blog/release/v0.10.8.md0000644000000000000000000000514012270121457017161 0ustar rootrootdate: Fri May 24 15:43:01 PDT 2013 version: 0.10.8 category: release title: Node v0.10.8 (Stable) slug: node-v0-10-8-stable 2013.05.24, Version 0.10.8 (Stable) * v8: update to 3.14.5.9 * uv: upgrade to 0.10.8 * npm: Upgrade to 1.2.23 * http: remove bodyHead from 'upgrade' events (Nathan Zadoks) * http: Return true on empty writes, not false (isaacs) * http: save roundtrips, convert buffers to strings (Ben Noordhuis) * configure: respect the --dest-os flag consistently (Nathan Rajlich) * buffer: throw when writing beyond buffer (Trevor Norris) * crypto: Clear error after DiffieHellman key errors (isaacs) * string_bytes: strip padding from base64 strings (Trevor Norris) Source Code: http://nodejs.org/dist/v0.10.8/node-v0.10.8.tar.gz Macintosh Installer (Universal): http://nodejs.org/dist/v0.10.8/node-v0.10.8.pkg Windows Installer: http://nodejs.org/dist/v0.10.8/node-v0.10.8-x86.msi Windows x64 Installer: http://nodejs.org/dist/v0.10.8/x64/node-v0.10.8-x64.msi Windows x64 Files: http://nodejs.org/dist/v0.10.8/x64/ Linux 32-bit Binary: http://nodejs.org/dist/v0.10.8/node-v0.10.8-linux-x86.tar.gz Linux 64-bit Binary: http://nodejs.org/dist/v0.10.8/node-v0.10.8-linux-x64.tar.gz Solaris 32-bit Binary: http://nodejs.org/dist/v0.10.8/node-v0.10.8-sunos-x86.tar.gz Solaris 64-bit Binary: http://nodejs.org/dist/v0.10.8/node-v0.10.8-sunos-x64.tar.gz Other release files: http://nodejs.org/dist/v0.10.8/ Website: http://nodejs.org/docs/v0.10.8/ Documentation: http://nodejs.org/docs/v0.10.8/api/ Shasums: ``` c1b81939e55d42fd7a90ec88ab23fd7a411ed77c node-v0.10.8-darwin-x64.tar.gz 4474b8d4222efd6f6076243a4aa78e72760ee01a node-v0.10.8-darwin-x86.tar.gz 898283b1ba8a9732c98ce38a89dc15af23291702 node-v0.10.8-linux-x64.tar.gz 2e15464289f618245fc6f420191490c144d81be3 node-v0.10.8-linux-x86.tar.gz 9a36b001ce5eef52641b836a42d1fc69c516d329 node-v0.10.8-sunos-x64.tar.gz 490d9a6d2a300fd2750a4a227288aed67a767713 node-v0.10.8-sunos-x86.tar.gz 96218cb0c14fbcaa76165fbe5a3af402883f898b node-v0.10.8-x86.msi a713f339195dd009d2614fac25b61bc88295f063 node-v0.10.8.pkg d650a09ae868bb04f424e3560658c15b9a885b5b node-v0.10.8.tar.gz 38034b7a6bca2dbe3aaacc3cc8aa9920394baaf7 node.exe 19cd4ae9f3edeaa259e5ca84abd28dea400a91d7 node.exp 1ccffaf0ff0f4bb11e8d23a2938366fd87b3e583 node.lib 079f617ef81507a6b5fe7e8bd1f5a2f109a574ec node.pdb 985d55d1ba49f47354ba13a419d678bf73634ef9 x64/node-v0.10.8-x64.msi 25d4d74c73cd57346094979e5c51c5b16d6dcb83 x64/node.exe 19587e8301371e721695c7aed335f74c6873dfaf x64/node.exp 4a002dd8a1742431fc99a2a92580a3040a796f2c x64/node.lib 8d18200f9fe81805fe81201355d9f3509bd0c81b x64/node.pdb ``` node-v0.10.25~dfsg2/doc/blog/release/node-v0-5-7-unstable.md0000644000000000000000000000265212270121457021645 0ustar rootrootversion: 0.5.7 title: Node v0.5.7 (unstable) author: ryandahl date: Fri Sep 16 2011 18:57:03 GMT-0700 (PDT) status: publish category: release slug: node-v0-5-7-unstable 2011.09.16, Version 0.5.7 (unstable)
    • Upgrade V8 to 3.6.4
    • Improve Windows compatibility
    • Documentation improvements
    • Debugger and REPL improvements (Fedor Indutny)
    • Add legacy API support: net.Stream(fd), process.stdout.writable, process.stdout.fd
    • Fix mkdir EEXIST handling (isaacs)
    • Use net_uv instead of net_legacy for stdio
    • Do not load readline from util.inspect
    • #1673 Fix bug related to V8 context with accessors (Fedor Indutny)
    • #1634 util: Fix inspection for Error (koichik)
    • #1645 fs: Add positioned file writing feature to fs.WriteStream (Thomas Shinnick)
    • #1637 fs: Unguarded fs.watchFile cache statWatchers checking fixed (Thomas Shinnick)
    • #1695 Forward customFds to ChildProcess.spawn
    • #1707 Fix hasOwnProperty security problem in querystring (isaacs)
    • #1719 Drain OpenSSL error queue
    Download: http://nodejs.org/dist/v0.5.7/node-v0.5.7.tar.gz Windows Executable: http://nodejs.org/dist/v0.5.7/node.exe Website: http://nodejs.org/docs/v0.5.7/ Documentation: http://nodejs.org/docs/v0.5.7/api/ node-v0.10.25~dfsg2/doc/blog/release/v0.8.24.md0000644000000000000000000000445512270121457017176 0ustar rootrootdate: Tue Jun 4 11:09:55 PDT 2013 version: 0.8.24 category: release title: Node v0.8.24 (Maintenance) slug: node-v0-8-24-maintenance 2013.06.04, Version 0.8.24 (maintenance) * npm: Upgrade to v1.2.24 * url: Properly parse certain oddly formed urls (isaacs) * http: Don't try to destroy nonexistent sockets (isaacs) * handle_wrap: fix NULL pointer dereference (Ben Noordhuis) Source Code: http://nodejs.org/dist/v0.8.24/node-v0.8.24.tar.gz Macintosh Installer (Universal): http://nodejs.org/dist/v0.8.24/node-v0.8.24.pkg Windows Installer: http://nodejs.org/dist/v0.8.24/node-v0.8.24-x86.msi Windows x64 Installer: http://nodejs.org/dist/v0.8.24/x64/node-v0.8.24-x64.msi Windows x64 Files: http://nodejs.org/dist/v0.8.24/x64/ Linux 32-bit Binary: http://nodejs.org/dist/v0.8.24/node-v0.8.24-linux-x86.tar.gz Linux 64-bit Binary: http://nodejs.org/dist/v0.8.24/node-v0.8.24-linux-x64.tar.gz Solaris 32-bit Binary: http://nodejs.org/dist/v0.8.24/node-v0.8.24-sunos-x86.tar.gz Solaris 64-bit Binary: http://nodejs.org/dist/v0.8.24/node-v0.8.24-sunos-x64.tar.gz Other release files: http://nodejs.org/dist/v0.8.24/ Website: http://nodejs.org/docs/v0.8.24/ Documentation: http://nodejs.org/docs/v0.8.24/api/ Shasums: ``` bd2f2c1dda9812d773a3d403ca69700d59471746 node-v0.8.24-darwin-x64.tar.gz 041553ba728039c7876bd109285263e654e95d80 node-v0.8.24-darwin-x86.tar.gz 4fb7ce5d80d1b9ac5cbe1d7ee1e7697e35536a35 node-v0.8.24-linux-x64.tar.gz 0cbdb661fde7414b75b5e0d7735405b1e7974b91 node-v0.8.24-linux-x86.tar.gz 0f48da822862122bc9690bdba063f6cf954c7f5a node-v0.8.24-sunos-x64.tar.gz 095fd055c9299906a11f30159443b5be784f9e20 node-v0.8.24-sunos-x86.tar.gz cf96df4d163bdb588044245cb5e082e136ed71d7 node-v0.8.24-x86.msi 82f3c12752b1891bb208677fe7f280f8cbec36ab node-v0.8.24.pkg 4035c547a98a9e9b9e7a036abe84f19c78220b8f node-v0.8.24.tar.gz b65113c23b0a653a3befec55e42f7a4a3db691e2 node.exe abd8a7ab174c6f3a8508cc0fa725a35aa8258738 node.exp 1601a02e694f60d6e37adefe29fae75ec4bedf52 node.lib b420062ebfe1fc3e9a14a65c76e50d7433ed7120 node.pdb 93d6cde7e7a72aac47a4053c5e8ceefd23e24344 x64/node-v0.8.24-x64.msi fa63de49e8839f581aece864249c61810f9af13f x64/node.exe b3737b22816b6324a44afab9ad6722c604ed317c x64/node.exp f08cdeb9f0414afb23ab4079f584edecc43e32ab x64/node.lib 4bdd92ba52fc3d9ff6184df00d9f9f53ef644cde x64/node.pdb ``` node-v0.10.25~dfsg2/doc/blog/release/node-v0-4-4.md0000644000000000000000000000160212270121457020020 0ustar rootrootversion: 0.4.4 title: Node v0.4.4 author: ryandahl date: Sat Mar 26 2011 08:58:45 GMT-0700 (PDT) status: publish category: release slug: node-v0-4-4 2011.03.26, Version 0.4.4 (stable)
    • CryptoStream.end shouldn't throw if not writable GH-820
    • Drop out if connection destroyed before connect() GH-819
    • expose https.Agent
    • Correctly setsid in tty.open GH-815
    • Bug fix for failed buffer construction
    • Added support for removing .once listeners (GH-806)
    • Upgrade V8 to 3.1.8.5
    Download: http://nodejs.org/dist/node-v0.4.4.tar.gz Website: http://nodejs.org/docs/v0.4.4 Documentation: http://nodejs.org/docs/v0.4.4/api announcement node-v0.10.25~dfsg2/doc/blog/release/v0.8.7.md0000644000000000000000000000516012270121457017111 0ustar rootrootversion: 0.8.7 title: Version 0.8.7 (stable) category: release slug: node-v0-8-7-stable date: 2012-08-15T23:23:16.131Z 2012.08.15, Version 0.8.7 (Stable) * npm: Upgrade to 1.1.49 * website: download page (Golo Roden) * crypto: fix uninitialized memory access in openssl (Ben Noordhuis) * buffer, crypto: fix buffer decoding (Ben Noordhuis) * build: compile with -fno-tree-vrp when gcc >= 4.0 (Ben Noordhuis) * tls: handle multiple CN fields when verifying cert (Ben Noordhuis) * doc: remove unused util from child_process (Kyle Robinson Young) * build: rework -fvisibility=hidden detection (Ben Noordhuis) * windows: don't duplicate invalid stdio handles (Bert Belder) * windows: fix typos in process-stdio.c (Bert Belder) Source Code: http://nodejs.org/dist/v0.8.7/node-v0.8.7.tar.gz Macintosh Installer (Universal): http://nodejs.org/dist/v0.8.7/node-v0.8.7.pkg Windows Installer: http://nodejs.org/dist/v0.8.7/node-v0.8.7-x86.msi Windows x64 Installer: http://nodejs.org/dist/v0.8.7/x64/node-v0.8.7-x64.msi Windows x64 Files: http://nodejs.org/dist/v0.8.7/x64/ Linux 32-bit Binary: http://nodejs.org/dist/v0.8.7/node-v0.8.7-linux-x86.tar.gz Linux 64-bit Binary: http://nodejs.org/dist/v0.8.7/node-v0.8.7-linux-x64.tar.gz Solaris 32-bit Binary: http://nodejs.org/dist/v0.8.7/node-v0.8.7-sunos-x86.tar.gz Solaris 64-bit Binary: http://nodejs.org/dist/v0.8.7/node-v0.8.7-sunos-x64.tar.gz Other release files: http://nodejs.org/dist/v0.8.7/ Website: http://nodejs.org/docs/v0.8.7/ Documentation: http://nodejs.org/docs/v0.8.7/api/ Shasums: ``` 3ff82e65a845a2d5f27ea57e8a1e29e6d10f5128 node-v0.8.7-darwin-x64.tar.gz d72ac02727aaefa094f8d06a0a124078da007df0 node-v0.8.7-darwin-x86.tar.gz 0882e19157e98c3e2214e772e3ae714125863ae6 node-v0.8.7-linux-x64.tar.gz 3e388d47f6e79acccfab117cceaeed19ceb1b14c node-v0.8.7-linux-x86.tar.gz ffb81708df10d3c225d8f2ce57965a40db6ca556 node-v0.8.7-sunos-x64.tar.gz 19df6ae999e4a5c1dada83b72516b3941eeb701e node-v0.8.7-sunos-x86.tar.gz 19f90a0cfa41c7eaf683393d46d06aecc2f99f84 node-v0.8.7-x86.msi 0c2dcf2d5491be7b429681193a13c18de1ba488a node-v0.8.7.pkg 58ffb5884304e2f8415d8cee7921c42f66fc8d7b node-v0.8.7.tar.gz ecaee480f0337e92870ca83aed1b49863b3f659d node.exe ea2e25daad114692357383bfc8b4ac910fe02d99 node.exp 70c8f054a5c42f6d4e3ca5154ca1a360f549d66f node.lib 180bcc036cd5deaef49bf12fddeeafc2e78152e3 node.pdb 12ad712ff9e28eb1bdf7e508ce3a2b872ec37d4d x64/node-v0.8.7-x64.msi c30607099ad4699b11e3ca37f94a9da196a36dc6 x64/node.exe f864ed339952604c2205e25927fb4851da5b79b6 x64/node.exp ce711929befe756f942a039213aeece2ef3edcc1 x64/node.lib 11bb755b054bc6ee2e441758f7d42d131cf6d557 x64/node.pdb ``` node-v0.10.25~dfsg2/doc/blog/release/v0.11.1.md0000644000000000000000000000510512270121457017154 0ustar rootrootdate: Fri Apr 19 09:11:40 PDT 2013 version: 0.11.1 category: release title: Node v0.11.1 (Unstable) slug: node-v0-11-1-unstable **Note**: This version does not work on 64-bit Windows systems Expect a fix for this bug in the next v0.11 release. As this is an unstable release, we opted to push out the changes for other systems, rather than delay. 2013.04.19, Version 0.11.1 (Unstable) * V8: upgrade to 3.18.0 * uv: Upgrade to v0.11.1 * http: split into multiple separate modules (Timothy J Fontaine) * http: escape unsafe characters in request path (Ben Noordhuis) * url: Escape all unwise characters (isaacs) * build: depend on v8 postmortem-metadata if enabled (Paddy Byers) * etw: update prototypes to match dtrace provider (Timothy J Fontaine) * buffer: change output of Buffer.prototype.toJSON() (David Braun) * dtrace: actually use the _handle.fd value (Timothy J Fontaine) * dtrace: pass more arguments to probes (Dave Pacheco) * build: allow building with dtrace on osx (Dave Pacheco) * zlib: allow passing options to convenience methods (Kyle Robinson Young) Source Code: http://nodejs.org/dist/v0.11.1/node-v0.11.1.tar.gz Macintosh Installer (Universal): http://nodejs.org/dist/v0.11.1/node-v0.11.1.pkg Windows Installer: http://nodejs.org/dist/v0.11.1/node-v0.11.1-x86.msi Linux 32-bit Binary: http://nodejs.org/dist/v0.11.1/node-v0.11.1-linux-x86.tar.gz Linux 64-bit Binary: http://nodejs.org/dist/v0.11.1/node-v0.11.1-linux-x64.tar.gz Solaris 32-bit Binary: http://nodejs.org/dist/v0.11.1/node-v0.11.1-sunos-x86.tar.gz Solaris 64-bit Binary: http://nodejs.org/dist/v0.11.1/node-v0.11.1-sunos-x64.tar.gz Other release files: http://nodejs.org/dist/v0.11.1/ Website: http://nodejs.org/docs/v0.11.1/ Documentation: http://nodejs.org/docs/v0.11.1/api/ Shasums: ``` 83f440046d64619b974487e3445d541fa1310ec6 node-v0.11.1-darwin-x64.tar.gz 684118ba684d21f07bf1095727a15457d301edf9 node-v0.11.1-darwin-x86.tar.gz 2c71490f3664421f58145f2945018efeb4d43652 node-v0.11.1-linux-x64.tar.gz 07b7ed48a50792605229efb2c256a3681d242b0e node-v0.11.1-linux-x86.tar.gz bbe383ba0954f47812ff5d853069069901d8160d node-v0.11.1-sunos-x64.tar.gz 6782ff3bdd3af79d8ba8c8b0f352ca2106fcfafc node-v0.11.1-sunos-x86.tar.gz 47bf9b530d662f67b7b07729d83cd4f5575846b8 node-v0.11.1-x86.msi b98e549850355be6a107044ca6a000518599a982 node-v0.11.1.pkg fe13c36f4d9116ed718af9894aab989d74a9d91c node-v0.11.1.tar.gz 655ab3f0ce8227ffd68714491c2dd5aa7bdc0d10 node.exe 43a8f8a9cf53c0a2318b2288b6ba0e0f2a052858 node.exp d54e5b303a0568f803ad09aa802b7f95b676180c node.lib 08098d40b362018f5df09f302d85c5834f127292 node.pdb ``` node-v0.10.25~dfsg2/doc/blog/release/v0.10.24.md0000644000000000000000000000502412270121457017240 0ustar rootrootdate: Thu Dec 19 09:02:48 PST 2013 version: 0.10.24 category: release title: Node v0.10.24 (Stable) slug: node-v0-10-24-stable 2013.12.18, Version 0.10.24 (Stable) * uv: Upgrade to v0.10.21 * npm: upgrade to 1.3.21 * v8: backport fix for CVE-2013-{6639|6640} * build: unix install node and dep library headers (Timothy J Fontaine) * cluster, v8: fix --logfile=%p.log (Ben Noordhuis) * module: only cache package main (Wyatt Preul) Source Code: http://nodejs.org/dist/v0.10.24/node-v0.10.24.tar.gz Macintosh Installer (Universal): http://nodejs.org/dist/v0.10.24/node-v0.10.24.pkg Windows Installer: http://nodejs.org/dist/v0.10.24/node-v0.10.24-x86.msi Windows x64 Installer: http://nodejs.org/dist/v0.10.24/x64/node-v0.10.24-x64.msi Windows x64 Files: http://nodejs.org/dist/v0.10.24/x64/ Linux 32-bit Binary: http://nodejs.org/dist/v0.10.24/node-v0.10.24-linux-x86.tar.gz Linux 64-bit Binary: http://nodejs.org/dist/v0.10.24/node-v0.10.24-linux-x64.tar.gz Solaris 32-bit Binary: http://nodejs.org/dist/v0.10.24/node-v0.10.24-sunos-x86.tar.gz Solaris 64-bit Binary: http://nodejs.org/dist/v0.10.24/node-v0.10.24-sunos-x64.tar.gz Other release files: http://nodejs.org/dist/v0.10.24/ Website: http://nodejs.org/docs/v0.10.24/ Documentation: http://nodejs.org/docs/v0.10.24/api/ Shasums: ``` 4a233e4e51ec24de3b2c3196b9128781665b4edc node-v0.10.24-darwin-x64.tar.gz 1b018a372d919462e8ebef29a0de4816a83e38ff node-v0.10.24-darwin-x86.tar.gz 423018f6a60b18d0dddf3007c325e0cc8cf55099 node-v0.10.24-linux-x64.tar.gz fb99761ce4cef4a43743c1ed630b185545152264 node-v0.10.24-linux-x86.tar.gz 9719b2b636d8f5caf5495e967cbe167fd16eb160 node-v0.10.24-sunos-x64.tar.gz 84d7645d88dad9050f72c01d5f783cc018a8dc2b node-v0.10.24-sunos-x86.tar.gz 4b3cd142e691033308bfab237b6bf79a1a7f5c10 node-v0.10.24-x86.msi 74aba302d8b34e1fc93b3e0babc3f5d9bd8c09f3 node-v0.10.24.pkg d162d01eb173cb5a0e7e46c9d706421c4c771039 node-v0.10.24.tar.gz 782c0b437f1d4205d7ba012e02157fb984d656b0 node.exe c3bf16e3e2e268340a96fca869a1e3ce3ead46b5 node.exp b81ceddb831981b200f04403718b2adcd24fd5ed node.lib 1c009c51c273512eb76ef3a1e36d5d1ccf1e4094 node.pdb 8c90873802c40ecadb304002401ba857ad728f9c pkgsrc/nodejs-ia32-0.10.24.tgz 94eda460e90dd59886ee2543bb55c8baea6daf1c pkgsrc/nodejs-x64-0.10.24.tgz 9b36fd16d8a6eb95c375ced0e1929b88b3dbb3e6 x64/node-v0.10.24-x64.msi 43c51bf9ff7c6aa421c4c89a4b14e0ab1cb0527a x64/node.exe 74d67c1cad72c0231fdc3498a0ca90c09e49abfb x64/node.exp 724463c1a1bd3ad386e1089f53c7fa0ca16c38b6 x64/node.lib 58a6bcec861c0a8d20e90db348d3a4fbd49e88cc x64/node.pdb ``` node-v0.10.25~dfsg2/doc/blog/release/node-v0-6-4.md0000644000000000000000000000272612270121457020032 0ustar rootrootversion: 0.6.4 title: Node v0.6.4 author: bennoordhuis date: Thu Dec 01 2011 18:20:14 GMT-0800 (PST) status: publish category: release slug: node-v0-6-4 2011.12.02, Version 0.6.4 (stable)
    • doc improvements (Kyle Young, Tim Oxley, Roman Shtylman, Mathias Bynens)
    • upgrade bundled npm (Isaac Schlueter)
    • polish Windows installer (Igor Zinkovsky, Isaac Schlueter)
    • punycode: upgrade to v0.2.1 (Mathias Bynens)
    • build: add --without-npm flag to configure script
    • sys: deprecate module some more, print stack trace if NODE_DEBUG=sys
    • cli: add -p switch, prints result of --eval
    • #1997: fix Blowfish ECB encryption and decryption (Ingmar Runge)
    • #2223: fix socket 'close' event being emitted twice
    • #2224: fix RSS memory usage > 4 GB reporting (Russ Bradberry)
    • #2225: fix util.inspect() object stringification bug (Nathan Rajlich)
    Source Code: http://nodejs.org/dist/v0.6.4/node-v0.6.4.tar.gz Windows Installer: http://nodejs.org/dist/v0.6.4/node-v0.6.4.msi Macintosh Installer: http://nodejs.org/dist/v0.6.4/node-v0.6.4.pkg Website: http://nodejs.org/docs/v0.6.4/ Documentation: http://nodejs.org/docs/v0.6.4/api/ node-v0.10.25~dfsg2/doc/blog/release/version-0-7-12.md0000644000000000000000000001152612270121457020462 0ustar rootrootversion: 0.7.12 title: Version 0.7.12 author: Isaac Schlueter date: Tue Jun 19 2012 16:31:09 GMT-0700 (PDT) status: publish category: release slug: version-0-7-12

    2012.06.19, Version 0.7.12 (unstable)

    This is the last release on the 0.7 branch. Version 0.8.0 will be released some time later this week, barring any major problems.

    As with other even-numbered Node releases before it, the v0.8.x releases will maintain API and binary compatibility.

    The major changes between v0.6 and v0.8 are detailed in https://github.com/joyent/node/wiki/API-changes-between-v0.6-and-v0.8

    Please try out this release. There will be very virtually no changes between this and the v0.8.x release family. This is the last chance to comment before it is locked down for stability. The API is effectively frozen now.

    This version adds backwards-compatible shims for binary addons that use libeio and libev directly. If you find that binary modules that could compile on v0.6 can not compile on this version, please let us know. Note that libev is officially deprecated in v0.8, and will be removed in v0.9. You should be porting your modules to use libuv as soon as possible.

    V8 is on 3.11.10 currently, and will remain on the V8 3.11.x branch for the duration of Node v0.8.x.

    • npm: Upgrade to 1.1.30
      - Improved 'npm init'
      - Fix the 'cb never called' error from 'oudated' and 'update'
      - Add --save-bundle|-B config
      - Fix isaacs/npm#2465: Make npm script and windows shims cygwin-aware
      - Fix isaacs/npm#2452 Use --save(-dev|-optional) in npm rm
      - logstream option to replace removed logfd (Rod Vagg)
      - Read default descriptions from README.md files

    • Shims to support deprecated ev_* and eio_* methods (Ben Noordhuis)

    • #3118 net.Socket: Delay pause/resume until after connect (isaacs)

    • #3465 Add ./configure --no-ifaddrs flag (isaacs)

    • child_process: add .stdin stream to forks (Fedor Indutny)

    • build: fix make install DESTDIR=/path (Ben Noordhuis)

    • tls: fix off-by-one error in renegotiation check (Ben Noordhuis)

    • crypto: Fix diffie-hellman key generation UTF-8 errors (Fedor Indutny)

    • node: change the constructor name of process from EventEmitter to process (Andreas Madsen)

    • net: Prevent property access throws during close (Reid Burke)

    • querystring: improved speed and code cleanup (Felix Böhm)

    • sunos: fix assertion errors breaking fs.watch() (Fedor Indutny)

    • unix: stat: detect sub-second changes (Ben Noordhuis)

    • add stat() based file watcher (Ben Noordhuis)

    Source Code: http://nodejs.org/dist/v0.7.12/node-v0.7.12.tar.gz

    Macintosh Installer (Universal): http://nodejs.org/dist/v0.7.12/node-v0.7.12.pkg

    Windows Installer: http://nodejs.org/dist/v0.7.12/node-v0.7.12-x86.msi

    Windows x64 Installer: http://nodejs.org/dist/v0.7.12/x64/node-v0.7.12-x64.msi

    Windows x64 Files: http://nodejs.org/dist/v0.7.12/x64/

    Other release files: http://nodejs.org/dist/v0.7.12/

    Website: http://nodejs.org/docs/v0.7.12/

    Documentation: http://nodejs.org/docs/v0.7.12/api/

    Shasums

    ded6a2197b1149b594eb45fea921e8538ba442aa  blog.html
    dfabff0923d4b4f1d53bd9831514c1ac8c4b1876  email.md
    be313d35511e6d7e43cae5fa2b18f3e0d2275ba1  node-v0.7.12-x86.msi
    8f7ba0c8283e3863de32fd5c034f5b599c78f830  node-v0.7.12.pkg
    cb570abacbf4eb7e23c3d2620d00dd3080d9c19d  node-v0.7.12.tar.gz
    e13a6edfcba1c67ffe794982dd20a222ce8ce40f  node.exe
    20906ad76a43eca52795b2a089654a105e11c1e6  node.exp
    acbcbb87b6f7f2af34a3ed0abe6131d9e7a237af  node.lib
    4013d5b25fe36ae4245433b972818686cd9a2205  node.pdb
    6c0a7a2e8ee360e2800156293fb2f6a5c1a57382  npm-1.1.30.tgz
    9d23e42e8260fa20001d5618d2583a62792bf63f  npm-1.1.30.zip
    840157b2d6f7389ba70b07fc9ddc048b92c501cc  x64/node-v0.7.12-x64.msi
    862d42706c21ea83bf73cd827101f0fe598b0cf7  x64/node.exe
    de0af95fac083762f99c875f91bab830dc030f71  x64/node.exp
    3122bd886dfb96f3b41846cef0bdd7e97326044a  x64/node.lib
    e0fa4e42cd19cadf8179e492ca606b7232bbc018  x64/node.pdb
    node-v0.10.25~dfsg2/doc/blog/release/node-v0-5-4.md0000644000000000000000000000243612270121457020027 0ustar rootrootversion: 0.5.4 title: Node v0.5.4 author: ryandahl date: Fri Aug 12 2011 08:38:26 GMT-0700 (PDT) status: publish category: release slug: node-v0-5-4 2011.08.12, Version 0.5.4 (unstable)
    • libuv/Windows compatibility improvements
    • Build on Microsoft Visual Studio via GYP. Use generate-projects.bat in the to build sln files. (Peter Bright, Igor Zinkovsky)
    • Make Mikeal's HTTP agent client the default. Use old HTTP client with --use-http1
    • Fixes https host header default port handling. (Mikeal Rogers)
    • #1440 strip byte order marker when loading *.js and *.json files (Ben Noordhuis)
    • #1434 Improve util.format() compatibility with browser. (Koichi Kobayashi)
    • Provide unchecked uint entry points for integer Buffer.read/writeInt methods. (Robert Mustacchi)
    • CMake improvements (Tom Huges)
    • Upgrade V8 to 3.5.4.
    Download: http://nodejs.org/dist/v0.5.4/node-v0.5.4.tar.gz Windows Executable: http://nodejs.org/dist/v0.5.4/node.exe Website: http://nodejs.org/dist/v0.5.4/docs Documentation: http://nodejs.org/dist/v0.5.4/docs/api node-v0.10.25~dfsg2/doc/blog/release/v0.10.23.md0000644000000000000000000000613412270121457017242 0ustar rootrootdate: Wed Dec 11 22:10:46 PST 2013 version: 0.10.23 category: release title: Node v0.10.23 (Stable) slug: node-v0-10-23-stable 2013.12.12, Version 0.10.23 (Stable) * uv: Upgrade to v0.10.20 (Timothy J Fontaine) * npm: Upgrade to 1.3.17 (isaacs) * gyp: update to 78b26f7 (Timothy J Fontaine) * build: include postmortem symbols on linux (Timothy J Fontaine) * crypto: Make Decipher._flush() emit errors. (Kai Groner) * dgram: fix abort when getting `fd` of closed dgram (Fedor Indutny) * events: do not accept NaN in setMaxListeners (Fedor Indutny) * events: avoid calling `once` functions twice (Tim Wood) * events: fix TypeError in removeAllListeners (Jeremy Martin) * fs: report correct path when EEXIST (Fedor Indutny) * process: enforce allowed signals for kill (Sam Roberts) * tls: emit 'end' on .receivedShutdown (Fedor Indutny) * tls: fix potential data corruption (Fedor Indutny) * tls: handle `ssl.start()` errors appropriately (Fedor Indutny) * tls: reset NPN callbacks after SNI (Fedor Indutny) Source Code: http://nodejs.org/dist/v0.10.23/node-v0.10.23.tar.gz Macintosh Installer (Universal): http://nodejs.org/dist/v0.10.23/node-v0.10.23.pkg Windows Installer: http://nodejs.org/dist/v0.10.23/node-v0.10.23-x86.msi Windows x64 Installer: http://nodejs.org/dist/v0.10.23/x64/node-v0.10.23-x64.msi Windows x64 Files: http://nodejs.org/dist/v0.10.23/x64/ Linux 32-bit Binary: http://nodejs.org/dist/v0.10.23/node-v0.10.23-linux-x86.tar.gz Linux 64-bit Binary: http://nodejs.org/dist/v0.10.23/node-v0.10.23-linux-x64.tar.gz Solaris 32-bit Binary: http://nodejs.org/dist/v0.10.23/node-v0.10.23-sunos-x86.tar.gz Solaris 64-bit Binary: http://nodejs.org/dist/v0.10.23/node-v0.10.23-sunos-x64.tar.gz Other release files: http://nodejs.org/dist/v0.10.23/ Website: http://nodejs.org/docs/v0.10.23/ Documentation: http://nodejs.org/docs/v0.10.23/api/ Shasums: ``` 80980a23ec1915a0d4522fd4423a2eee25bf9ba5 node-v0.10.23-darwin-x64.tar.gz c9c0f6772f2bda746d3997f4d821da9090dcd2a3 node-v0.10.23-darwin-x86.tar.gz 4c7d17ae61c753750e8f5ae989e3d80f7c8f89ea node-v0.10.23-linux-x64.tar.gz afa901a312350ec8b271d402261a7882e1d3640b node-v0.10.23-linux-x86.tar.gz 30d5e06cfed35eea80d5ee4643858c157d104a85 node-v0.10.23-sunos-x64.tar.gz 2c4ce154b8595848119bb63164ca021f4fe8457e node-v0.10.23-sunos-x86.tar.gz d51b641354a41243830ff6e3bdd1e03a7758fc38 node-v0.10.23-x86.msi a7711fbb958350011641c218dae64c0c6f1f80a8 node-v0.10.23.pkg 8717942d1bdfa8902ce65cd33b4293d16b486c64 node-v0.10.23.tar.gz 12d1e0a6373bb2b67129c7f0ebc514b793b106af node.exe 9f107c4dba21fee76bbb5ac2fe552d40e6ae5e70 node.exp 52b4c463f8b667c24a54a0d8cd583b677706ae3c node.lib ec619173e2e867b929d4178ecbe561639aed4cb2 node.pdb 837ff717c2842c32e0804ce6c131404fc8599d8d pkgsrc/nodejs-ia32-0.10.23.tgz 395e9fe9e32874a24febffa17adacd7e1e387e63 pkgsrc/nodejs-x64-0.10.23.tgz 56892aadf1c9d2d2bc637ee87bd08775a139b252 x64/node-v0.10.23-x64.msi 663d9dd7face6399f5c0b7d6082ec2d5b4acc2c3 x64/node.exe 601b564b73df1f4a871ed55e2e2c9aee5b28f04d x64/node.exp 523e3f96f45132d2e5e2eb39a1dbd0c5bf6b8822 x64/node.lib 2624cddcbd23c84d947af2bf2b91b1e0b64e3602 x64/node.pdb ``` node-v0.10.25~dfsg2/doc/blog/release/v0.10.7.md0000644000000000000000000000446612270121457017172 0ustar rootrootdate: Fri May 17 14:36:03 PDT 2013 version: 0.10.7 category: release title: Node v0.10.7 (Stable) slug: node-v0-10-7-stable 2013.05.17, Version 0.10.7 (Stable) * uv: upgrade to v0.10.7 * npm: Upgrade to 1.2.21 * crypto: Don't ignore verify encoding argument (isaacs) * buffer, crypto: fix default encoding regression (Ben Noordhuis) * timers: fix setInterval() assert (Ben Noordhuis) Source Code: http://nodejs.org/dist/v0.10.7/node-v0.10.7.tar.gz Macintosh Installer (Universal): http://nodejs.org/dist/v0.10.7/node-v0.10.7.pkg Windows Installer: http://nodejs.org/dist/v0.10.7/node-v0.10.7-x86.msi Windows x64 Installer: http://nodejs.org/dist/v0.10.7/x64/node-v0.10.7-x64.msi Windows x64 Files: http://nodejs.org/dist/v0.10.7/x64/ Linux 32-bit Binary: http://nodejs.org/dist/v0.10.7/node-v0.10.7-linux-x86.tar.gz Linux 64-bit Binary: http://nodejs.org/dist/v0.10.7/node-v0.10.7-linux-x64.tar.gz Solaris 32-bit Binary: http://nodejs.org/dist/v0.10.7/node-v0.10.7-sunos-x86.tar.gz Solaris 64-bit Binary: http://nodejs.org/dist/v0.10.7/node-v0.10.7-sunos-x64.tar.gz Other release files: http://nodejs.org/dist/v0.10.7/ Website: http://nodejs.org/docs/v0.10.7/ Documentation: http://nodejs.org/docs/v0.10.7/api/ Shasums: ``` 95d64001ccd5a17c2c25f1ae4b0358b6131e7cb8 node-v0.10.7-darwin-x64.tar.gz c34f991cc0752679002f763b2b3c8927babb08d8 node-v0.10.7-darwin-x86.tar.gz 673c287bcf671eced6aa94637b7c91e5149f4c56 node-v0.10.7-linux-x64.tar.gz 9f14d4f9add721148f0c15f093d3e6b1fa3820c9 node-v0.10.7-linux-x86.tar.gz 1fb7dc4195a9dd228039f5f7ca2cb9f7c35b105a node-v0.10.7-sunos-x64.tar.gz d84cd8afb50df44483b9dab0c65d5c81f07ac4a2 node-v0.10.7-sunos-x86.tar.gz d7794a7da103d639fdec4b9e7236a5a0a4330297 node-v0.10.7-x86.msi 0524ad9268095c9ed435708268e6aad7968309f7 node-v0.10.7.pkg f2bde505faf6ffed3084c8e550a9e6d4311f13d5 node-v0.10.7.tar.gz 5f50384766dd5435dba4989d95032452754150bf node.exe 809f12f84c8495d101ce6ae443890e8533695ab0 node.exp 5a7355e2f75ae3f72deab75f4c9f93e4e5325584 node.lib 6e45953bd7488a4236c43fea93b05da0854158a7 node.pdb fc5e3b2b1c74e53f1d214a9e2d5af30fe5247381 x64/node-v0.10.7-x64.msi aa67bbd421f26b37fa09ce30d5e626106677853e x64/node.exe b289989a156d4d7055554962e6f00ba3e380aeea x64/node.exp 0dbecc5007c9e28ad488d2058157f8360eaed958 x64/node.lib e4b63472787a3db6a3d85237e8c7fb4d973f797b x64/node.pdb ``` node-v0.10.25~dfsg2/doc/blog/release/v0.10.21.md0000644000000000000000000000533212270121457017237 0ustar rootrootdate: Fri Oct 18 15:39:23 PDT 2013 version: 0.10.21 category: release title: Node v0.10.21 (Stable) slug: node-v0-10-21-stable This release contains a security fix for the http server implementation, please upgrade as soon as possible. Details will be released soon. 2013.10.18, Version 0.10.21 (Stable) * uv: Upgrade to v0.10.18 * crypto: clear errors from verify failure (Timothy J Fontaine) * dtrace: interpret two byte strings (Dave Pacheco) * fs: fix fs.truncate() file content zeroing bug (Ben Noordhuis) * http: provide backpressure for pipeline flood (isaacs) * tls: fix premature connection termination (Ben Noordhuis) Source Code: http://nodejs.org/dist/v0.10.21/node-v0.10.21.tar.gz Macintosh Installer (Universal): http://nodejs.org/dist/v0.10.21/node-v0.10.21.pkg Windows Installer: http://nodejs.org/dist/v0.10.21/node-v0.10.21-x86.msi Windows x64 Installer: http://nodejs.org/dist/v0.10.21/x64/node-v0.10.21-x64.msi Windows x64 Files: http://nodejs.org/dist/v0.10.21/x64/ Linux 32-bit Binary: http://nodejs.org/dist/v0.10.21/node-v0.10.21-linux-x86.tar.gz Linux 64-bit Binary: http://nodejs.org/dist/v0.10.21/node-v0.10.21-linux-x64.tar.gz Solaris 32-bit Binary: http://nodejs.org/dist/v0.10.21/node-v0.10.21-sunos-x86.tar.gz Solaris 64-bit Binary: http://nodejs.org/dist/v0.10.21/node-v0.10.21-sunos-x64.tar.gz Other release files: http://nodejs.org/dist/v0.10.21/ Website: http://nodejs.org/docs/v0.10.21/ Documentation: http://nodejs.org/docs/v0.10.21/api/ Shasums: ``` fb1318fb7721aa292310599e7c6696edebcfd70d node-v0.10.21-darwin-x64.tar.gz 486235cc54d269d1961dfb150b1479ec14e83541 node-v0.10.21-darwin-x86.tar.gz 7528d2fa240a5dd88d37e4847cebec50ef40c8eb node-v0.10.21-linux-x64.tar.gz b372abf9d9c53bfe675e2c3f71dcfdece44edddd node-v0.10.21-linux-x86.tar.gz cb873cdff3f30aa198b52c8be3588745d2ee3933 node-v0.10.21-sunos-x64.tar.gz 020d202d7066b68f160d0ceebe8cc8306de25956 node-v0.10.21-sunos-x86.tar.gz 037ea0e3be3512da2bc94aa765fa89d61da3e275 node-v0.10.21-x86.msi de2bd0e858f99098ef24f99f972b8088c1f0405c node-v0.10.21.pkg b7fd2a3660635af40e3719ca0db49280d10359b2 node-v0.10.21.tar.gz a0e3988170beee1273a2fb6d650bf17db8495c67 node.exe 99332a03aeba8a22254d671665b9b2161a64bd84 node.exp 263dafeec907bd1f28ceb8272b9caaadceacb4d6 node.lib 76d578bf352772dc4db9ebb95fb61cf18e34c80d node.pdb b6d11b67ce7aaff5c7a456a4c85c80849a3d576e pkgsrc/nodejs-ia32-0.10.21.tgz b116825d1d2cbcfd567f730b1c2452424508b062 pkgsrc/nodejs-x64-0.10.21.tgz 29632c5a21a4ebf89703e417852306a676f6ede8 x64/node-v0.10.21-x64.msi 033b0a2b57e031a9e47f0b28eb4dc50a5389b592 x64/node.exe f62b53229d77eaddf1f3a7909ef6533eea0e2295 x64/node.exp 8d5cfe83c3bc78ddcf79de9d065d1b4f2af9347e x64/node.lib 6844e78e9ba80bfa48f6c150544e3e73d83dd316 x64/node.pdb ``` node-v0.10.25~dfsg2/doc/blog/release/version-0-7-10-unstable.md0000644000000000000000000000612412270121457022271 0ustar rootrootversion: 0.7.10 title: Version 0.7.10 (unstable) author: Isaac Schlueter date: Mon Jun 11 2012 09:00:25 GMT-0700 (PDT) status: publish category: release slug: version-0-7-10-unstable

    2012.06.11, Version 0.7.10 (unstable)

    This is the second-to-last release on the 0.7 branch. Version 0.8.0 will be released some time next week. As other even-numbered Node releases before it, the v0.8.x releases will maintain API and binary compatibility.

    The major changes are detailed in https://github.com/joyent/node/wiki/API-changes-between-v0.6-and-v0.8

    Please try out this release. There will be very few changes between this and the v0.8.x release family. This is the last chance to comment on the API before it is locked down for stability.

    • Roll V8 back to 3.9.24.31

    • build: x64 target should always pass -m64 (Robert Mustacchi)

    • add NODE_EXTERN to node::Start (Joel Brandt)

    • repl: Warn about running npm commands (isaacs)

    • slab_allocator: fix crash in dtor if V8 is dead (Ben Noordhuis)

    • slab_allocator: fix leak of Persistent handles (Shigeki Ohtsu)

    • windows/msi: add node.js prompt to startmenu (Jeroen Janssen)

    • windows/msi: fix adding node to PATH (Jeroen Janssen)

    • windows/msi: add start menu links when installing (Jeroen Janssen)

    • windows: don't install x64 version into the 'program files (x86)' folder (Matt Gollob)

    • domain: Fix #3379 domain.intercept no longer passes error arg to cb (Marc Harter)

    • fs: make callbacks run in global context (Ben Noordhuis)

    • fs: enable fs.realpath on windows (isaacs)

    • child_process: expose UV_PROCESS_DETACHED as options.detached (Charlie McConnell)

    • child_process: new stdio API for .spawn() method (Fedor Indutny)

    • child_process: spawn().ref() and spawn().unref() (Fedor Indutny)

    • Upgrade npm to 1.1.25

      • Enable npm link on windows
      • Properly remove sh-shim on Windows
      • Abstract out registry client and logger

    Source Code: http://nodejs.org/dist/v0.7.10/node-v0.7.10.tar.gz

    Windows Installer: http://nodejs.org/dist/v0.7.10/node-v0.7.10.msi

    Windows x64 Files: http://nodejs.org/dist/v0.7.10/x64/

    Macintosh Installer (Universal): http://nodejs.org/dist/v0.7.10/node-v0.7.10.pkg

    Other release files: http://nodejs.org/dist/v0.7.10/

    Website: http://nodejs.org/docs/v0.7.10/

    Documentation: http://nodejs.org/docs/v0.7.10/api/

    node-v0.10.25~dfsg2/doc/blog/release/v0.9.12.md0000644000000000000000000000726212270121457017173 0ustar rootrootdate: Wed Mar 6 13:51:00 PST 2013 version: 0.9.12 category: release title: Node v0.9.12 (Unstable) slug: node-v0-9-12-unstable As of this release, Node v0.9 is finally performing faster than v0.8 on HTTP, file system, and TLS benchmarks. Unless there are serious problems found, v0.10.0 will be released on Monday, 2013.03.11, along with more details about the benchmark results and the plans for what comes next. Please consider this a v0.10 Release Candidate. Use it in your programs. It is as stable as 0.9 is going to get. ---- 2013.03.06, Version 0.9.12 (Unstable) * stream: Allow strings in Readable.push/unshift (isaacs) * stream: Remove bufferSize option (isaacs) * stream: Increase highWaterMark on large reads (isaacs) * stream: _write: takes an encoding argument (isaacs) * stream: _transform: remove output() method, provide encoding (isaacs) * stream: Don't require read(0) to emit 'readable' event (isaacs) * node: Add --throw-deprecation (isaacs) * http: fix multiple timeout events (Eugene Girshov) * http: More useful setTimeout API on server (isaacs) * net: use close callback, not process.nextTick (Ben Noordhuis) * net: Provide better error when writing after FIN (isaacs) * dns: Support NAPTR queries (Pavel Lang) * dns: fix ReferenceError in resolve() error path (Xidorn Quan) * child_process: handle ENOENT correctly on Windows (Scott Blomquist) * cluster: Rename destroy() to kill(signal=SIGTERM) (isaacs) * build: define nightly tag external to build system (Timothy J Fontaine) * build: make msi build work when spaces are present in the path (Bert Belder) * build: fix msi build issue with WiX 3.7/3.8 (Raymond Feng) * repl: make compatible with domains (Dave Olszewski) * events: Code cleanup and performance improvements (Trevor Norris) Source Code: http://nodejs.org/dist/v0.9.12/node-v0.9.12.tar.gz Macintosh Installer (Universal): http://nodejs.org/dist/v0.9.12/node-v0.9.12.pkg Windows Installer: http://nodejs.org/dist/v0.9.12/node-v0.9.12-x86.msi Windows x64 Installer: http://nodejs.org/dist/v0.9.12/x64/node-v0.9.12-x64.msi Windows x64 Files: http://nodejs.org/dist/v0.9.12/x64/ Linux 32-bit Binary: http://nodejs.org/dist/v0.9.12/node-v0.9.12-linux-x86.tar.gz Linux 64-bit Binary: http://nodejs.org/dist/v0.9.12/node-v0.9.12-linux-x64.tar.gz Solaris 32-bit Binary: http://nodejs.org/dist/v0.9.12/node-v0.9.12-sunos-x86.tar.gz Solaris 64-bit Binary: http://nodejs.org/dist/v0.9.12/node-v0.9.12-sunos-x64.tar.gz Other release files: http://nodejs.org/dist/v0.9.12/ Website: http://nodejs.org/docs/v0.9.12/ Documentation: http://nodejs.org/docs/v0.9.12/api/ Shasums: ``` caa171a35f7eb36fd585f4e16dbf1c60f9d056af node-v0.9.12-darwin-x64.tar.gz ffd98e60cdb630c4239c3d94e89b5ba84fb8d234 node-v0.9.12-darwin-x86.tar.gz 85c008721b33872085c3af6253b6e92a6587a467 node-v0.9.12-linux-x64.tar.gz cc3d50b8ba0474f1907959aae5dfa5e64801bc6b node-v0.9.12-linux-x86.tar.gz bcedc7c18f9984ea8873752672a09622e56008e1 node-v0.9.12-sunos-x64.tar.gz 4a7e2baf41fc994044c204a9c90eb894b60ee4c3 node-v0.9.12-sunos-x86.tar.gz 0f7c4f600768736c0e7107e7da33a748a4e2d61e node-v0.9.12-x86.msi a9e610225a6cad24923a7242eba97ab1577f3886 node-v0.9.12.pkg 2353d3e5c6518f75202b74236fa9d8eeecd26ca3 node-v0.9.12.tar.gz 9be76f46fbfc66a84fbd02210b6422f14d5dd7eb node.exe 1f528fdf910036bb791fc6031e2dc9aff300f7eb node.exp 6aec59165f64fea2e89b6ec4ddbf55ab630b318f node.lib fd575f13dc714fdeb64f814e67db9ef5d142e7f8 node.pdb 442dae32457159a579eb44da12c7c5f182c1ae4c x64/node-v0.9.12-x64.msi 8dc7f6fec9172a5e606ca1b6b3520178313caa29 x64/node.exe f441fb3807930ee658a105db97ec61a2b5e331d4 x64/node.exp f8b3880e5fa00151343bf0000f324ea9e96155a7 x64/node.lib 7adb54566301d39866e93506ffc9391870f9c644 x64/node.pdb ``` node-v0.10.25~dfsg2/doc/blog/release/v0.11.5.md0000644000000000000000000000615112270121457017162 0ustar rootrootdate: Tue Aug 6 17:05:46 PDT 2013 version: 0.11.5 category: release title: Node v0.11.5 (Unstable) slug: node-v0-11-5-unstable 2013.08.06, Version 0.11.5 (Unstable) * v8: upgrade to 3.20.11 * uv: upgrade to v0.11.7 * buffer: return offset for end of last write (Trevor Norris) * build: embed the mdb_v8.so into the binary (Timothy J Fontaine) * build: fix --without-ssl build (Ben Noordhuis) * child_process: add 'shell' option to .exec() (Ben Noordhuis) * dgram: report send errors to cb, don't pass bytes (Ben Noordhuis) * fs: write strings directly to disk (Trevor Norris) * https: fix default port (Koichi Kobayashi) * openssl: use asm for sha, md5, rmd (Fedor Indutny) * os: add mac address to networkInterfaces() output (Brian White) * smalloc: introduce smalloc module (Trevor Norris) * stream: Simplify flowing, passive data listening (streams3) (isaacs) * tls: asynchronous SNICallback (Fedor Indutny) * tls: share tls tickets key between cluster workers (Fedor Indutny) * util: don't throw on circular %j input to format() (Ben Noordhuis) Source Code: http://nodejs.org/dist/v0.11.5/node-v0.11.5.tar.gz Macintosh Installer (Universal): http://nodejs.org/dist/v0.11.5/node-v0.11.5.pkg Windows Installer: http://nodejs.org/dist/v0.11.5/node-v0.11.5-x86.msi Windows x64 Installer: http://nodejs.org/dist/v0.11.5/x64/node-v0.11.5-x64.msi Windows x64 Files: http://nodejs.org/dist/v0.11.5/x64/ Linux 32-bit Binary: http://nodejs.org/dist/v0.11.5/node-v0.11.5-linux-x86.tar.gz Linux 64-bit Binary: http://nodejs.org/dist/v0.11.5/node-v0.11.5-linux-x64.tar.gz Solaris 32-bit Binary: http://nodejs.org/dist/v0.11.5/node-v0.11.5-sunos-x86.tar.gz Solaris 64-bit Binary: http://nodejs.org/dist/v0.11.5/node-v0.11.5-sunos-x64.tar.gz Other release files: http://nodejs.org/dist/v0.11.5/ Website: http://nodejs.org/docs/v0.11.5/ Documentation: http://nodejs.org/docs/v0.11.5/api/ Shasums: ``` a48c7c1ffa0344ab4c7f9b3466ed76d8b7ce4385 node-v0.11.5-darwin-x64.tar.gz c18ef8b45a4a6a8afebaa0c43f7388f20c6dee92 node-v0.11.5-darwin-x86.tar.gz caa13a498ef32b09c717c86c7b9e5be1feb34a42 node-v0.11.5-linux-x64.tar.gz 1b55090713d6cb4fadab080f4e50bc5e2b9ee2fe node-v0.11.5-linux-x86.tar.gz 7cfc4574dd70517d46856c03751e362e61049d70 node-v0.11.5-sunos-x64.tar.gz 443e4e51a49e34b5d62b7ead3e0b1079cae05dd9 node-v0.11.5-sunos-x86.tar.gz 1042917fb1fa5ae8d387f918924a8dcd15f4d6a3 node-v0.11.5-x86.msi 0e832e2e466c1ffffed1e7ed781fb9366339d053 node-v0.11.5.pkg 5cd49ac41bb6929a43aaf77037d051fe794e5ad3 node-v0.11.5.tar.gz 432da8b8e801ec8660ddbeb73524fc8cb74da8ea node.exe 1d724ca5211148180ba0154575648edd758ec2c8 node.exp ef12c19e95e671debfa96afe3496afbb8f16283d node.lib 12fefe001a90260ca6e403aa27d770611d2bdd51 node.pdb 96e15938a6845895cde1ca6db64ba86350bd4d06 pkgsrc/nodejs-ia32-0.11.5.tgz 960ade5a3cf7ac7b1b35755f204e9adfb784cc4a pkgsrc/nodejs-x64-0.11.5.tgz 151ab6ffe45d84918edd9c95bda378fdefe170b8 x64/node-v0.11.5-x64.msi c2b0f6130539a6ad22206308050b34a44026ce26 x64/node.exe 89c631942ec57e30165ddbb637da0100493c3f7b x64/node.exp 719b857474a8e3eb7269778414d7af2aee855ede x64/node.lib f2eebec1949f4d7da59d3a2135207ac4c2fe0161 x64/node.pdb ``` node-v0.10.25~dfsg2/doc/blog/release/node-v0-5-1.md0000644000000000000000000000231212270121457020015 0ustar rootrootversion: 0.5.1 title: Node v0.5.1 author: ryandahl date: Thu Jul 14 2011 23:48:08 GMT-0700 (PDT) status: publish category: release slug: node-v0-5-1 2011.07.14, Version 0.5.1 (unstable)
    • #1233 Fix os.totalmem on FreeBSD amd64 (Artem Zaytsev)
    • #1149 IDNA and Punycode support in url.parse (Jeremy Selier, Ben Noordhuis, isaacs)
    • Export $CC and $CXX to uv and V8's build systems
    • Include pthread-win32 static libraries in build (Igor Zinkovsky)
    • #1199, #1094 Fix fs can't handle large file on 64bit platform (koichik)
    • #1281 Make require a public member of module (isaacs)
    • #1303 Stream.pipe returns the destination (Elijah Insua)
    • #1229 Addons should not -DEV_MULTIPLICITY=0 (Brian White)
    • libuv backend improvements
    • Upgrade V8 to 3.4.10
    Download: http://nodejs.org/dist/v0.5.1/node-v0.5.1.tar.gz Windows Build: http://nodejs.org/dist/v0.5.1/node.exe Documentation: http://nodejs.org/dist/v0.5.1/docs/api/ Website: http://nodejs.org/dist/v0.5.1/docs node-v0.10.25~dfsg2/doc/blog/release/node-v0-5-9.md0000644000000000000000000000246412270121457020035 0ustar rootrootversion: 0.5.9 title: Node v0.5.9 author: ryandahl date: Mon Oct 10 2011 19:06:21 GMT-0700 (PDT) status: publish category: release slug: node-v0-5-9 2011.10.10, Version 0.5.9 (unstable)
    • fs.watch interface backed by kqueue, inotify, and ReadDirectoryChangesW (Igor Zinkovsky, Ben Noordhuis)
    • add dns.resolveTxt (Christian Tellnes)
    • Remove legacy http library (Ben Noordhuis)
    • child_process.fork returns and works on Windows. Allows passing handles. (Igor Zinkovsky, Bert Belder)
    • #1774 Lint and clean up for --harmony_block_scoping (Tyler Larson, Colton Baker)
    • #1813 Fix ctrl+c on Windows (Bert Belder)
    • #1844 unbreak --use-legacy (Ben Noordhuis)
    • process.stderr now goes through libuv. Both process.stdout and process.stderr are blocking when referencing a TTY.
    • net_uv performance improvements (Ben Noordhuis, Bert Belder)
    Download: http://nodejs.org/dist/v0.5.9/node-v0.5.9.tar.gz Windows Executable: http://nodejs.org/dist/v0.5.9/node.exe Website: http://nodejs.org/docs/v0.5.9/ Documentation: http://nodejs.org/docs/v0.5.9/api/ node-v0.10.25~dfsg2/doc/blog/release/v0.8.1.md0000644000000000000000000000456312270121457017111 0ustar rootrootversion: 0.8.1 title: Version 0.8.1 (stable) category: release slug: node-v0-8-1-stable date: 2012.06.29 2012.06.29, Version 0.8.1 (stable) * V8: upgrade to v3.11.10.12 * npm: upgrade to v1.1.33 - Support for parallel use of the cache folder - Retry on registry timeouts or network failures (Trent Mick) - Reduce 'engines' failures to a warning - Use new zsh completion if available (Jeremy Cantrell) * Fix #3577 Un-break require('sys') * util: speed up formatting of large arrays/objects (Ben Noordhuis) * windows: make fs.realpath(Sync) work with UNC paths (Bert Belder) * build: fix --shared-v8 option (Ben Noordhuis) * doc: `detached` is a boolean (Andreas Madsen) * build: use proper python interpreter (Ben Noordhuis) * build: expand ~ in `./configure --prefix=~/a/b/c` (Ben Noordhuis) * build: handle CC env var with spaces (Gabriel de Perthuis) * build: fix V8 build when compiling with gcc 4.5 (Ben Noordhuis) * build: fix --shared-v8 option (Ben Noordhuis) * windows msi: Fix icon issue which caused huge file size (Bert Belder) * unix: assume that dlopen() may clobber dlerror() (Ben Noordhuis) * sunos: fix memory corruption bugs (Ben Noordhuis) * windows: better (f)utimes and (f)stat (Bert Belder) Source Code: http://nodejs.org/dist/v0.8.1/node-v0.8.1.tar.gz Macintosh Installer (Universal): http://nodejs.org/dist/v0.8.1/node-v0.8.1.pkg Windows Installer: http://nodejs.org/dist/v0.8.1/node-v0.8.1-x86.msi Windows x64 Installer: http://nodejs.org/dist/v0.8.1/x64/node-v0.8.1-x64.msi Windows x64 Files: http://nodejs.org/dist/v0.8.1/x64/ Other release files: http://nodejs.org/dist/v0.8.1/ Website: http://nodejs.org/docs/v0.8.1/ Documentation: http://nodejs.org/docs/v0.8.1/api/ Shasums: ``` 64f10cb29aaaabda83300c81d61b56a436308126 node-v0.8.1-x86.msi 75a1afca1221719ec4a9dd8ed35c0e0adbaaf153 node-v0.8.1.pkg 892790553b8121ba8624d8293d0cb7d8b01094d7 node-v0.8.1.tar.gz 85ce513182bd66c1aa3e144438022dbe4caa56a7 node.exe 592426620080c904c55ac83e151a85d42275656e node.exp 88a9177dba73597ffc08f30b886542c4d76378e2 node.lib 6b06ffd2b6e28e34189663af7b3efda5d12dd1bf node.pdb c6d99aa58167c5489e56e2f99da99731fb4f282e x64/node-v0.8.1-x64.msi 4266ba03b2b4516d10cbc5d16eb15d5df13ebb47 x64/node.exe 7a6d0b28be88c6941aae74426199e9fb82ddfaa5 x64/node.exp ac21ec0f61baaf584f89a92db403cd9d38ff4850 x64/node.lib 9e514c4c6c427dd4ae16edf1d2ad7a46ef9893c0 x64/node.pdb ``` node-v0.10.25~dfsg2/doc/blog/release/v0.8.4.md0000644000000000000000000000353512270121457017112 0ustar rootrootcategory: release date: 2012-07-25T17:21:16.176Z version: 0.8.4 title: Version 0.8.4 (Stable) slug: node-v0-8-4-stable 2012.07.25, Version 0.8.4 (Stable) * V8: Upgrade to 3.11.10.17 * npm: Upgrade to 1.1.45 * net: fix Socket({ fd: 42 }) api (Ben Noordhuis) * readline: Remove event listeners on close (isaacs) * windows: correctly prep long path for fs.exists(Sync) (Bert Belder) * debugger: wake up the event loop when a debugger command is dispatched (Peter Rybin) * tls: verify server's identity (Fedor Indutny) * net: ignore socket.setTimeout(Infinity or NaN) (Fedor Indutny) Source Code: http://nodejs.org/dist/v0.8.4/node-v0.8.4.tar.gz Macintosh Installer (Universal): http://nodejs.org/dist/v0.8.4/node-v0.8.4.pkg Windows Installer: http://nodejs.org/dist/v0.8.4/node-v0.8.4-x86.msi Windows x64 Installer: http://nodejs.org/dist/v0.8.4/x64/node-v0.8.4-x64.msi Windows x64 Files: http://nodejs.org/dist/v0.8.4/x64/ Other release files: http://nodejs.org/dist/v0.8.4/ Website: http://nodejs.org/docs/v0.8.4/ Documentation: http://nodejs.org/docs/v0.8.4/api/ Shasums: ``` 387d7ac58d79dac301960510dfb7ee96fbf39072 node-v0.8.4-x86.msi 66687da0ef190e8c07d5499ae3c408a6cca7ac30 node-v0.8.4.pkg 8473e3dd48ab3734e2c92de0518cb80c2cdf750f node-v0.8.4.tar.gz 724ec6dc5e86805bfac79c8a702638c353850ea3 node.exe 9bf483f72ad7884988d0678f7dc5bc000f4d21d2 node.exp 3b7bd3915b62896e5c2f5701fd5d1c7fb53cdd27 node.lib 9c3079ee727d471cef9fd91c7067d0a72349bfcb node.pdb 236a693074f2c69157e2918d1342a7850fc939ca npm-1.1.45.tgz 7126700cb321f688901e7773785eb88274906d50 npm-1.1.45.zip e9f414ba043f1daa5eee65506ef33c5377d87a09 x64/node-v0.8.4-x64.msi 4cc86f21285b7f3d3cbd594ba604f06fb3434502 x64/node.exe 6bf207a6b587bf1b01f18e9d0f2eefb528d82c2f x64/node.exp e7b0d65992324b0688c61f6e534f3527e7e0b59f x64/node.lib 9a0072f528f9055531dee2bfa991882836b235de x64/node.pdb ``` node-v0.10.25~dfsg2/doc/blog/release/node-version-0-7-9-unstable.md0000644000000000000000000000477312270121457023154 0ustar rootrootversion: 0.7.9 title: Node Version 0.7.9 (unstable) author: Isaac Schlueter date: Tue May 29 2012 10:11:45 GMT-0700 (PDT) status: publish category: release slug: node-version-0-7-9-unstable

    2012.05.28, Version 0.7.9 (unstable)

    • Upgrade V8 to 3.11.1

    • Upgrade npm to 1.1.23

    • uv: rework reference counting scheme (Ben Noordhuis)

    • uv: add interface for joining external event loops (Bert Belder)

    • repl, readline: Handle Ctrl+Z and SIGCONT better (Nathan Rajlich)

    • fs: 64bit offsets for fs calls (Igor Zinkovsky)

    • fs: add sync open flags 'rs' and 'rs+' (Kevin Bowman)

    • windows: enable creating directory junctions with fs.symlink (Igor Zinkovsky, Bert Belder)

    • windows: fix fs.lstat to properly detect symlinks. (Igor Zinkovsky)

    • Fix #3270 Escape url.parse delims (isaacs)

    • http: make http.get() accept a URL (Adam Malcontenti-Wilson)

    • Cleanup vm module memory leakage (Marcel Laverdet)

    • Optimize writing strings with Socket.write (Bert Belder)

    • add support for CESU-8 and UTF-16LE encodings (koichik)

    • path: add path.sep to get the path separator. (Yi, EungJun)

    • net, http: add backlog parameter to .listen() (Erik Dubbelboer)

    • debugger: support mirroring Date objects (Fedor Indutny)

    • addon: add AtExit() function (Ben Noordhuis)

    • net: signal localAddress bind failure in connect (Brian Schroeder)

    • util: handle non-string return value in .inspect() (Alex Kocharin)

    Source Code: http://nodejs.org/dist/v0.7.9/node-v0.7.9.tar.gz

    Windows Installer: http://nodejs.org/dist/v0.7.9/node-v0.7.9.msi

    Windows x64 Files: http://nodejs.org/dist/v0.7.9/x64/

    Macintosh Installer (Universal): http://nodejs.org/dist/v0.7.9/node-v0.7.9.pkg

    Other release files: http://nodejs.org/dist/v0.7.9/

    Website: http://nodejs.org/docs/v0.7.9/

    Documentation: http://nodejs.org/docs/v0.7.9/api/

    node-v0.10.25~dfsg2/doc/blog/release/node-version-0-6-19-stable.md0000644000000000000000000000443212270121457022661 0ustar rootrootversion: 0.6.19 title: Node Version 0.6.19 (stable) author: Isaac Schlueter date: Wed Jun 06 2012 09:55:37 GMT-0700 (PDT) status: publish category: release slug: node-version-0-6-19-stable

    2012.06.06 Version 0.6.19 (stable)

    • npm: upgrade to 1.1.24

    • fs: no end emit after createReadStream.pause() (Andreas Madsen)

    • vm: cleanup module memory leakage (Marcel Laverdet)

    • unix: fix loop starvation under high network load (Ben Noordhuis)

    • unix: remove abort() in ev_unref() (Ben Noordhuis)

    • windows/tty: never report error after forcibly aborting line-buffered read (Bert Belder)

    • windows: skip GetFileAttributes call when opening a file (Bert Belder)

    Source Code: http://nodejs.org/dist/v0.6.19/node-v0.6.19.tar.gz

    Windows Installer: http://nodejs.org/dist/v0.6.19/node-v0.6.19.msi

    Windows x64 Files: http://nodejs.org/dist/v0.6.19/x64/

    Macintosh Installer (Universal): http://nodejs.org/dist/v0.6.19/node-v0.6.19.pkg

    Other release files: http://nodejs.org/dist/v0.6.19/

    Website: http://nodejs.org/docs/v0.6.19/

    Documentation: http://nodejs.org/docs/v0.6.19/api/

    Shasums:

    ef4f5c1e5f12f6ef3478a794d6a81f59669332f9  node-v0.6.19.msi
    781616f33208f532f168633758a648c20e1ea68b  node-v0.6.19.pkg
    f6c5cfbadff4788ac3a95f8263a0c2f4e07444b6  node-v0.6.19.tar.gz
    10f729ca236825821d97556441fa64f994cb4ca8  node.exe
    5b8cd02e5f92ed6512aabdac11766ad8c1abc436  node.exp
    20037e4901de605e08e48d0c85531334912844e3  node.lib
    c44f62852918d449850014d9b29dd073cb6920a5  node.pdb
    04db25c93c5357394941dd2de12cb61959eb82d1  x64/node-v0.6.19.msi
    f77c77f2e470cfc9071853af2f277ba91d660b9c  x64/node.exe
    fcf26a3f984a3f19804e0567414604b77b1d3bac  x64/node.exp
    bfed2a24f253dbac99379d6f22fc8e9e85ade7ed  x64/node.lib
    95226c1cc5170ea05c2e54431040f06c3e95e99f  x64/node.pdb
    node-v0.10.25~dfsg2/doc/blog/release/v0.8.12.md0000644000000000000000000000516712270121457017174 0ustar rootrootcategory: release version: v0.8.12 date: Fri Oct 12 08:52:06 PDT 2012 slug: node-v0.8.12 title: Node v0.8.12 (Stable) 2012.10.12, Version 0.8.12 (Stable) * npm: Upgrade to 1.1.63 * crypto: Reduce stability index to 2-Unstable (isaacs) * windows: fix handle leak in uv_fs_utime (Bert Belder) * windows: fix application crashed popup in debug version (Bert Belder) * buffer: report proper retained size in profiler (Ben Noordhuis) * buffer: fix byteLength with UTF-16LE (koichik) * repl: make "end of input" JSON.parse() errors throw in the REPL (Nathan Rajlich) * repl: make invalid RegExp modifiers throw in the REPL (Nathan Rajlich) * http: handle multiple Proxy-Authenticate values (Willi Eggeling) Source Code: http://nodejs.org/dist/v0.8.12/node-v0.8.12.tar.gz Macintosh Installer (Universal): http://nodejs.org/dist/v0.8.12/node-v0.8.12.pkg Windows Installer: http://nodejs.org/dist/v0.8.12/node-v0.8.12-x86.msi Windows x64 Installer: http://nodejs.org/dist/v0.8.12/x64/node-v0.8.12-x64.msi Windows x64 Files: http://nodejs.org/dist/v0.8.12/x64/ Linux 32-bit Binary: http://nodejs.org/dist/v0.8.12/node-v0.8.12-linux-x86.tar.gz Linux 64-bit Binary: http://nodejs.org/dist/v0.8.12/node-v0.8.12-linux-x64.tar.gz Solaris 32-bit Binary: http://nodejs.org/dist/v0.8.12/node-v0.8.12-sunos-x86.tar.gz Solaris 64-bit Binary: http://nodejs.org/dist/v0.8.12/node-v0.8.12-sunos-x64.tar.gz Other release files: http://nodejs.org/dist/v0.8.12/ Website: http://nodejs.org/docs/v0.8.12/ Documentation: http://nodejs.org/docs/v0.8.12/api/ Shasums: ``` 2d40157436b34e9e347c587de9945e7022eb9acc node-v0.8.12-darwin-x64.tar.gz b6ba1d2e478881e0a5248cb319ce0913ca39a51b node-v0.8.12-darwin-x86.tar.gz 5353dfab2005992deee13e6e00a30509c8c86d4b node-v0.8.12-linux-x64.tar.gz 9e501b995469d554e3356b6f5f85b72abed83310 node-v0.8.12-linux-x86.tar.gz b3e8e655b3c6f0a2c641dcb0e22372edb6f45ffd node-v0.8.12-sunos-x64.tar.gz 82c46d12a52e09bda3ad4bd0cdb8ad18480e679a node-v0.8.12-sunos-x86.tar.gz d70e7bc718699651281110cd9f3f13ae50ac36be node-v0.8.12-x86.msi d24d17d34425eb86cc237b8e68fdd5d199cb0ad8 node-v0.8.12.pkg 719397c7f65365b2ec6510863ac62bd291784910 node-v0.8.12.tar.gz ac7151c05730982eb37a7f390386219c4d05b57d node.exe 000771bbc1e26f8ac5d11183b6538f25214b64a6 node.exp b036c368ff65f96ca44ac0ccf8d742c41ce00a95 node.lib 98edc84132157d44df7a4d08b6788843fe542961 node.pdb d1cccae53dcb54e08a8771ef0f9406e327ac4db3 x64/node-v0.8.12-x64.msi 0aa3088bd6a55864d25e84091b3a3b796ce20ce9 x64/node.exe 1d6dc06515cead63a2e547aacc73cfb7ad8003a2 x64/node.exp 7f55dd2367523c151e4d8492c596f076e0e5d151 x64/node.lib e34d679b61c77026dd0f437d3d91a84b83a422d3 x64/node.pdb ``` node-v0.10.25~dfsg2/doc/blog/release/version-0-7-8-unstable.md0000644000000000000000000000450712270121457022223 0ustar rootrootversion: 0.7.8 title: Version 0.7.8 (unstable) author: Isaac Schlueter date: Wed Apr 18 2012 10:39:02 GMT-0700 (PDT) status: publish category: release slug: version-0-7-8-unstable

    2012.04.18, Version 0.7.8, (unstable)

    • Upgrade V8 to 3.9.24.9

    • Upgrade OpenSSL to 1.0.0f

    • Upgrade npm to 1.1.18

    • Show licenses in Binary installers

    • Domains (isaacs)

    • readline: rename "end" to "close" (Nathan Rajlich)

    • tcp: make getsockname() return address family as string (Shigeki Ohtsu)

    • http, https: fix .setTimeout() (ssuda)

    • os: add cross platform EOL character (Mustansir Golawala)

    • typed arrays: unexport SizeOfArrayElementForType() (Aaron Jacobs)

    • net: honor 'enable' flag in .setNoDelay() (Ben Noordhuis)

    • child_process: emit error when .kill fails (Andreas Madsen)

    • gyp: fix 'argument list too long' build error (Ben Noordhuis)

    • fs.WriteStream: Handle modifications to fs.open (isaacs)

    • repl, readline: Handle newlines better (Nathan Rajlich, Nathan Friedly)

    • build: target OSX 10.5 when building on darwin (Nathan Rajlich)

    • Fix #3052 Handle errors properly in zlib (isaacs)

    • build: add support for DTrace and postmortem (Dave Pacheco)

    • core: add reusable Slab allocator (Ben Noordhuis)

    Source Code: http://nodejs.org/dist/v0.7.8/node-v0.7.8.tar.gz

    Windows Installer: http://nodejs.org/dist/v0.7.8/node-v0.7.8.msi

    Windows x64 Files: http://nodejs.org/dist/v0.7.8/x64/

    Macintosh Installer (Universal): http://nodejs.org/dist/v0.7.8/node-v0.7.8.pkg

    Other release files: http://nodejs.org/dist/v0.7.8/

    Website: http://nodejs.org/docs/v0.7.8/

    Documentation: http://nodejs.org/docs/v0.7.8/api/

    node-v0.10.25~dfsg2/doc/blog/release/v0.9.4.md0000644000000000000000000000656012270121457017114 0ustar rootrootdate: Fri Dec 21 12:30:15 PST 2012 version: 0.9.4 category: release slug: node-v0-9-4-unstable title: Node v0.9.4 (Unstable) 2012.12.21, Version 0.9.4 (Unstable) * streams: Update all streaming interfaces to use new classes (isaacs) * node: remove idle gc (Ben Noordhuis) * http: protect against response splitting attacks (Bert Belder) * fs: Raise error when null bytes detected in paths (isaacs) * fs: fix 'object is not a function' callback errors (Ben Noordhuis) * fs: add autoClose=true option to fs.createReadStream (Farid Neshat) * process: add getgroups(), setgroups(), initgroups() (Ben Noordhuis) * openssl: optimized asm code on x86 and x64 (Bert Belder) * crypto: fix leak in GetPeerCertificate (Fedor Indutny) * add systemtap support (Jan Wynholds) * windows: add ETW and PerfCounters support (Scott Blomquist) * windows: fix normalization of UNC paths (Bert Belder) * crypto: fix ssl error handling (Sergey Kholodilov) * node: remove eio-emul.h (Ben Noordhuis) * os: add os.endianness() function (Nathan Rajlich) * readline: don't emit "line" events with a trailing 'n' char (Nathan Rajlich) * build: add configure option to generate xcode build files (Timothy J Fontaine) * build: allow linking against system libuv, cares, http_parser (Stephen Gallagher) * typed arrays: add slice() support to ArrayBuffer (Anthony Pesch) * debugger: exit and kill child on SIGTERM or SIGHUP (Fedor Indutny) * url: url.format escapes delimiters in path and query (J. Lee Coltrane) Source Code: http://nodejs.org/dist/v0.9.4/node-v0.9.4.tar.gz Macintosh Installer (Universal): http://nodejs.org/dist/v0.9.4/node-v0.9.4.pkg Windows Installer: http://nodejs.org/dist/v0.9.4/node-v0.9.4-x86.msi Windows x64 Installer: http://nodejs.org/dist/v0.9.4/x64/node-v0.9.4-x64.msi Windows x64 Files: http://nodejs.org/dist/v0.9.4/x64/ Linux 32-bit Binary: http://nodejs.org/dist/v0.9.4/node-v0.9.4-linux-x86.tar.gz Linux 64-bit Binary: http://nodejs.org/dist/v0.9.4/node-v0.9.4-linux-x64.tar.gz Solaris 32-bit Binary: http://nodejs.org/dist/v0.9.4/node-v0.9.4-sunos-x86.tar.gz Solaris 64-bit Binary: http://nodejs.org/dist/v0.9.4/node-v0.9.4-sunos-x64.tar.gz Other release files: http://nodejs.org/dist/v0.9.4/ Website: http://nodejs.org/docs/v0.9.4/ Documentation: http://nodejs.org/docs/v0.9.4/api/ Shasums: ``` 7919d5fa63583c9a38a8ade1e977809b53476f7f node-v0.9.4-darwin-x64.tar.gz 82eb2f39c61b14be8a9d2c1b6ba624030ab3ddbe node-v0.9.4-darwin-x86.tar.gz 34cd2f6bed15d4d7d28944575b7098f4500651e2 node-v0.9.4-linux-x64.tar.gz bf5da5432a5d80343e1d53c57b242283be11c97f node-v0.9.4-linux-x86.tar.gz 6eebcf27a545d598c0ffa8056d7d5c83add5746c node-v0.9.4-sunos-x64.tar.gz 1c2e28389b34a0e51f5ad2a1c09677f2941765b1 node-v0.9.4-sunos-x86.tar.gz 4d7b4dfd150f17dac787400e74fc469b3432f3a2 node-v0.9.4-x86.msi 20ceaafeb6d4ecf5d2f37d3d825d47cc81927dd6 node-v0.9.4.pkg 30b3f8dee0b2ace3d83c200eeffc6f450d3b4366 node-v0.9.4.tar.gz a5b4304f4a50ac3385577f7833890ca6f44301c0 node.exe 5b960053a6bddfd10cf6408ea1581b7237512248 node.exp f1aaac71a21e7a0c884211957e5d79bed1deb1d3 node.lib 73016ab15ee7ee6f6363391d3e41a698ed764e65 node.pdb 5a624fc9a5dac85a6f00945ccc2d31d9b8a51499 x64/node-v0.9.4-x64.msi fe738e969f9b050b7b1675ecf3cda567021e121b x64/node.exe d32c7ea441ad0d24cd2fd2b4932d2924a95f25ec x64/node.exp 753f7fadc501a1b86d94af23710137f6e93c5cff x64/node.lib a707ef46e6483f40a30c85c037eeadbf9e5923b8 x64/node.pdb ``` node-v0.10.25~dfsg2/doc/blog/release/node-v0-6-1.md0000644000000000000000000000302112270121457020014 0ustar rootrootversion: 0.6.1 title: Node v0.6.1 author: ryandahl date: Fri Nov 11 2011 15:34:15 GMT-0800 (PST) status: publish category: release slug: node-v0-6-1 2011.11.11, Version 0.6.1 (stable)
    • doc improvements (Eric Lovett, Ben Noordhuis, Scott Anderson, Yoji SHIDARA)
    • crypto: make thread-safe (Ben Noordhuis)
    • fix process.kill error object
    • debugger: correctly handle source with multi-byte characters (Shigeki Ohtsu)
    • make stdout and stderr non-destroyable (Igor Zinkovsky)
    • fs: don't close uninitialized fs.watch handle (Ben Noordhuis)
    • #2026 fix man page install on BSDs (Ben Noordhuis)
    • #2040 fix unrecognized errno assert in uv_err_name
    • #2043 fs: mkdir() should call callback if mode is omitted
    • #2045 fs: fix fs.realpath on windows to return on error (Benjamin Pasero)
    • #2047 minor cluster improvements
    • #2052 readline get window columns correctly
    • Upgrade V8 to 3.6.6.7
    Source Code: http://nodejs.org/dist/v0.6.1/node-v0.6.1.tar.gz Windows Installer: http://nodejs.org/dist/v0.6.1/node-v0.6.1.msi Macintosh Installer: http://nodejs.org/dist/v0.6.1/node-v0.6.1.pkg Website: http://nodejs.org/docs/v0.6.1/ Documentation: http://nodejs.org/docs/v0.6.1/api/ node-v0.10.25~dfsg2/doc/blog/release/v0.9.0.md0000644000000000000000000000364312270121457017107 0ustar rootrootcategory: release version: 0.9.0 date: Fri Jul 20 11:37:15 PDT 2012 title: Version 0.9.0 (Unstable) slug: version-0-9-0-unstable 2012.07.20, Version 0.9.0 (Unstable) * punycode: update to v1.1.1 (Mathias Bynens) * c-ares: upgrade to 1.9.0 (Saúl Ibarra Corretgé) * dns: ignore rogue DNS servers reported by windows (Saúl Ibarra Corretgé) * unix: speed up uv_async_send() (Ben Noordhuis) * darwin: get cpu model correctly on mac (Xidorn Quan) * nextTick: Handle tick callbacks before any other I/O (isaacs) * Enable color customization of `util.inspect` (Pavel Lang) * tls: Speed and memory improvements (Fedor Indutny) * readline: Use one history item for reentered line (Vladimir Beloborodov) * Fix #3521 Make process.env more like a regular Object (isaacs) Source Code: http://nodejs.org/dist/v0.9.0/node-v0.9.0.tar.gz Macintosh Installer (Universal): http://nodejs.org/dist/v0.9.0/node-v0.9.0.pkg Windows Installer: http://nodejs.org/dist/v0.9.0/node-v0.9.0-x86.msi Windows x64 Installer: http://nodejs.org/dist/v0.9.0/x64/node-v0.9.0-x64.msi Windows x64 Files: http://nodejs.org/dist/v0.9.0/x64/ Other release files: http://nodejs.org/dist/v0.9.0/ Website: http://nodejs.org/docs/v0.9.0/ Documentation: http://nodejs.org/docs/v0.9.0/api/ Shasums: ``` 4d6881934f5e41da651b478f914f71543d21d3cc node-v0.9.0-x86.msi ec00cc6f0830f64cd9e8246a299abf9a2a6ed73e node-v0.9.0.pkg 912d0eb3139b8f6f99199dae5ec1ecb300ed9c9b node-v0.9.0.tar.gz 7e56dddbb1d3e243549db7182f1bf2dd4518eaae node.exe 31718ad3e0de9b0ea6c207966a13d4bafaf9ef64 node.exp 0738b4d91de4c87cdee2547d83144668cb232c24 node.lib baca86ec3c12a5261abb940cd8107bdeb40713cc node.pdb cf3892596a7d2a27a63672b537b06b8828125fe9 x64/node-v0.9.0-x64.msi cad4bf9b2be85476d1a897ea17b3f927ec49c96a x64/node.exe 29ea3654f7728efef6fa046943ded57af42b91f3 x64/node.exp 1dfa57b111d5942b4fe701b625176eae73c82d82 x64/node.lib 9093b2120f8adf0236f965982e4a32697af2af5d x64/node.pdb ``` node-v0.10.25~dfsg2/doc/blog/release/v0.8.13.md0000644000000000000000000000522612270121457017171 0ustar rootrootcategory: release version: v0.8.13 date: Thu Oct 25 12:26:44 PDT 2012 slug: node-v0.8.13 title: Node v0.8.13 (Stable) Warning: This version contains a regression in the EventEmitter class. Please use 0.8.14 instead. 2012.10.25, Version 0.8.13 (Stable) * V8: Upgrade to 3.11.10.25 * npm: Upgrade to 1.1.65 * url: parse hostnames that start with - or _ (Ben Noordhuis) * repl: Fix Windows 8 terminal issue (Bert Belder) * typed arrays: use signed char for signed int8s (Aaron Jacobs) * crypto: fix bugs in DiffieHellman (Ben Noordhuis) * configure: turn on VFPv3 on ARMv7 (Ben Noordhuis) * Re-enable OpenSSL UI for entering passphrases via tty (Ben Noordhuis) * repl: ensure each REPL instance gets its own "context" (Nathan Rajlich) Source Code: http://nodejs.org/dist/v0.8.13/node-v0.8.13.tar.gz Macintosh Installer (Universal): http://nodejs.org/dist/v0.8.13/node-v0.8.13.pkg Windows Installer: http://nodejs.org/dist/v0.8.13/node-v0.8.13-x86.msi Windows x64 Installer: http://nodejs.org/dist/v0.8.13/x64/node-v0.8.13-x64.msi Windows x64 Files: http://nodejs.org/dist/v0.8.13/x64/ Linux 32-bit Binary: http://nodejs.org/dist/v0.8.13/node-v0.8.13-linux-x86.tar.gz Linux 64-bit Binary: http://nodejs.org/dist/v0.8.13/node-v0.8.13-linux-x64.tar.gz Solaris 32-bit Binary: http://nodejs.org/dist/v0.8.13/node-v0.8.13-sunos-x86.tar.gz Solaris 64-bit Binary: http://nodejs.org/dist/v0.8.13/node-v0.8.13-sunos-x64.tar.gz Other release files: http://nodejs.org/dist/v0.8.13/ Website: http://nodejs.org/docs/v0.8.13/ Documentation: http://nodejs.org/docs/v0.8.13/api/ Shasums: ``` 1f396f068e40639f70e5d60e8e33d0cbb5597748 node-v0.8.13-darwin-x64.tar.gz afa416c3b6209f3d72926537c85d5943b3b07a0d node-v0.8.13-darwin-x86.tar.gz bdcf8b69ccba2ca326c8ff2921232c1663a79d78 node-v0.8.13-linux-x64.tar.gz d1fc168b092234bac665dc65d242f3367dfc0f24 node-v0.8.13-linux-x86.tar.gz d3d5b19c133c73f060efa4bbe274195c9579f4be node-v0.8.13-sunos-x64.tar.gz 98916b4f0c9855dd02d87223d6369f5fa281cbe5 node-v0.8.13-sunos-x86.tar.gz 732f70fbb800c8fee6202e939502c0f23f76d4a1 node-v0.8.13-x86.msi e2da495a2f8dd4b0cd25810c3b4e6b2e9e71cfe3 node-v0.8.13.pkg 9112a128d83f3e7d26ba0965eb426de0f18c3149 node-v0.8.13.tar.gz f8c75e5877f103a842067adff6f6580d1c250c9b node.exe b950a56fa0a00b78212c5d95e4ca6381f8285df9 node.exp 6fcfb00aaf78be643330f645d2d83d461bc1cbe7 node.lib b6b0d540061e83bbe165afbc25aeeb19b00fbbf2 node.pdb 8017014664dca6b255724f30827553ca420580af x64/node-v0.8.13-x64.msi 8a9fd20b6b24aa3bb8eda8f2f9fa1ede19588a41 x64/node.exe 74ceab4f7d3192bbd2d13d602fe66e3caf7d08e2 x64/node.exp 780c395cab41a0ef59bdd82fe39f370fa1c5e839 x64/node.lib 526bd6fadffcea8f56b0a761ccae01f65b018947 x64/node.pdb ``` node-v0.10.25~dfsg2/doc/blog/release/node-v0-4-6.md0000644000000000000000000000233612270121457020027 0ustar rootrootversion: 0.4.6 title: Node v0.4.6 author: ryandahl date: Thu Apr 14 2011 05:00:30 GMT-0700 (PDT) status: publish category: release slug: node-v0-4-6 2011.04.13, Version 0.4.6 (stable)
    • Don't error on ENOTCONN from shutdown() #670
    • Auto completion of built-in debugger suggests prefix match rather than partial match. (koichik)
    • circular reference in vm modules. #822 (Jakub Lekstan)
    • http response.readable should be false after 'end' #867 (Abe Fettig)
    • Implement os.cpus() and os.uptime() on Solaris (Scott McWhirter)
    • fs.ReadStream: Allow omission of end option for range reads #801 (Felix Geisendörfer)
    • Buffer.write() with UCS-2 should not be write partial char #916 (koichik)
    • Pass secureProtocol through on tls.Server creation (Theo Schlossnagle)
    • TLS use RC4-SHA by default
    • Don't strangely drop out of event loop on HTTPS client uploads #892
    • Doc improvements
    • Upgrade v8 to 3.1.8.10
    Download: http://nodejs.org/dist/node-v0.4.6.tar.gz Website: http://nodejs.org/docs/v0.4.6/ Documentation: http://nodejs.org/docs/v0.4.6/api/ node-v0.10.25~dfsg2/doc/blog/release/v0.9.5.md0000644000000000000000000000557012270121457017115 0ustar rootrootcategory: release version: 0.9.5 date: Sun Dec 30 01:19:51 UTC 2012 slug: node-v0-9-5-unstable title: Node v0.9.5 (Unstable) 2012.12.30, Version 0.9.5 (Unstable) * assert: improve support for new execution contexts (lukebayes) * domain: use camelCase instead of snake_case (isaacs) * domain: Do not use uncaughtException handler (isaacs) * fs: make 'end' work with ReadStream without 'start' (Ben Noordhuis) * https: optimize createConnection() (Ryunosuke SATO) * buffer: speed up base64 encoding by 20% (Ben Noordhuis) * doc: Colorize API stabilitity index headers in docs (Luke Arduini) * net: socket.readyState corrections (bentaber) * http: Performance enhancements for http under streams2 (isaacs) * stream: fix to emit end event on http.ClientResponse (Shigeki Ohtsu) * stream: fix event handler leak in readstream pipe and unpipe (Andreas Madsen) * build: Support ./configure --tag switch (Maciej Małecki) * repl: don't touch `require.cache` (Nathan Rajlich) * node: Emit 'exit' event when exiting for an uncaught exception (isaacs) Source Code: http://nodejs.org/dist/v0.9.5/node-v0.9.5.tar.gz Macintosh Installer (Universal): http://nodejs.org/dist/v0.9.5/node-v0.9.5.pkg Windows Installer: http://nodejs.org/dist/v0.9.5/node-v0.9.5-x86.msi Windows x64 Installer: http://nodejs.org/dist/v0.9.5/x64/node-v0.9.5-x64.msi Windows x64 Files: http://nodejs.org/dist/v0.9.5/x64/ Linux 32-bit Binary: http://nodejs.org/dist/v0.9.5/node-v0.9.5-linux-x86.tar.gz Linux 64-bit Binary: http://nodejs.org/dist/v0.9.5/node-v0.9.5-linux-x64.tar.gz Solaris 32-bit Binary: http://nodejs.org/dist/v0.9.5/node-v0.9.5-sunos-x86.tar.gz Solaris 64-bit Binary: http://nodejs.org/dist/v0.9.5/node-v0.9.5-sunos-x64.tar.gz Other release files: http://nodejs.org/dist/v0.9.5/ Website: http://nodejs.org/docs/v0.9.5/ Documentation: http://nodejs.org/docs/v0.9.5/api/ Shasums: ``` d44535e086c3f0fe47152b9323189c18a488d995 node-v0.9.5-darwin-x64.tar.gz b588332e38e3ddd0424b18d14a3c6c65c5cad6f6 node-v0.9.5-darwin-x86.tar.gz 17b07641b59bc56582e68db6bd52c1b41bb06a5e node-v0.9.5-linux-x64.tar.gz 89656e3dc094a6fa4244a03ac85e9b08b7443a50 node-v0.9.5-linux-x86.tar.gz bf84b80ea80b4cb20767d4b3f276979f0f3d8866 node-v0.9.5-sunos-x64.tar.gz 4f98560e55db63f323b6f75b22538d96b199892c node-v0.9.5-sunos-x86.tar.gz 7ed38be34e5377f45e8906c4d887de262c1925e2 node-v0.9.5-x86.msi a1f1322fcaa5535ae830f3242bcdd213388357cc node-v0.9.5.tar.gz 94c22b744945e9bc8b3f9fd31991cb6b87f727ce node.exe e809779c8071abf05650fbb47e207140829dc62c node.exp cec09944297546185070c809a78931839e3c2695 node.lib 5a3a4f3de4b8bf4209ecc2e6d40418d6a7e8fcac node.pdb 55c986c14a72081757002f8df43272b20f024c57 x64/node-v0.9.5-x64.msi 55514dd925a9b24cb3925f89facbec5efb2a99aa x64/node.exe 920e2d3319eac8a3356023a1cb8c61f139f80398 x64/node.exp e072006328dacce920e4951596e457e58e6310d0 x64/node.lib 633816d865155148129ca21399e411f1240b2cce x64/node.pdb ``` node-v0.10.25~dfsg2/doc/blog/release/v0.9.1.md0000644000000000000000000000764012270121457017111 0ustar rootrootversion: 0.9.1 title: Version 0.9.1 (Unstable) category: release slug: node-v0-9-1-unstable date: 2012-08-28T22:33:45.659Z 2012.08.28, Version 0.9.1 (Unstable) * buffer: Add Buffer.isEncoding(enc) to test for valid encoding values (isaacs) * Raise UV_ECANCELED on premature close. (Ben Noordhuis) * Remove c-ares from libuv, move to a top-level node dependency (Bert Belder) * ref/unref for all HandleWraps, timers, servers, and sockets (Timothy J Fontaine) * addon: remove node-waf, superseded by node-gyp (Ben Noordhuis) * child_process: emit error on exec failure (Ben Noordhuis) * cluster: do not use internal server API (Andreas Madsen) * constants: add O_DIRECT (Ian Babrou) * crypto: add sync interface to crypto.pbkdf2() (Ben Noordhuis) * darwin: emulate fdatasync() (Fedor Indutny) * dgram: make .bind() always asynchronous (Ben Noordhuis) * events: Make emitter.listeners() side-effect free (isaacs, Joe Andaverde) * fs: Throw early on invalid encoding args (isaacs) * fs: fix naming of truncate/ftruncate functions (isaacs) * http: bubble up parser errors to ClientRequest (Brian White) * linux: improve cpuinfo parser on ARM and MIPS (Ben Noordhuis) * net: add support for IPv6 addresses ending in :: (Josh Erickson) * net: support Server.listen(Pipe) (Andreas Madsen) * node: don't scan add-on for "init" symbol (Ben Noordhuis) * remove process.uvCounters() (Ben Noordhuis) * repl: console writes to repl rather than process stdio (Nathan Rajlich) * timers: implement setImmediate (Timothy J Fontaine) * tls: fix segfault in pummel/test-tls-ci-reneg-attack (Ben Noordhuis) * tools: Move gyp addon tools to node-gyp (Nathan Rajlich) * unix: preliminary signal handler support (Ben Noordhuis) * unix: remove dependency on ev_child (Ben Noordhuis) * unix: work around darwin bug, don't poll() on pipe (Fedor Indutny) * util: Formally deprecate util.pump() (Ben Noordhuis) * windows: make active and closing handle state independent (Bert Belder) * windows: report spawn errors to the exit callback (Bert Belder) * windows: signal handling support with uv_signal_t (Bert Belder) Source Code: http://nodejs.org/dist/v0.9.1/node-v0.9.1.tar.gz Macintosh Installer (Universal): http://nodejs.org/dist/v0.9.1/node-v0.9.1.pkg Windows Installer: http://nodejs.org/dist/v0.9.1/node-v0.9.1-x86.msi Windows x64 Installer: http://nodejs.org/dist/v0.9.1/x64/node-v0.9.1-x64.msi Windows x64 Files: http://nodejs.org/dist/v0.9.1/x64/ Linux 32-bit Binary: http://nodejs.org/dist/v0.9.1/node-v0.9.1-linux-x86.tar.gz Linux 64-bit Binary: http://nodejs.org/dist/v0.9.1/node-v0.9.1-linux-x64.tar.gz Solaris 32-bit Binary: http://nodejs.org/dist/v0.9.1/node-v0.9.1-sunos-x86.tar.gz Solaris 64-bit Binary: http://nodejs.org/dist/v0.9.1/node-v0.9.1-sunos-x64.tar.gz Other release files: http://nodejs.org/dist/v0.9.1/ Website: http://nodejs.org/docs/v0.9.1/ Documentation: http://nodejs.org/docs/v0.9.1/api/ Shasums: ``` b86a5b0b2c9a89d08baaeb3d5270a8f247b4ba43 node-v0.9.1-darwin-x64.tar.gz 800af9d15a4b65e624351bb94dedc3b7eb322b86 node-v0.9.1-darwin-x86.tar.gz a7ea43b0db472ca84dc9838960dae57ff0abaa72 node-v0.9.1-linux-x64.tar.gz 89c4be492a946eefa45aa87d16787875aa0f2dff node-v0.9.1-linux-x86.tar.gz 6495d2814541e945dba5941b8d3facf2a61dc55d node-v0.9.1-sunos-x64.tar.gz 05ea83ba4d648f5b949833bb28d69e6eeebabb78 node-v0.9.1-sunos-x86.tar.gz 3ccf1ac2fea7f2d05bcaed590bc54ee61c982fbb node-v0.9.1-x86.msi bd0ede40e4681b16088284fe6a18ae3a5c5a3795 node-v0.9.1.tar.gz 159470a999ef23fa940ad3c54265053c3d2a4332 node.exe 02472e388a44b91e2644178a0fe011354fcd361e node.exp c6d6ce22be4b47ad022d82dd91ebd4c040742fee node.lib 7b4cec8b4106d90a077388fe483fdbb13119dcb1 node.pdb a5fbf5e22c7623a9206abc6608d084ff53c7c4c9 x64/node-v0.9.1-x64.msi 9755685a9d7bea6dc63d3260829c26c5b0430a7a x64/node.exe 621f177733647848f7f667926fe4f498a1f50c97 x64/node.exp 5877dffbf012c458dab88f3392af59cb33720d2f x64/node.lib dc513ce5c16771dcfab9c1777d5949252290b412 x64/node.pdb ``` node-v0.10.25~dfsg2/doc/blog/release/version-0-6-18-stable.md0000644000000000000000000000414112270121457021732 0ustar rootrootversion: 0.6.18 title: Version 0.6.18 (stable) author: Isaac Schlueter date: Tue May 15 2012 10:06:13 GMT-0700 (PDT) status: publish category: release slug: version-0-6-18-stable

    2012.05.15 Version 0.6.18 (stable)

    • windows: skip GetFileAttributes call when opening a file (Bert Belder)

    • crypto: add PKCS12/PFX support (Sambasiva Suda)

    • #3240: child_process: delete NODE_CHANNEL_FD from env in spawn (Ben Noordhuis)

    • windows: add test for path.normalize with UNC paths (Bert Belder)

    • windows: make path.normalize convert all slashes to backslashes (Bert Belder)

    • fs: Automatically close FSWatcher on error (Bert Belder)

    • #3258: fs.ReadStream.pause() emits duplicate data event (koichik)

    • pipe_wrap: don't assert() on pipe accept errors (Ben Noordhuis)

    • Better exception output for module load and process.nextTick (Felix Geisendörfer)

    • zlib: fix error reporting (Ben Noordhuis)

    • http: Don't destroy on timeout (isaacs)

    • #3231: http: Don't try to emit error on a null'ed req object (isaacs)

    • #3236: http: Refactor ClientRequest.onSocket (isaacs)

    Source Code: http://nodejs.org/dist/v0.6.18/node-v0.6.18.tar.gz

    Windows Installer: http://nodejs.org/dist/v0.6.18/node-v0.6.18.msi

    Windows x64 Files: http://nodejs.org/dist/v0.6.18/x64/

    Macintosh Installer (Universal): http://nodejs.org/dist/v0.6.18/node-v0.6.18.pkg

    Other release files: http://nodejs.org/dist/v0.6.18/

    Website: http://nodejs.org/docs/v0.6.18/

    Documentation: http://nodejs.org/docs/v0.6.18/api/

    node-v0.10.25~dfsg2/doc/blog/release/node-v0-5-8.md0000644000000000000000000000215212270121457020026 0ustar rootrootversion: 0.5.8 title: Node v0.5.8 author: ryandahl date: Fri Sep 30 2011 16:47:11 GMT-0700 (PDT) status: publish category: release slug: node-v0-5-8 2011.09.30, Version 0.5.8 (unstable)
    • zlib bindings (isaacs)
    • Windows supports TTY ANSI escape codes (Bert Belder)
    • Debugger improvements (Fedor Indutny)
    • crypto: look up SSL errors with ERR_print_errors() (Ben Noordhuis)
    • dns callbacks go through MakeCallback now
    • Raise an error when a malformed package.json file is found. (Ben Leslie)
    • buffers: handle bad length argument in constructor (Ben Noordhuis)
    • #1726, unref process.stdout
    • Doc improvements (Ben Noordhuis, Fedor Indutny, koichik)
    • Upgrade libuv to fe18438
    Download: http://nodejs.org/dist/v0.5.8/node-v0.5.8.tar.gz Windows Executable: http://nodejs.org/dist/v0.5.8/node.exe Website: http://nodejs.org/docs/v0.5.8/ Documentation: http://nodejs.org/docs/v0.5.8/api/ node-v0.10.25~dfsg2/doc/blog/release/node-v0-4-5.md0000644000000000000000000000171212270121457020023 0ustar rootrootversion: 0.4.5 title: node v0.4.5 author: ryandahl date: Sat Apr 02 2011 02:04:58 GMT-0700 (PDT) status: publish category: release slug: node-v0-4-5 2011.04.01, Version 0.4.5 (stable)
    • Fix listener leak in stream.pipe() (Mikeal Rogers)
    • Retain buffers in fs.read/write() GH-814 (Jorge Chamorro Bieling)
    • TLS performance improvements
    • SlowBuffer.prototype.slice bug GH-843
    • process.stderr.write should return true
    • Immediate pause/resume race condition GH-535 (isaacs)
    • Set default host header properly GH-721 (isaacs)
    • Upgrade V8 to 3.1.8.8
    Download: http://nodejs.org/dist/node-v0.4.5.tar.gz Website: http://nodejs.org/docs/v0.4.5 Documentation: http://nodejs.org/docs/v0.4.5/api announcement node-v0.10.25~dfsg2/doc/blog/release/version-0-6-17-stable.md0000644000000000000000000000306612270121457021736 0ustar rootrootversion: 0.6.17 title: Version 0.6.17 (stable) author: Isaac Schlueter date: Fri May 04 2012 13:33:12 GMT-0700 (PDT) status: publish category: release slug: version-0-6-17-stable

    2012.05.04 Version 0.6.17 (stable)

    • Upgrade npm to 1.1.21

    • uv: Add support for EROFS errors (Ben Noordhuis, Maciej Małecki)

    • uv: Add support for EIO and ENOSPC errors (Fedor Indutny)

    • windows: Add support for EXDEV errors (Bert Belder)

    • http: Fix client memory leaks (isaacs, Vincent Voyer)

    • fs: fix file descriptor leak in sync functions (Ben Noordhuis)

    • fs: fix ReadStream / WriteStream double close bug (Ben Noordhuis)

    Source Code: http://nodejs.org/dist/v0.6.17/node-v0.6.17.tar.gz

    Windows Installer: http://nodejs.org/dist/v0.6.17/node-v0.6.17.msi

    Windows x64 Files: http://nodejs.org/dist/v0.6.17/x64/

    Macintosh Installer (Universal): http://nodejs.org/dist/v0.6.17/node-v0.6.17.pkg

    Other release files: http://nodejs.org/dist/v0.6.17/

    Website: http://nodejs.org/docs/v0.6.17/

    Documentation: http://nodejs.org/docs/v0.6.17/api/

    node-v0.10.25~dfsg2/doc/blog/release/node-v0-7-2-unstable.md0000644000000000000000000000333112270121457021635 0ustar rootrootversion: 0.7.2 title: Node v0.7.2 (unstable) author: Isaac Schlueter date: Wed Feb 01 2012 13:13:04 GMT-0800 (PST) status: publish category: release slug: node-v0-7-2-unstable

    2012.02.01, Version 0.7.2 (unstable)

    • Update V8 to 3.8.9

    • Support for sharing streams across Isolates (Igor Zinkovsky)

    • #2636 - Fix case where http_parsers are freed too early (koichik)

    • url: Support for IPv6 addresses in URLs (Łukasz Walukiewicz)

    • child_process: Add disconnect() method to child processes (Andreas Madsen)

    • fs: add O_EXCL support, exclusive open file (Ben Noordhuis)

    • fs: more specific error messages (Tj Holowaychuk)

    • tty: emit 'unknown' key event if key sequence not found (Dan VerWeire, Nathan Rajlich)

    • build: compile release build too if BUILDTYPE=Debug (Ben Noordhuis)

    • module: fix --debug-brk on symlinked scripts (Fedor Indutny)

    • zlib: fix Failed to set dictionary issue (Fedor Indutny)

    • waf: predict target arch for OS X (Fedor Indutny)

    Source Code: http://nodejs.org/dist/v0.7.2/node-v0.7.2.tar.gz

    Windows Installer: http://nodejs.org/dist/v0.7.2/node-v0.7.2.msi

    Macintosh Installer: http://nodejs.org/dist/v0.7.2/node-v0.7.2.pkg

    Website: http://nodejs.org/docs/v0.7.2/

    Documentation: http://nodejs.org/docs/v0.7.2/api/

    node-v0.10.25~dfsg2/doc/blog/release/v0.8.25.md0000644000000000000000000000426012270121457017171 0ustar rootrootdate: Thu Jun 13 13:18:09 PDT 2013 version: 0.8.25 category: release title: Node v0.8.25 (Maintenance) slug: node-v0-8-25-maintenance 2013.06.13, Version 0.8.25 (maintenance) * npm: Upgrade to 1.2.30 * child_process: fix handle delivery (Ben Noordhuis) Source Code: http://nodejs.org/dist/v0.8.25/node-v0.8.25.tar.gz Macintosh Installer (Universal): http://nodejs.org/dist/v0.8.25/node-v0.8.25.pkg Windows Installer: http://nodejs.org/dist/v0.8.25/node-v0.8.25-x86.msi Windows x64 Installer: http://nodejs.org/dist/v0.8.25/x64/node-v0.8.25-x64.msi Windows x64 Files: http://nodejs.org/dist/v0.8.25/x64/ Linux 32-bit Binary: http://nodejs.org/dist/v0.8.25/node-v0.8.25-linux-x86.tar.gz Linux 64-bit Binary: http://nodejs.org/dist/v0.8.25/node-v0.8.25-linux-x64.tar.gz Solaris 32-bit Binary: http://nodejs.org/dist/v0.8.25/node-v0.8.25-sunos-x86.tar.gz Solaris 64-bit Binary: http://nodejs.org/dist/v0.8.25/node-v0.8.25-sunos-x64.tar.gz Other release files: http://nodejs.org/dist/v0.8.25/ Website: http://nodejs.org/docs/v0.8.25/ Documentation: http://nodejs.org/docs/v0.8.25/api/ Shasums: ``` c650dca3031ea09535a5cb95648a9edf43dcb23a node-v0.8.25-darwin-x64.tar.gz d479e24f693331bd09b7a29e9cb2b2140f5f0606 node-v0.8.25-darwin-x86.tar.gz 5fbf6e7718cb8576682479e002081c23b5ebb299 node-v0.8.25-linux-x64.tar.gz c037c589f77e597503a606d66c5ab7a0d1e1b3fb node-v0.8.25-linux-x86.tar.gz ed5709fbd80c167183ca60cf4c435caa49d35034 node-v0.8.25-sunos-x64.tar.gz 6c2914ec896330e9f6eba65cbec738b042712663 node-v0.8.25-sunos-x86.tar.gz 26cc19bc19e344e4b51ab33775d00e811bf9b1eb node-v0.8.25-x86.msi 4c7ec87036616ec6e96f8c4b7242c86c3380231e node-v0.8.25.pkg df91c9de8f3f14efb4cbe52d3ca8beb754b2a39a node-v0.8.25.tar.gz d111ef9ac2b2cb4d3126f147c2714ce2441d37aa node.exe a8cd86993a6dcf8a22d1cfda2fcd6c4865aac1da node.exp 5f8538ebd80078a1eee7dfe11f1b6d21d32f38f8 node.lib bc4b361c1594a47902e94dddf8308be5b48b4f81 node.pdb a6a559c81802f43cd220b83e13712f71d5f13484 x64/node-v0.8.25-x64.msi fb004a281f3914961ce2c08e859c007b5c7d61a5 x64/node.exe 8954509d45e6a9d160130acc4313a8cb4ee870f4 x64/node.exp cc332ca7a4b34ed834e5ad07abdbe1ce79bba5a6 x64/node.lib 24511046a8504ef65f77cbd30e5bad6b18751148 x64/node.pdb ``` node-v0.10.25~dfsg2/doc/blog/release/v0.11.7.md0000644000000000000000000000645512270121457017173 0ustar rootrootdate: Wed Sep 4 15:18:08 PDT 2013 version: 0.11.7 category: release title: Node v0.11.7 (Unstable) slug: node-v0-11-7-unstable 2013.08.21, Version 0.11.7 (Unstable) * uv: upgrade to v0.11.13 * v8: upgrade to 3.20.17 * buffer: adhere to INSPECT_MAX_BYTES (Timothy J Fontaine) * buffer: fix regression for large buffer creation (Trevor Norris) * buffer: don't throw if slice length too long (Trevor Norris) * buffer: Buffer(buf) constructor copies into the proper buffer (Ben Noordhuis) * cli: remove --max-stack-size (Ben Noordhuis) * cli: unknown command line options are errors (Ben Noordhuis) * child_process: exec accept buffer as an encoding (Seth Fitzsimmons) * crypto: make randomBytes/pbkdf2 callbacks domain aware (Ben Noordhuis) * domain: deprecate domain.dispose(). (Forrest L Norvell) * fs: Expose birthtime on stat objects (isaacs) * http: Only send connection:keep-alive if necessary (isaacs) * repl: Catch syntax errors better (isaacs, Nathan Rajlich) * stream: change default highWaterMark for objectMode to 16 (Mathias Buus) * stream: make setEncoding/pause/resume chainable (Julian Gruber, isaacs) * util: pass opts to custom inspect functions (Timothy J Fontaine) * vm: rewritten to behave like Contextify (Domenic Denicola) Source Code: http://nodejs.org/dist/v0.11.7/node-v0.11.7.tar.gz Macintosh Installer (Universal): http://nodejs.org/dist/v0.11.7/node-v0.11.7.pkg Windows Installer: http://nodejs.org/dist/v0.11.7/node-v0.11.7-x86.msi Windows x64 Installer: http://nodejs.org/dist/v0.11.7/x64/node-v0.11.7-x64.msi Windows x64 Files: http://nodejs.org/dist/v0.11.7/x64/ Linux 32-bit Binary: http://nodejs.org/dist/v0.11.7/node-v0.11.7-linux-x86.tar.gz Linux 64-bit Binary: http://nodejs.org/dist/v0.11.7/node-v0.11.7-linux-x64.tar.gz Solaris 32-bit Binary: http://nodejs.org/dist/v0.11.7/node-v0.11.7-sunos-x86.tar.gz Solaris 64-bit Binary: http://nodejs.org/dist/v0.11.7/node-v0.11.7-sunos-x64.tar.gz Other release files: http://nodejs.org/dist/v0.11.7/ Website: http://nodejs.org/docs/v0.11.7/ Documentation: http://nodejs.org/docs/v0.11.7/api/ Shasums: ``` 7ce3cf1297b6a8cda2aa134424890dcc6eaacc12 node-v0.11.7-darwin-x64.tar.gz 183b4a29eb65dabb5de732f2ab15cdac8c5e5c94 node-v0.11.7-darwin-x86.tar.gz 7d39c046388e7ec6bb2d53a575a0c9ed1d4a9bcc node-v0.11.7-linux-x64.tar.gz 4cf9a367b614b76722324ec6a3beb3295412100c node-v0.11.7-linux-x86.tar.gz 1d98fa4117f3ac7c7f081eea22a016c8549b27c1 node-v0.11.7-sunos-x64.tar.gz 9c04eb5ca9485370d757b0be94b223b5a0180b7a node-v0.11.7-sunos-x86.tar.gz f131bca701ad9dac61d8929362a3c8cde41845de node-v0.11.7-x86.msi 95c1ab2d08f3ba1bb514469ad8786af6ecb18f57 node-v0.11.7.pkg a3b0d7fb818754ad55f06a02745d7ec53986de64 node-v0.11.7.tar.gz 33371cadab85e7c3864d5eafae4041a9ca0f3ca2 node.exe 823487bfaa44f10770ecc9c8deec1bbe63bc955e node.exp 194c286bf8ef6608a891dc2c27cd38471da780a3 node.lib 0491c4e8d45fe420cc065be4de05dbcff0d4223a node.pdb d8b2d7e034d6031c083fb3c88c251f179b18b4ca pkgsrc/nodejs-ia32-0.11.7.tgz a9e7822718212a22b5630057efcba174041db9ff pkgsrc/nodejs-x64-0.11.7.tgz 44e7eeafb0982f81778a15ece00c8f25cc4d00f5 x64/node-v0.11.7-x64.msi 88067c4d19af87f5645a3f8bc81ec7d1610580de x64/node.exe d150573f7567a0da4418d5086410fecabcc1fae8 x64/node.exp e0482e1cca25faacaa1111e2de647025bca5e7f5 x64/node.lib e9a87b9b7aa1ff220ce4b4b5cb0758c9071c8ce2 x64/node.pdb ``` node-v0.10.25~dfsg2/doc/blog/release/node-v0-7-0-unstable.md0000644000000000000000000000222412270121457021633 0ustar rootrootversion: 0.7.0 title: Node v0.7.0 (Unstable) author: ryandahl date: Mon Jan 16 2012 19:58:28 GMT-0800 (PST) status: publish category: release slug: node-v0-7-0-unstable This is the first release in the unstable v0.7 series. Almost all users will want to remain using the stable v0.6 releases. 2012.01.16, Version 0.7.0 (unstable)
    • Upgrade V8 to 3.8.6
    • Use GYP build system on unix (Ben Noordhuis)
    • Experimental isolates support (Ben Noordhuis)
    • Improvements to Cluster API (Andreas Madsen)
    • Use isolates for internal debugger (Fedor Indutny)
    • Bug fixes
    Source Code: http://nodejs.org/dist/v0.7.0/node-v0.7.0.tar.gz Windows Installer: http://nodejs.org/dist/v0.7.0/node-v0.7.0.msi Macintosh Installer: http://nodejs.org/dist/v0.7.0/node-v0.7.0.pkg Website: http://nodejs.org/docs/v0.7.0/ Documentation: http://nodejs.org/docs/v0.7.0/api/ node-v0.10.25~dfsg2/doc/blog/release/v0.8.6.md0000644000000000000000000000602612270121457017112 0ustar rootrootversion: 0.8.6 title: Version 0.8.6 (stable) category: release slug: node-v0-8-6-stable date: 2012-08-07T19:03:55.905Z 2012.08.07, Version 0.8.6 (Stable) This is the first release to include binary distributions for all supported Unix operating systems (Linux, Darwin, and SunOS). To use the binary distribution tarballs, you can unpack them directly into a destination directory: cd ~/node/ # or /usr/local if you're feeling brave tar xzvf /path/to/binary.tar.gz --strip=1 This is an experimental feature. Please use it and provide feedback. * npm: Upgrade to v1.1.48 * Add 'make binary' to build binary tarballs for all Unixes (Nathan Rajlich) * zlib: Emit 'close' on destroy(). (Dominic Tarr) * child_process: Fix stdout=null when stdio=['pipe'] (Tyler Neylon) * installer: prevent ETXTBSY errors (Ben Noordhuis) * installer: honor --without-npm, default install path (Ben Noordhuis) * net: make pause work with connecting sockets (Bert Belder) * installer: fix cross-compile installs (Ben Noordhuis) * net: fix .listen({fd:0}) (Ben Noordhuis) * windows: map WSANO_DATA to UV_ENOENT (Bert Belder) Source Code: http://nodejs.org/dist/v0.8.6/node-v0.8.6.tar.gz Macintosh Installer (Universal): http://nodejs.org/dist/v0.8.6/node-v0.8.6.pkg Windows Installer: http://nodejs.org/dist/v0.8.6/node-v0.8.6-x86.msi Windows x64 Installer: http://nodejs.org/dist/v0.8.6/x64/node-v0.8.6-x64.msi Windows x64 Files: http://nodejs.org/dist/v0.8.6/x64/ Linux 32-bit Binary Package: http://nodejs.org/dist/v0.8.6/node-v0.8.6-linux-x86.tar.gz Linux 64-bit Binary Package: http://nodejs.org/dist/v0.8.6/node-v0.8.6-linux-x64.tar.gz Solaris 32-bit Binary Package: http://nodejs.org/dist/v0.8.6/node-v0.8.6-sunos-x86.tar.gz Solaris 64-bit Binary Package: http://nodejs.org/dist/v0.8.6/node-v0.8.6-sunos-x64.tar.gz Other release files: http://nodejs.org/dist/v0.8.6/ Website: http://nodejs.org/docs/v0.8.6/ Documentation: http://nodejs.org/docs/v0.8.6/api/ Shasums: ``` c23a57601150b3ec59aeeb0eef607d9e430e17c2 node-v0.8.6-darwin-x64.tar.gz 8f7e4e837f61991eff4605678ab27c82e854bc38 node-v0.8.6-darwin-x86.tar.gz 32ce9d28d6a294878ce9ee8f23b6fa7ecb3130e7 node-v0.8.6-linux-x64.tar.gz 6f71518f044705ff1a7d9400a573906a99c5834c node-v0.8.6-linux-x86.tar.gz ec9c02e9713a81d8f4848924cc38e5ed28a06fc4 node-v0.8.6-sunos-x64.tar.gz ac96cc4ce3eee4dc54ef7936ad4fd8eb04fbe359 node-v0.8.6-sunos-x86.tar.gz 0a2aca229c9cb2ec4a4a82ff88de7ea0868d1890 node-v0.8.6-x86.msi 84127d73a968f5951a9682b592a79779d1396c9e node-v0.8.6.pkg 34c7ad2bb5450653748c65840155852d67742258 node-v0.8.6.tar.gz 42f3b792326efdfc9b0d95eebd7f9f716cadb1c0 node.exe fc56e816081ebef450ce7ed92bfd543d53191ac3 node.exp e91f1648e4e8f7586790443248326222101c286c node.lib 8106b33d1cdae69103ca07b16c7f5d690308d751 node.pdb 6226474859e1cf2f1314d92b6207183bb36c6007 x64/node-v0.8.6-x64.msi 3c1ac597956ea9f1e7eab62f85a23e3e436cd0e8 x64/node.exe 599df091faecff536f52d17463c70e07cf9ed54f x64/node.exp 70bac4dcb9f845c8c8cb9443ff09f839fc86aac7 x64/node.lib eb59a0ed841c9e93c406b4c636b2048973cbfae4 x64/node.pdb ``` node-v0.10.25~dfsg2/doc/blog/release/v0.10.22.md0000644000000000000000000000543312270121457017242 0ustar rootrootdate: Tue Nov 12 12:52:56 PST 2013 version: 0.10.22 category: release title: Node v0.10.22 (Stable) slug: node-v0-10-22-stable 2013.11.12, Version 0.10.22 (Stable) * npm: Upgrade to 1.3.14 * uv: Upgrade to v0.10.19 * child_process: don't assert on stale file descriptor events (Fedor Indutny) * darwin: Fix "Not Responding" in Mavericks activity monitor (Fedor Indutny) * debugger: Fix bug in sb() with unnamed script (Maxim Bogushevich) * repl: do not insert duplicates into completions (Maciej Małecki) * src: Fix memory leak on closed handles (Timothy J Fontaine) * tls: prevent stalls by using read(0) (Fedor Indutny) * v8: use correct timezone information on Solaris (Maciej Małecki) Source Code: http://nodejs.org/dist/v0.10.22/node-v0.10.22.tar.gz Macintosh Installer (Universal): http://nodejs.org/dist/v0.10.22/node-v0.10.22.pkg Windows Installer: http://nodejs.org/dist/v0.10.22/node-v0.10.22-x86.msi Windows x64 Installer: http://nodejs.org/dist/v0.10.22/x64/node-v0.10.22-x64.msi Windows x64 Files: http://nodejs.org/dist/v0.10.22/x64/ Linux 32-bit Binary: http://nodejs.org/dist/v0.10.22/node-v0.10.22-linux-x86.tar.gz Linux 64-bit Binary: http://nodejs.org/dist/v0.10.22/node-v0.10.22-linux-x64.tar.gz Solaris 32-bit Binary: http://nodejs.org/dist/v0.10.22/node-v0.10.22-sunos-x86.tar.gz Solaris 64-bit Binary: http://nodejs.org/dist/v0.10.22/node-v0.10.22-sunos-x64.tar.gz Other release files: http://nodejs.org/dist/v0.10.22/ Website: http://nodejs.org/docs/v0.10.22/ Documentation: http://nodejs.org/docs/v0.10.22/api/ Shasums: ``` 3082a8d13dfafa7212a7f75bd0a83447fb4d7b99 node-v0.10.22-darwin-x64.tar.gz dca37fa37c8ce3c0df68e74643ed822bec7a12b3 node-v0.10.22-darwin-x86.tar.gz 3739f75bbb85c920a237ceb1c34cb872409d61f7 node-v0.10.22-linux-x64.tar.gz 7e99b654c21bc2a5cbccc33f1bae3ce6e26b3d12 node-v0.10.22-linux-x86.tar.gz 3dfb3585386ca0645ba02b5ad06014ddccda8cbe node-v0.10.22-sunos-x64.tar.gz e6004f073fc81826335dc0c8fba04a82beada0bc node-v0.10.22-sunos-x86.tar.gz 3beff0c7893e39df54e416307b624eb642bffa62 node-v0.10.22-x86.msi b4433b98f87f3f06130adad410e2fb5f959bbf37 node-v0.10.22.pkg d7c6a39dfa714eae1f8da7a00c9a07efd74a03b3 node-v0.10.22.tar.gz 0ff278f5d6225d2be2a51bd4c7ba8fa0d15e98a4 node.exe 6cded62495794c53f6642745d34cbeb7a28266b1 node.exp caaa11790ac8ec40d074e141afa7ffa611f216b4 node.lib 3c7592832d403c93a17b29852f2c828760a45128 node.pdb f335aef2844a6bf9d8d5a9782e7c631d730acc2e pkgsrc/nodejs-ia32-0.10.22.tgz 6d47f98efd86faa71e1e9887aa63916e884bb2a8 pkgsrc/nodejs-x64-0.10.22.tgz c3c169304c6371ee7bd119151bcbced61a322394 x64/node-v0.10.22-x64.msi 307de602a091fa2af3adaa64812200e32ee00fdc x64/node.exe 67440fca57eb4be5800434245ef1a5d16f5aea01 x64/node.exp e6ee29859cd069ff5b8bf749a598112d9f09ed3c x64/node.lib fee98420155b88c0c4b11616aa416d2328cec97d x64/node.pdb ``` node-v0.10.25~dfsg2/doc/blog/release/v0.10.18.md0000644000000000000000000000464012270121457017246 0ustar rootrootdate: Wed Sep 4 11:24:48 PDT 2013 version: 0.10.18 category: release title: Node v0.10.18 (Stable) slug: node-v0-10-18-stable 2013.09.04, Version 0.10.18 (Stable) * uv: Upgrade to v0.10.15 * stream: Don't crash on unset _events property (isaacs) * stream: Pass 'buffer' encoding with decoded writable chunks (isaacs) Source Code: http://nodejs.org/dist/v0.10.18/node-v0.10.18.tar.gz Macintosh Installer (Universal): http://nodejs.org/dist/v0.10.18/node-v0.10.18.pkg Windows Installer: http://nodejs.org/dist/v0.10.18/node-v0.10.18-x86.msi Windows x64 Installer: http://nodejs.org/dist/v0.10.18/x64/node-v0.10.18-x64.msi Windows x64 Files: http://nodejs.org/dist/v0.10.18/x64/ Linux 32-bit Binary: http://nodejs.org/dist/v0.10.18/node-v0.10.18-linux-x86.tar.gz Linux 64-bit Binary: http://nodejs.org/dist/v0.10.18/node-v0.10.18-linux-x64.tar.gz Solaris 32-bit Binary: http://nodejs.org/dist/v0.10.18/node-v0.10.18-sunos-x86.tar.gz Solaris 64-bit Binary: http://nodejs.org/dist/v0.10.18/node-v0.10.18-sunos-x64.tar.gz Other release files: http://nodejs.org/dist/v0.10.18/ Website: http://nodejs.org/docs/v0.10.18/ Documentation: http://nodejs.org/docs/v0.10.18/api/ Shasums: ``` c0219a68aa25369f4c83c5bdbb5ccc0db2cb8230 node-v0.10.18-darwin-x64.tar.gz 32261191c3b9f0988d4f132e442969714da3281f node-v0.10.18-darwin-x86.tar.gz 07923fa9613b2976b3be3a1bbe36d21b9f69f3c9 node-v0.10.18-linux-x64.tar.gz 4d4c6f485a110bf28e273020c20987c6045d2c57 node-v0.10.18-linux-x86.tar.gz 7b61c0c12fa99f8d0ab6ed0153359ed1c914e224 node-v0.10.18-sunos-x64.tar.gz 9f57be4b041058ea941b7f4c6f0a2ad9f431d46f node-v0.10.18-sunos-x86.tar.gz fd50e0563e1ccf3efc903a33df40f86b6bfe2e62 node-v0.10.18-x86.msi ff71d0e8003fc1b4674f98ceb912fba2161c8224 node-v0.10.18.pkg 0bc3c544ca1707ea4b8bd601706304e9c0609fe5 node-v0.10.18.tar.gz ed35cc393d930fa05f4e1fbcadfa53e2837d59cb node.exe 5bb6f7af79fefa21ce936bdd60355d8d097c6cb6 node.exp 3581c8563d475642d07657fd639f48e595d2693d node.lib 7eb7f20b9e4dfb7d866b6d84916931630159230c node.pdb 192d7996c413e72a7f525039eca75ebdf0d5bc1f pkgsrc/nodejs-ia32-0.10.18.tgz 6c508f63bd76627ece633d04957a29bce52521c7 pkgsrc/nodejs-x64-0.10.18.tgz 8b845fe8723480f740d2efbfac3da11cb712ce66 x64/node-v0.10.18-x64.msi dab63ee4c72612392cfa26c48808d45859cf6b4a x64/node.exe 90e37b4c9c7ea0e96a7035aa6473405da245006c x64/node.exp 1c19d9d5c6e7ced70742875a43085306b91d402d x64/node.lib 4e90849c7c96c4d2caffb64f062d91d14d152261 x64/node.pdb ``` node-v0.10.25~dfsg2/doc/blog/release/node-v0-6-0.md0000644000000000000000000001170212270121457020020 0ustar rootrootversion: 0.6.0 title: Node v0.6.0 author: ryandahl date: Sat Nov 05 2011 02:07:10 GMT-0700 (PDT) status: publish category: release slug: node-v0-6-0 We are happy to announce the third stable branch of Node v0.6. We will be freezing JavaScript, C++, and binary interfaces for all v0.6 releases. The major differences between v0.4 and v0.6 are
    • Native Windows support using I/O Completion Ports for sockets.
    • Integrated load balancing over multiple processes. docs
    • Better support for IPC between Node instances docs
    • Improved command line debugger docs
    • Built-in binding to zlib for compression docs
    • Upgrade v8 from 3.1 to 3.6
    In order to support Windows we reworked much of the core architecture. There was some fear that our work would degrade performance on UNIX systems but this was not the case. Here is a Linux system we benched for demonstration:
    v0.4.12 (linux)v0.6.0 (linux)
    http_simple.js /bytes/1024 5461 r/s 6263 r/s
    io.js read 19.75 mB/s 26.63 mB/s
    io.js write 21.60 mB/s 17.40 mB/s
    startup.js 74.7 ms 49.6 ms
    Bigger is better in http and io benchmarks, smaller is better in startup. The http benchmark was done with 600 clients on a 10GE network served from three load generation machines. In the last version of Node, v0.4, we could only run Node on Windows with Cygwin. Therefore we've gotten massive improvements by targeting the native APIs. Benchmarks on the same machine:
    v0.4.12 (windows)v0.6.0 (windows)
    http_simple.js /bytes/1024 3858 r/s 5823 r/s
    io.js read 12.41 mB/s 26.51 mB/s
    io.js write 12.61 mB/s 33.58 mB/s
    startup.js 152.81 ms 52.04 ms
    We consider this a good intermediate stage for the Windows port. There is still work to be done. For example, we are not yet providing users with a blessed path for building addon modules in MS Visual Studio. Work will continue in later releases. For users upgrading code bases from v0.4 to v0.6 we've documented most of the issues that you will run into. Most people find the change painless. Despite the long list of changes most core APIs remain untouched. Our release cycle will be tightened dramatically now. Expect to see a new stable branch in January. We wish to eventually have our releases in sync with Chrome and V8's 6 week cycle. Thank you to everyone who contributed code, tests, docs, or sent in bug reports. Here are the changes between v0.5.12 and v0.6.0: 2011.11.04, Version 0.6.0 (stable)
    • print undefined on undefined values in REPL (Nathan Rajlich)
    • doc improvements (koichik, seebees, bnoordhuis, Maciej Małecki, Jacob Kragh)
    • support native addon loading in windows (Bert Belder)
    • rename getNetworkInterfaces() to networkInterfaces() (bnoordhuis)
    • add pending accepts knob for windows (igorzi)
    • http.request(url.parse(x)) (seebees)
    • #1929 zlib Respond to 'resume' events properly (isaacs)
    • stream.pipe: Remove resume and pause events
    • test fixes for windows (igorzi)
    • build system improvements (bnoordhuis)
    • #1936 tls: does not emit 'end' from EncryptedStream (koichik)
    • #758 tls: add address(), remoteAddress/remotePort
    • #1399 http: emit Error object after .abort() (bnoordhuis)
    • #1999 fs: make mkdir() default to 0777 permissions (bnoordhuis)
    • #2001 fix pipe error codes
    • #2002 Socket.write should reset timeout timer
    • stdout and stderr are blocking when associated with file too.
    • remote debugger support on windows (Bert Belder)
    • convenience methods for zlib (Matt Robenolt)
    • process.kill support on windows (igorzi)
    • process.uptime() support on windows (igorzi)
    • Return IPv4 addresses before IPv6 addresses from getaddrinfo
    • util.inspect improvements (Nathan Rajlich)
    • cluster module api changes
    • Downgrade V8 to 3.6.6.6
    Download: http://nodejs.org/dist/v0.6.0/node-v0.6.0.tar.gz Windows Executable: http://nodejs.org/dist/v0.6.0/node.exe Website: http://nodejs.org/docs/v0.6.0/ Documentation: http://nodejs.org/docs/v0.6.0/api/ node-v0.10.25~dfsg2/doc/blog/release/node-v0-5-10.md0000644000000000000000000000411512270121457020100 0ustar rootrootversion: 0.5.10 title: Node v0.5.10 author: ryandahl date: Fri Oct 21 2011 19:12:31 GMT-0700 (PDT) status: publish category: release slug: node-v0-5-10 2011.10.21, Version 0.5.10 (unstable)
    • Remove cmake build system, support for Cygwin, legacy code base, process.ENV, process.ARGV, process.memoryUsage().vsize, os.openOSHandle
    • Documentation improvments (Igor Zinkovsky, Bert Belder, Ilya Dmitrichenko, koichik, Maciej Małecki, Guglielmo Ferri, isaacs)
    • Performance improvements (Daniel Ennis, Bert Belder, Ben Noordhuis)
    • Long process.title support (Ben Noordhuis)
    • net: register net.Server callback only once (Simen Brekken)
    • net: fix connect queue bugs (Ben Noordhuis)
    • debugger: fix backtrace err handling (Fedor Indutny)
    • Use getaddrinfo instead of c-ares for dns.lookup
    • Emit 'end' from crypto streams on close
    • repl: print out `undefined` (Nathan Rajlich)
    • #1902 buffer: use NO_NULL_TERMINATION flag (koichik)
    • #1907 http: Added support for HTTP PATCH verb (Thomas Parslow)
    • #1644 add GetCPUInfo on windows (Karl Skomski)
    • #1484, #1834, #1482, #771 Don't use a separate context for the repl. (isaacs)
    • #1882 zlib Update 'availOutBefore' value, and test (isaacs)
    • #1888 child_process.fork: don't modify args (koichik)
    • #1516 tls: requestCert unusable with Firefox and Chrome (koichik)
    • #1467 tls: The TLS API is inconsistent with the TCP API (koichik)
    • #1894 net: fix error handling in listen() (koichik)
    • #1860 console.error now goes through uv_tty_t
    • Upgrade V8 to 3.7.0
    • Upgrade GYP to r1081
    Download: http://nodejs.org/dist/v0.5.10/node-v0.5.10.tar.gz Windows Executable: http://nodejs.org/dist/v0.5.10/node.exe Website: http://nodejs.org/docs/v0.5.10/ Documentation: http://nodejs.org/docs/v0.5.10/api/ node-v0.10.25~dfsg2/doc/blog/release/v0.9.10.md0000644000000000000000000000573212270121457017171 0ustar rootrootcategory: release date: Tue Feb 19 14:00:08 PST 2013 slug: node-v0-9-10-unstable title: Node v0.9.10 (Unstable) version: 0.9.10 2013.02.19, Version 0.9.10 (Unstable) * V8: Upgrade to 3.15.11.15 * npm: Upgrade to 1.2.12 * fs: Change default WriteStream config, increase perf (isaacs) * process: streamlining tick callback logic (Trevor Norris) * stream_wrap, udp_wrap: add read-only fd property (Ben Noordhuis) * buffer: accept negative indices in Buffer#slice() (Ben Noordhuis) * tls: Cycle data when underlying socket drains (isaacs) * stream: read(0) should not always trigger _read(n,cb) (isaacs) * stream: Empty strings/buffers do not signal EOF any longer (isaacs) * crypto: improve cipher/decipher error messages (Ben Noordhuis) * net: Respect the 'readable' flag on sockets (isaacs) * net: don't suppress ECONNRESET (Ben Noordhuis) * typed arrays: copy Buffer in typed array constructor (Ben Noordhuis) * typed arrays: make DataView throw on non-ArrayBuffer (Ben Noordhuis) * windows: MSI installer enhancements (Scott Blomquist, Jim Schubert) Source Code: http://nodejs.org/dist/v0.9.10/node-v0.9.10.tar.gz Macintosh Installer (Universal): http://nodejs.org/dist/v0.9.10/node-v0.9.10.pkg Windows Installer: http://nodejs.org/dist/v0.9.10/node-v0.9.10-x86.msi Windows x64 Installer: http://nodejs.org/dist/v0.9.10/x64/node-v0.9.10-x64.msi Windows x64 Files: http://nodejs.org/dist/v0.9.10/x64/ Linux 32-bit Binary: http://nodejs.org/dist/v0.9.10/node-v0.9.10-linux-x86.tar.gz Linux 64-bit Binary: http://nodejs.org/dist/v0.9.10/node-v0.9.10-linux-x64.tar.gz Solaris 32-bit Binary: http://nodejs.org/dist/v0.9.10/node-v0.9.10-sunos-x86.tar.gz Solaris 64-bit Binary: http://nodejs.org/dist/v0.9.10/node-v0.9.10-sunos-x64.tar.gz Other release files: http://nodejs.org/dist/v0.9.10/ Website: http://nodejs.org/docs/v0.9.10/ Documentation: http://nodejs.org/docs/v0.9.10/api/ Shasums: ``` 813d5f42b156b7d64f00b86e13d26ada3ef352e5 node-v0.9.10-darwin-x64.tar.gz 99dbe66fd0fc176fb3459ffcf62212dcb27bef10 node-v0.9.10-darwin-x86.tar.gz 3a5a465238cbdbdac9786c204fd27be61ce7159a node-v0.9.10-linux-x64.tar.gz 3340ac206ec1a1f827c954efdfa1351dcfe9f419 node-v0.9.10-linux-x86.tar.gz b920b2e57c6df1e080966fdeccbfd1b384b156d4 node-v0.9.10-sunos-x64.tar.gz 9c1744352bb1bc71f48f8aea1aff6aeefe35a394 node-v0.9.10-sunos-x86.tar.gz f1daaafc330cc9993a3a6f7ca8b9cc870b49e75c node-v0.9.10-x86.msi 2b6c70f57c1513e8f5151785b1ac263565983918 node-v0.9.10.pkg 265542c15cf939b7c71a545758d835ed44d791d3 node-v0.9.10.tar.gz 653f24d53f411217d57ed18d73921ff4721f00dd node.exe 7d62da67a7b33628d7d90c9d5037cf564dfc5ce4 node.exp cfebbcd81db602b2f051328a9924e19ca2cb6235 node.lib a31694cb9e03d13a616f3cc634852d8dc98e69b8 node.pdb 5f94c1cc9301a8b85082fee7549aa376aedd8ec5 x64/node-v0.9.10-x64.msi 7716c01ce60f7c65100cc405726badf8476afebd x64/node.exe 121d4a721968ba4631d29de07e5d6c326d259b4b x64/node.exp 17f651000f6b0c840efe539ae5257cb894481c49 x64/node.lib d04242a5ec3a3104931ec8de6a846a8f7746b1fd x64/node.pdb ``` node-v0.10.25~dfsg2/doc/blog/release/v0.8.26.md0000644000000000000000000000523312270121457017173 0ustar rootrootdate: Fri Oct 18 14:52:30 PDT 2013 version: 0.8.26 category: release title: Node v0.8.26 (Maintenance) slug: node-v0-8-26-maintenance This release contains a security fix for the http server implementation, please upgrade as soon as possible. Details will be released soon. 2013.10.13, Version 0.8.26 (maintenance) * v8: Upgrade to 3.11.10.26 * crypto: clear openssl error stack when handled (Ben Noordhuis) * crypto: clear errors from verify failure (Timothy J Fontaine) * crypto: fix memory leak in LoadPKCS12 (Fedor Indutny) * http: provide backpressure for pipeline flood (isaacs) * http_parser: expose pause/resume method for parser (Timothy J Fontaine) * readline: pause stdin before turning off terminal raw mode (Daniel Chatfield) Source Code: http://nodejs.org/dist/v0.8.26/node-v0.8.26.tar.gz Macintosh Installer (Universal): http://nodejs.org/dist/v0.8.26/node-v0.8.26.pkg Windows Installer: http://nodejs.org/dist/v0.8.26/node-v0.8.26-x86.msi Windows x64 Installer: http://nodejs.org/dist/v0.8.26/x64/node-v0.8.26-x64.msi Windows x64 Files: http://nodejs.org/dist/v0.8.26/x64/ Linux 32-bit Binary: http://nodejs.org/dist/v0.8.26/node-v0.8.26-linux-x86.tar.gz Linux 64-bit Binary: http://nodejs.org/dist/v0.8.26/node-v0.8.26-linux-x64.tar.gz Solaris 32-bit Binary: http://nodejs.org/dist/v0.8.26/node-v0.8.26-sunos-x86.tar.gz Solaris 64-bit Binary: http://nodejs.org/dist/v0.8.26/node-v0.8.26-sunos-x64.tar.gz Other release files: http://nodejs.org/dist/v0.8.26/ Website: http://nodejs.org/docs/v0.8.26/ Documentation: http://nodejs.org/docs/v0.8.26/api/ Shasums: ``` b9fa5fca6282a01d491ab585b6a6a64f23ea4da2 node-v0.8.26-darwin-x64.tar.gz ba760b282f38f62ad333c2ecc69d3b296f87cf4a node-v0.8.26-darwin-x86.tar.gz c96470908234656c6060cbe0dab4502f90ca7cd1 node-v0.8.26-linux-x64.tar.gz 3b5c776ae8632df2a4c67b89bdd37d843135be90 node-v0.8.26-linux-x86.tar.gz 6b9b6bb2676b37ff63f240931f68aa22e9187e99 node-v0.8.26-sunos-x64.tar.gz cb3f975293f9561fdda0b46571aee570576e0406 node-v0.8.26-sunos-x86.tar.gz 668bbc8240497675bb4ed3b61c6f7fb79772b264 node-v0.8.26-x86.msi e51a33c28e2c75b0e40826100e5f6b84d5cf8d98 node-v0.8.26.pkg 2ec960bcc8cd38da271f83c1b2007c12da5153b3 node-v0.8.26.tar.gz 860ec0bcb6e89fcee3e45e56e469dd28cfcf400c node.exe ad0e366a82e8570768f5c92d97eebd8fd4a54f8f node.exp 559a7b4e3c49b1071d1cd1374cf4bc4bae2aa558 node.lib 687eeb71782ac36f26aaba60e07bd92f47bfcf36 node.pdb b10e28a100ab40169759bd431ccc855de1763fa8 x64/node-v0.8.26-x64.msi 19b5210e212b3b5473c251786c3d22b8cb919f5f x64/node.exe 6129121aad9d48ffa19a712f59e6acb9bff14eb1 x64/node.exp 4eb1822b10ec3b7a17deff1126725c30c5ef65b1 x64/node.lib 7f39e38b62ad44c774ae381a661726494b2f066e x64/node.pdb ``` node-v0.10.25~dfsg2/doc/blog/release/node-v0.8.0.md0000644000000000000000000003445512270121457020036 0ustar rootroottitle: Node v0.8.0 date: Mon Jun 25 2012 09:00:00 GMT-0700 (PDT) version: 0.8.0 category: release author: Isaac Z. Schlueter slug: node-v0-8-0 status: publish I am thrilled to announce the arrival of a new stable version of Node.js. Compared with the v0.6 releases of Node, this release brings significant improvements in many key performance metrics, as well as cleanup in several core APIs, and the addition of new debugging features. ## tl;dr With version 0.8.0: 1. Node got a lot faster. 2. Node got more stable. 3. You can do stuff with file descriptors again. 4. The [cluster module](http://nodejs.org/api/cluster.html) is much more awesome. 5. The [domain module](http://nodejs.org/api/domain.html) was added. 6. The repl is better. 7. The build system changed from waf to gyp. 8. [Some other stuff changed, too.](https://github.com/joyent/node/wiki/API-changes-between-v0.6-and-v0.8) 9. Scroll to the bottom for the links to install it. ## Performance This version brings a few key enhancements in V8 and libuv that result in significantly improved throughput. All of these benchmarks were run on my OS X laptop, but the results are typical of what we're seeing on SmartOS, Linux, and Windows. ``` # io.js # 0.6.19, writes Wrote 1024 byte buffers: 19.428793471925395 mB/s Wrote 4096 byte buffers: 59.737156511350065 mB/s Wrote 16384 byte buffers: 83.97010664203543 mB/s Wrote 65536 byte buffers: 97.4184120798831 mB/s # 0.8.0, writes Wrote 1024 byte buffers: 61.236987140232706 mB/s +215.19% Wrote 4096 byte buffers: 109.05125408942203 mB/s +82.55% Wrote 16384 byte buffers: 182.18254691200585 mB/s +116.96% Wrote 65536 byte buffers: 181.91740949608877 mB/s +86.74% # v0.6.19, reads Read 1024 byte buffers: 29.96883241428914 mB/s Read 4096 byte buffers: 62.34413965087282 mB/s Read 16384 byte buffers: 165.7550140891762 mB/s Read 65536 byte buffers: 266.73779674579885 mB/s # v0.8.0, reads Read 1024 byte buffers: 57.63688760806916 mB/s +92.32% Read 4096 byte buffers: 136.7801942278758 mB/s +119.40% Read 16384 byte buffers: 244.8579823702253 mB/s +47.72% Read 65536 byte buffers: 302.2974607013301 mB/s +13.33% ``` The difference is not small. If you are writing network programs with node, and pushing a lot of traffic, you will notice this improvement. The speed of reading files got quite a bit faster as well: ``` # v0.6.19 read the file 110948 times (higher is better) 90141.32 ns per read (lower is better) 11093.69 reads per sec (higher is better) # v0.8.0 read the file 158193 times (higher is better) +42.58% 63217.16 ns per read (lower is better) -29.87% 15818.48 reads per sec (higher is better) +42.59% ``` And of course, the ubiquitous 'hello, world' http server benchmark got significantly faster, especially for large message sizes: ``` $ TYPE=bytes LENGTH=123 bash benchmark/http.sh 2>&1 | grep Req # 0.6.19 Requests per second: 3317.24 [#/sec] (mean) # 0.8.0 Requests per second: 3795.34 [#/sec] (mean) +14.41% $ TYPE=bytes LENGTH=1024 bash benchmark/http.sh 2>&1 | grep Req # v0.6.19 Requests per second: 3258.42 [#/sec] (mean) # 0.8.0 Requests per second: 3585.62 [#/sec] (mean) +10.04% $ TYPE=bytes LENGTH=123456 bash benchmark/http.sh 2>&1 | grep Req # v0.6.19 Requests per second: 218.51 [#/sec] (mean) # 0.8.0 Requests per second: 749.17 [#/sec] (mean) +242.85% ``` The difference with Unicode responses is even more pronounced: ``` $ TYPE=unicode LENGTH=1024 bash benchmark/http.sh 2>&1 | grep Req # v0.6.19 Requests per second: 3228.23 [#/sec] (mean) # v0.8.0 Requests per second: 3317.60 [#/sec] (mean) +2.77% $ TYPE=unicode LENGTH=12345 bash benchmark/http.sh 2>&1 | grep Req # v0.6.19 Requests per second: 1703.96 [#/sec] (mean) # v0.8.0 Requests per second: 2431.61 [#/sec] (mean) +42.70% $ TYPE=unicode LENGTH=55555 bash benchmark/http.sh 2>&1 | grep Req #v0.6.19 Requests per second: 161.65 [#/sec] (mean) #v0.8.0 Requests per second: 980.38 [#/sec] (mean) +506.48% $ TYPE=unicode LENGTH=99999 bash benchmark/http.sh 2>&1 | grep Req # v0.6.19 ^C # lost patience after a few hours # v0.8.0 Requests per second: 252.69 [#/sec] (mean) ``` The more bytes you're pushing, and the more work you're doing, the more win you'll see with node 0.8 over 0.6. The vast majority of the performance boost is due to improvements in V8. They've been very responsive to the needs of the Node.js project. A lot of Node's success is due to being built on such a stellar VM. ## Build System Since its inception Node has used the WAF build system which is a Python based system similar to SCons. The Chrome project recently changed to the GYP meta-build system from SCons. GYP generates Makefiles, Visual Studio project files, or XCode files depending on the target. V8, being part of the Chrome project, now defines its build in GYP. By using GYP, Node is able to: - integrate with the optimal build system on all platforms, - easily able to integrate V8's build process into its own, and - define its compilation declaratively for better manageability GYP was used already in Node v0.6 to build on Windows, but now it defines the build on all platforms. Node is still in the process of migrating external addon modules to GYP, and node-gyp is included with npm. In future releases, node-waf will be officially deprecated. If you are currently using a wscript in your addon, please migrate to gyp as soon as possible. ## Stabler The transition from libev and libeio to libuv in 0.6 was somewhat destabilizing for many node internals. The gambit paid off: libuv is the obvious choice in cross-platform asynchronous IO libraries, and Node.js is impressively performant on both Windows and Unix. But it made the transition from 0.4 to 0.6 was very rocky for a lot of users. Libuv wasn't as mature as node, and it showed in those early releases. At this point, with very few exceptions, if your v0.6 program doesn't run on v0.8, it should be easy and obvious to make whatever changes are necessary. Libuv has come a very long way, and Node 0.8 is a simpler and more efficient machine as a result. See the [migration wiki](https://github.com/joyent/node/wiki/API-changes-between-v0.6-and-v0.8) for details on the specific APIs that changed. ## The Return of File Descriptors In Node 0.4, there was a `listenFD` method that servers could use to listen on a specific file descriptor that was already bound to a socket or port. In 0.6, that functionality went away, largely because it was very Unix-specific, and couldn't be easily made to work with the new cross-platform libuv base. Since the most common use case for listenFD was as a method for having servers in multiple node processes share the same underlying handle, the `cluster` module was added in its place. However, this still left a lot of use cases unaddressed, and was a reason why some people could not use node 0.6 for their programs. In 0.8, we've replaced this functionality, as `server.listen({ fd: number })`. The other feature in node 0.4 that got dropped in 0.6 was the ability to pass arbitrary file descriptors as a child process's stdio, using the `customFds` array. In Node 0.6, `customFds` could be used to inherit the parent's stdio handles, but not to pass arbitrary handles or file descriptors to the child's stdio. Also, there was never a way to pass more than the standard `in, out, err` trio, so programs that expected FD 4 to be opened in some specific way were out of luck. In 0.8, we've added the `stdio` array on the `child_process.spawn` options. Pass as many file descriptors, handles, etc. as you like, and the child process will see them as already-opened FDs. ## More Powerful Cluster The cluster module in 0.8 is so much improved over 0.6, it's basically a complete rewrite. The API is mostly backwards compatible, but not entirely. (See the [migration wiki](https://github.com/joyent/node/wiki/API-changes-between-v0.6-and-v0.8) for details.) Barring these very minor API changes, if you were using cluster in 0.6, then your program will still work, but it'll be faster and more well-behaved now. And if you aren't taking advantage of the new features in 0.8's cluster, you're really missing out. There's too much even to do it justice here. Go read [the API docs](http://nodejs.org/api/cluster.html). ## Domains The original idea for Domains was a way to join multiple different IO actions, so that you can have some context when an error occurs. Since Ryan discussed the feature with node users at NodeConf Summer Camp last year, the domains feature has gone through many revisions. The problem is fairly well understood, but most attempts to solve it resulted in serious performance regressions, or uncovered difficult edge cases. What we ended up with in 0.8 is a very stripped-down version of this idea. It's entirely opt-in, with minimal performance impact when it's used (and none when it isn't). There are a lot of examples in [the API documentation](http://nodejs.org/api/domain.html), so check them out, and start handling your crashes smarter. The domain module is still experimental. We are looking forward to your feedback, so please use it and let us know what you think. ## Repl, Readline, TTY The Repl, Readline, and TTY modules have all had a major facelift. The interfaces between these three modules are cleaned up and refactored, removing a lot of common pain points and making it easier to use for debugging your programs. It may seem minor at times, but a good repl dramatically increases the quality of the overall experience. My personal favorites are: 1. Typing `fs` or `net` or `path` will automatically load the module. 2. Typing `npm install ...` will give you a helpful message. 3. It doesn't do that stupid thing where long lines wrap and then the backspace makes it get all confused and crazy. Instead of that, it does the right thing. ## Looking Forward Like other even-numbered version families before it, v0.8 will maintain API and ABI stability throughout its lifetime. The v0.6 release family will continue to see releases for critical bugfixes and security issues through the end of 2012. However, it will not be the main focus of the core team's attention. The v0.9 releases will start in the next couple weeks. The main focus of v0.9 will be: * The HTTP implementation - It has seen a lot of real-world use now, but the http module is in dire need of a cleanup and refactor. Special attention will be paid to making the interfaces more consistent, improve performance, and increase correctness in more edge cases. * The Streams API - The concept of the Stream API is very core to node. However, it is also (like HTTP) a feature that grew up organically, and is now in need of a cleanup. It is currently too hard to get right, especially regarding error handling. * Libuv Streams - The handle interfaces in libuv are going to be refactored for added consistency throughout the codebase and across platforms. Looking past that, there are a few areas where Node.js still has room for improvement in terms of internal consistency, idiomatic JavaScript usage, and performance. None of these are fully-fleshed out ideas yet, but these are some of the items on our radar: * We ought to move to TypedArrays in favor of Buffers. Buffers will continue to work, but since TypedArray is a JavaScript native, it makes sense to move towards that as the preferred API. * SSL performance leaves much to be desired at the moment. Node's interface with OpenSSL is somewhat naive and leaves a lot of potential optimization on the table. * The VM module needs massive improvement. It lacks features required to emulate a web browser JavaScript context, which means that it is inadequate. * The Crypto module still uses some very dated APIs. In 0.8, it can accept Buffers for many things (finally!) but it still does not present a Node-like streaming interface. At this point, the scope of Node's feature set is pretty much locked down. We may move things around internally for these cleanup tasks, but as you can see, there are no major new features planned. We've drawn our boundaries, and now it's time to continue focusing on improving stability and performance of the core, so that more innovation can happen in **your** programs. And now, for those of you who may be wondering what was added since v0.7.12, your regularly scheduled release announcement: ## 2012.06.25, Version 0.8.0 (stable) * V8: upgrade to v3.11.10.10 * npm: Upgrade to 1.1.32 * Deprecate iowatcher (Ben Noordhuis) * windows: update icon (Bert Belder) * http: Hush 'MUST NOT have a body' warnings to debug() (isaacs) * Move blog.nodejs.org content into repository (isaacs) * Fix #3503: stdin: resume() on pipe(dest) (isaacs) * crypto: fix error reporting in SetKey() (Fedor Indutny) * Add --no-deprecation and --trace-deprecation command-line flags (isaacs) * fs: fix fs.watchFile() (Ben Noordhuis) * fs: Fix fs.readfile() on pipes (isaacs) * Rename GYP variable node_use_system_openssl to be consistent (Ryan Dahl) Source Code: http://nodejs.org/dist/v0.8.0/node-v0.8.0.tar.gz Macintosh Installer (Universal): http://nodejs.org/dist/v0.8.0/node-v0.8.0.pkg Windows Installer: http://nodejs.org/dist/v0.8.0/node-v0.8.0-x86.msi Windows x64 Installer: http://nodejs.org/dist/v0.8.0/x64/node-v0.8.0-x64.msi Windows x64 Files: http://nodejs.org/dist/v0.8.0/x64/ Other release files: http://nodejs.org/dist/v0.8.0/ Website: http://nodejs.org/docs/v0.8.0/ Documentation: http://nodejs.org/docs/v0.8.0/api/ Shasums: ``` b92208b291ad420025c65661a7df51fc618e21ca license.rtf 0786bcda79bd651b9981682527a1bbabe0250700 node-v0.8.0-x86.msi 8f160a742a01fdfc1b1423b3fc742d184f1ab70c node-v0.8.0-x86.wixpdb 6035d6d59304add21e462cd7eb89491570b4970d node-v0.8.0.pkg 5171fb46fbfee5ac7129c4b17207a3f35a1f57e8 node-v0.8.0.tar.gz 742100a4ee4cd4d190031a30d9b22b2b69b6872e node.exe 52d20d285e9aec53043af0843f5ecc4153210693 node.exp 6d67a64274d844548cc6099c76181a50feafc233 node.lib aa2af08d5ab869e6c8b67f01ed67129c1cad8bce node.pdb b92208b291ad420025c65661a7df51fc618e21ca x64/license.rtf c4d4164d4f78ea68e0e2a85b96f9b355f3b1df8b x64/node-v0.8.0-x64.msi df8bb178ee4cb9562d93fe80bbe59b2acf1b9e6b x64/node-v0.8.0-x64.wixpdb fc07b475d943f7681e1904d6d7d666b41874a6fa x64/node.exe 895002806dfb6d5bb141ef0f43cad3b540a4ff6c x64/node.exp 686c60d5ae5dad7fcffcdc88049c63b2cd23cffc x64/node.lib 75549cffab0c11107348a66ab0d94d4897bd6a27 x64/node.pdb ``` Edited by Tim Oxley to provide percentage differences in the benchmarks. node-v0.10.25~dfsg2/doc/blog/release/v0.9.11.md0000644000000000000000000000577512270121457017201 0ustar rootrootdate: Fri Mar 1 11:17:40 PST 2013 version: 0.9.11 category: release title: Node v0.9.11 (Unstable) slug: node-v0-9-11-unstable 2013.03.01, Version 0.9.11 (Unstable) * V8: downgrade 3.14.5 * openssl: update to 1.0.1e * darwin: Make process.title work properly (Ben Noordhuis) * fs: Support mode/flag options to read/append/writeFile (isaacs) * stream: _read() no longer takes a callback (isaacs) * stream: Add stream.unshift(chunk) (isaacs) * stream: remove lowWaterMark feature (isaacs) * net: omit superfluous 'connect' event (Ben Noordhuis) * build, windows: disable SEH (Ben Noordhuis) * core: remove errno global (Ben Noordhuis) * core: Remove the nextTick for running the main file (isaacs) * core: Mark exit() calls with status codes (isaacs) * core: Fix debug signal handler race condition lock (isaacs) * crypto: clear error stack (Ben Noordhuis) * test: optionally set common.PORT via env variable (Timothy J Fontaine) * path: Throw TypeError on non-string args to path.resolve/join (isaacs, Arianit Uka) * crypto: fix uninitialized memory access in openssl (Ben Noordhuis) Source Code: http://nodejs.org/dist/v0.9.11/node-v0.9.11.tar.gz Macintosh Installer (Universal): http://nodejs.org/dist/v0.9.11/node-v0.9.11.pkg Windows Installer: http://nodejs.org/dist/v0.9.11/node-v0.9.11-x86.msi Windows x64 Installer: http://nodejs.org/dist/v0.9.11/x64/node-v0.9.11-x64.msi Windows x64 Files: http://nodejs.org/dist/v0.9.11/x64/ Linux 32-bit Binary: http://nodejs.org/dist/v0.9.11/node-v0.9.11-linux-x86.tar.gz Linux 64-bit Binary: http://nodejs.org/dist/v0.9.11/node-v0.9.11-linux-x64.tar.gz Solaris 32-bit Binary: http://nodejs.org/dist/v0.9.11/node-v0.9.11-sunos-x86.tar.gz Solaris 64-bit Binary: http://nodejs.org/dist/v0.9.11/node-v0.9.11-sunos-x64.tar.gz Other release files: http://nodejs.org/dist/v0.9.11/ Website: http://nodejs.org/docs/v0.9.11/ Documentation: http://nodejs.org/docs/v0.9.11/api/ Shasums: ``` 2e11c53449523642f1b3f2cad9726d032ebf0a1b node-v0.9.11-darwin-x64.tar.gz 6a8c18185d67ff50979a143b9e100d56b35aedde node-v0.9.11-darwin-x86.tar.gz 16a95dfc6974ba3562801d9f7bb9e2fa0c001d32 node-v0.9.11-linux-x64.tar.gz 4711aae106edf9a2bf9f644b08db1b608e9829c1 node-v0.9.11-linux-x86.tar.gz 897c21d0fc59faebbdf515e0dfee27551386c4af node-v0.9.11-sunos-x64.tar.gz 09c2b469ef984237bbd606d78f523d1c8b92e680 node-v0.9.11-sunos-x86.tar.gz 81627efd5c591f636147100e2e95bbbb17fd0290 node-v0.9.11-x86.msi a0e91028c7fd091db1667ccf9dba6216ee321e98 node-v0.9.11.pkg 66370601eb824305b12c7f3e5b2a5e8ca94f1209 node-v0.9.11.tar.gz db08f56a8258dd8a6a525595a023ad9eb72603e6 node.exe 759fe57cbceeee5820c7de176b6ef8c2a5af7fab node.exp 299f0f8aebbc755b37fc6b40e463cb455a5bb1c6 node.lib f12b3dc557ae16834ae3a793d768e251d1ba5db3 node.pdb 807520a39d6f7518e53da796fa1ca62316219146 x64/node-v0.9.11-x64.msi e27a6adc077629ae9a367b4a5cb7fb31853863d3 x64/node.exe fdcf8ccea3b2c5e3f4f99fa606715e1e27a96acc x64/node.exp fa0db53aac8d97bab3566c7d80fceb8e148c6d0d x64/node.lib e24cf62376b8439ae40b84d37c55ab23fbad4e47 x64/node.pdb ``` node-v0.10.25~dfsg2/doc/blog/release/version-0-7-11-unstable.md0000644000000000000000000000542012270121457022270 0ustar rootrootversion: 0.7.11 title: Version 0.7.11 (unstable) author: Isaac Schlueter date: Fri Jun 15 2012 12:45:20 GMT-0700 (PDT) status: publish category: release slug: version-0-7-11-unstable

    This is the most stable 0.7 release yet. Please try it out.

    Version 0.8 will be out very soon. You can follow the remaining issues on the github issue tracker.

    https://github.com/joyent/node/issues?milestone=10&state=open

    2012.06.15, Version 0.7.11 (unstable)

    • V8: Upgrade to v3.11.10

    • npm: Upgrade to 1.1.26

    • doc: Improve cross-linking in API docs markdown (Ben Kelly)

    • Fix #3425: removeAllListeners should delete array (Reid Burke)

    • cluster: don't silently drop messages when the write queue gets big (Bert Belder)

    • Add Buffer.concat method (isaacs)

    • windows: make symlinks tolerant to forward slashes (Bert Belder)

    • build: Add node.d and node.1 to installer (isaacs)

    • cluster: rename worker.unqiueID to worker.id (Andreas Madsen)

    • Windows: Enable ETW events on Windows for existing DTrace probes. (Igor Zinkovsky)

    • test: bundle node-weak in test/gc so that it doesn't need to be downloaded (Nathan Rajlich)

    • Make many tests pass on Windows (Bert Belder)

    • Fix #3388 Support listening on file descriptors (isaacs)

    • Fix #3407 Add os.tmpDir() (isaacs)

    • Unbreak the snapshotted build on Windows (Bert Belder)

    • Clean up child_process.kill throws (Bert Belder)

    • crypto: make cipher/decipher accept buffer args (Ben Noordhuis)

    Source Code: http://nodejs.org/dist/v0.7.11/node-v0.7.11.tar.gz

    Macintosh Installer (Universal): http://nodejs.org/dist/v0.7.11/node-v0.7.11.pkg

    Windows Installer: http://nodejs.org/dist/v0.7.11/node-v0.7.11-x86.msi

    Windows x64 Installer: http://nodejs.org/dist/v0.7.11/node-v0.7.11-x64.msi

    Windows x64 Files: http://nodejs.org/dist/v0.7.11/x64/

    Other release files: http://nodejs.org/dist/v0.7.11/

    Website: http://nodejs.org/docs/v0.7.11/

    Documentation: http://nodejs.org/docs/v0.7.11/api/

    node-v0.10.25~dfsg2/doc/blog/release/v0.10.4.md0000644000000000000000000000566212270121457017166 0ustar rootrootdate: Thu Apr 11 10:52:56 PDT 2013 version: 0.10.4 category: release title: Node v0.10.4 (Stable) slug: node-v0-10-4-stable 2013.04.11, Version 0.10.4 (Stable) * uv: Upgrade to 0.10.4 * npm: Upgrade to 1.2.18 * v8: Avoid excessive memory growth in JSON.parse (Fedor Indutny) * child_process, cluster: fix O(n*m) scan of cmd string (Ben Noordhuis) * net: fix socket.bytesWritten Buffers support (Fedor Indutny) * buffer: fix offset checks (Łukasz Walukiewicz) * stream: call write cb before finish event (isaacs) * http: Support write(data, 'hex') (isaacs) * crypto: dh secret should be left-padded (Fedor Indutny) * process: expose NODE_MODULE_VERSION in process.versions (Rod Vagg) * crypto: fix constructor call in crypto streams (Andreas Madsen) * net: account for encoding in .byteLength (Fedor Indutny) * net: fix buffer iteration in bytesWritten (Fedor Indutny) * crypto: zero is not an error if writing 0 bytes (Fedor Indutny) * tls: Re-enable check of CN-ID in cert verification (Tobias Müllerleile) Source Code: http://nodejs.org/dist/v0.10.4/node-v0.10.4.tar.gz Macintosh Installer (Universal): http://nodejs.org/dist/v0.10.4/node-v0.10.4.pkg Windows Installer: http://nodejs.org/dist/v0.10.4/node-v0.10.4-x86.msi Windows x64 Installer: http://nodejs.org/dist/v0.10.4/x64/node-v0.10.4-x64.msi Windows x64 Files: http://nodejs.org/dist/v0.10.4/x64/ Linux 32-bit Binary: http://nodejs.org/dist/v0.10.4/node-v0.10.4-linux-x86.tar.gz Linux 64-bit Binary: http://nodejs.org/dist/v0.10.4/node-v0.10.4-linux-x64.tar.gz Solaris 32-bit Binary: http://nodejs.org/dist/v0.10.4/node-v0.10.4-sunos-x86.tar.gz Solaris 64-bit Binary: http://nodejs.org/dist/v0.10.4/node-v0.10.4-sunos-x64.tar.gz Other release files: http://nodejs.org/dist/v0.10.4/ Website: http://nodejs.org/docs/v0.10.4/ Documentation: http://nodejs.org/docs/v0.10.4/api/ Shasums: ``` 0bebde7d5d698e93fd96ad1b5d223166cd0c5892 node-v0.10.4-darwin-x64.tar.gz 8d847a68f8178b102c72c3f35861f496e12fe455 node-v0.10.4-darwin-x86.tar.gz 28e3a4d2702a13454a3c1d9e1035ee07ef8764bc node-v0.10.4-linux-x64.tar.gz 839be3dfe4504072e372b2a3f597e0b0f4e26331 node-v0.10.4-linux-x86.tar.gz 94d68094afacb70b71a3393f07f81eff6e8a14f1 node-v0.10.4-sunos-x64.tar.gz 6b287dcdb9498cb7d59acbab8faaea4455ffe2c4 node-v0.10.4-sunos-x86.tar.gz 1863868f40d4e3af876d21976d9b06a9e99d1dcf node-v0.10.4-x86.msi bafb80cff0ada4cdfd98c917459d627d7df408d5 node-v0.10.4.pkg 901c1410b7c28a79644292567d3384255f3a6274 node-v0.10.4.tar.gz 73b5f6eaea8417f4b937bf99812263dc170696e0 node.exe 85064a019b8e6416152ae609ace81469331f773c node.exp e5b26b8480c3979ddab5ea3bf6bfb0fbef9ecb54 node.lib 0098965a1a2206a1fc148ab776d182018b80d0ba node.pdb 31bd64f33436fa543f0599f80c5df97c14b10224 x64/node-v0.10.4-x64.msi 8280dbeb5a1296fe3496f57376a619467c4c6263 x64/node.exe e317e0db2693e42851f3774a20dc98e02a9a90fe x64/node.exp 7f0aa389465ac7983a4c099671bb52c7a6988676 x64/node.lib a7fb9a08d6337225dd8c5b1db5fb95a2f39fd773 x64/node.pdb ``` node-v0.10.25~dfsg2/doc/blog/release/version-0-7-7-unstable.md0000644000000000000000000000473212270121457022222 0ustar rootrootversion: 0.7.7 title: Version 0.7.7 (unstable) author: Isaac Schlueter date: Fri Mar 30 2012 11:56:19 GMT-0700 (PDT) status: publish category: release slug: version-0-7-7-unstable

    2012.03.30, Version 0.7.7 (unstable)

    • Upgrade V8 to 3.9.24.7

    • Upgrade npm to 1.1.15

    • Handle Emoji characters properly (Erik Corry, Bert Belder)

    • readline: migrate ansi/vt100 logic from tty to readline (Nathan Rajlich)

    • readline: Fix multiline handling (Alex Kocharin)

    • add a -i/--interactive flag to force the REPL (Nathan Rajlich)

    • debugger: add breakOnException command (Fedor Indutny)

    • cluster: kill workers when master dies (Andreas Madsen)

    • cluster: add graceful disconnect support (Andreas Madsen)

    • child_process: Separate 'close' event from 'exit' (Charlie McConnell)

    • typed arrays: add Uint8ClampedArray (Mikael Bourges-Sevenier)

    • buffer: Fix byte alignment issues (Ben Noordhuis, Erik Lundin)

    • tls: fix CryptoStream.setKeepAlive() (Shigeki Ohtsu)

    • Expose http parse error codes (Felix Geisendörfer)

    • events: don't delete the listeners array (Ben Noordhuis, Nathan Rajlich)

    • process: add process.config to view node's ./configure settings (Nathan Rajlich)

    • process: process.execArgv to see node's arguments (Micheil Smith)

    • process: fix process.title setter (Ben Noordhuis)

    • timers: handle negative or non-numeric timeout values (Ben Noordhuis)

    Source Code: http://nodejs.org/dist/v0.7.7/node-v0.7.7.tar.gz

    Windows Installer: http://nodejs.org/dist/v0.7.7/node-v0.7.7.msi

    Windows x64 Files: http://nodejs.org/dist/v0.7.7/x64/

    Macintosh Installer (Universal): http://nodejs.org/dist/v0.7.7/node-v0.7.7.pkg

    Other release files: http://nodejs.org/dist/v0.7.7/

    Website: http://nodejs.org/docs/v0.7.7/

    Documentation: http://nodejs.org/docs/v0.7.7/api/

    node-v0.10.25~dfsg2/doc/blog/release/0.6.21.md0000644000000000000000000000262512270121457017000 0ustar rootrootversion: 0.6.21 title: Version 0.6.21 (maintenance) category: release slug: node-v0-6-21-maintenance date: Fri Aug 03 2012 14:44:02 GMT-0700 (PDT) 2012.08.03 Version 0.6.21 (maintenance) * sunos: work around OS bug to prevent fs.watch() from spinning (Bryan Cantrill) * net: make pause/resume work with connecting sockets (Bert Belder) Source Code: http://nodejs.org/dist/v0.6.21/node-v0.6.21.tar.gz Windows Installer: http://nodejs.org/dist/v0.6.21/node-v0.6.21.msi Windows x64 Files: http://nodejs.org/dist/v0.6.21/x64/ Macintosh Installer (Universal): http://nodejs.org/dist/v0.6.21/node-v0.6.21.pkg Other release files: http://nodejs.org/dist/v0.6.21/ Website: http://nodejs.org/docs/v0.6.21/ Documentation: http://nodejs.org/docs/v0.6.21/api/ Shasums: ``` 04f58b0da23c3db291d84ac55a924332ad83c427 node-v0.6.21.pkg 31f564bf34c64b07cae3b9a88a87b4a08bab4dc5 node-v0.6.21.tar.gz 1e3184fe2cfe7140a88b5dcc9c2ec7d32f1f5af5 node.exe b8887a056152622c08ee10f5867bd27910260477 node.exp c6468ffe2e145e7db1bb3e2d66adb9f5d50271ad node.lib 2a896bcb7c83f2fa710650116580daf4ac5e6c4c node.msi 207441e8c3dc184c478367b775dc7ece1ee36501 node.pdb 715ad9946db5f97c54a53bdea6bbe9ba69f2f299 x64/node.exe 2fa2c2d82fedeec1ed8be5d908b790f473d4a7c2 x64/node.exp b403cb71d4cf21e97a78d446403cedc9795bcf69 x64/node.lib ef47520dbc6a1a68ec37d290c421031cfd670048 x64/node.msi fb15e3991c420f3ae67ade92b11b07bb9112124a x64/node.pdb ``` node-v0.10.25~dfsg2/doc/blog/release/v0.10.12.md0000644000000000000000000000466212270121457017244 0ustar rootrootdate: Tue Jun 18 11:12:19 PDT 2013 version: 0.10.12 category: release title: Node v0.10.12 (Stable) slug: node-v0-10-12-stable 2013.06.18, Version 0.10.12 (Stable) * npm: Upgrade to 1.2.32 * readline: make `ctrl + L` clear the screen (Yuan Chuan) * v8: add setVariableValue debugger command (Ben Noordhuis) * net: Do not destroy socket mid-write (isaacs) * v8: fix build for mips32r2 architecture (Andrei Sedoi) * configure: fix cross-compilation host_arch_cc() (Andrei Sedoi) Source Code: http://nodejs.org/dist/v0.10.12/node-v0.10.12.tar.gz Macintosh Installer (Universal): http://nodejs.org/dist/v0.10.12/node-v0.10.12.pkg Windows Installer: http://nodejs.org/dist/v0.10.12/node-v0.10.12-x86.msi Windows x64 Installer: http://nodejs.org/dist/v0.10.12/x64/node-v0.10.12-x64.msi Windows x64 Files: http://nodejs.org/dist/v0.10.12/x64/ Linux 32-bit Binary: http://nodejs.org/dist/v0.10.12/node-v0.10.12-linux-x86.tar.gz Linux 64-bit Binary: http://nodejs.org/dist/v0.10.12/node-v0.10.12-linux-x64.tar.gz Solaris 32-bit Binary: http://nodejs.org/dist/v0.10.12/node-v0.10.12-sunos-x86.tar.gz Solaris 64-bit Binary: http://nodejs.org/dist/v0.10.12/node-v0.10.12-sunos-x64.tar.gz Other release files: http://nodejs.org/dist/v0.10.12/ Website: http://nodejs.org/docs/v0.10.12/ Documentation: http://nodejs.org/docs/v0.10.12/api/ Shasums: ``` e3c28629938d70dac535dca0b78199ae7e4e7cf6 node-v0.10.12-darwin-x64.tar.gz d777c8c50270b7c834ee9ca95c186d30e181f885 node-v0.10.12-darwin-x86.tar.gz c5b9cbb9b6329767f11a89c14e09afa795e3f9e9 node-v0.10.12-linux-x64.tar.gz f7a7ac317ab3a8406ec11ec118c38971d5e4c508 node-v0.10.12-linux-x86.tar.gz c5f446d6768298ad0d917f920f422a1e82d92fce node-v0.10.12-sunos-x64.tar.gz 05725a5255f762193838dac7175cbba418ef77c7 node-v0.10.12-sunos-x86.tar.gz 3403fed2cedf23764de50e17d0eeb5c960e88b79 node-v0.10.12-x86.msi 8e7cfecf737886014616d7c683bbb8a5ef38f4f7 node-v0.10.12.pkg 3e4f692fb9156c0cee4dd35bd8a6be4ff89a29de node-v0.10.12.tar.gz d1cb17e753a5e0370c9ffe7f753e5c9b1d5bb9ff node.exe af802e62b0da817543f5a4d51304d7fc49b4e56c node.exp 737eb43e0daed76112e8371f85176151dc380ac5 node.lib b273075995dba44e7ae02641c3c8ba4c6301be8d node.pdb e109532cc9d83599d7ebe18c325d14bdc7087ae8 x64/node-v0.10.12-x64.msi 1d902d66ecfd78c5bfef4181bab075119377006d x64/node.exe 3d79a1f3a94c31f73c095d9b3fd83ae80e14042f x64/node.exp 80295d8b0cb4922dbae01d85a0726f2721f0db00 x64/node.lib 2b5663f50946b13a1df4d9fcf7f9edd9605e130c x64/node.pdb ``` node-v0.10.25~dfsg2/doc/blog/release/node-v0-4-10.md0000644000000000000000000000214412270121457020077 0ustar rootrootversion: 0.4.10 title: Node v0.4.10 author: ryandahl date: Wed Jul 20 2011 07:36:38 GMT-0700 (PDT) status: publish category: release slug: node-v0-4-10 2011.07.19, Version 0.4.10 (stable)
    • #394 Fix Buffer drops last null character in UTF-8
    • #829 Backport r8577 from V8 (Ben Noordhuis)
    • #877 Don't wait for HTTP Agent socket pool to establish connections.
    • #915 Find kqueue on FreeBSD correctly (Brett Kiefer)
    • #1085 HTTP: Fix race in abort/dispatch code (Stefan Rusu)
    • #1274 debugger improvement (Yoshihiro Kikuchi)
    • #1291 Properly respond to HEAD during end(body) hot path (Reid Burke)
    • #1304 TLS: Fix race in abort/connection code (Stefan Rusu)
    • #1360 Allow _ in url hostnames.
    • Revert 37d529f8 - unbreaks debugger command parsing.
    • Bring back global execScript
    • Doc improvements
    Download: http://nodejs.org/dist/node-v0.4.10.tar.gz Website: http://nodejs.org/docs/v0.4.10 Documentation: http://nodejs.org/docs/v0.4.10/api node-v0.10.25~dfsg2/doc/blog/release/version-0-7-5-unstable.md0000644000000000000000000000412712270121457022216 0ustar rootrootversion: 0.7.5 title: Version 0.7.5 (unstable) author: Isaac Schlueter date: Thu Feb 23 2012 14:45:21 GMT-0800 (PST) status: publish category: release slug: version-0-7-5-unstable

    2012.02.23, Version 0.7.5 (unstable)

    • startup speed improvements (Maciej Małecki)

    • crypto: add function getDiffieHellman() (Tomasz Buchert)

    • buffer: support decoding of URL-safe base64 (Ben Noordhuis)

    • Make QueryString.parse() even faster (Brian White)

    • url: decode url entities in auth section (Ben Noordhuis)

    • http: support PURGE request method (Ben Noordhuis)

    • http: Generate Date headers on responses (Mark Nottingham)

    • Fix #2762: Add callback to close function. (Mikeal Rogers)

    • dgram: fix out-of-bound memory read (Ben Noordhuis)

    • repl: add automatic loading of built-in libs (Brandon Benvie)

    • repl: remove double calls where possible (Fedor Indutny)

    • Readline improvements. Related: #2737 #2756 (Colton Baker)

    • build: disable -fomit-frame-pointer on solaris (Dave Pacheco)

    • build: arch detection improvements (Nathan Rajlich)

    • build: Make a fat binary for the OS X make pkg. (Nathan Rajlich)

    • jslint src/ and lib/ on 'make test' (isaacs)

    Source Code: http://nodejs.org/dist/v0.7.5/node-v0.7.5.tar.gz

    Windows Installer: http://nodejs.org/dist/v0.7.5/node-v0.7.5.msi

    Macintosh Installer: http://nodejs.org/dist/v0.7.5/node-v0.7.5.pkg

    Other release files: http://nodejs.org/dist/v0.7.5/

    Website: http://nodejs.org/docs/v0.7.5/

    Documentation: http://nodejs.org/docs/v0.7.5/api/

    node-v0.10.25~dfsg2/doc/blog/release/v0.8.22.md0000644000000000000000000000442412270121457017170 0ustar rootrootdate: Thu Mar 7 00:16:34 UTC 2013 version: 0.8.22 category: release title: Node v0.8.22 (Stable) slug: node-v0-8-22-stable 2013.03.07, Version 0.8.22 (Stable) * npm: Update to 1.2.14 * cluster: propagate bind errors (Ben Noordhuis) * crypto: don't assert when calling Cipher#final() twice (Ben Noordhuis) * build, windows: disable SEH (Ben Noordhuis) Source Code: http://nodejs.org/dist/v0.8.22/node-v0.8.22.tar.gz Macintosh Installer (Universal): http://nodejs.org/dist/v0.8.22/node-v0.8.22.pkg Windows Installer: http://nodejs.org/dist/v0.8.22/node-v0.8.22-x86.msi Windows x64 Installer: http://nodejs.org/dist/v0.8.22/x64/node-v0.8.22-x64.msi Windows x64 Files: http://nodejs.org/dist/v0.8.22/x64/ Linux 32-bit Binary: http://nodejs.org/dist/v0.8.22/node-v0.8.22-linux-x86.tar.gz Linux 64-bit Binary: http://nodejs.org/dist/v0.8.22/node-v0.8.22-linux-x64.tar.gz Solaris 32-bit Binary: http://nodejs.org/dist/v0.8.22/node-v0.8.22-sunos-x86.tar.gz Solaris 64-bit Binary: http://nodejs.org/dist/v0.8.22/node-v0.8.22-sunos-x64.tar.gz Other release files: http://nodejs.org/dist/v0.8.22/ Website: http://nodejs.org/docs/v0.8.22/ Documentation: http://nodejs.org/docs/v0.8.22/api/ Shasums: ``` c536e71f028213e1dd195f6c143c43d4d92b3fda node-v0.8.22-darwin-x64.tar.gz c3993a424034022a675c8822a44402d1a04567d3 node-v0.8.22-darwin-x86.tar.gz fb2cd76139f258ff73980b2940c23e3d05ec7fc3 node-v0.8.22-linux-x64.tar.gz 540154b5be3a5c378b9c6b5b955942eede604e22 node-v0.8.22-linux-x86.tar.gz 607943d795c9e4e421e0d2b9b887f81057535f72 node-v0.8.22-sunos-x64.tar.gz 518a6d6e1cc03ef5c25f408f3a6f7b2ba0e27750 node-v0.8.22-sunos-x86.tar.gz 7eae67719868fe45d016a04a031bf3e95bd3b05e node-v0.8.22-x86.msi efe68fecb78059b990e03970eaf8df7eb690d662 node-v0.8.22.pkg 1b7e65da70e2b3c2feacb1b13f673dfe43beb381 node-v0.8.22.tar.gz 190ead83110217ab9e6c52e6ac08bac8a305d6b3 node.exe 7e5b75cbe0af651a4200e0fa4a1429466a97df0a node.exp 35b92f30e337696ef7c34206a5a808cc4a9d0184 node.lib 29ced022452a877255aaa0bc395f031b12aa695e node.pdb a4251271f65e3b210426dfa44cfbbc39b79b1efc x64/node-v0.8.22-x64.msi 93f9106d855e9b6269a392cfcbd8aca2c7403293 x64/node.exe 95b77dd57b652d7f11fc8de7bb742fc48ee0223c x64/node.exp 03499f2f1d163821927a11ff633ac9a25737910e x64/node.lib 405108c20af639582116ef15cb759791298ba4b9 x64/node.pdb ``` node-v0.10.25~dfsg2/doc/blog/release/v0.8.14.md0000644000000000000000000000550312270121457017170 0ustar rootrootcategory: release version: v0.8.14 date: Thu Oct 25 14:26:44 PDT 2012 slug: node-v0.8.14 title: Node v0.8.14 (Stable) Note: v0.8.13 contains a regression in the EventEmitter class. This is a bugfix release, but contains no new features. Most of the release notes are copied from v0.8.13, since it didn't live long. 2012.10.25, Version 0.8.14 (Stable) * events: Don't clobber pre-existing _events obj in EE ctor (isaacs) * V8: Upgrade to 3.11.10.25 * npm: Upgrade to 1.1.65 * url: parse hostnames that start with - or _ (Ben Noordhuis) * repl: Fix Windows 8 terminal issue (Bert Belder) * typed arrays: use signed char for signed int8s (Aaron Jacobs) * crypto: fix bugs in DiffieHellman (Ben Noordhuis) * configure: turn on VFPv3 on ARMv7 (Ben Noordhuis) * Re-enable OpenSSL UI for entering passphrases via tty (Ben Noordhuis) * repl: ensure each REPL instance gets its own "context" (Nathan Rajlich) Source Code: http://nodejs.org/dist/v0.8.14/node-v0.8.14.tar.gz Macintosh Installer (Universal): http://nodejs.org/dist/v0.8.14/node-v0.8.14.pkg Windows Installer: http://nodejs.org/dist/v0.8.14/node-v0.8.14-x86.msi Windows x64 Installer: http://nodejs.org/dist/v0.8.14/x64/node-v0.8.14-x64.msi Windows x64 Files: http://nodejs.org/dist/v0.8.14/x64/ Linux 32-bit Binary: http://nodejs.org/dist/v0.8.14/node-v0.8.14-linux-x86.tar.gz Linux 64-bit Binary: http://nodejs.org/dist/v0.8.14/node-v0.8.14-linux-x64.tar.gz Solaris 32-bit Binary: http://nodejs.org/dist/v0.8.14/node-v0.8.14-sunos-x86.tar.gz Solaris 64-bit Binary: http://nodejs.org/dist/v0.8.14/node-v0.8.14-sunos-x64.tar.gz Other release files: http://nodejs.org/dist/v0.8.14/ Website: http://nodejs.org/docs/v0.8.14/ Documentation: http://nodejs.org/docs/v0.8.14/api/ Shasums: ``` 519a0d5daa52eb3f412f5ea86779a1a7f3f73f3d node-v0.8.14-darwin-x64.tar.gz 93c38392cb07e5e7386503e8e8b1932dabcd3f09 node-v0.8.14-darwin-x86.tar.gz f737747a3c2b62c5e059d866ea27f2f050a12e0a node-v0.8.14-linux-x64.tar.gz cd9db5907cf0796b5277954cb994789a9815f72c node-v0.8.14-linux-x86.tar.gz b6e1c21c2bc9543255bda936bb7206490085dd6b node-v0.8.14-sunos-x64.tar.gz c16a01e116fda023db9b1cd14f8e9520d39cf2c7 node-v0.8.14-sunos-x86.tar.gz 3d38d581316bb378f39786a2bf0be5072360ab02 node-v0.8.14-x86.msi 23d5bd298dc5ef77dbcb4f5a1d4ec35a10c9ab79 node-v0.8.14.pkg 47a1186004f6ce5e25a8555429d72b15519bc7f1 node-v0.8.14.tar.gz 0150ec86f83c86a4ce99e33671f1a6c00c19981d node.exe 7cc38da3b6d550c6a681f8e7e479f95a109f12c7 node.exp d9a92fe10b696beb98fca60bc38183990833106b node.lib 03e211e842ae613b3e27a2a0d79ed9cf9c864802 node.pdb 8df2cc066f6cee53deb43eba92a3a1bfd30e9ae7 x64/node-v0.8.14-x64.msi 84f44295f9ed0f09ee80fd85b3ad1e0c93212795 x64/node.exe b20a8aa61f386166c9ce1b51bb14d97eefd39090 x64/node.exp dd254fab57148ad6315d87fd6c8ef6ef45baae35 x64/node.lib c4ad89d4d71d82f20c7ce620319ad35aca7e56ad x64/node.pdb ``` node-v0.10.25~dfsg2/doc/blog/release/node-v0-4-12.md0000644000000000000000000000201712270121457020100 0ustar rootrootversion: 0.4.12 title: Node v0.4.12 author: ryandahl date: Thu Sep 15 2011 17:32:07 GMT-0700 (PDT) status: publish category: release slug: node-v0-4-12 2011.09.15, Version 0.4.12 (stable)
    • Improve docs
    • #1563 overflow in ChildProcess custom_fd.
    • #1569, parse error on multi-line HTTP headers. (Ben Noordhuis)
    • #1586 net: Socket write encoding case sensitivity (koichik)
    • #1610 Remove DigiNotar CA from trusted list (isaacs)
    • #1624 buffer: Avoid overrun with 'binary' encoding. (koichik)
    • #1633 buffer: write() should always set _charsWritten. (koichik)
    • #1707 hasOwnProperty usage security hole in querystring (isaacs)
    • #1719 Drain OpenSSL error queue
    • Fix error reporting in net.Server.listen
    Download: http://nodejs.org/dist/node-v0.4.12.tar.gz Website: http://nodejs.org/docs/v0.4.12/ Documentation: http://nodejs.org/docs/v0.4.12/api/ node-v0.10.25~dfsg2/doc/blog/release/v0.9.7.md0000644000000000000000000000545612270121457017122 0ustar rootrootcategory: release version: 0.9.7 date: Fri Jan 18 11:38:32 PST 2013 title: Node v0.9.7 (Unstable) slug: node-v0-9-7-unstable 2013.01.18, Version 0.9.7 (Unstable) * V8: Upgrade to 3.15.11.7 * npm: Upgrade to 1.2.2 * punycode: Upgrade to 1.2.0 (Mathias Bynens) * repl: make built-in modules available by default (Felix Böhm) * windows: add support for '_Total' perf counters (Scott Blomquist) * cluster: make --prof work for workers (Ben Noordhuis) * child_process: do not keep list of sent sockets (Fedor Indutny) * tls: Follow RFC6125 more strictly (Fedor Indutny) * buffer: floating point read/write improvements (Trevor Norris) * TypedArrays: Improve dataview perf without endian param (Dean McNamee) * module: assert require() called with a non-empty string (Felix Böhm, James Campos) * stdio: Set readable/writable flags properly (isaacs) * stream: Properly handle large reads from push-streams (isaacs) Source Code: http://nodejs.org/dist/v0.9.7/node-v0.9.7.tar.gz Macintosh Installer (Universal): http://nodejs.org/dist/v0.9.7/node-v0.9.7.pkg Windows Installer: http://nodejs.org/dist/v0.9.7/node-v0.9.7-x86.msi Windows x64 Installer: http://nodejs.org/dist/v0.9.7/x64/node-v0.9.7-x64.msi Windows x64 Files: http://nodejs.org/dist/v0.9.7/x64/ Linux 32-bit Binary: http://nodejs.org/dist/v0.9.7/node-v0.9.7-linux-x86.tar.gz Linux 64-bit Binary: http://nodejs.org/dist/v0.9.7/node-v0.9.7-linux-x64.tar.gz Solaris 32-bit Binary: http://nodejs.org/dist/v0.9.7/node-v0.9.7-sunos-x86.tar.gz Solaris 64-bit Binary: http://nodejs.org/dist/v0.9.7/node-v0.9.7-sunos-x64.tar.gz Other release files: http://nodejs.org/dist/v0.9.7/ Website: http://nodejs.org/docs/v0.9.7/ Documentation: http://nodejs.org/docs/v0.9.7/api/ Shasums: ``` fa5771999205beae787e56bbffa3be3c496dbb3e node-v0.9.7-darwin-x64.tar.gz 3790a0323e82598d9286470a3ca8b079b25d815c node-v0.9.7-darwin-x86.tar.gz 70da0da05a2d76dfba389b413112aa1c31289114 node-v0.9.7-linux-x64.tar.gz b7448f020820302a6c648744a9ba4b6e1979fbf8 node-v0.9.7-linux-x86.tar.gz a0148c804c37ecbcfd4039213e469ba2757b6125 node-v0.9.7-sunos-x64.tar.gz 121cd6fe2fbab0ca20644256914433bfa02ca6c4 node-v0.9.7-sunos-x86.tar.gz 8938d57fc9cff896bb13901a43b5cff989785a23 node-v0.9.7-x86.msi 23b86861de7c6111311f869c722431cf84d93761 node-v0.9.7.pkg 527a86ee094f7ed77967eda3dff4b2aff3f29384 node-v0.9.7.tar.gz 5231f327979f900d4ba927f2e63e67635001268c node.exe 6a78465d3f6e34aab82a529839c522abbab715ac node.exp d814bd0733ba22a3cd9c086d34c68706d6c77663 node.lib 5c9df4dcf16c9baafce9b6982907ada586e878a2 node.pdb f49f1e0706ef38facba45af75cfdf44678b21f5a x64/node-v0.9.7-x64.msi 13f9ee5c81b89bf77c5bfe46993905de4e3384d7 x64/node.exe 3f9c67381a7f2b3fc2f6c14b66036dde02de2820 x64/node.exp cac98eebe21aeb05741a2fec6e2c7eaf5bb111a6 x64/node.lib 563932b95c08ebdb923358cd8b68ee17ac7ad781 x64/node.pdb ``` node-v0.10.25~dfsg2/doc/blog/release/v0.9.2.md0000644000000000000000000000622312270121457017106 0ustar rootroottitle: Version 0.9.2 (Unstable) category: release version: 0.9.2 date: Mon Sep 17 18:25:53 PDT 2012 slug: node-v0-9-2-unstable 2012.09.17, Version 0.9.2 (Unstable) * http_parser: upgrade to ad3b631 * openssl: upgrade 1.0.1c * darwin: use FSEvents to watch directory changes (Fedor Indutny) * unix: support missing API on NetBSD (Shigeki Ohtsu) * unix: fix EMFILE busy loop (Ben Noordhuis) * windows: un-break writable tty handles (Bert Belder) * windows: map WSAESHUTDOWN to UV_EPIPE (Bert Belder) * windows: make spawn with custom environment work again (Bert Belder) * windows: map ERROR_DIRECTORY to UV_ENOENT (Bert Belder) * tls, https: validate server certificate by default (Ben Noordhuis) * tls, https: throw exception on missing key/cert (Ben Noordhuis) * tls: async session storage (Fedor Indutny) * installer: don't install header files (Ben Noordhuis) * buffer: implement Buffer.prototype.toJSON() (Nathan Rajlich) * buffer: added support for writing NaN and Infinity (koichik) * http: make http.ServerResponse emit 'end' (Ben Noordhuis) * build: ./configure --ninja (Ben Noordhuis, Timothy J Fontaine) * installer: fix --without-npm (Ben Noordhuis) * cli: make -p equivalent to -pe (Ben Noordhuis) * url: Go much faster by using Url class (isaacs) Source Code: http://nodejs.org/dist/v0.9.2/node-v0.9.2.tar.gz Macintosh Installer (Universal): http://nodejs.org/dist/v0.9.2/node-v0.9.2.pkg Windows Installer: http://nodejs.org/dist/v0.9.2/node-v0.9.2-x86.msi Windows x64 Installer: http://nodejs.org/dist/v0.9.2/x64/node-v0.9.2-x64.msi Windows x64 Files: http://nodejs.org/dist/v0.9.2/x64/ Linux 32-bit Binary: http://nodejs.org/dist/v0.9.2/node-v0.9.2-linux-x86.tar.gz Linux 64-bit Binary: http://nodejs.org/dist/v0.9.2/node-v0.9.2-linux-x64.tar.gz Solaris 32-bit Binary: http://nodejs.org/dist/v0.9.2/node-v0.9.2-sunos-x86.tar.gz Solaris 64-bit Binary: http://nodejs.org/dist/v0.9.2/node-v0.9.2-sunos-x64.tar.gz Other release files: http://nodejs.org/dist/v0.9.2/ Website: http://nodejs.org/docs/v0.9.2/ Documentation: http://nodejs.org/docs/v0.9.2/api/ Shasums: ``` 3d1bb82013cbefd199abedaf0fe91d18579939b5 node-v0.9.2-darwin-x64.tar.gz 0a8e43e13ae6ce13ee3c8bb281d9a26aacc3ba3c node-v0.9.2-darwin-x86.tar.gz c5c2708d796d0e37c5a401af39bfa17c9c3b67c0 node-v0.9.2-linux-x64.tar.gz 0d0a09b34b74f2c9f310f044cd142d0b80885c22 node-v0.9.2-linux-x86.tar.gz 0bcc9a23e601cd8bef42a2e250d918ccb03b3f5b node-v0.9.2-sunos-x64.tar.gz 7827998ec5ca442f26f824f46b51f33d0c9bbbb7 node-v0.9.2-sunos-x86.tar.gz ed1c7d8a966c786969e3b4f68081cc5b3c753a03 node-v0.9.2-x86.msi e1a1270d3f2a398738a363c68e8f30fd47dd5eb6 node-v0.9.2.pkg 09dd5e2135ab67ee9544f2b6ce0c5ab0e95b02b8 node-v0.9.2.tar.gz 8bfd33550b0115f71aed15a0c114a13cd573e10b node.exe 3484b1c61442bd2ca7e00d06c61ad7fa6f61acad node.exp 37dcaa77234b63a3ce3cecdea27041b7565698cc node.lib 52abfb1b09f6facb0cda7c2e27b1bb48f8e75404 node.pdb c4c3f87c5dd7a0d36d682fb449cc6a8a245a4789 x64/node-v0.9.2-x64.msi d60fb389deada9eb753948bedb84b2f797424a93 x64/node.exe 04190c31210b2bc7ee80679167920567c166db75 x64/node.exp dfb5a231905da844279bf86984813440e152becf x64/node.lib d5c5e26395e5c714efd4855505dcf0a31c57e22e x64/node.pdb ``` node-v0.10.25~dfsg2/doc/blog/release/node-v0-6-8.md0000644000000000000000000000276612270121457020042 0ustar rootrootversion: 0.6.8 title: Node v0.6.8 author: Isaac Schlueter date: Thu Jan 19 2012 19:59:53 GMT-0800 (PST) status: publish category: release slug: node-v0-6-8

    2012.01.19, Version 0.6.8 (stable)

    • Update V8 to 3.6.6.19

    • Numeric key hash collision fix for V8 (Erik Corry, Fedor Indutny)

    • Add missing TTY key translations for F1-F5 on Windows (Brandon Benvie)

    • path.extname bugfix with . and .. paths (Bert Belder)

    • cluster: don't always kill the master on uncaughtException (Ben Noordhuis)

    • Update npm to 1.1.0-2 (isaacs)

    • typed arrays: set class name (Ben Noordhuis)

    • zlib binding cleanup (isaacs, Bert Belder)

    • dgram: use slab memory allocator (Michael Bernstein)

    • fix segfault #2473

    • #2521 60% improvement in fs.stat on Windows (Igor Zinkovsky)

    Source Code: http://nodejs.org/dist/v0.6.8/node-v0.6.8.tar.gz

    Windows Installer: http://nodejs.org/dist/v0.6.8/node-v0.6.8.msi

    Macintosh Installer: http://nodejs.org/dist/v0.6.8/node-v0.6.8.pkg

    Website: http://nodejs.org/docs/v0.6.8/

    Documentation: http://nodejs.org/docs/v0.6.8/api/

    node-v0.10.25~dfsg2/doc/blog/release/node-v0-5-3.md0000644000000000000000000000341412270121457020023 0ustar rootrootversion: 0.5.3 title: Node v0.5.3 author: ryandahl date: Tue Aug 02 2011 08:03:06 GMT-0700 (PDT) status: publish category: release slug: node-v0-5-3 2011.08.01, Version 0.5.3 (unstable)
    • Fix crypto encryption/decryption with Base64. (SAWADA Tadashi)
    • #243 Add an optional length argument to Buffer.write() (koichik)
    • #657 convert nonbuffer data to string in fs.writeFile/Sync (Daniel Pihlström)
    • Add process.features, remove process.useUV (Ben Noordhuis)
    • #324 Fix crypto hmac to accept binary keys + add test cases from rfc 2202 and 4231 (Stefan Bühler)
    • Add Socket::bytesRead, Socket::bytesWritten (Alexander Uvarov)
    • #572 Don't print result of --eval in CLI (Ben Noordhuis)
    • #1223 Fix http.ClientRequest crashes if end() was called twice (koichik)
    • #1383 Emit 'close' after all connections have closed (Felix Geisendörfer)
    • Add sprintf-like util.format() function (Ben Noordhuis)
    • Add support for TLS SNI (Fedor Indutny)
    • New http agent implementation. Off by default the command line flag --use-http2 will enable it. make test-http2 will run the tests for the new implementation. (Mikeal Rogers)
    • Revert AMD compatibility. (isaacs)
    • Windows: improvements, child_process support.
    • Remove pkg-config file.
    • Fix startup time regressions.
    • doc improvements
    Download: http://nodejs.org/dist/v0.5.3/node-v0.5.3.tar.gz Windows Executable: http://nodejs.org/dist/v0.5.3/node.exe Website: http://nodejs.org/dist/v0.5.3/docs Documentation: http://nodejs.org/dist/v0.5.3/docs/api node-v0.10.25~dfsg2/doc/blog/release/v0.11.6.md0000644000000000000000000000743112270121457017165 0ustar rootrootdate: Wed Aug 21 14:11:09 PDT 2013 version: 0.11.6 category: release title: Node v0.11.6 (Unstable) slug: node-v0-11-6-unstable 2013.08.21, Version 0.11.6 (Unstable) * uv: Upgrade to v0.11.8 * v8: upgrade v8 to 3.20.14.1 * build: disable SSLv2 by default (Ben Noordhuis) * build: don't auto-destroy existing configuration (Ben Noordhuis) * crypto: add TLS 1.1 and 1.2 to secureProtocol list (Matthias Bartelmeß) * crypto: fix memory leak in randomBytes() error path (Ben Noordhuis) * dgram: don't call into js when send cb is omitted (Ben Noordhuis) * dgram: fix regression in string argument handling (Ben Noordhuis) * domains: performance improvements (Trevor Norris) * events: EventEmitter = require('events') (Jake Verbaten) * http: Add write()/end() callbacks (isaacs) * http: Consistent 'finish' event semantics (isaacs) * http: Prefer 'binary' over 'ascii' (isaacs) * http: Support legacy agent.addRequest API (isaacs) * http: Write hex/base64 chunks properly (isaacs) * http: add agent.maxFreeSockets option (isaacs) * http: provide access to raw headers/trailers (isaacs) * http: removed headers stay removed (James Halliday) * http,timers: improve callback performance (Ben Noordhuis) * net: family option in net.connect (Vsevolod Strukchinsky) * readline: pause stdin before turning off terminal raw mode (Daniel Chatfield) * smalloc: allow different external array types (Trevor Norris) * smalloc: expose ExternalArraySize (Trevor Norris) * stream: Short-circuit buffer pushes when flowing (isaacs) * tls: handle errors on socket before releasing it (Fedor Indutny) * util: fix isPrimitive check (Trevor Norris) * util: isObject should always return boolean (Trevor Norris) Source Code: http://nodejs.org/dist/v0.11.6/node-v0.11.6.tar.gz Macintosh Installer (Universal): http://nodejs.org/dist/v0.11.6/node-v0.11.6.pkg Windows Installer: http://nodejs.org/dist/v0.11.6/node-v0.11.6-x86.msi Windows x64 Installer: http://nodejs.org/dist/v0.11.6/x64/node-v0.11.6-x64.msi Windows x64 Files: http://nodejs.org/dist/v0.11.6/x64/ Linux 32-bit Binary: http://nodejs.org/dist/v0.11.6/node-v0.11.6-linux-x86.tar.gz Linux 64-bit Binary: http://nodejs.org/dist/v0.11.6/node-v0.11.6-linux-x64.tar.gz Solaris 32-bit Binary: http://nodejs.org/dist/v0.11.6/node-v0.11.6-sunos-x86.tar.gz Solaris 64-bit Binary: http://nodejs.org/dist/v0.11.6/node-v0.11.6-sunos-x64.tar.gz Other release files: http://nodejs.org/dist/v0.11.6/ Website: http://nodejs.org/docs/v0.11.6/ Documentation: http://nodejs.org/docs/v0.11.6/api/ Shasums: ``` 5bab906e0ec1d5d2c2a750f17253955ba8c590b1 ./node-v0.11.6-darwin-x64.tar.gz 085a4ecf18ec3200e6e8bd140b3dc7f9fa65f8b5 ./node-v0.11.6-darwin-x86.tar.gz c162932132977820e06b856ba9cc84c7d4b57749 ./node-v0.11.6-linux-x64.tar.gz ed188f465c62da99d870bf8fa17fbd0d543d8d2e ./node-v0.11.6-linux-x86.tar.gz 0f52a91353d2c51b4d59c07b2a3b5d2e26060c93 ./node-v0.11.6-sunos-x64.tar.gz eac97868a552eae2dad92d633d0b78e069d05bed ./node-v0.11.6-sunos-x86.tar.gz 3bdcfd9305fca8bc81197c53c5aff4c4a0745966 ./node-v0.11.6-x86.msi 92abb4a4cc83bf9d3f1ed2f86a8aecd19672e7cf ./node-v0.11.6.pkg 4f3a643b4913ef085175aef180c3bfd9259a4357 ./node-v0.11.6.tar.gz 8051915c27eaee334a3d89a32fe1593e2b01182b ./node.exe 29f62a9272ae7679118f4a21c536eb2384fa3af4 ./node.exp dc060de643dec7f17a696c533d9443bfdf25ee61 ./node.lib 6438410f3685c585379e44b8bf39240ff0e65175 ./node.pdb dddfd481d376a215f0e039143ff1d22b317ca1d3 ./pkgsrc/nodejs-ia32-0.11.6.tgz 634c9249428fde318e9087eebc9d50401c110521 ./pkgsrc/nodejs-x64-0.11.6.tgz 90b58cb39a655591c240388942b629ff725fb076 ./x64/node-v0.11.6-x64.msi faeda12db9ca90a89dbd1d131702be39a883e7a2 ./x64/node.exe d6ab6da893cefd30795163a4e0d5585a996f13ec ./x64/node.exp f8f598114199b8876ef2cf7414eee488fcf713b9 ./x64/node.lib e09f49b3d3b881f2c3dcdff24369176572cc7338 ./x64/node.pdb ``` node-v0.10.25~dfsg2/doc/blog/release/v0.10.13.md0000644000000000000000000000527112270121457017242 0ustar rootrootdate: Tue Jul 9 14:24:47 PDT 2013 version: 0.10.13 category: release title: Node v0.10.13 (Stable) slug: node-v0-10-13-stable 2013.07.09, Version 0.10.13 (Stable) * uv: Upgrade to v0.10.12 * npm: Upgrade to 1.3.2 * windows: get proper errno (Ben Noordhuis) * tls: only wait for finish if we haven't seen it (Timothy J Fontaine) * http: Dump response when request is aborted (isaacs) * http: use an unref'd timer to fix delay in exit (Peter Rust) * zlib: level can be negative (Brian White) * zlib: allow zero values for level and strategy (Brian White) * buffer: add comment explaining buffer alignment (Ben Noordhuis) * string_bytes: properly detect 64bit (Timothy J Fontaine) * src: fix memory leak in UsingDomains() (Ben Noordhuis) Source Code: http://nodejs.org/dist/v0.10.13/node-v0.10.13.tar.gz Macintosh Installer (Universal): http://nodejs.org/dist/v0.10.13/node-v0.10.13.pkg Windows Installer: http://nodejs.org/dist/v0.10.13/node-v0.10.13-x86.msi Windows x64 Installer: http://nodejs.org/dist/v0.10.13/x64/node-v0.10.13-x64.msi Windows x64 Files: http://nodejs.org/dist/v0.10.13/x64/ Linux 32-bit Binary: http://nodejs.org/dist/v0.10.13/node-v0.10.13-linux-x86.tar.gz Linux 64-bit Binary: http://nodejs.org/dist/v0.10.13/node-v0.10.13-linux-x64.tar.gz Solaris 32-bit Binary: http://nodejs.org/dist/v0.10.13/node-v0.10.13-sunos-x86.tar.gz Solaris 64-bit Binary: http://nodejs.org/dist/v0.10.13/node-v0.10.13-sunos-x64.tar.gz Other release files: http://nodejs.org/dist/v0.10.13/ Website: http://nodejs.org/docs/v0.10.13/ Documentation: http://nodejs.org/docs/v0.10.13/api/ Shasums: ``` ae0b5d8e9afc57da259c7f30d266c968c16479bb node-v0.10.13-darwin-x64.tar.gz 5e5629a546f9aa2c1e11883021c416a6e0e12ad2 node-v0.10.13-darwin-x86.tar.gz 83b8f07aa7981694e557a9aae7e5bc4c312d800c node-v0.10.13-linux-x64.tar.gz ec016d282d85036151dc096cd5cee6c8bd20fdd8 node-v0.10.13-linux-x86.tar.gz 3464241dc541bbf094ed11c0cd2ef8edb6419ee7 node-v0.10.13-sunos-x64.tar.gz abca9f52cfac47cc0b3e92e3bc18b578a92915e6 node-v0.10.13-sunos-x86.tar.gz 5d020e9d3ef1021216e5cc294449c1a699b3f458 node-v0.10.13-x86.msi 841803a64e824f84361d4e7f6e1abd8ff31056ca node-v0.10.13.pkg f73d5f134296ed0aa16cbec5d727f94587844155 node-v0.10.13.tar.gz 19beeb0f418b226a7ec7f15cdc0dccdf5f0d9e55 node.exe eca52e8f39d4ac5bf3d07f6b50722f41b0494cc9 node.exp 2c47530c0d7c8e60f5c0daa78c105772b5638c9d node.lib 23c917f0c2c0e85677fb85583668b5e695315ced node.pdb 76cc14f56a3225e51f25b60faebe971cfb3ca322 x64/node-v0.10.13-x64.msi e96c1687d447ed642ffd85134c0d949428a0b400 x64/node.exe 1962db68f17ffbd44c0ff82c0ff75b4ffe338319 x64/node.exp 95f162082c359d8610dd59ea634d4bd80d40c8aa x64/node.lib 3ec49f4849d5fdb3e1acbcff8e3eb02d9d55d332 x64/node.pdb ``` node-v0.10.25~dfsg2/doc/blog/release/v0.11.2.md0000644000000000000000000000575112270121457017164 0ustar rootrootdate: Mon May 13 15:53:06 PDT 2013 version: 0.11.2 category: release title: Node v0.11.2 (Unstable) slug: node-v0-11-2-unstable 2013.05.13, Version 0.11.2 (Unstable) * uv: Upgrade to 0.11.2 * V8: Upgrade to 3.19.0 * npm: Upgrade to 1.2.21 * build: Makefile should respect configure --prefix (Timothy J Fontaine) * cluster: use round-robin load balancing (Ben Noordhuis) * debugger, cluster: each worker has new debug port (Miroslav Bajtoš) * debugger: `restart` with custom debug port (Miroslav Bajtoš) * debugger: breakpoints in scripts not loaded yet (Miroslav Bajtoš) * event: EventEmitter#setMaxListeners() returns this (Sam Roberts) * events: add EventEmitter.defaultMaxListeners (Ben Noordhuis) * install: Support $(PREFIX) install target directory prefix (Olof Johansson) * os: Include netmask in os.networkInterfaces() (Ben Kelly) * path: add path.isAbsolute(path) (Ryan Doenges) * stream: Guarantee ordering of 'finish' event (isaacs) * streams: introduce .cork/.uncork/._writev (Fedor Indutny) * vm: add support for timeout argument (Andrew Paprocki) Source Code: http://nodejs.org/dist/v0.11.2/node-v0.11.2.tar.gz Macintosh Installer (Universal): http://nodejs.org/dist/v0.11.2/node-v0.11.2.pkg Windows Installer: http://nodejs.org/dist/v0.11.2/node-v0.11.2-x86.msi Windows x64 Installer: http://nodejs.org/dist/v0.11.2/x64/node-v0.11.2-x64.msi Windows x64 Files: http://nodejs.org/dist/v0.11.2/x64/ Linux 32-bit Binary: http://nodejs.org/dist/v0.11.2/node-v0.11.2-linux-x86.tar.gz Linux 64-bit Binary: http://nodejs.org/dist/v0.11.2/node-v0.11.2-linux-x64.tar.gz Solaris 32-bit Binary: http://nodejs.org/dist/v0.11.2/node-v0.11.2-sunos-x86.tar.gz Solaris 64-bit Binary: http://nodejs.org/dist/v0.11.2/node-v0.11.2-sunos-x64.tar.gz Other release files: http://nodejs.org/dist/v0.11.2/ Website: http://nodejs.org/docs/v0.11.2/ Documentation: http://nodejs.org/docs/v0.11.2/api/ Shasums: ``` ddc85fd6ed70057c64d7c9cd64bb94f28596d163 node-v0.11.2-darwin-x64.tar.gz 9893a3a3598d2e5ed24bfee8642b72c37808dbae node-v0.11.2-darwin-x86.tar.gz f81189c30aa268f2b43572e1795fedd50f3495c3 node-v0.11.2-linux-x64.tar.gz 6322bf3be78f907a3b5e06f38af1b33c52957612 node-v0.11.2-linux-x86.tar.gz 3becca01532e104081ca51a265f07e77b6e9e25f node-v0.11.2-sunos-x64.tar.gz 9489238384edb456d9a603e5bef1128dfafe69b1 node-v0.11.2-sunos-x86.tar.gz 76421e22cff4d4f4d1cb2ce3e3566e2c9004cdee node-v0.11.2-x86.msi a23d607f7b433197533cd6d88c981c75463efff8 node-v0.11.2.pkg 1d1080598431062ccb4bbbf7ecbb7596fe664c67 node-v0.11.2.tar.gz b45a04167d32887c32a2479c4567af394627c8ad node.exe c65ce6e073e173ae5769fe4dd9ff83f2f56ce05d node.exp 31f569697cb8447492e3172e614c3c4cfff81d09 node.lib c98f8a717ef9d660ff3d45e86e2ee396ca02e721 node.pdb 7caabd3a774c96a8126f10d2e184727bd5160526 x64/node-v0.11.2-x64.msi 3b049227e3c392fdb88de9a5da7ad1ec14c82d17 x64/node.exe c95f9746e180c064a5225ab83cca604bf918e59a x64/node.exp 78c94386c312ded2f7cb0c84951535b67e36fecf x64/node.lib ad774b472a3cfa03374aac2d1dac19f9599ad2f8 x64/node.pdb ``` node-v0.10.25~dfsg2/doc/blog/release/node-v0-6-5.md0000644000000000000000000000151212270121457020023 0ustar rootrootversion: 0.6.5 title: Node v0.6.5 author: ryandahl date: Sun Dec 04 2011 00:59:57 GMT-0800 (PST) status: publish category: release slug: node-v0-6-5 2011.12.04, Version 0.6.5 (stable)
    • npm workaround Windows antivirus software (isaacs)
    • Upgrade V8 to 3.6.6.11
    Source Code: http://nodejs.org/dist/v0.6.5/node-v0.6.5.tar.gz Windows Installer: http://nodejs.org/dist/v0.6.5/node-v0.6.5.msi Macintosh Installer: http://nodejs.org/dist/v0.6.5/node-v0.6.5.pkg Website: http://nodejs.org/docs/v0.6.5/ Documentation: http://nodejs.org/docs/v0.6.5/api/ node-v0.10.25~dfsg2/doc/blog/release/v0.11.10.md0000644000000000000000000000727012270121457017241 0ustar rootrootdate: Tue Dec 31 16:20:57 PST 2013 version: 0.11.10 category: release title: Node v0.11.10 (Unstable) slug: node-v0-11-10-unstable 2013.12.31, Version 0.11.10 (Unstable) * http_parser: update to 2.2 * uv: Upgrade to v0.11.17 * v8: Upgrade to 3.22.24.10 * buffer: optimize writeInt* methods (Paul Loyd) * child_process: better error handling (Alexis Campailla) * cluster: do not synchronously emit 'setup' event (Sam Roberts) * cluster: restore backwards compatibility and various fixes (Sam Roberts) * crypto: remove unnecessary OpenSSL_add_all_digests (Yorkie) * crypto: support GCM authenticated encryption mode. (Ingmar Runge) * dns: add resolveSoa and 'SOA' rrtype (Tuğrul Topuz) * events: move EE c'tor guts to EventEmitter.init (Bert Belder) * http: DELETE shouldn't default to chunked encoding (Lalit Kapoor) * http: parse the status message in a http response. (Cam Swords) * node: fix removing AsyncListener in callback (Vladimir Kurchatkin) * node: follow specification, zero-fill ArrayBuffers (Trevor Norris) * openssl: use ASM optimized routines (Fedor Indutny) * process: allow nextTick infinite recursion (Trevor Norris) * querystring: remove `name` from `stringify()` (Yorkie) * timers: setImmediate v8 optimization fix (pflannery) * tls: add serialNumber to getPeerCertificate() (Ben Noordhuis) * tls: reintroduce socket.encrypted (Fedor Indutny) * tls: fix handling of asterisk in SNI context (Fedor Indutny) * util: Format negative zero as '-0' (David Chan) * vm: fix race condition in timeout (Alexis Campailla) * windows: fix dns lookup of localhost with ipv6 (Alexis Campailla) Source Code: http://nodejs.org/dist/v0.11.10/node-v0.11.10.tar.gz Macintosh Installer (Universal): http://nodejs.org/dist/v0.11.10/node-v0.11.10.pkg Windows Installer: http://nodejs.org/dist/v0.11.10/node-v0.11.10-x86.msi Windows x64 Installer: http://nodejs.org/dist/v0.11.10/x64/node-v0.11.10-x64.msi Windows x64 Files: http://nodejs.org/dist/v0.11.10/x64/ Linux 32-bit Binary: http://nodejs.org/dist/v0.11.10/node-v0.11.10-linux-x86.tar.gz Linux 64-bit Binary: http://nodejs.org/dist/v0.11.10/node-v0.11.10-linux-x64.tar.gz Solaris 32-bit Binary: http://nodejs.org/dist/v0.11.10/node-v0.11.10-sunos-x86.tar.gz Solaris 64-bit Binary: http://nodejs.org/dist/v0.11.10/node-v0.11.10-sunos-x64.tar.gz Other release files: http://nodejs.org/dist/v0.11.10/ Website: http://nodejs.org/docs/v0.11.10/ Documentation: http://nodejs.org/docs/v0.11.10/api/ Shasums: ``` 4f7d0d43c1ee7593035ddb3cf09020a18a03c794 node-v0.11.10-darwin-x64.tar.gz 3b7100bcff39e39b6db5118805fcfc76d8524da2 node-v0.11.10-darwin-x86.tar.gz 3df4cb183a78bb975c831155d3c0aa29a274dec4 node-v0.11.10-linux-x64.tar.gz 12fc680b0a26cc73b4df0a0e9544b0db2bc06e96 node-v0.11.10-linux-x86.tar.gz 145417c8d801174a42255dc273da962cde94ffc9 node-v0.11.10-sunos-x64.tar.gz 981baba494e9be8978fa1bb336b3048367e809ce node-v0.11.10-sunos-x86.tar.gz 5f4d96c37cfb1423cc844f52e0547cb5bca99dd8 node-v0.11.10-x86.msi 8bd455fb7539609a7ee6bed87875a908fd6221ea node-v0.11.10.pkg b860f511e4fc657a64594fc9f3f1225c1a140e5e node-v0.11.10.tar.gz 80976bffed871310a86d31694e2767ccbe9f6c35 node.exe f11675958a492a83f057f356dd224ad507e82c61 node.exp 5a80c4ab5b1d0984b3a118536ca6421b4b9bc14f node.lib 207daafc40fba36200504fa52869b9c41cdbf5c9 node.pdb 3aa165e2d235888037f8099abd5bc9dca4b12100 pkgsrc/nodejs-ia32-0.11.10.tgz 1d5ef599b93c7d8c0d34ff2ab3dd4255babfaf72 pkgsrc/nodejs-x64-0.11.10.tgz a6b16441721c34bae732b2b14134d0e1fd9706de x64/node-v0.11.10-x64.msi 933ff8a0a42c6e69fcbd51b9eaae4e4d14f043ae x64/node.exe 31c9abd54e5ba431f0645fa04d315f15dc010107 x64/node.exp 66bec5eae9033972463a6bd89183aa97bb84bfd1 x64/node.lib 43fbac8665dfcd121e547f56b1434a1c6039091d x64/node.pdb ``` node-v0.10.25~dfsg2/doc/blog/release/v0.10.9.md0000644000000000000000000000454112270121457017166 0ustar rootrootdate: Thu May 30 11:12:12 PDT 2013 version: 0.10.9 category: release title: Node v0.10.9 (Stable) slug: node-v0-10-9-stable 2013.05.30, Version 0.10.9 (Stable) * npm: Upgrade to 1.2.24 * uv: Upgrade to v0.10.9 * repl: fix JSON.parse error check (Brian White) * tls: proper .destroySoon (Fedor Indutny) * tls: invoke write cb only after opposite read end (Fedor Indutny) * tls: ignore .shutdown() syscall error (Fedor Indutny) Source Code: http://nodejs.org/dist/v0.10.9/node-v0.10.9.tar.gz Macintosh Installer (Universal): http://nodejs.org/dist/v0.10.9/node-v0.10.9.pkg Windows Installer: http://nodejs.org/dist/v0.10.9/node-v0.10.9-x86.msi Windows x64 Installer: http://nodejs.org/dist/v0.10.9/x64/node-v0.10.9-x64.msi Windows x64 Files: http://nodejs.org/dist/v0.10.9/x64/ Linux 32-bit Binary: http://nodejs.org/dist/v0.10.9/node-v0.10.9-linux-x86.tar.gz Linux 64-bit Binary: http://nodejs.org/dist/v0.10.9/node-v0.10.9-linux-x64.tar.gz Solaris 32-bit Binary: http://nodejs.org/dist/v0.10.9/node-v0.10.9-sunos-x86.tar.gz Solaris 64-bit Binary: http://nodejs.org/dist/v0.10.9/node-v0.10.9-sunos-x64.tar.gz Other release files: http://nodejs.org/dist/v0.10.9/ Website: http://nodejs.org/docs/v0.10.9/ Documentation: http://nodejs.org/docs/v0.10.9/api/ Shasums: ``` b527f5cf879fd834cb70cec630fce34eb30b5a02 node-v0.10.9-darwin-x64.tar.gz b2c9b14aa4a2aa17dd63f2ebe5a4f27171eb64f7 node-v0.10.9-darwin-x86.tar.gz 4626105fbf907c76314bf487460662e5c97e14ea node-v0.10.9-linux-x64.tar.gz 29a4aa89ca61b5a4f3c520f0f798b8b19ce2d3d3 node-v0.10.9-linux-x86.tar.gz 6d755df136dec6dc085cc6b214154245402a5372 node-v0.10.9-sunos-x64.tar.gz 2dadf9feca00bb3e681ea31ebd4086ab926a1c39 node-v0.10.9-sunos-x86.tar.gz 5ff6c7ed7174af8502f54f4476bf8de616180625 node-v0.10.9-x86.msi 7d945ed2102fcfab28e26dca5f4698b6cf0b921a node-v0.10.9.pkg e4b2bb8c42da2ec90e6fd81da1e6b382ba499608 node-v0.10.9.tar.gz 889e9c4cb614c79fb728816790a622d13ce9ca88 node.exe 3b9b15f8ab5fc5378e05301f465114d93ade237a node.exp 3c8034b9e4eef1f46d186a266a60690edd17b1f4 node.lib b9f1d9452f2815b43df98b40ab1b6cf2c358ad8a node.pdb 4b767d596c8a395fe22215d065f9d31b3a5b9423 x64/node-v0.10.9-x64.msi e763bc24888254ddd992a4b7302d1ad4538ad920 x64/node.exe eec159254e209f172bca37dc547f0bfcfa1bd87c x64/node.exp 6ae5f3a36ffba256cb8077c47a218749449f798c x64/node.lib 5c2283b50c74a8b43708fdc29cb5c314fbe2d018 x64/node.pdb ``` node-v0.10.25~dfsg2/doc/blog/release/v0.11.3.md0000644000000000000000000000661712270121457017167 0ustar rootrootdate: Wed Jun 26 16:55:29 PDT 2013 version: 0.11.3 category: release title: Node v0.11.3 (Unstable) slug: node-v0-11-3-unstable 2013.06.26, Version 0.11.3 (Unstable) * uv: Upgrade to v0.11.5 * c-ares: upgrade to 1.10.0 * v8: upgrade to v3.19.13 * punycode: update to v1.2.3 (Mathias Bynens) * debugger: break on uncaught exception (Miroslav Bajtos) * child_process: emit 'disconnect' asynchronously (Ben Noordhuis) * dtrace: enable uv's probes if enabled (Timothy J Fontaine) * dtrace: unify dtrace and systemtap interfaces (Timothy J Fontaine) * buffer: New API for backing data store (Trevor Norris) * buffer: return `this` in fill() for chainability (Brian White) * build: fix include order for building on windows (Timothy J Fontaine) * build: add android support (Linus Mårtensson) * readline: strip ctrl chars for prompt width calc (Krzysztof Chrapka) * tls: introduce TLSSocket based on tls_wrap binding (Fedor Indutny) * tls: add localAddress and localPort properties (Ben Noordhuis) * crypto: free excessive memory in NodeBIO (Fedor Indutny) * process: remove maxTickDepth (Trevor Norris) * timers: use uv_now instead of Date.now (Timothy J Fontaine) * util: Add debuglog, deprecate console lookalikes (isaacs) * module: use path.sep instead of a custom solution (Robert Kowalski) * http: don't escape request path, reject bad chars (Ben Noordhuis) * net: emit dns 'lookup' event before connect (Ben Noordhuis) * dns: add getServers and setServers (Timothy J Fontaine) Source Code: http://nodejs.org/dist/v0.11.3/node-v0.11.3.tar.gz Macintosh Installer (Universal): http://nodejs.org/dist/v0.11.3/node-v0.11.3.pkg Windows Installer: http://nodejs.org/dist/v0.11.3/node-v0.11.3-x86.msi Windows x64 Installer: http://nodejs.org/dist/v0.11.3/x64/node-v0.11.3-x64.msi Windows x64 Files: http://nodejs.org/dist/v0.11.3/x64/ Linux 32-bit Binary: http://nodejs.org/dist/v0.11.3/node-v0.11.3-linux-x86.tar.gz Linux 64-bit Binary: http://nodejs.org/dist/v0.11.3/node-v0.11.3-linux-x64.tar.gz Solaris 32-bit Binary: http://nodejs.org/dist/v0.11.3/node-v0.11.3-sunos-x86.tar.gz Solaris 64-bit Binary: http://nodejs.org/dist/v0.11.3/node-v0.11.3-sunos-x64.tar.gz Other release files: http://nodejs.org/dist/v0.11.3/ Website: http://nodejs.org/docs/v0.11.3/ Documentation: http://nodejs.org/docs/v0.11.3/api/ Shasums: ``` 8320d6167f4c49d85b42bde41a201dabc125540d node-v0.11.3-darwin-x64.tar.gz df9a540da0f5eb80682b5f63a8f7c841876ae9b2 node-v0.11.3-darwin-x86.tar.gz 76839ea31e90046c80af088b36c619eae622a6c0 node-v0.11.3-linux-x64.tar.gz fd571ebfcdf5d7e35a2fbd972967ac24326ecb39 node-v0.11.3-linux-x86.tar.gz 85c03b89d61245ddfc911784a358e32a8a801c4f node-v0.11.3-sunos-x64.tar.gz 58f7824fdbe8b57e13865630c11100ac920474f9 node-v0.11.3-sunos-x86.tar.gz 507bbb003c755865f2b9cfc7a656ec9b142624fd node-v0.11.3-x86.msi 613ac2e985738ac06859394daf64347594b1e073 node-v0.11.3.pkg 4b82d58ed3ce38fa67a8484b42cfd47179b6a4a5 node-v0.11.3.tar.gz e8628e45ee979ed0e666ff4ddce82444251afc85 node.exe e883f3f4b110e78cd11d03848003829fd7377ddb node.exp 5e82f6ef29379d8d39fb0661a0533bdbed412432 node.lib cc3ee23230b947159282161481491f39f9a36c85 node.pdb 2f7adfe4cfb69efc5d9f0b94b18787a0e14c3021 x64/node-v0.11.3-x64.msi 625fd4ab66816e57b08d73853a9438ea9e16f720 x64/node.exe dbc8cc48c651b342980b408fdc07da01e6e3e67e x64/node.exp 9203d66c50a34c1658928d525d1f1d2eaae9718c x64/node.lib 9b1261772868734a7962848e1d1db55efde2bce9 x64/node.pdb ``` node-v0.10.25~dfsg2/doc/blog/release/v0.8.21.md0000644000000000000000000000673212270121457017173 0ustar rootrootdate: Mon Feb 25 13:48:51 PST 2013 version: 0.8.21 category: release title: Node v0.8.21 (Stable) slug: node-v0-8-21-stable 2013.02.25, Version 0.8.21 (Stable) * http: Do not free the wrong parser on socket close (isaacs) * http: Handle hangup writes more gently (isaacs) * zlib: fix assert on bad input (Ben Noordhuis) * test: add TAP output to the test runner (Timothy J Fontaine) * unix: Handle EINPROGRESS from domain sockets (Ben Noordhuis) Source Code: http://nodejs.org/dist/v0.8.21/node-v0.8.21.tar.gz Macintosh Installer (Universal): http://nodejs.org/dist/v0.8.21/node-v0.8.21.pkg Windows Installer: http://nodejs.org/dist/v0.8.21/node-v0.8.21-x86.msi Windows x64 Installer: http://nodejs.org/dist/v0.8.21/x64/node-v0.8.21-x64.msi Windows x64 Files: http://nodejs.org/dist/v0.8.21/x64/ Linux 32-bit Binary: http://nodejs.org/dist/v0.8.21/node-v0.8.21-linux-x86.tar.gz Linux 64-bit Binary: http://nodejs.org/dist/v0.8.21/node-v0.8.21-linux-x64.tar.gz Solaris 32-bit Binary: http://nodejs.org/dist/v0.8.21/node-v0.8.21-sunos-x86.tar.gz Solaris 64-bit Binary: http://nodejs.org/dist/v0.8.21/node-v0.8.21-sunos-x64.tar.gz Other release files: http://nodejs.org/dist/v0.8.21/ Website: http://nodejs.org/docs/v0.8.21/ Documentation: http://nodejs.org/docs/v0.8.21/api/ Shasums: ``` 383b9009a587b7390a5a00cef4ece441fb16dd82 node-v0.8.21-darwin-x64.tar.gz 47654ca8ecc93c846e6f7493a19931b99d5e4b87 node-v0.8.21-darwin-x86.tar.gz 46d66f3b95f447811e9253d66050859b4bb81ea0 node-v0.8.21-linux-x64.tar.gz 1f16e50dacd5e942970c28be1e578e6260a116c4 node-v0.8.21-linux-x86.tar.gz b24b5e0acc53f004122c0cb2df775c4493b1e048 node-v0.8.21-sunos-x64.tar.gz 54ca0c94dff35e941fe90d10755427a15d6519ae node-v0.8.21-sunos-x86.tar.gz 38c5855c1ebd70fde111d50343a163a03cff9765 node-v0.8.21-x86.msi 60cd1fb8f43943bd3ed7c07745df1b3e81bafc13 node-v0.8.21.pkg 8b75377eafb5e77d6dff141c9533202d5a589ce4 node-v0.8.21.tar.gz c310779c80d21be7556ec0921d5afca8f64792eb node.exe 61b98f9dfbe70184788b6f010ce7667c9cba0fdc node.exp 78c37ac837bbb8fefd691e351b3c20f136b212ee node.lib 40cc197db5c9fc4ded4509b5ae21bc53d178998e node.pdb ec29a824e51308349f7895c010469f8e59939094 x64/node-v0.8.21-x64.msi e4c5563c38a01dac1a97f6366175d1fef86da262 x64/node.exe 8e51783d5e03148f01db8386102e4ffc4e30deda x64/node.exp a6017052052bb469a50327b4f40c990c25da0932 x64/node.lib fb8d24e5208b14d35997bc3b46e325316e6ad94d x64/node.pdb ``` Shasums: ``` 62cd69928ce2da9e8512b3efb96aba353ee54a91 node-v0.8.21-darwin-x64.tar.gz 62cf9b990f8e424e7fdb1d50a46d779e4d508b23 node-v0.8.21-darwin-x86.tar.gz 83e92aec4f4a0167e7c5b3ef04388fc33712d97b node-v0.8.21-linux-x64.tar.gz 83a8aa10dafa196b372958d1052f61fe1c16c2a4 node-v0.8.21-linux-x86.tar.gz 588830b0d095c0ef3583d9f7f574426f5b456e2e node-v0.8.21-sunos-x64.tar.gz e4eff5914432da3cf12a833aaa0444693671cca1 node-v0.8.21-sunos-x86.tar.gz 8146b2254caa814157aa511075dcf7b42d0ecb59 node-v0.8.21-x86.msi 60cd1fb8f43943bd3ed7c07745df1b3e81bafc13 node-v0.8.21.pkg 65ab7307f1aee12be4c88e396e2510967a52b1c6 node-v0.8.21.tar.gz 5d770ad554ee4a73278b2d90029e758e0a676074 node.exe 17514f32c57c64bd0d367c71ed0e6dc399fc9e12 node.exp 9404eff8562dfb0a6e0e72167278ac6131be5d3a node.lib 94908174f715d2707d48e6d53a1f96f33059f56c node.pdb 36750abf56120a63d9fa9b2b75bdc98dfac051f7 x64/node-v0.8.21-x64.msi b61b9620e936bc9c19043a02625aed9922aeb653 x64/node.exe 21a0e855e652e7fbe84e7efc1f7a3542fa870372 x64/node.exp f9d017c07030599e3442a958020381a37402dc81 x64/node.lib 3b35fbac0962aaff46bdd2f06412dcb1f80b9895 x64/node.pdb ``` node-v0.10.25~dfsg2/doc/blog/release/v0.8.18.md0000644000000000000000000000460212270121457017173 0ustar rootrootcategory: release date: Fri Jan 18 12:49:35 PST 2013 version: 0.8.18 title: Node v0.8.18 (Stable) slug: node-v0-8-18-stable 2013.01.18, Version 0.8.18 (Stable) * npm: Upgrade to v1.2.2 * dns: make error message match errno (Dan Milon) * tls: follow RFC6125 more stricly (Fedor Indutny) * buffer: reject negative SlowBuffer offsets (Ben Noordhuis) * install: add simplejson fallback (Chris Dent) * http: fix "Cannot call method 'emit' of null" (Ben Noordhuis) Source Code: http://nodejs.org/dist/v0.8.18/node-v0.8.18.tar.gz Macintosh Installer (Universal): http://nodejs.org/dist/v0.8.18/node-v0.8.18.pkg Windows Installer: http://nodejs.org/dist/v0.8.18/node-v0.8.18-x86.msi Windows x64 Installer: http://nodejs.org/dist/v0.8.18/x64/node-v0.8.18-x64.msi Windows x64 Files: http://nodejs.org/dist/v0.8.18/x64/ Linux 32-bit Binary: http://nodejs.org/dist/v0.8.18/node-v0.8.18-linux-x86.tar.gz Linux 64-bit Binary: http://nodejs.org/dist/v0.8.18/node-v0.8.18-linux-x64.tar.gz Solaris 32-bit Binary: http://nodejs.org/dist/v0.8.18/node-v0.8.18-sunos-x86.tar.gz Solaris 64-bit Binary: http://nodejs.org/dist/v0.8.18/node-v0.8.18-sunos-x64.tar.gz Other release files: http://nodejs.org/dist/v0.8.18/ Website: http://nodejs.org/docs/v0.8.18/ Documentation: http://nodejs.org/docs/v0.8.18/api/ Shasums: ``` ddf4062ec395abd2aab18bdadbf94e0c36b9133d node-v0.8.18-darwin-x64.tar.gz a4f6fc9cfddbcbcfc0733abbee24d9834924e648 node-v0.8.18-darwin-x86.tar.gz 7fbadf6d78f97ee96a20e7d0072e672d160e745b node-v0.8.18-linux-x64.tar.gz 0081950ce52058e1d0bb6609f5dd85819e39b90c node-v0.8.18-linux-x86.tar.gz 976bcf6a4f64e12bb570618f4a24ac77e74a592c node-v0.8.18-sunos-x64.tar.gz 68e21c766f49673cda6b44afaa0462625336c488 node-v0.8.18-sunos-x86.tar.gz 1a709f10740c08ec0f88e84fc4c61e908de9fa17 node-v0.8.18-x86.msi fb07bfaed311607f9e8003171b870928bf64a801 node-v0.8.18.pkg e3bc9b64f60f76a32b7d9b35bf86b5d1b8166717 node-v0.8.18.tar.gz 72c8a2a99f83e48641d55467a1ad2d8d224f048d node.exe 9c3ac616aac6c663b2c82a9bca998c99878ef92f node.exp 18fb36d6cc766ed506ddf5b0db67394d05368165 node.lib 155a12e9822a1d65101680774c27481d2de81f0e node.pdb f95437a1e5684e8b246d8b6b0a6d3d2ffcfd1ac6 x64/node-v0.8.18-x64.msi 3d2b9f1f2e2971fbefee32ed9783fe6b8c1f7d48 x64/node.exe 282de6e02f75bae87c3e7dda998b26c25ae8e709 x64/node.exp d7612894c40655155e72188bf584dbd8c09b0739 x64/node.lib 49abf88f55028304e50bfb368d68157aed1d0291 x64/node.pdb ``` node-v0.10.25~dfsg2/doc/blog/release/v0.11.9.md0000644000000000000000000000642212270121457017167 0ustar rootrootdate: Wed Nov 20 16:40:35 PST 2013 version: 0.11.9 category: release title: Node v0.11.9 (Unstable) slug: node-v0-11-9-unstable 2013.11.20, Version 0.11.9 (Unstable) * uv: upgrade to v0.11.15 (Timothy J Fontaine) * v8: upgrade to 3.22.24.5 (Timothy J Fontaine) * buffer: remove warning when no encoding is passed (Trevor Norris) * build: make v8 use random seed for hash tables (Ben Noordhuis) * crypto: build with shared openssl without NPN (Ben Noordhuis) * crypto: update root certificates (Ben Noordhuis) * debugger: pass on v8 debug switches (Ben Noordhuis) * domain: use AsyncListener API (Trevor Norris) * fs: add recursive subdirectory support to fs.watch (Nick Simmons) * fs: make fs.watch() non-recursive by default (Ben Noordhuis) * http: cleanup freeSockets when socket destroyed (fengmk2) * http: force socket encoding to be null (isaacs) * http: make DELETE requests set `req.method` (Nathan Rajlich) * node: add AsyncListener support (Trevor Norris) * src: remove global HandleScope that hid memory leaks (Ben Noordhuis) * tls: add ECDH ciphers support (Erik Dubbelboer) * tls: do not default to 'localhost' servername (Fedor Indutny) * tls: more accurate wrapping of connecting socket (Fedor Indutny) Source Code: http://nodejs.org/dist/v0.11.9/node-v0.11.9.tar.gz Macintosh Installer (Universal): http://nodejs.org/dist/v0.11.9/node-v0.11.9.pkg Windows Installer: http://nodejs.org/dist/v0.11.9/node-v0.11.9-x86.msi Windows x64 Installer: http://nodejs.org/dist/v0.11.9/x64/node-v0.11.9-x64.msi Windows x64 Files: http://nodejs.org/dist/v0.11.9/x64/ Linux 32-bit Binary: http://nodejs.org/dist/v0.11.9/node-v0.11.9-linux-x86.tar.gz Linux 64-bit Binary: http://nodejs.org/dist/v0.11.9/node-v0.11.9-linux-x64.tar.gz Solaris 32-bit Binary: http://nodejs.org/dist/v0.11.9/node-v0.11.9-sunos-x86.tar.gz Solaris 64-bit Binary: http://nodejs.org/dist/v0.11.9/node-v0.11.9-sunos-x64.tar.gz Other release files: http://nodejs.org/dist/v0.11.9/ Website: http://nodejs.org/docs/v0.11.9/ Documentation: http://nodejs.org/docs/v0.11.9/api/ Shasums: ``` 3a1af0d716042d617e51a82b43b2f97542f6c03a node-v0.11.9-darwin-x64.tar.gz 580696c5b2f30c8394cdee265c4888ad67e03b89 node-v0.11.9-darwin-x86.tar.gz 585df0690254afc22b29d7dc5f12fcb50f1bb588 node-v0.11.9-linux-x64.tar.gz 16fb7e69b90b6b6ac84a9120202918f197d4c0c0 node-v0.11.9-linux-x86.tar.gz bff51e2ab3752f4ae338adca14c2c453294e6017 node-v0.11.9-sunos-x64.tar.gz 9a7ada5c862174d6ce4b524d5816e26a36b763a8 node-v0.11.9-sunos-x86.tar.gz 3a4de2ae0dd8268592546b4fdcbd78f1cbc68118 node-v0.11.9-x86.msi 8c70de5cd39ecd33e6c02d4b0f6ca4010d21372e node-v0.11.9.pkg b4fc0e38ccde4edae45db198f331499055d77ca2 node-v0.11.9.tar.gz 9a4b04f0d40251696fac9161567e97c228d4e57d node.exe 96bfa67a417599c96818461d6d27f50401a74a36 node.exp 5f56ef7c2204ea75916876f6ab9e641b312dff11 node.lib 2db6eb844b36d96a0e34370ad1d311a57facd3d6 node.pdb 4a3590db0e6131739661628632ae1b8d70e2247b pkgsrc/nodejs-ia32-0.11.9.tgz 3ce0291cf0972ac5a2c0543fd1672d8b20569891 pkgsrc/nodejs-x64-0.11.9.tgz 9b736ec896e6b1b5856730869471c7e736f6ce78 x64/node-v0.11.9-x64.msi 1ec3593262b6e281457748ff3f3f195cd682592d x64/node.exe 1cf9ba6d503d5f8b18bfc2c1554bce04eba8a536 x64/node.exp 0a3e79ceecd05add6dab97bb6d9f460a61adddbc x64/node.lib 2037b32bbcb14e24d10c6cb2abe128bc9a85a932 x64/node.pdb ``` node-v0.10.25~dfsg2/doc/blog/README.md0000644000000000000000000000174112270121457015567 0ustar rootroottitle: README.md status: private # How This Blog Works Each `.md` file in this folder structure is a blog post. It has a few headers and a markdown body. (HTML is allowed in the body as well.) The relevant headers are: 1. title 2. author 3. status: Only posts with a status of "publish" are published. 4. category: The "release" category is treated a bit specially. 5. version: Only relevant for "release" category. 6. date 7. slug: The bit that goes on the url. Must be unique, will be generated from the title and date if missing. Posts in the "release" category are only shown in the main lists when they are the most recent release for that version family. The stable branch supersedes its unstable counterpart, so the presence of a `0.8.2` release notice will cause `0.7.10` to be hidden, but `0.6.19` would be unaffected. The folder structure in the blog source does not matter. Organize files here however makes sense. The metadata will be sorted out in the build later. node-v0.10.25~dfsg2/doc/blog/npm/0000755000000000000000000000000012270121457015077 5ustar rootrootnode-v0.10.25~dfsg2/doc/blog/npm/managing-node-js-dependencies-with-shrinkwrap.md0000644000000000000000000003733412270121457026334 0ustar rootroottitle: Managing Node.js Dependencies with Shrinkwrap author: Dave Pacheco date: Mon Feb 27 2012 10:51:59 GMT-0800 (PST) status: publish category: npm slug: managing-node-js-dependencies-with-shrinkwrap


    Photo by Luc Viatour (flickr)

    Managing dependencies is a fundamental problem in building complex software. The terrific success of github and npm have made code reuse especially easy in the Node world, where packages don't exist in isolation but rather as nodes in a large graph. The software is constantly changing (releasing new versions), and each package has its own constraints about what other packages it requires to run (dependencies). npm keeps track of these constraints, and authors express what kind of changes are compatible using semantic versioning, allowing authors to specify that their package will work with even future versions of its dependencies as long as the semantic versions are assigned properly.

    This does mean that when you "npm install" a package with dependencies, there's no guarantee that you'll get the same set of code now that you would have gotten an hour ago, or that you would get if you were to run it again an hour later. You may get a bunch of bug fixes now that weren't available an hour ago. This is great during development, where you want to keep up with changes upstream. It's not necessarily what you want for deployment, though, where you want to validate whatever bits you're actually shipping.

    Put differently, it's understood that all software changes incur some risk, and it's critical to be able to manage this risk on your own terms. Taking that risk in development is good because by definition that's when you're incorporating and testing software changes. On the other hand, if you're shipping production software, you probably don't want to take this risk when cutting a release candidate (i.e. build time) or when you actually ship (i.e. deploy time) because you want to validate whatever you ship.

    You can address a simple case of this problem by only depending on specific versions of packages, allowing no semver flexibility at all, but this falls apart when you depend on packages that don't also adopt the same principle. Many of us at Joyent started wondering: can we generalize this approach?

    Shrinkwrapping packages

    That brings us to npm shrinkwrap[1]:

    NAME
           npm-shrinkwrap -- Lock down dependency versions
    
    SYNOPSIS
           npm shrinkwrap
    
    DESCRIPTION
           This  command  locks down the versions of a package's dependencies so
           that you can control exactly which versions of each  dependency  will
           be used when your package is installed.

    Let's consider package A:

    {
        "name": "A",
        "version": "0.1.0",
        "dependencies": {
            "B": "<0.1.0"
        }
    }

    package B:

    {
        "name": "B",
        "version": "0.0.1",
        "dependencies": {
            "C": "<0.1.0"
        }
    }

    and package C:

    {
        "name": "C,
        "version": "0.0.1"
    }

    If these are the only versions of A, B, and C available in the registry, then a normal "npm install A" will install:

    A@0.1.0
    └─┬ B@0.0.1
      └── C@0.0.1

    Then if B@0.0.2 is published, then a fresh "npm install A" will install:

    A@0.1.0
    └─┬ B@0.0.2
      └── C@0.0.1

    assuming the new version did not modify B's dependencies. Of course, the new version of B could include a new version of C and any number of new dependencies. As we said before, if A's author doesn't want that, she could specify a dependency on B@0.0.1. But if A's author and B's author are not the same person, there's no way for A's author to say that she does not want to pull in newly published versions of C when B hasn't changed at all.

    In this case, A's author can use

    # npm shrinkwrap

    This generates npm-shrinkwrap.json, which will look something like this:

    {
        "name": "A",
        "dependencies": {
            "B": {
                "version": "0.0.1",
                "dependencies": {
                    "C": {  "version": "0.1.0" }
                }
            }
        }
    }

    The shrinkwrap command has locked down the dependencies based on what's currently installed in node_modules. When "npm install" installs a package with a npm-shrinkwrap.json file in the package root, the shrinkwrap file (rather than package.json files) completely drives the installation of that package and all of its dependencies (recursively). So now the author publishes A@0.1.0, and subsequent installs of this package will use B@0.0.1 and C@0.1.0, regardless the dependencies and versions listed in A's, B's, and C's package.json files. If the authors of B and C publish new versions, they won't be used to install A because the shrinkwrap refers to older versions. Even if you generate a new shrinkwrap, it will still reference the older versions, since "npm shrinkwrap" uses what's installed locally rather than what's available in the registry.

    Using shrinkwrapped packages

    Using a shrinkwrapped package is no different than using any other package: you can "npm install" it by hand, or add a dependency to your package.json file and "npm install" it.

    Building shrinkwrapped packages

    To shrinkwrap an existing package:

    1. Run "npm install" in the package root to install the current versions of all dependencies.
    2. Validate that the package works as expected with these versions.
    3. Run "npm shrinkwrap", add npm-shrinkwrap.json to git, and publish your package.

    To add or update a dependency in a shrinkwrapped package:

    1. Run "npm install" in the package root to install the current versions of all dependencies.
    2. Add or update dependencies. "npm install" each new or updated package individually and then update package.json.
    3. Validate that the package works as expected with the new dependencies.
    4. Run "npm shrinkwrap", commit the new npm-shrinkwrap.json, and publish your package.

    You can still use npm outdated(1) to view which dependencies have newer versions available.

    For more details, check out the full docs on npm shrinkwrap, from which much of the above is taken.

    Why not just check node_modules into git?

    One previously proposed solution is to "npm install" your dependencies during development and commit the results into source control. Then you deploy your app from a specific git SHA knowing you've got exactly the same bits that you tested in development. This does address the problem, but it has its own issues: for one, binaries are tricky because you need to "npm install" them to get their sources, but this builds the [system-dependent] binary too. You can avoid checking in the binaries and use "npm rebuild" at build time, but we've had a lot of difficulty trying to do this.[2] At best, this is second-class treatment for binary modules, which are critical for many important types of Node applications.[3]

    Besides the issues with binary modules, this approach just felt wrong to many of us. There's a reason we don't check binaries into source control, and it's not just because they're platform-dependent. (After all, we could build and check in binaries for all supported platforms and operating systems.) It's because that approach is error-prone and redundant: error-prone because it introduces a new human failure mode where someone checks in a source change but doesn't regenerate all the binaries, and redundant because the binaries can always be built from the sources alone. An important principle of software version control is that you don't check in files derived directly from other files by a simple transformation.[4] Instead, you check in the original sources and automate the transformations via the build process.

    Dependencies are just like binaries in this regard: they're files derived from a simple transformation of something else that is (or could easily be) already available: the name and version of the dependency. Checking them in has all the same problems as checking in binaries: people could update package.json without updating the checked-in module (or vice versa). Besides that, adding new dependencies has to be done by hand, introducing more opportunities for error (checking in the wrong files, not checking in certain files, inadvertently changing files, and so on). Our feeling was: why check in this whole dependency tree (and create a mess for binary add-ons) when we could just check in the package name and version and have the build process do the rest?

    Finally, the approach of checking in node_modules doesn't really scale for us. We've got at least a dozen repos that will use restify, and it doesn't make sense to check that in everywhere when we could instead just specify which version each one is using. There's another principle at work here, which is separation of concerns: each repo specifies what it needs, while the build process figures out where to get it.

    What if an author republishes an existing version of a package?

    We're not suggesting deploying a shrinkwrapped package directly and running "npm install" to install from shrinkwrap in production. We already have a build process to deal with binary modules and other automateable tasks. That's where we do the "npm install". We tar up the result and distribute the tarball. Since we test each build before shipping, we won't deploy something we didn't test.

    It's still possible to pick up newly published versions of existing packages at build time. We assume force publish is not that common in the first place, let alone force publish that breaks compatibility. If you're worried about this, you can use git SHAs in the shrinkwrap or even consider maintaining a mirror of the part of the npm registry that you use and require human confirmation before mirroring unpublishes.

    Final thoughts

    Of course, the details of each use case matter a lot, and the world doesn't have to pick just one solution. If you like checking in node_modules, you should keep doing that. We've chosen the shrinkwrap route because that works better for us.

    It's not exactly news that Joyent is heavy on Node. Node is the heart of our SmartDataCenter (SDC) product, whose public-facing web portal, public API, Cloud Analytics, provisioning, billing, heartbeating, and other services are all implemented in Node. That's why it's so important to us to have robust components (like logging and REST) and tools for understanding production failures postmortem, profile Node apps in production, and now managing Node dependencies. Again, we're interested to hear feedback from others using these tools.


    Dave Pacheco blogs at dtrace.org.

    [1] Much of this section is taken directly from the "npm shrinkwrap" documentation.

    [2] We've had a lot of trouble with checking in node_modules with binary dependencies. The first problem is figuring out exactly which files not to check in (.o, .node, .dynlib, .so, *.a, ...). When Mark went to apply this to one of our internal services, the "npm rebuild" step blew away half of the dependency tree because it ran "make clean", which in dependency ldapjs brings the repo to a clean slate by blowing away its dependencies. Later, a new (but highly experienced) engineer on our team was tasked with fixing a bug in our Node-based DHCP server. To fix the bug, we went with a new dependency. He tried checking in node_modules, which added 190,000 lines of code (to this repo that was previously a few hundred LOC). And despite doing everything he could think of to do this correctly and test it properly, the change broke the build because of the binary modules. So having tried this approach a few times now, it appears quite difficult to get right, and as I pointed out above, the lack of actual documentation and real world examples suggests others either aren't using binary modules (which we know isn't true) or haven't had much better luck with this approach.

    [3] Like a good Node-based distributed system, our architecture uses lots of small HTTP servers. Each of these serves a REST API using restify. restify uses the binary module node-dtrace-provider, which gives each of our services deep DTrace-based observability for free. So literally almost all of our components are or will soon be depending on a binary add-on. Additionally, the foundation of Cloud Analytics are a pair of binary modules that extract data from DTrace and kstat. So this isn't a corner case for us, and we don't believe we're exceptional in this regard. The popular hiredis package for interfacing with redis from Node is also a binary module.

    [4] Note that I said this is an important principle for software version control, not using git in general. People use git for lots of things where checking in binaries and other derived files is probably fine. Also, I'm not interested in proselytizing; if you want to do this for software version control too, go ahead. But don't do it out of ignorance of existing successful software engineering practices.

    node-v0.10.25~dfsg2/doc/blog/npm/peer-dependencies.md0000644000000000000000000001517212270121457021006 0ustar rootrootcategory: npm title: Peer Dependencies date: 2013-02-08T00:00:00Z author: Domenic Denicola slug: peer-dependencies Reposted from [Domenic's blog](http://domenic.me/2013/02/08/peer-dependencies/) with permission. Thanks! npm is awesome as a package manager. In particular, it handles sub-dependencies very well: if my package depends on `request` version 2 and `some-other-library`, but `some-other-library` depends on `request` version 1, the resulting dependency graph looks like: ```text ├── request@2.12.0 └─┬ some-other-library@1.2.3 └── request@1.9.9 ``` This is, generally, great: now `some-other-library` has its own copy of `request` v1 that it can use, while not interfering with my package's v2 copy. Everyone's code works! ## The Problem: Plugins There's one use case where this falls down, however: *plugins*. A plugin package is meant to be used with another "host" package, even though it does not always directly *use* the host package. There are many examples of this pattern in the Node.js package ecosystem already: - Grunt [plugins](http://gruntjs.com/#plugins-all) - Chai [plugins](http://chaijs.com/plugins) - LevelUP [plugins](https://github.com/rvagg/node-levelup/wiki/Modules) - Express [middleware](http://expressjs.com/api.html#middleware) - Winston [transports](https://github.com/flatiron/winston/blob/master/docs/transports.md) Even if you're not familiar with any of those use cases, surely you recall "jQuery plugins" from back when you were a client-side developer: little ` node-v0.10.25~dfsg2/doc/changelog-head.html0000644000000000000000000000310412270121457017074 0ustar rootroot Node.js ChangeLog

    Node.js ChangeLog


    node-v0.10.25~dfsg2/doc/blog.html0000644000000000000000000001651112270121457015177 0ustar rootroot <%= title || "Node.js Blog" %>

    <%- title %>

    <% if (typeof post !== 'undefined') { // just one post on this page %>

    <%- post.date.toUTCString().replace(/ GMT$/, '') + ' UTC' + (post.author ? ' - ' + post.author : '') + (post.category ? ' - ' + post.category + '' : '') %>

    <%- post.content %>

    Please post feedback and comments on the Node.JS user mailing list.
    Please post bugs and feature requests on the Node.JS github repository.

    <% if (post.next || post.prev) { if (post.prev) { %>

    ← <%= post.prev.title %>

    <% } if (post.next) { %>

    <%= post.next.title %> →

    <% } } } else { // not single post page if (paginated && total > 1 ) { if (page > 0) { // add 1 to all of the displayed numbers, because // humans are not zero-indexed like they ought to be. %>

    ← Page <%- page %>

    <% } if (page < total - 1) { %>

    Page <%- page + 2 %> →

    <% } } posts.forEach(function(post) { %>

    <%- post.date.toUTCString().replace(/ GMT$/, '') + ' UTC' + (post.author ? ' - ' + post.author : '') + (post.category ? ' - ' + post.category + '' : '') %>

    <%- post.content %>
    <% }); if (paginated && total > 1 ) { if (page > 0) { // add 1 to all of the displayed numbers, because // humans are not zero-indexed like they ought to be. %>

    ← Page <%- page %>

    <% } if (page < total - 1) { %>

    Page <%- page + 2 %> →

    <% } } // pagination } // not a single post %>
    node-v0.10.25~dfsg2/doc/api/0000755000000000000000000000000012270264601014132 5ustar rootrootnode-v0.10.25~dfsg2/doc/api/fs.markdown0000644000000000000000000005410112270121457016310 0ustar rootroot# File System Stability: 3 - Stable File I/O is provided by simple wrappers around standard POSIX functions. To use this module do `require('fs')`. All the methods have asynchronous and synchronous forms. The asynchronous form always take a completion callback as its last argument. The arguments passed to the completion callback depend on the method, but the first argument is always reserved for an exception. If the operation was completed successfully, then the first argument will be `null` or `undefined`. When using the synchronous form any exceptions are immediately thrown. You can use try/catch to handle exceptions or allow them to bubble up. Here is an example of the asynchronous version: var fs = require('fs'); fs.unlink('/tmp/hello', function (err) { if (err) throw err; console.log('successfully deleted /tmp/hello'); }); Here is the synchronous version: var fs = require('fs'); fs.unlinkSync('/tmp/hello') console.log('successfully deleted /tmp/hello'); With the asynchronous methods there is no guaranteed ordering. So the following is prone to error: fs.rename('/tmp/hello', '/tmp/world', function (err) { if (err) throw err; console.log('renamed complete'); }); fs.stat('/tmp/world', function (err, stats) { if (err) throw err; console.log('stats: ' + JSON.stringify(stats)); }); It could be that `fs.stat` is executed before `fs.rename`. The correct way to do this is to chain the callbacks. fs.rename('/tmp/hello', '/tmp/world', function (err) { if (err) throw err; fs.stat('/tmp/world', function (err, stats) { if (err) throw err; console.log('stats: ' + JSON.stringify(stats)); }); }); In busy processes, the programmer is _strongly encouraged_ to use the asynchronous versions of these calls. The synchronous versions will block the entire process until they complete--halting all connections. Relative path to filename can be used, remember however that this path will be relative to `process.cwd()`. Most fs functions let you omit the callback argument. If you do, a default callback is used that ignores errors, but prints a deprecation warning. **IMPORTANT**: Omitting the callback is deprecated. v0.12 will throw the errors as exceptions. ## fs.rename(oldPath, newPath, callback) Asynchronous rename(2). No arguments other than a possible exception are given to the completion callback. ## fs.renameSync(oldPath, newPath) Synchronous rename(2). ## fs.ftruncate(fd, len, callback) Asynchronous ftruncate(2). No arguments other than a possible exception are given to the completion callback. ## fs.ftruncateSync(fd, len) Synchronous ftruncate(2). ## fs.truncate(path, len, callback) Asynchronous truncate(2). No arguments other than a possible exception are given to the completion callback. ## fs.truncateSync(path, len) Synchronous truncate(2). ## fs.chown(path, uid, gid, callback) Asynchronous chown(2). No arguments other than a possible exception are given to the completion callback. ## fs.chownSync(path, uid, gid) Synchronous chown(2). ## fs.fchown(fd, uid, gid, callback) Asynchronous fchown(2). No arguments other than a possible exception are given to the completion callback. ## fs.fchownSync(fd, uid, gid) Synchronous fchown(2). ## fs.lchown(path, uid, gid, callback) Asynchronous lchown(2). No arguments other than a possible exception are given to the completion callback. ## fs.lchownSync(path, uid, gid) Synchronous lchown(2). ## fs.chmod(path, mode, callback) Asynchronous chmod(2). No arguments other than a possible exception are given to the completion callback. ## fs.chmodSync(path, mode) Synchronous chmod(2). ## fs.fchmod(fd, mode, callback) Asynchronous fchmod(2). No arguments other than a possible exception are given to the completion callback. ## fs.fchmodSync(fd, mode) Synchronous fchmod(2). ## fs.lchmod(path, mode, callback) Asynchronous lchmod(2). No arguments other than a possible exception are given to the completion callback. Only available on Mac OS X. ## fs.lchmodSync(path, mode) Synchronous lchmod(2). ## fs.stat(path, callback) Asynchronous stat(2). The callback gets two arguments `(err, stats)` where `stats` is a [fs.Stats](#fs_class_fs_stats) object. See the [fs.Stats](#fs_class_fs_stats) section below for more information. ## fs.lstat(path, callback) Asynchronous lstat(2). The callback gets two arguments `(err, stats)` where `stats` is a `fs.Stats` object. `lstat()` is identical to `stat()`, except that if `path` is a symbolic link, then the link itself is stat-ed, not the file that it refers to. ## fs.fstat(fd, callback) Asynchronous fstat(2). The callback gets two arguments `(err, stats)` where `stats` is a `fs.Stats` object. `fstat()` is identical to `stat()`, except that the file to be stat-ed is specified by the file descriptor `fd`. ## fs.statSync(path) Synchronous stat(2). Returns an instance of `fs.Stats`. ## fs.lstatSync(path) Synchronous lstat(2). Returns an instance of `fs.Stats`. ## fs.fstatSync(fd) Synchronous fstat(2). Returns an instance of `fs.Stats`. ## fs.link(srcpath, dstpath, callback) Asynchronous link(2). No arguments other than a possible exception are given to the completion callback. ## fs.linkSync(srcpath, dstpath) Synchronous link(2). ## fs.symlink(srcpath, dstpath, [type], callback) Asynchronous symlink(2). No arguments other than a possible exception are given to the completion callback. The `type` argument can be set to `'dir'`, `'file'`, or `'junction'` (default is `'file'`) and is only available on Windows (ignored on other platforms). Note that Windows junction points require the destination path to be absolute. When using `'junction'`, the `destination` argument will automatically be normalized to absolute path. ## fs.symlinkSync(srcpath, dstpath, [type]) Synchronous symlink(2). ## fs.readlink(path, callback) Asynchronous readlink(2). The callback gets two arguments `(err, linkString)`. ## fs.readlinkSync(path) Synchronous readlink(2). Returns the symbolic link's string value. ## fs.realpath(path, [cache], callback) Asynchronous realpath(2). The `callback` gets two arguments `(err, resolvedPath)`. May use `process.cwd` to resolve relative paths. `cache` is an object literal of mapped paths that can be used to force a specific path resolution or avoid additional `fs.stat` calls for known real paths. Example: var cache = {'/etc':'/private/etc'}; fs.realpath('/etc/passwd', cache, function (err, resolvedPath) { if (err) throw err; console.log(resolvedPath); }); ## fs.realpathSync(path, [cache]) Synchronous realpath(2). Returns the resolved path. ## fs.unlink(path, callback) Asynchronous unlink(2). No arguments other than a possible exception are given to the completion callback. ## fs.unlinkSync(path) Synchronous unlink(2). ## fs.rmdir(path, callback) Asynchronous rmdir(2). No arguments other than a possible exception are given to the completion callback. ## fs.rmdirSync(path) Synchronous rmdir(2). ## fs.mkdir(path, [mode], callback) Asynchronous mkdir(2). No arguments other than a possible exception are given to the completion callback. `mode` defaults to `0777`. ## fs.mkdirSync(path, [mode]) Synchronous mkdir(2). ## fs.readdir(path, callback) Asynchronous readdir(3). Reads the contents of a directory. The callback gets two arguments `(err, files)` where `files` is an array of the names of the files in the directory excluding `'.'` and `'..'`. ## fs.readdirSync(path) Synchronous readdir(3). Returns an array of filenames excluding `'.'` and `'..'`. ## fs.close(fd, callback) Asynchronous close(2). No arguments other than a possible exception are given to the completion callback. ## fs.closeSync(fd) Synchronous close(2). ## fs.open(path, flags, [mode], callback) Asynchronous file open. See open(2). `flags` can be: * `'r'` - Open file for reading. An exception occurs if the file does not exist. * `'r+'` - Open file for reading and writing. An exception occurs if the file does not exist. * `'rs'` - Open file for reading in synchronous mode. Instructs the operating system to bypass the local file system cache. This is primarily useful for opening files on NFS mounts as it allows you to skip the potentially stale local cache. It has a very real impact on I/O performance so don't use this flag unless you need it. Note that this doesn't turn `fs.open()` into a synchronous blocking call. If that's what you want then you should be using `fs.openSync()` * `'rs+'` - Open file for reading and writing, telling the OS to open it synchronously. See notes for `'rs'` about using this with caution. * `'w'` - Open file for writing. The file is created (if it does not exist) or truncated (if it exists). * `'wx'` - Like `'w'` but fails if `path` exists. * `'w+'` - Open file for reading and writing. The file is created (if it does not exist) or truncated (if it exists). * `'wx+'` - Like `'w+'` but fails if `path` exists. * `'a'` - Open file for appending. The file is created if it does not exist. * `'ax'` - Like `'a'` but fails if `path` exists. * `'a+'` - Open file for reading and appending. The file is created if it does not exist. * `'ax+'` - Like `'a+'` but fails if `path` exists. `mode` sets the file mode (permission and sticky bits), but only if the file was created. It defaults to `0666`, readable and writeable. The callback gets two arguments `(err, fd)`. The exclusive flag `'x'` (`O_EXCL` flag in open(2)) ensures that `path` is newly created. On POSIX systems, `path` is considered to exist even if it is a symlink to a non-existent file. The exclusive flag may or may not work with network file systems. On Linux, positional writes don't work when the file is opened in append mode. The kernel ignores the position argument and always appends the data to the end of the file. ## fs.openSync(path, flags, [mode]) Synchronous version of `fs.open()`. ## fs.utimes(path, atime, mtime, callback) ## fs.utimesSync(path, atime, mtime) Change file timestamps of the file referenced by the supplied path. ## fs.futimes(fd, atime, mtime, callback) ## fs.futimesSync(fd, atime, mtime) Change the file timestamps of a file referenced by the supplied file descriptor. ## fs.fsync(fd, callback) Asynchronous fsync(2). No arguments other than a possible exception are given to the completion callback. ## fs.fsyncSync(fd) Synchronous fsync(2). ## fs.write(fd, buffer, offset, length, position, callback) Write `buffer` to the file specified by `fd`. `offset` and `length` determine the part of the buffer to be written. `position` refers to the offset from the beginning of the file where this data should be written. If `position` is `null`, the data will be written at the current position. See pwrite(2). The callback will be given three arguments `(err, written, buffer)` where `written` specifies how many _bytes_ were written from `buffer`. Note that it is unsafe to use `fs.write` multiple times on the same file without waiting for the callback. For this scenario, `fs.createWriteStream` is strongly recommended. On Linux, positional writes don't work when the file is opened in append mode. The kernel ignores the position argument and always appends the data to the end of the file. ## fs.writeSync(fd, buffer, offset, length, position) Synchronous version of `fs.write()`. Returns the number of bytes written. ## fs.read(fd, buffer, offset, length, position, callback) Read data from the file specified by `fd`. `buffer` is the buffer that the data will be written to. `offset` is the offset in the buffer to start writing at. `length` is an integer specifying the number of bytes to read. `position` is an integer specifying where to begin reading from in the file. If `position` is `null`, data will be read from the current file position. The callback is given the three arguments, `(err, bytesRead, buffer)`. ## fs.readSync(fd, buffer, offset, length, position) Synchronous version of `fs.read`. Returns the number of `bytesRead`. ## fs.readFile(filename, [options], callback) * `filename` {String} * `options` {Object} * `encoding` {String | Null} default = `null` * `flag` {String} default = `'r'` * `callback` {Function} Asynchronously reads the entire contents of a file. Example: fs.readFile('/etc/passwd', function (err, data) { if (err) throw err; console.log(data); }); The callback is passed two arguments `(err, data)`, where `data` is the contents of the file. If no encoding is specified, then the raw buffer is returned. ## fs.readFileSync(filename, [options]) Synchronous version of `fs.readFile`. Returns the contents of the `filename`. If the `encoding` option is specified then this function returns a string. Otherwise it returns a buffer. ## fs.writeFile(filename, data, [options], callback) * `filename` {String} * `data` {String | Buffer} * `options` {Object} * `encoding` {String | Null} default = `'utf8'` * `mode` {Number} default = `438` (aka `0666` in Octal) * `flag` {String} default = `'w'` * `callback` {Function} Asynchronously writes data to a file, replacing the file if it already exists. `data` can be a string or a buffer. The `encoding` option is ignored if `data` is a buffer. It defaults to `'utf8'`. Example: fs.writeFile('message.txt', 'Hello Node', function (err) { if (err) throw err; console.log('It\'s saved!'); }); ## fs.writeFileSync(filename, data, [options]) The synchronous version of `fs.writeFile`. ## fs.appendFile(filename, data, [options], callback) * `filename` {String} * `data` {String | Buffer} * `options` {Object} * `encoding` {String | Null} default = `'utf8'` * `mode` {Number} default = `438` (aka `0666` in Octal) * `flag` {String} default = `'a'` * `callback` {Function} Asynchronously append data to a file, creating the file if it not yet exists. `data` can be a string or a buffer. Example: fs.appendFile('message.txt', 'data to append', function (err) { if (err) throw err; console.log('The "data to append" was appended to file!'); }); ## fs.appendFileSync(filename, data, [options]) The synchronous version of `fs.appendFile`. ## fs.watchFile(filename, [options], listener) Stability: 2 - Unstable. Use fs.watch instead, if possible. Watch for changes on `filename`. The callback `listener` will be called each time the file is accessed. The second argument is optional. The `options` if provided should be an object containing two members a boolean, `persistent`, and `interval`. `persistent` indicates whether the process should continue to run as long as files are being watched. `interval` indicates how often the target should be polled, in milliseconds. The default is `{ persistent: true, interval: 5007 }`. The `listener` gets two arguments the current stat object and the previous stat object: fs.watchFile('message.text', function (curr, prev) { console.log('the current mtime is: ' + curr.mtime); console.log('the previous mtime was: ' + prev.mtime); }); These stat objects are instances of `fs.Stat`. If you want to be notified when the file was modified, not just accessed you need to compare `curr.mtime` and `prev.mtime`. ## fs.unwatchFile(filename, [listener]) Stability: 2 - Unstable. Use fs.watch instead, if possible. Stop watching for changes on `filename`. If `listener` is specified, only that particular listener is removed. Otherwise, *all* listeners are removed and you have effectively stopped watching `filename`. Calling `fs.unwatchFile()` with a filename that is not being watched is a no-op, not an error. ## fs.watch(filename, [options], [listener]) Stability: 2 - Unstable. Watch for changes on `filename`, where `filename` is either a file or a directory. The returned object is a [fs.FSWatcher](#fs_class_fs_fswatcher). The second argument is optional. The `options` if provided should be an object containing a boolean member `persistent`, which indicates whether the process should continue to run as long as files are being watched. The default is `{ persistent: true }`. The listener callback gets two arguments `(event, filename)`. `event` is either 'rename' or 'change', and `filename` is the name of the file which triggered the event. ### Caveats The `fs.watch` API is not 100% consistent across platforms, and is unavailable in some situations. #### Availability This feature depends on the underlying operating system providing a way to be notified of filesystem changes. * On Linux systems, this uses `inotify`. * On BSD systems (including OS X), this uses `kqueue`. * On SunOS systems (including Solaris and SmartOS), this uses `event ports`. * On Windows systems, this feature depends on `ReadDirectoryChangesW`. If the underlying functionality is not available for some reason, then `fs.watch` will not be able to function. For example, watching files or directories on network file systems (NFS, SMB, etc.) often doesn't work reliably or at all. You can still use `fs.watchFile`, which uses stat polling, but it is slower and less reliable. #### Filename Argument Providing `filename` argument in the callback is not supported on every platform (currently it's only supported on Linux and Windows). Even on supported platforms `filename` is not always guaranteed to be provided. Therefore, don't assume that `filename` argument is always provided in the callback, and have some fallback logic if it is null. fs.watch('somedir', function (event, filename) { console.log('event is: ' + event); if (filename) { console.log('filename provided: ' + filename); } else { console.log('filename not provided'); } }); ## fs.exists(path, callback) Test whether or not the given path exists by checking with the file system. Then call the `callback` argument with either true or false. Example: fs.exists('/etc/passwd', function (exists) { util.debug(exists ? "it's there" : "no passwd!"); }); `fs.exists()` is an anachronism and exists only for historical reasons. There should almost never be a reason to use it in your own code. In particular, checking if a file exists before opening it is an anti-pattern that leaves you vulnerable to race conditions: another process may remove the file between the calls to `fs.exists()` and `fs.open()`. Just open the file and handle the error when it's not there. ## fs.existsSync(path) Synchronous version of `fs.exists`. ## Class: fs.Stats Objects returned from `fs.stat()`, `fs.lstat()` and `fs.fstat()` and their synchronous counterparts are of this type. - `stats.isFile()` - `stats.isDirectory()` - `stats.isBlockDevice()` - `stats.isCharacterDevice()` - `stats.isSymbolicLink()` (only valid with `fs.lstat()`) - `stats.isFIFO()` - `stats.isSocket()` For a regular file `util.inspect(stats)` would return a string very similar to this: { dev: 2114, ino: 48064969, mode: 33188, nlink: 1, uid: 85, gid: 100, rdev: 0, size: 527, blksize: 4096, blocks: 8, atime: Mon, 10 Oct 2011 23:24:11 GMT, mtime: Mon, 10 Oct 2011 23:24:11 GMT, ctime: Mon, 10 Oct 2011 23:24:11 GMT } Please note that `atime`, `mtime` and `ctime` are instances of [Date][MDN-Date] object and to compare the values of these objects you should use appropriate methods. For most general uses [getTime()][MDN-Date-getTime] will return the number of milliseconds elapsed since _1 January 1970 00:00:00 UTC_ and this integer should be sufficient for any comparison, however there additional methods which can be used for displaying fuzzy information. More details can be found in the [MDN JavaScript Reference][MDN-Date] page. [MDN-Date]: https://developer.mozilla.org/en/JavaScript/Reference/Global_Objects/Date [MDN-Date-getTime]: https://developer.mozilla.org/en/JavaScript/Reference/Global_Objects/Date/getTime ## fs.createReadStream(path, [options]) Returns a new ReadStream object (See `Readable Stream`). `options` is an object with the following defaults: { flags: 'r', encoding: null, fd: null, mode: 0666, autoClose: true } `options` can include `start` and `end` values to read a range of bytes from the file instead of the entire file. Both `start` and `end` are inclusive and start at 0. The `encoding` can be `'utf8'`, `'ascii'`, or `'base64'`. If `autoClose` is false, then the file descriptor won't be closed, even if there's an error. It is your responsiblity to close it and make sure there's no file descriptor leak. If `autoClose` is set to true (default behavior), on `error` or `end` the file descriptor will be closed automatically. An example to read the last 10 bytes of a file which is 100 bytes long: fs.createReadStream('sample.txt', {start: 90, end: 99}); ## Class: fs.ReadStream `ReadStream` is a [Readable Stream](stream.html#stream_class_stream_readable). ### Event: 'open' * `fd` {Integer} file descriptor used by the ReadStream. Emitted when the ReadStream's file is opened. ## fs.createWriteStream(path, [options]) Returns a new WriteStream object (See `Writable Stream`). `options` is an object with the following defaults: { flags: 'w', encoding: null, mode: 0666 } `options` may also include a `start` option to allow writing data at some position past the beginning of the file. Modifying a file rather than replacing it may require a `flags` mode of `r+` rather than the default mode `w`. ## Class: fs.WriteStream `WriteStream` is a [Writable Stream](stream.html#stream_class_stream_writable). ### Event: 'open' * `fd` {Integer} file descriptor used by the WriteStream. Emitted when the WriteStream's file is opened. ### file.bytesWritten The number of bytes written so far. Does not include data that is still queued for writing. ## Class: fs.FSWatcher Objects returned from `fs.watch()` are of this type. ### watcher.close() Stop watching for changes on the given `fs.FSWatcher`. ### Event: 'change' * `event` {String} The type of fs change * `filename` {String} The filename that changed (if relevant/available) Emitted when something changes in a watched directory or file. See more details in [fs.watch](#fs_fs_watch_filename_options_listener). ### Event: 'error' * `error` {Error object} Emitted when an error occurs. node-v0.10.25~dfsg2/doc/api/domain.markdown0000644000000000000000000003424012270121457017151 0ustar rootroot# Domain Stability: 2 - Unstable Domains provide a way to handle multiple different IO operations as a single group. If any of the event emitters or callbacks registered to a domain emit an `error` event, or throw an error, then the domain object will be notified, rather than losing the context of the error in the `process.on('uncaughtException')` handler, or causing the program to exit immediately with an error code. ## Warning: Don't Ignore Errors! Domain error handlers are not a substitute for closing down your process when an error occurs. By the very nature of how `throw` works in JavaScript, there is almost never any way to safely "pick up where you left off", without leaking references, or creating some other sort of undefined brittle state. The safest way to respond to a thrown error is to shut down the process. Of course, in a normal web server, you might have many connections open, and it is not reasonable to abruptly shut those down because an error was triggered by someone else. The better approach is send an error response to the request that triggered the error, while letting the others finish in their normal time, and stop listening for new requests in that worker. In this way, `domain` usage goes hand-in-hand with the cluster module, since the master process can fork a new worker when a worker encounters an error. For node programs that scale to multiple machines, the terminating proxy or service registry can take note of the failure, and react accordingly. For example, this is not a good idea: ```javascript // XXX WARNING! BAD IDEA! var d = require('domain').create(); d.on('error', function(er) { // The error won't crash the process, but what it does is worse! // Though we've prevented abrupt process restarting, we are leaking // resources like crazy if this ever happens. // This is no better than process.on('uncaughtException')! console.log('error, but oh well', er.message); }); d.run(function() { require('http').createServer(function(req, res) { handleRequest(req, res); }).listen(PORT); }); ``` By using the context of a domain, and the resilience of separating our program into multiple worker processes, we can react more appropriately, and handle errors with much greater safety. ```javascript // Much better! var cluster = require('cluster'); var PORT = +process.env.PORT || 1337; if (cluster.isMaster) { // In real life, you'd probably use more than just 2 workers, // and perhaps not put the master and worker in the same file. // // You can also of course get a bit fancier about logging, and // implement whatever custom logic you need to prevent DoS // attacks and other bad behavior. // // See the options in the cluster documentation. // // The important thing is that the master does very little, // increasing our resilience to unexpected errors. cluster.fork(); cluster.fork(); cluster.on('disconnect', function(worker) { console.error('disconnect!'); cluster.fork(); }); } else { // the worker // // This is where we put our bugs! var domain = require('domain'); // See the cluster documentation for more details about using // worker processes to serve requests. How it works, caveats, etc. var server = require('http').createServer(function(req, res) { var d = domain.create(); d.on('error', function(er) { console.error('error', er.stack); // Note: we're in dangerous territory! // By definition, something unexpected occurred, // which we probably didn't want. // Anything can happen now! Be very careful! try { // make sure we close down within 30 seconds var killtimer = setTimeout(function() { process.exit(1); }, 30000); // But don't keep the process open just for that! killtimer.unref(); // stop taking new requests. server.close(); // Let the master know we're dead. This will trigger a // 'disconnect' in the cluster master, and then it will fork // a new worker. cluster.worker.disconnect(); // try to send an error to the request that triggered the problem res.statusCode = 500; res.setHeader('content-type', 'text/plain'); res.end('Oops, there was a problem!\n'); } catch (er2) { // oh well, not much we can do at this point. console.error('Error sending 500!', er2.stack); } }); // Because req and res were created before this domain existed, // we need to explicitly add them. // See the explanation of implicit vs explicit binding below. d.add(req); d.add(res); // Now run the handler function in the domain. d.run(function() { handleRequest(req, res); }); }); server.listen(PORT); } // This part isn't important. Just an example routing thing. // You'd put your fancy application logic here. function handleRequest(req, res) { switch(req.url) { case '/error': // We do some async stuff, and then... setTimeout(function() { // Whoops! flerb.bark(); }); break; default: res.end('ok'); } } ``` ## Additions to Error objects Any time an Error object is routed through a domain, a few extra fields are added to it. * `error.domain` The domain that first handled the error. * `error.domainEmitter` The event emitter that emitted an 'error' event with the error object. * `error.domainBound` The callback function which was bound to the domain, and passed an error as its first argument. * `error.domainThrown` A boolean indicating whether the error was thrown, emitted, or passed to a bound callback function. ## Implicit Binding If domains are in use, then all **new** EventEmitter objects (including Stream objects, requests, responses, etc.) will be implicitly bound to the active domain at the time of their creation. Additionally, callbacks passed to lowlevel event loop requests (such as to fs.open, or other callback-taking methods) will automatically be bound to the active domain. If they throw, then the domain will catch the error. In order to prevent excessive memory usage, Domain objects themselves are not implicitly added as children of the active domain. If they were, then it would be too easy to prevent request and response objects from being properly garbage collected. If you *want* to nest Domain objects as children of a parent Domain, then you must explicitly add them. Implicit binding routes thrown errors and `'error'` events to the Domain's `error` event, but does not register the EventEmitter on the Domain, so `domain.dispose()` will not shut down the EventEmitter. Implicit binding only takes care of thrown errors and `'error'` events. ## Explicit Binding Sometimes, the domain in use is not the one that ought to be used for a specific event emitter. Or, the event emitter could have been created in the context of one domain, but ought to instead be bound to some other domain. For example, there could be one domain in use for an HTTP server, but perhaps we would like to have a separate domain to use for each request. That is possible via explicit binding. For example: ``` // create a top-level domain for the server var serverDomain = domain.create(); serverDomain.run(function() { // server is created in the scope of serverDomain http.createServer(function(req, res) { // req and res are also created in the scope of serverDomain // however, we'd prefer to have a separate domain for each request. // create it first thing, and add req and res to it. var reqd = domain.create(); reqd.add(req); reqd.add(res); reqd.on('error', function(er) { console.error('Error', er, req.url); try { res.writeHead(500); res.end('Error occurred, sorry.'); } catch (er) { console.error('Error sending 500', er, req.url); } }); }).listen(1337); }); ``` ## domain.create() * return: {Domain} Returns a new Domain object. ## Class: Domain The Domain class encapsulates the functionality of routing errors and uncaught exceptions to the active Domain object. Domain is a child class of [EventEmitter][]. To handle the errors that it catches, listen to its `error` event. ### domain.run(fn) * `fn` {Function} Run the supplied function in the context of the domain, implicitly binding all event emitters, timers, and lowlevel requests that are created in that context. This is the most basic way to use a domain. Example: ``` var d = domain.create(); d.on('error', function(er) { console.error('Caught error!', er); }); d.run(function() { process.nextTick(function() { setTimeout(function() { // simulating some various async stuff fs.open('non-existent file', 'r', function(er, fd) { if (er) throw er; // proceed... }); }, 100); }); }); ``` In this example, the `d.on('error')` handler will be triggered, rather than crashing the program. ### domain.members * {Array} An array of timers and event emitters that have been explicitly added to the domain. ### domain.add(emitter) * `emitter` {EventEmitter | Timer} emitter or timer to be added to the domain Explicitly adds an emitter to the domain. If any event handlers called by the emitter throw an error, or if the emitter emits an `error` event, it will be routed to the domain's `error` event, just like with implicit binding. This also works with timers that are returned from `setInterval` and `setTimeout`. If their callback function throws, it will be caught by the domain 'error' handler. If the Timer or EventEmitter was already bound to a domain, it is removed from that one, and bound to this one instead. ### domain.remove(emitter) * `emitter` {EventEmitter | Timer} emitter or timer to be removed from the domain The opposite of `domain.add(emitter)`. Removes domain handling from the specified emitter. ### domain.bind(callback) * `callback` {Function} The callback function * return: {Function} The bound function The returned function will be a wrapper around the supplied callback function. When the returned function is called, any errors that are thrown will be routed to the domain's `error` event. #### Example var d = domain.create(); function readSomeFile(filename, cb) { fs.readFile(filename, 'utf8', d.bind(function(er, data) { // if this throws, it will also be passed to the domain return cb(er, data ? JSON.parse(data) : null); })); } d.on('error', function(er) { // an error occurred somewhere. // if we throw it now, it will crash the program // with the normal line number and stack message. }); ### domain.intercept(callback) * `callback` {Function} The callback function * return: {Function} The intercepted function This method is almost identical to `domain.bind(callback)`. However, in addition to catching thrown errors, it will also intercept `Error` objects sent as the first argument to the function. In this way, the common `if (er) return callback(er);` pattern can be replaced with a single error handler in a single place. #### Example var d = domain.create(); function readSomeFile(filename, cb) { fs.readFile(filename, 'utf8', d.intercept(function(data) { // note, the first argument is never passed to the // callback since it is assumed to be the 'Error' argument // and thus intercepted by the domain. // if this throws, it will also be passed to the domain // so the error-handling logic can be moved to the 'error' // event on the domain instead of being repeated throughout // the program. return cb(null, JSON.parse(data)); })); } d.on('error', function(er) { // an error occurred somewhere. // if we throw it now, it will crash the program // with the normal line number and stack message. }); ### domain.enter() The `enter` method is plumbing used by the `run`, `bind`, and `intercept` methods to set the active domain. It sets `domain.active` and `process.domain` to the domain, and implicitly pushes the domain onto the domain stack managed by the domain module (see `domain.exit()` for details on the domain stack). The call to `enter` delimits the beginning of a chain of asynchronous calls and I/O operations bound to a domain. Calling `enter` changes only the active domain, and does not alter the domain itself. `Enter` and `exit` can be called an arbitrary number of times on a single domain. If the domain on which `enter` is called has been disposed, `enter` will return without setting the domain. ### domain.exit() The `exit` method exits the current domain, popping it off the domain stack. Any time execution is going to switch to the context of a different chain of asynchronous calls, it's important to ensure that the current domain is exited. The call to `exit` delimits either the end of or an interruption to the chain of asynchronous calls and I/O operations bound to a domain. If there are multiple, nested domains bound to the current execution context, `exit` will exit any domains nested within this domain. Calling `exit` changes only the active domain, and does not alter the domain itself. `Enter` and `exit` can be called an arbitrary number of times on a single domain. If the domain on which `exit` is called has been disposed, `exit` will return without exiting the domain. ### domain.dispose() The dispose method destroys a domain, and makes a best effort attempt to clean up any and all IO that is associated with the domain. Streams are aborted, ended, closed, and/or destroyed. Timers are cleared. Explicitly bound callbacks are no longer called. Any error events that are raised as a result of this are ignored. The intention of calling `dispose` is generally to prevent cascading errors when a critical part of the Domain context is found to be in an error state. Once the domain is disposed the `dispose` event will emit. Note that IO might still be performed. However, to the highest degree possible, once a domain is disposed, further errors from the emitters in that set will be ignored. So, even if some remaining actions are still in flight, Node.js will not communicate further about them. [EventEmitter]: events.html#events_class_events_eventemitter node-v0.10.25~dfsg2/doc/api/dgram.json0000644000000000000000000005233712270264601016131 0ustar rootroot{ "source": "doc/api/dgram.markdown", "modules": [ { "textRaw": "UDP / Datagram Sockets", "name": "dgram", "stability": 3, "stabilityText": "Stable", "desc": "

    Datagram sockets are available through require('dgram').\n\n

    \n

    Important note: the behavior of dgram.Socket#bind() has changed in v0.10\nand is always asynchronous now. If you have code that looks like this:\n\n

    \n
    var s = dgram.createSocket('udp4');\ns.bind(1234);\ns.addMembership('224.0.0.114');
    \n

    You have to change it to this:\n\n

    \n
    var s = dgram.createSocket('udp4');\ns.bind(1234, function() {\n  s.addMembership('224.0.0.114');\n});
    \n", "methods": [ { "textRaw": "dgram.createSocket(type, [callback])", "type": "method", "name": "createSocket", "signatures": [ { "return": { "textRaw": "Returns: Socket object ", "name": "return", "desc": "Socket object" }, "params": [ { "textRaw": "`type` String. Either 'udp4' or 'udp6' ", "name": "type", "desc": "String. Either 'udp4' or 'udp6'" }, { "textRaw": "`callback` Function. Attached as a listener to `message` events. Optional ", "name": "callback", "optional": true, "desc": "Function. Attached as a listener to `message` events." } ] }, { "params": [ { "name": "type" }, { "name": "callback", "optional": true } ] } ], "desc": "

    Creates a datagram Socket of the specified types. Valid types are udp4\nand udp6.\n\n

    \n

    Takes an optional callback which is added as a listener for message events.\n\n

    \n

    Call socket.bind if you want to receive datagrams. socket.bind() will bind\nto the "all interfaces" address on a random port (it does the right thing for\nboth udp4 and udp6 sockets). You can then retrieve the address and port\nwith socket.address().address and socket.address().port.\n\n

    \n" } ], "classes": [ { "textRaw": "Class: dgram.Socket", "type": "class", "name": "dgram.Socket", "desc": "

    The dgram Socket class encapsulates the datagram functionality. It\nshould be created via dgram.createSocket(type, [callback]).\n\n

    \n", "events": [ { "textRaw": "Event: 'message'", "type": "event", "name": "message", "params": [], "desc": "

    Emitted when a new datagram is available on a socket. msg is a Buffer and rinfo is\nan object with the sender's address information and the number of bytes in the datagram.\n\n

    \n" }, { "textRaw": "Event: 'listening'", "type": "event", "name": "listening", "desc": "

    Emitted when a socket starts listening for datagrams. This happens as soon as UDP sockets\nare created.\n\n

    \n", "params": [] }, { "textRaw": "Event: 'close'", "type": "event", "name": "close", "desc": "

    Emitted when a socket is closed with close(). No new message events will be emitted\non this socket.\n\n

    \n", "params": [] }, { "textRaw": "Event: 'error'", "type": "event", "name": "error", "params": [], "desc": "

    Emitted when an error occurs.\n\n

    \n" } ], "methods": [ { "textRaw": "socket.send(buf, offset, length, port, address, [callback])", "type": "method", "name": "send", "signatures": [ { "params": [ { "textRaw": "`buf` Buffer object. Message to be sent ", "name": "buf", "desc": "Buffer object. Message to be sent" }, { "textRaw": "`offset` Integer. Offset in the buffer where the message starts. ", "name": "offset", "desc": "Integer. Offset in the buffer where the message starts." }, { "textRaw": "`length` Integer. Number of bytes in the message. ", "name": "length", "desc": "Integer. Number of bytes in the message." }, { "textRaw": "`port` Integer. Destination port. ", "name": "port", "desc": "Integer. Destination port." }, { "textRaw": "`address` String. Destination hostname or IP address. ", "name": "address", "desc": "String. Destination hostname or IP address." }, { "textRaw": "`callback` Function. Called when the message has been sent. Optional. ", "name": "callback", "desc": "Function. Called when the message has been sent. Optional.", "optional": true } ] }, { "params": [ { "name": "buf" }, { "name": "offset" }, { "name": "length" }, { "name": "port" }, { "name": "address" }, { "name": "callback", "optional": true } ] } ], "desc": "

    For UDP sockets, the destination port and address must be specified. A string\nmay be supplied for the address parameter, and it will be resolved with DNS.\n\n

    \n

    If the address is omitted or is an empty string, '0.0.0.0' or '::0' is used\ninstead. Depending on the network configuration, those defaults may or may not\nwork; it's best to be explicit about the destination address.\n\n

    \n

    If the socket has not been previously bound with a call to bind, it gets\nassigned a random port number and is bound to the "all interfaces" address\n('0.0.0.0' for udp4 sockets, '::0' for udp6 sockets.)\n\n

    \n

    An optional callback may be specified to detect DNS errors or for determining\nwhen it's safe to reuse the buf object. Note that DNS lookups delay the time\nto send for at least one tick. The only way to know for sure that the datagram\nhas been sent is by using a callback.\n\n

    \n

    Example of sending a UDP packet to a random port on localhost;\n\n

    \n
    var dgram = require('dgram');\nvar message = new Buffer("Some bytes");\nvar client = dgram.createSocket("udp4");\nclient.send(message, 0, message.length, 41234, "localhost", function(err, bytes) {\n  client.close();\n});
    \n

    A Note about UDP datagram size\n\n

    \n

    The maximum size of an IPv4/v6 datagram depends on the MTU (Maximum Transmission Unit)\nand on the Payload Length field size.\n\n

    \n
      \n
    • The Payload Length field is 16 bits wide, which means that a normal payload\ncannot be larger than 64K octets including internet header and data\n(65,507 bytes = 65,535 − 8 bytes UDP header − 20 bytes IP header);\nthis is generally true for loopback interfaces, but such long datagrams\nare impractical for most hosts and networks.

      \n
    • \n
    • The MTU is the largest size a given link layer technology can support for datagrams.\nFor any link, IPv4 mandates a minimum MTU of 68 octets, while the recommended MTU\nfor IPv4 is 576 (typically recommended as the MTU for dial-up type applications),\nwhether they arrive whole or in fragments.

      \n

      For IPv6, the minimum MTU is 1280 octets, however, the mandatory minimum\nfragment reassembly buffer size is 1500 octets.\nThe value of 68 octets is very small, since most current link layer technologies have\na minimum MTU of 1500 (like Ethernet).

      \n
    • \n
    \n

    Note that it's impossible to know in advance the MTU of each link through which\na packet might travel, and that generally sending a datagram greater than\nthe (receiver) MTU won't work (the packet gets silently dropped, without\ninforming the source that the data did not reach its intended recipient).\n\n

    \n" }, { "textRaw": "socket.bind(port, [address], [callback])", "type": "method", "name": "bind", "signatures": [ { "params": [ { "textRaw": "`port` Integer ", "name": "port", "desc": "Integer" }, { "textRaw": "`address` String, Optional ", "name": "address", "optional": true, "desc": "String" }, { "textRaw": "`callback` Function with no parameters, Optional. Callback when binding is done. ", "name": "callback", "desc": "Function with no parameters, Optional. Callback when binding is done.", "optional": true } ] }, { "params": [ { "name": "port" }, { "name": "address", "optional": true }, { "name": "callback", "optional": true } ] } ], "desc": "

    For UDP sockets, listen for datagrams on a named port and optional\naddress. If address is not specified, the OS will try to listen on\nall addresses. After binding is done, a "listening" event is emitted\nand the callback(if specified) is called. Specifying both a\n"listening" event listener and callback is not harmful but not very\nuseful.\n\n

    \n

    A bound datagram socket keeps the node process running to receive\ndatagrams.\n\n

    \n

    If binding fails, an "error" event is generated. In rare case (e.g.\nbinding a closed socket), an Error may be thrown by this method.\n\n

    \n

    Example of a UDP server listening on port 41234:\n\n

    \n
    var dgram = require("dgram");\n\nvar server = dgram.createSocket("udp4");\n\nserver.on("error", function (err) {\n  console.log("server error:\\n" + err.stack);\n  server.close();\n});\n\nserver.on("message", function (msg, rinfo) {\n  console.log("server got: " + msg + " from " +\n    rinfo.address + ":" + rinfo.port);\n});\n\nserver.on("listening", function () {\n  var address = server.address();\n  console.log("server listening " +\n      address.address + ":" + address.port);\n});\n\nserver.bind(41234);\n// server listening 0.0.0.0:41234
    \n" }, { "textRaw": "socket.close()", "type": "method", "name": "close", "desc": "

    Close the underlying socket and stop listening for data on it.\n\n

    \n", "signatures": [ { "params": [] } ] }, { "textRaw": "socket.address()", "type": "method", "name": "address", "desc": "

    Returns an object containing the address information for a socket. For UDP sockets,\nthis object will contain address , family and port.\n\n

    \n", "signatures": [ { "params": [] } ] }, { "textRaw": "socket.setBroadcast(flag)", "type": "method", "name": "setBroadcast", "signatures": [ { "params": [ { "textRaw": "`flag` Boolean ", "name": "flag", "desc": "Boolean" } ] }, { "params": [ { "name": "flag" } ] } ], "desc": "

    Sets or clears the SO_BROADCAST socket option. When this option is set, UDP packets\nmay be sent to a local interface's broadcast address.\n\n

    \n" }, { "textRaw": "socket.setTTL(ttl)", "type": "method", "name": "setTTL", "signatures": [ { "params": [ { "textRaw": "`ttl` Integer ", "name": "ttl", "desc": "Integer" } ] }, { "params": [ { "name": "ttl" } ] } ], "desc": "

    Sets the IP_TTL socket option. TTL stands for "Time to Live," but in this context it\nspecifies the number of IP hops that a packet is allowed to go through. Each router or\ngateway that forwards a packet decrements the TTL. If the TTL is decremented to 0 by a\nrouter, it will not be forwarded. Changing TTL values is typically done for network\nprobes or when multicasting.\n\n

    \n

    The argument to setTTL() is a number of hops between 1 and 255. The default on most\nsystems is 64.\n\n

    \n" }, { "textRaw": "socket.setMulticastTTL(ttl)", "type": "method", "name": "setMulticastTTL", "signatures": [ { "params": [ { "textRaw": "`ttl` Integer ", "name": "ttl", "desc": "Integer" } ] }, { "params": [ { "name": "ttl" } ] } ], "desc": "

    Sets the IP_MULTICAST_TTL socket option. TTL stands for "Time to Live," but in this\ncontext it specifies the number of IP hops that a packet is allowed to go through,\nspecifically for multicast traffic. Each router or gateway that forwards a packet\ndecrements the TTL. If the TTL is decremented to 0 by a router, it will not be forwarded.\n\n

    \n

    The argument to setMulticastTTL() is a number of hops between 0 and 255. The default on most\nsystems is 1.\n\n

    \n" }, { "textRaw": "socket.setMulticastLoopback(flag)", "type": "method", "name": "setMulticastLoopback", "signatures": [ { "params": [ { "textRaw": "`flag` Boolean ", "name": "flag", "desc": "Boolean" } ] }, { "params": [ { "name": "flag" } ] } ], "desc": "

    Sets or clears the IP_MULTICAST_LOOP socket option. When this option is set, multicast\npackets will also be received on the local interface.\n\n

    \n" }, { "textRaw": "socket.addMembership(multicastAddress, [multicastInterface])", "type": "method", "name": "addMembership", "signatures": [ { "params": [ { "textRaw": "`multicastAddress` String ", "name": "multicastAddress", "desc": "String" }, { "textRaw": "`multicastInterface` String, Optional ", "name": "multicastInterface", "optional": true, "desc": "String" } ] }, { "params": [ { "name": "multicastAddress" }, { "name": "multicastInterface", "optional": true } ] } ], "desc": "

    Tells the kernel to join a multicast group with IP_ADD_MEMBERSHIP socket option.\n\n

    \n

    If multicastInterface is not specified, the OS will try to add membership to all valid\ninterfaces.\n\n

    \n" }, { "textRaw": "socket.dropMembership(multicastAddress, [multicastInterface])", "type": "method", "name": "dropMembership", "signatures": [ { "params": [ { "textRaw": "`multicastAddress` String ", "name": "multicastAddress", "desc": "String" }, { "textRaw": "`multicastInterface` String, Optional ", "name": "multicastInterface", "optional": true, "desc": "String" } ] }, { "params": [ { "name": "multicastAddress" }, { "name": "multicastInterface", "optional": true } ] } ], "desc": "

    Opposite of addMembership - tells the kernel to leave a multicast group with\nIP_DROP_MEMBERSHIP socket option. This is automatically called by the kernel\nwhen the socket is closed or process terminates, so most apps will never need to call\nthis.\n\n

    \n

    If multicastInterface is not specified, the OS will try to drop membership to all valid\ninterfaces.\n\n

    \n" }, { "textRaw": "socket.unref()", "type": "method", "name": "unref", "desc": "

    Calling unref on a socket will allow the program to exit if this is the only\nactive socket in the event system. If the socket is already unrefd calling\nunref again will have no effect.\n\n

    \n", "signatures": [ { "params": [] } ] }, { "textRaw": "socket.ref()", "type": "method", "name": "ref", "desc": "

    Opposite of unref, calling ref on a previously unrefd socket will not\nlet the program exit if it's the only socket left (the default behavior). If\nthe socket is refd calling ref again will have no effect.\n

    \n", "signatures": [ { "params": [] } ] } ] } ], "type": "module", "displayName": "dgram" } ] } node-v0.10.25~dfsg2/doc/api/fs.html0000644000000000000000000013526412270264601015443 0ustar rootroot File System Node.js v0.10.25 Manual & Documentation

    Node.js v0.10.25 Manual & Documentation


    Table of Contents

    File System#

    Stability: 3 - Stable

    File I/O is provided by simple wrappers around standard POSIX functions. To use this module do require('fs'). All the methods have asynchronous and synchronous forms.

    The asynchronous form always take a completion callback as its last argument. The arguments passed to the completion callback depend on the method, but the first argument is always reserved for an exception. If the operation was completed successfully, then the first argument will be null or undefined.

    When using the synchronous form any exceptions are immediately thrown. You can use try/catch to handle exceptions or allow them to bubble up.

    Here is an example of the asynchronous version:

    var fs = require('fs');
    
    fs.unlink('/tmp/hello', function (err) {
      if (err) throw err;
      console.log('successfully deleted /tmp/hello');
    });

    Here is the synchronous version:

    var fs = require('fs');
    
    fs.unlinkSync('/tmp/hello')
    console.log('successfully deleted /tmp/hello');

    With the asynchronous methods there is no guaranteed ordering. So the following is prone to error:

    fs.rename('/tmp/hello', '/tmp/world', function (err) {
      if (err) throw err;
      console.log('renamed complete');
    });
    fs.stat('/tmp/world', function (err, stats) {
      if (err) throw err;
      console.log('stats: ' + JSON.stringify(stats));
    });

    It could be that fs.stat is executed before fs.rename. The correct way to do this is to chain the callbacks.

    fs.rename('/tmp/hello', '/tmp/world', function (err) {
      if (err) throw err;
      fs.stat('/tmp/world', function (err, stats) {
        if (err) throw err;
        console.log('stats: ' + JSON.stringify(stats));
      });
    });

    In busy processes, the programmer is strongly encouraged to use the asynchronous versions of these calls. The synchronous versions will block the entire process until they complete--halting all connections.

    Relative path to filename can be used, remember however that this path will be relative to process.cwd().

    Most fs functions let you omit the callback argument. If you do, a default callback is used that ignores errors, but prints a deprecation warning.

    IMPORTANT: Omitting the callback is deprecated. v0.12 will throw the errors as exceptions.

    fs.rename(oldPath, newPath, callback)#

    Asynchronous rename(2). No arguments other than a possible exception are given to the completion callback.

    fs.renameSync(oldPath, newPath)#

    Synchronous rename(2).

    fs.ftruncate(fd, len, callback)#

    Asynchronous ftruncate(2). No arguments other than a possible exception are given to the completion callback.

    fs.ftruncateSync(fd, len)#

    Synchronous ftruncate(2).

    fs.truncate(path, len, callback)#

    Asynchronous truncate(2). No arguments other than a possible exception are given to the completion callback.

    fs.truncateSync(path, len)#

    Synchronous truncate(2).

    fs.chown(path, uid, gid, callback)#

    Asynchronous chown(2). No arguments other than a possible exception are given to the completion callback.

    fs.chownSync(path, uid, gid)#

    Synchronous chown(2).

    fs.fchown(fd, uid, gid, callback)#

    Asynchronous fchown(2). No arguments other than a possible exception are given to the completion callback.

    fs.fchownSync(fd, uid, gid)#

    Synchronous fchown(2).

    fs.lchown(path, uid, gid, callback)#

    Asynchronous lchown(2). No arguments other than a possible exception are given to the completion callback.

    fs.lchownSync(path, uid, gid)#

    Synchronous lchown(2).

    fs.chmod(path, mode, callback)#

    Asynchronous chmod(2). No arguments other than a possible exception are given to the completion callback.

    fs.chmodSync(path, mode)#

    Synchronous chmod(2).

    fs.fchmod(fd, mode, callback)#

    Asynchronous fchmod(2). No arguments other than a possible exception are given to the completion callback.

    fs.fchmodSync(fd, mode)#

    Synchronous fchmod(2).

    fs.lchmod(path, mode, callback)#

    Asynchronous lchmod(2). No arguments other than a possible exception are given to the completion callback.

    Only available on Mac OS X.

    fs.lchmodSync(path, mode)#

    Synchronous lchmod(2).

    fs.stat(path, callback)#

    Asynchronous stat(2). The callback gets two arguments (err, stats) where stats is a fs.Stats object. See the fs.Stats section below for more information.

    fs.lstat(path, callback)#

    Asynchronous lstat(2). The callback gets two arguments (err, stats) where stats is a fs.Stats object. lstat() is identical to stat(), except that if path is a symbolic link, then the link itself is stat-ed, not the file that it refers to.

    fs.fstat(fd, callback)#

    Asynchronous fstat(2). The callback gets two arguments (err, stats) where stats is a fs.Stats object. fstat() is identical to stat(), except that the file to be stat-ed is specified by the file descriptor fd.

    fs.statSync(path)#

    Synchronous stat(2). Returns an instance of fs.Stats.

    fs.lstatSync(path)#

    Synchronous lstat(2). Returns an instance of fs.Stats.

    fs.fstatSync(fd)#

    Synchronous fstat(2). Returns an instance of fs.Stats.

    fs.link(srcpath, dstpath, callback)#

    Asynchronous link(2). No arguments other than a possible exception are given to the completion callback.

    fs.linkSync(srcpath, dstpath)#

    Synchronous link(2).

    fs.symlink(srcpath, dstpath, [type], callback)#

    Asynchronous symlink(2). No arguments other than a possible exception are given to the completion callback. The type argument can be set to 'dir', 'file', or 'junction' (default is 'file') and is only available on Windows (ignored on other platforms). Note that Windows junction points require the destination path to be absolute. When using 'junction', the destination argument will automatically be normalized to absolute path.

    fs.symlinkSync(srcpath, dstpath, [type])#

    Synchronous symlink(2).

    fs.readlink(path, callback)#

    Asynchronous readlink(2). The callback gets two arguments (err, linkString).

    fs.readlinkSync(path)#

    Synchronous readlink(2). Returns the symbolic link's string value.

    fs.realpath(path, [cache], callback)#

    Asynchronous realpath(2). The callback gets two arguments (err, resolvedPath). May use process.cwd to resolve relative paths. cache is an object literal of mapped paths that can be used to force a specific path resolution or avoid additional fs.stat calls for known real paths.

    Example:

    var cache = {'/etc':'/private/etc'};
    fs.realpath('/etc/passwd', cache, function (err, resolvedPath) {
      if (err) throw err;
      console.log(resolvedPath);
    });

    fs.realpathSync(path, [cache])#

    Synchronous realpath(2). Returns the resolved path.

    fs.unlink(path, callback)#

    Asynchronous unlink(2). No arguments other than a possible exception are given to the completion callback.

    fs.unlinkSync(path)#

    Synchronous unlink(2).

    fs.rmdir(path, callback)#

    Asynchronous rmdir(2). No arguments other than a possible exception are given to the completion callback.

    fs.rmdirSync(path)#

    Synchronous rmdir(2).

    fs.mkdir(path, [mode], callback)#

    Asynchronous mkdir(2). No arguments other than a possible exception are given to the completion callback. mode defaults to 0777.

    fs.mkdirSync(path, [mode])#

    Synchronous mkdir(2).

    fs.readdir(path, callback)#

    Asynchronous readdir(3). Reads the contents of a directory. The callback gets two arguments (err, files) where files is an array of the names of the files in the directory excluding '.' and '..'.

    fs.readdirSync(path)#

    Synchronous readdir(3). Returns an array of filenames excluding '.' and '..'.

    fs.close(fd, callback)#

    Asynchronous close(2). No arguments other than a possible exception are given to the completion callback.

    fs.closeSync(fd)#

    Synchronous close(2).

    fs.open(path, flags, [mode], callback)#

    Asynchronous file open. See open(2). flags can be:

    • 'r' - Open file for reading. An exception occurs if the file does not exist.

    • 'r+' - Open file for reading and writing. An exception occurs if the file does not exist.

    • 'rs' - Open file for reading in synchronous mode. Instructs the operating system to bypass the local file system cache.

      This is primarily useful for opening files on NFS mounts as it allows you to skip the potentially stale local cache. It has a very real impact on I/O performance so don't use this flag unless you need it.

      Note that this doesn't turn fs.open() into a synchronous blocking call. If that's what you want then you should be using fs.openSync()

    • 'rs+' - Open file for reading and writing, telling the OS to open it synchronously. See notes for 'rs' about using this with caution.

    • 'w' - Open file for writing. The file is created (if it does not exist) or truncated (if it exists).

    • 'wx' - Like 'w' but fails if path exists.

    • 'w+' - Open file for reading and writing. The file is created (if it does not exist) or truncated (if it exists).

    • 'wx+' - Like 'w+' but fails if path exists.

    • 'a' - Open file for appending. The file is created if it does not exist.

    • 'ax' - Like 'a' but fails if path exists.

    • 'a+' - Open file for reading and appending. The file is created if it does not exist.

    • 'ax+' - Like 'a+' but fails if path exists.

    mode sets the file mode (permission and sticky bits), but only if the file was created. It defaults to 0666, readable and writeable.

    The callback gets two arguments (err, fd).

    The exclusive flag 'x' (O_EXCL flag in open(2)) ensures that path is newly created. On POSIX systems, path is considered to exist even if it is a symlink to a non-existent file. The exclusive flag may or may not work with network file systems.

    On Linux, positional writes don't work when the file is opened in append mode. The kernel ignores the position argument and always appends the data to the end of the file.

    fs.openSync(path, flags, [mode])#

    Synchronous version of fs.open().

    fs.utimes(path, atime, mtime, callback)#

    fs.utimesSync(path, atime, mtime)#

    Change file timestamps of the file referenced by the supplied path.

    fs.futimes(fd, atime, mtime, callback)#

    fs.futimesSync(fd, atime, mtime)#

    Change the file timestamps of a file referenced by the supplied file descriptor.

    fs.fsync(fd, callback)#

    Asynchronous fsync(2). No arguments other than a possible exception are given to the completion callback.

    fs.fsyncSync(fd)#

    Synchronous fsync(2).

    fs.write(fd, buffer, offset, length, position, callback)#

    Write buffer to the file specified by fd.

    offset and length determine the part of the buffer to be written.

    position refers to the offset from the beginning of the file where this data should be written. If position is null, the data will be written at the current position. See pwrite(2).

    The callback will be given three arguments (err, written, buffer) where written specifies how many bytes were written from buffer.

    Note that it is unsafe to use fs.write multiple times on the same file without waiting for the callback. For this scenario, fs.createWriteStream is strongly recommended.

    On Linux, positional writes don't work when the file is opened in append mode. The kernel ignores the position argument and always appends the data to the end of the file.

    fs.writeSync(fd, buffer, offset, length, position)#

    Synchronous version of fs.write(). Returns the number of bytes written.

    fs.read(fd, buffer, offset, length, position, callback)#

    Read data from the file specified by fd.

    buffer is the buffer that the data will be written to.

    offset is the offset in the buffer to start writing at.

    length is an integer specifying the number of bytes to read.

    position is an integer specifying where to begin reading from in the file. If position is null, data will be read from the current file position.

    The callback is given the three arguments, (err, bytesRead, buffer).

    fs.readSync(fd, buffer, offset, length, position)#

    Synchronous version of fs.read. Returns the number of bytesRead.

    fs.readFile(filename, [options], callback)#

    • filename String
    • options Object
      • encoding String | Null default = null
      • flag String default = 'r'
    • callback Function

    Asynchronously reads the entire contents of a file. Example:

    fs.readFile('/etc/passwd', function (err, data) {
      if (err) throw err;
      console.log(data);
    });

    The callback is passed two arguments (err, data), where data is the contents of the file.

    If no encoding is specified, then the raw buffer is returned.

    fs.readFileSync(filename, [options])#

    Synchronous version of fs.readFile. Returns the contents of the filename.

    If the encoding option is specified then this function returns a string. Otherwise it returns a buffer.

    fs.writeFile(filename, data, [options], callback)#

    • filename String
    • data String | Buffer
    • options Object
      • encoding String | Null default = 'utf8'
      • mode Number default = 438 (aka 0666 in Octal)
      • flag String default = 'w'
    • callback Function

    Asynchronously writes data to a file, replacing the file if it already exists. data can be a string or a buffer.

    The encoding option is ignored if data is a buffer. It defaults to 'utf8'.

    Example:

    fs.writeFile('message.txt', 'Hello Node', function (err) {
      if (err) throw err;
      console.log('It\'s saved!');
    });

    fs.writeFileSync(filename, data, [options])#

    The synchronous version of fs.writeFile.

    fs.appendFile(filename, data, [options], callback)#

    • filename String
    • data String | Buffer
    • options Object
      • encoding String | Null default = 'utf8'
      • mode Number default = 438 (aka 0666 in Octal)
      • flag String default = 'a'
    • callback Function

    Asynchronously append data to a file, creating the file if it not yet exists. data can be a string or a buffer.

    Example:

    fs.appendFile('message.txt', 'data to append', function (err) {
      if (err) throw err;
      console.log('The "data to append" was appended to file!');
    });

    fs.appendFileSync(filename, data, [options])#

    The synchronous version of fs.appendFile.

    fs.watchFile(filename, [options], listener)#

    Stability: 2 - Unstable.  Use fs.watch instead, if possible.

    Watch for changes on filename. The callback listener will be called each time the file is accessed.

    The second argument is optional. The options if provided should be an object containing two members a boolean, persistent, and interval. persistent indicates whether the process should continue to run as long as files are being watched. interval indicates how often the target should be polled, in milliseconds. The default is { persistent: true, interval: 5007 }.

    The listener gets two arguments the current stat object and the previous stat object:

    fs.watchFile('message.text', function (curr, prev) {
      console.log('the current mtime is: ' + curr.mtime);
      console.log('the previous mtime was: ' + prev.mtime);
    });

    These stat objects are instances of fs.Stat.

    If you want to be notified when the file was modified, not just accessed you need to compare curr.mtime and prev.mtime.

    fs.unwatchFile(filename, [listener])#

    Stability: 2 - Unstable.  Use fs.watch instead, if possible.

    Stop watching for changes on filename. If listener is specified, only that particular listener is removed. Otherwise, all listeners are removed and you have effectively stopped watching filename.

    Calling fs.unwatchFile() with a filename that is not being watched is a no-op, not an error.

    fs.watch(filename, [options], [listener])#

    Stability: 2 - Unstable.

    Watch for changes on filename, where filename is either a file or a directory. The returned object is a fs.FSWatcher.

    The second argument is optional. The options if provided should be an object containing a boolean member persistent, which indicates whether the process should continue to run as long as files are being watched. The default is { persistent: true }.

    The listener callback gets two arguments (event, filename). event is either 'rename' or 'change', and filename is the name of the file which triggered the event.

    Caveats#

    The fs.watch API is not 100% consistent across platforms, and is unavailable in some situations.

    Availability#

    This feature depends on the underlying operating system providing a way to be notified of filesystem changes.

    • On Linux systems, this uses inotify.
    • On BSD systems (including OS X), this uses kqueue.
    • On SunOS systems (including Solaris and SmartOS), this uses event ports.
    • On Windows systems, this feature depends on ReadDirectoryChangesW.

    If the underlying functionality is not available for some reason, then fs.watch will not be able to function. For example, watching files or directories on network file systems (NFS, SMB, etc.) often doesn't work reliably or at all.

    You can still use fs.watchFile, which uses stat polling, but it is slower and less reliable.

    Filename Argument#

    Providing filename argument in the callback is not supported on every platform (currently it's only supported on Linux and Windows). Even on supported platforms filename is not always guaranteed to be provided. Therefore, don't assume that filename argument is always provided in the callback, and have some fallback logic if it is null.

    fs.watch('somedir', function (event, filename) {
      console.log('event is: ' + event);
      if (filename) {
        console.log('filename provided: ' + filename);
      } else {
        console.log('filename not provided');
      }
    });

    fs.exists(path, callback)#

    Test whether or not the given path exists by checking with the file system. Then call the callback argument with either true or false. Example:

    fs.exists('/etc/passwd', function (exists) {
      util.debug(exists ? "it's there" : "no passwd!");
    });

    fs.exists() is an anachronism and exists only for historical reasons. There should almost never be a reason to use it in your own code.

    In particular, checking if a file exists before opening it is an anti-pattern that leaves you vulnerable to race conditions: another process may remove the file between the calls to fs.exists() and fs.open(). Just open the file and handle the error when it's not there.

    fs.existsSync(path)#

    Synchronous version of fs.exists.

    Class: fs.Stats#

    Objects returned from fs.stat(), fs.lstat() and fs.fstat() and their synchronous counterparts are of this type.

    • stats.isFile()
    • stats.isDirectory()
    • stats.isBlockDevice()
    • stats.isCharacterDevice()
    • stats.isSymbolicLink() (only valid with fs.lstat())
    • stats.isFIFO()
    • stats.isSocket()

    For a regular file util.inspect(stats) would return a string very similar to this:

    { dev: 2114,
      ino: 48064969,
      mode: 33188,
      nlink: 1,
      uid: 85,
      gid: 100,
      rdev: 0,
      size: 527,
      blksize: 4096,
      blocks: 8,
      atime: Mon, 10 Oct 2011 23:24:11 GMT,
      mtime: Mon, 10 Oct 2011 23:24:11 GMT,
      ctime: Mon, 10 Oct 2011 23:24:11 GMT }

    Please note that atime, mtime and ctime are instances of Date object and to compare the values of these objects you should use appropriate methods. For most general uses getTime() will return the number of milliseconds elapsed since 1 January 1970 00:00:00 UTC and this integer should be sufficient for any comparison, however there additional methods which can be used for displaying fuzzy information. More details can be found in the MDN JavaScript Reference page.

    fs.createReadStream(path, [options])#

    Returns a new ReadStream object (See Readable Stream).

    options is an object with the following defaults:

    { flags: 'r',
      encoding: null,
      fd: null,
      mode: 0666,
      autoClose: true
    }

    options can include start and end values to read a range of bytes from the file instead of the entire file. Both start and end are inclusive and start at 0. The encoding can be 'utf8', 'ascii', or 'base64'.

    If autoClose is false, then the file descriptor won't be closed, even if there's an error. It is your responsiblity to close it and make sure there's no file descriptor leak. If autoClose is set to true (default behavior), on error or end the file descriptor will be closed automatically.

    An example to read the last 10 bytes of a file which is 100 bytes long:

    fs.createReadStream('sample.txt', {start: 90, end: 99});

    Class: fs.ReadStream#

    ReadStream is a Readable Stream.

    Event: 'open'#

    • fd Integer file descriptor used by the ReadStream.

    Emitted when the ReadStream's file is opened.

    fs.createWriteStream(path, [options])#

    Returns a new WriteStream object (See Writable Stream).

    options is an object with the following defaults:

    { flags: 'w',
      encoding: null,
      mode: 0666 }

    options may also include a start option to allow writing data at some position past the beginning of the file. Modifying a file rather than replacing it may require a flags mode of r+ rather than the default mode w.

    Class: fs.WriteStream#

    WriteStream is a Writable Stream.

    Event: 'open'#

    • fd Integer file descriptor used by the WriteStream.

    Emitted when the WriteStream's file is opened.

    file.bytesWritten#

    The number of bytes written so far. Does not include data that is still queued for writing.

    Class: fs.FSWatcher#

    Objects returned from fs.watch() are of this type.

    watcher.close()#

    Stop watching for changes on the given fs.FSWatcher.

    Event: 'change'#

    • event String The type of fs change
    • filename String The filename that changed (if relevant/available)

    Emitted when something changes in a watched directory or file. See more details in fs.watch.

    Event: 'error'#

    • error Error object

    Emitted when an error occurs.

    node-v0.10.25~dfsg2/doc/api/process.html0000644000000000000000000007445612270264601016516 0ustar rootroot process Node.js v0.10.25 Manual & Documentation

    Node.js v0.10.25 Manual & Documentation


    process#

    The process object is a global object and can be accessed from anywhere. It is an instance of EventEmitter.

    Event: 'exit'#

    Emitted when the process is about to exit. There is no way to prevent the exiting of the event loop at this point, and once all exit listeners have finished running the process will exit. Therefore you must only perform synchronous operations in this handler. This is a good hook to perform checks on the module's state (like for unit tests). The callback takes one argument, the code the process is exiting with.

    Example of listening for exit:

    process.on('exit', function(code) {
      // do *NOT* do this
      setTimeout(function() {
        console.log('This will not run');
      }, 0);
      console.log('About to exit with code:', code);
    });

    Event: 'uncaughtException'#

    Emitted when an exception bubbles all the way back to the event loop. If a listener is added for this exception, the default action (which is to print a stack trace and exit) will not occur.

    Example of listening for uncaughtException:

    process.on('uncaughtException', function(err) {
      console.log('Caught exception: ' + err);
    });
    
    setTimeout(function() {
      console.log('This will still run.');
    }, 500);
    
    // Intentionally cause an exception, but don't catch it.
    nonexistentFunc();
    console.log('This will not run.');

    Note that uncaughtException is a very crude mechanism for exception handling and may be removed in the future.

    Don't use it, use domains instead. If you do use it, restart your application after every unhandled exception!

    Do not use it as the node.js equivalent of On Error Resume Next. An unhandled exception means your application - and by extension node.js itself - is in an undefined state. Blindly resuming means anything could happen.

    Think of resuming as pulling the power cord when you are upgrading your system. Nine out of ten times nothing happens - but the 10th time, your system is bust.

    You have been warned.

    Signal Events#

    Emitted when the processes receives a signal. See sigaction(2) for a list of standard POSIX signal names such as SIGINT, SIGHUP, etc.

    Example of listening for SIGINT:

    // Start reading from stdin so we don't exit.
    process.stdin.resume();
    
    process.on('SIGINT', function() {
      console.log('Got SIGINT.  Press Control-D to exit.');
    });

    An easy way to send the SIGINT signal is with Control-C in most terminal programs.

    Note:

    • SIGUSR1 is reserved by node.js to start the debugger. It's possible to install a listener but that won't stop the debugger from starting.
    • SIGTERM and SIGINT have default handlers on non-Windows platforms that resets the terminal mode before exiting with code 128 + signal number. If one of these signals has a listener installed, its default behaviour will be removed (node will no longer exit).
    • SIGPIPE is ignored by default, it can have a listener installed.
    • SIGHUP is generated on Windows when the console window is closed, and on other platforms under various similar conditions, see signal(7). It can have a listener installed, however node will be unconditionally terminated by Windows about 10 seconds later. On non-Windows platforms, the default behaviour of SIGHUP is to terminate node, but once a listener has been installed its default behaviour will be removed.
    • SIGTERM is not supported on Windows, it can be listened on.
    • SIGINT from the terminal is supported on all platforms, and can usually be generated with CTRL+C (though this may be configurable). It is not generated when terminal raw mode is enabled.
    • SIGBREAK is delivered on Windows when CTRL+BREAK is pressed, on non-Windows platforms it can be listened on, but there is no way to send or generate it.
    • SIGWINCH is delivered when the console has been resized. On Windows, this will only happen on write to the console when the cursor is being moved, or when a readable tty is used in raw mode.
    • SIGKILL cannot have a listener installed, it will unconditionally terminate node on all platforms.
    • SIGSTOP cannot have a listener installed.

    Note that Windows does not support sending Signals, but node offers some emulation with process.kill(), and child_process.kill(): - Sending signal 0 can be used to search for the existence of a process - Sending SIGINT, SIGTERM, and SIGKILL cause the unconditional exit of the target process.

    process.stdout#

    A Writable Stream to stdout.

    Example: the definition of console.log

    console.log = function(d) {
      process.stdout.write(d + '\n');
    };

    process.stderr and process.stdout are unlike other streams in Node in that writes to them are usually blocking. They are blocking in the case that they refer to regular files or TTY file descriptors. In the case they refer to pipes, they are non-blocking like other streams.

    To check if Node is being run in a TTY context, read the isTTY property on process.stderr, process.stdout, or process.stdin:

    $ node -p "Boolean(process.stdin.isTTY)"
    true
    $ echo "foo" | node -p "Boolean(process.stdin.isTTY)"
    false
    
    $ node -p "Boolean(process.stdout.isTTY)"
    true
    $ node -p "Boolean(process.stdout.isTTY)" | cat
    false

    See the tty docs for more information.

    process.stderr#

    A writable stream to stderr.

    process.stderr and process.stdout are unlike other streams in Node in that writes to them are usually blocking. They are blocking in the case that they refer to regular files or TTY file descriptors. In the case they refer to pipes, they are non-blocking like other streams.

    process.stdin#

    A Readable Stream for stdin. The stdin stream is paused by default, so one must call process.stdin.resume() to read from it.

    Example of opening standard input and listening for both events:

    process.stdin.resume();
    process.stdin.setEncoding('utf8');
    
    process.stdin.on('data', function(chunk) {
      process.stdout.write('data: ' + chunk);
    });
    
    process.stdin.on('end', function() {
      process.stdout.write('end');
    });

    process.argv#

    An array containing the command line arguments. The first element will be 'node', the second element will be the name of the JavaScript file. The next elements will be any additional command line arguments.

    // print process.argv
    process.argv.forEach(function(val, index, array) {
      console.log(index + ': ' + val);
    });

    This will generate:

    $ node process-2.js one two=three four
    0: node
    1: /Users/mjr/work/node/process-2.js
    2: one
    3: two=three
    4: four

    process.execPath#

    This is the absolute pathname of the executable that started the process.

    Example:

    /usr/local/bin/node

    process.execArgv#

    This is the set of node-specific command line options from the executable that started the process. These options do not show up in process.argv, and do not include the node executable, the name of the script, or any options following the script name. These options are useful in order to spawn child processes with the same execution environment as the parent.

    Example:

    $ node --harmony script.js --version

    results in process.execArgv:

    ['--harmony']

    and process.argv:

    ['/usr/local/bin/node', 'script.js', '--version']

    process.abort()#

    This causes node to emit an abort. This will cause node to exit and generate a core file.

    process.chdir(directory)#

    Changes the current working directory of the process or throws an exception if that fails.

    console.log('Starting directory: ' + process.cwd());
    try {
      process.chdir('/tmp');
      console.log('New directory: ' + process.cwd());
    }
    catch (err) {
      console.log('chdir: ' + err);
    }

    process.cwd()#

    Returns the current working directory of the process.

    console.log('Current directory: ' + process.cwd());

    process.env#

    An object containing the user environment. See environ(7).

    process.exit([code])#

    Ends the process with the specified code. If omitted, exit uses the 'success' code 0.

    To exit with a 'failure' code:

    process.exit(1);

    The shell that executed node should see the exit code as 1.

    process.getgid()#

    Note: this function is only available on POSIX platforms (i.e. not Windows)

    Gets the group identity of the process. (See getgid(2).) This is the numerical group id, not the group name.

    if (process.getgid) {
      console.log('Current gid: ' + process.getgid());
    }

    process.setgid(id)#

    Note: this function is only available on POSIX platforms (i.e. not Windows)

    Sets the group identity of the process. (See setgid(2).) This accepts either a numerical ID or a groupname string. If a groupname is specified, this method blocks while resolving it to a numerical ID.

    if (process.getgid && process.setgid) {
      console.log('Current gid: ' + process.getgid());
      try {
        process.setgid(501);
        console.log('New gid: ' + process.getgid());
      }
      catch (err) {
        console.log('Failed to set gid: ' + err);
      }
    }

    process.getuid()#

    Note: this function is only available on POSIX platforms (i.e. not Windows)

    Gets the user identity of the process. (See getuid(2).) This is the numerical userid, not the username.

    if (process.getuid) {
      console.log('Current uid: ' + process.getuid());
    }

    process.setuid(id)#

    Note: this function is only available on POSIX platforms (i.e. not Windows)

    Sets the user identity of the process. (See setuid(2).) This accepts either a numerical ID or a username string. If a username is specified, this method blocks while resolving it to a numerical ID.

    if (process.getuid && process.setuid) {
      console.log('Current uid: ' + process.getuid());
      try {
        process.setuid(501);
        console.log('New uid: ' + process.getuid());
      }
      catch (err) {
        console.log('Failed to set uid: ' + err);
      }
    }

    process.getgroups()#

    Note: this function is only available on POSIX platforms (i.e. not Windows)

    Returns an array with the supplementary group IDs. POSIX leaves it unspecified if the effective group ID is included but node.js ensures it always is.

    process.setgroups(groups)#

    Note: this function is only available on POSIX platforms (i.e. not Windows)

    Sets the supplementary group IDs. This is a privileged operation, meaning you need to be root or have the CAP_SETGID capability.

    The list can contain group IDs, group names or both.

    process.initgroups(user, extra_group)#

    Note: this function is only available on POSIX platforms (i.e. not Windows)

    Reads /etc/group and initializes the group access list, using all groups of which the user is a member. This is a privileged operation, meaning you need to be root or have the CAP_SETGID capability.

    user is a user name or user ID. extra_group is a group name or group ID.

    Some care needs to be taken when dropping privileges. Example:

    console.log(process.getgroups());         // [ 0 ]
    process.initgroups('bnoordhuis', 1000);   // switch user
    console.log(process.getgroups());         // [ 27, 30, 46, 1000, 0 ]
    process.setgid(1000);                     // drop root gid
    console.log(process.getgroups());         // [ 27, 30, 46, 1000 ]

    process.version#

    A compiled-in property that exposes NODE_VERSION.

    console.log('Version: ' + process.version);

    process.versions#

    A property exposing version strings of node and its dependencies.

    console.log(process.versions);

    Will print something like:

    { http_parser: '1.0',
      node: '0.10.4',
      v8: '3.14.5.8',
      ares: '1.9.0-DEV',
      uv: '0.10.3',
      zlib: '1.2.3',
      modules: '11',
      openssl: '1.0.1e' }

    process.config#

    An Object containing the JavaScript representation of the configure options that were used to compile the current node executable. This is the same as the "config.gypi" file that was produced when running the ./configure script.

    An example of the possible output looks like:

    { target_defaults:
       { cflags: [],
         default_configuration: 'Release',
         defines: [],
         include_dirs: [],
         libraries: [] },
      variables:
       { host_arch: 'x64',
         node_install_npm: 'true',
         node_prefix: '',
         node_shared_cares: 'false',
         node_shared_http_parser: 'false',
         node_shared_libuv: 'false',
         node_shared_v8: 'false',
         node_shared_zlib: 'false',
         node_use_dtrace: 'false',
         node_use_openssl: 'true',
         node_shared_openssl: 'false',
         strict_aliasing: 'true',
         target_arch: 'x64',
         v8_use_snapshot: 'true' } }

    process.kill(pid, [signal])#

    Send a signal to a process. pid is the process id and signal is the string describing the signal to send. Signal names are strings like 'SIGINT' or 'SIGHUP'. If omitted, the signal will be 'SIGTERM'. See Signal Events and kill(2) for more information.

    Will throw an error if target does not exist, and as a special case, a signal of 0 can be used to test for the existence of a process.

    Note that just because the name of this function is process.kill, it is really just a signal sender, like the kill system call. The signal sent may do something other than kill the target process.

    Example of sending a signal to yourself:

    process.on('SIGHUP', function() {
      console.log('Got SIGHUP signal.');
    });
    
    setTimeout(function() {
      console.log('Exiting.');
      process.exit(0);
    }, 100);
    
    process.kill(process.pid, 'SIGHUP');

    Note: When SIGUSR1 is received by Node.js it starts the debugger, see Signal Events.

    process.pid#

    The PID of the process.

    console.log('This process is pid ' + process.pid);

    process.title#

    Getter/setter to set what is displayed in 'ps'.

    When used as a setter, the maximum length is platform-specific and probably short.

    On Linux and OS X, it's limited to the size of the binary name plus the length of the command line arguments because it overwrites the argv memory.

    v0.8 allowed for longer process title strings by also overwriting the environ memory but that was potentially insecure/confusing in some (rather obscure) cases.

    process.arch#

    What processor architecture you're running on: 'arm', 'ia32', or 'x64'.

    console.log('This processor architecture is ' + process.arch);

    process.platform#

    What platform you're running on: 'darwin', 'freebsd', 'linux', 'sunos' or 'win32'

    console.log('This platform is ' + process.platform);

    process.memoryUsage()#

    Returns an object describing the memory usage of the Node process measured in bytes.

    var util = require('util');
    
    console.log(util.inspect(process.memoryUsage()));

    This will generate:

    { rss: 4935680,
      heapTotal: 1826816,
      heapUsed: 650472 }

    heapTotal and heapUsed refer to V8's memory usage.

    process.nextTick(callback)#

    On the next loop around the event loop call this callback. This is not a simple alias to setTimeout(fn, 0), it's much more efficient. It typically runs before any other I/O events fire, but there are some exceptions. See process.maxTickDepth below.

    process.nextTick(function() {
      console.log('nextTick callback');
    });

    This is important in developing APIs where you want to give the user the chance to assign event handlers after an object has been constructed, but before any I/O has occurred.

    function MyThing(options) {
      this.setupOptions(options);
    
      process.nextTick(function() {
        this.startDoingStuff();
      }.bind(this));
    }
    
    var thing = new MyThing();
    thing.getReadyForStuff();
    
    // thing.startDoingStuff() gets called now, not before.

    It is very important for APIs to be either 100% synchronous or 100% asynchronous. Consider this example:

    // WARNING!  DO NOT USE!  BAD UNSAFE HAZARD!
    function maybeSync(arg, cb) {
      if (arg) {
        cb();
        return;
      }
    
      fs.stat('file', cb);
    }

    This API is hazardous. If you do this:

    maybeSync(true, function() {
      foo();
    });
    bar();

    then it's not clear whether foo() or bar() will be called first.

    This approach is much better:

    function definitelyAsync(arg, cb) {
      if (arg) {
        process.nextTick(cb);
        return;
      }
    
      fs.stat('file', cb);
    }

    process.maxTickDepth#

    • Number Default = 1000

    Callbacks passed to process.nextTick will usually be called at the end of the current flow of execution, and are thus approximately as fast as calling a function synchronously. Left unchecked, this would starve the event loop, preventing any I/O from occurring.

    Consider this code:

    process.nextTick(function foo() {
      process.nextTick(foo);
    });

    In order to avoid the situation where Node is blocked by an infinite loop of recursive series of nextTick calls, it defers to allow some I/O to be done every so often.

    The process.maxTickDepth value is the maximum depth of nextTick-calling nextTick-callbacks that will be evaluated before allowing other forms of I/O to occur.

    process.umask([mask])#

    Sets or reads the process's file mode creation mask. Child processes inherit the mask from the parent process. Returns the old mask if mask argument is given, otherwise returns the current mask.

    var oldmask, newmask = 0644;
    
    oldmask = process.umask(newmask);
    console.log('Changed umask from: ' + oldmask.toString(8) +
                ' to ' + newmask.toString(8));

    process.uptime()#

    Number of seconds Node has been running.

    process.hrtime()#

    Returns the current high-resolution real time in a [seconds, nanoseconds] tuple Array. It is relative to an arbitrary time in the past. It is not related to the time of day and therefore not subject to clock drift. The primary use is for measuring performance between intervals.

    You may pass in the result of a previous call to process.hrtime() to get a diff reading, useful for benchmarks and measuring intervals:

    var time = process.hrtime();
    // [ 1800216, 25 ]
    
    setTimeout(function() {
      var diff = process.hrtime(time);
      // [ 1, 552 ]
    
      console.log('benchmark took %d nanoseconds', diff[0] * 1e9 + diff[1]);
      // benchmark took 1000000527 nanoseconds
    }, 1000);
    node-v0.10.25~dfsg2/doc/api/documentation.markdown0000644000000000000000000000520612270121457020553 0ustar rootroot# About this Documentation The goal of this documentation is to comprehensively explain the Node.js API, both from a reference as well as a conceptual point of view. Each section describes a built-in module or high-level concept. Where appropriate, property types, method arguments, and the arguments provided to event handlers are detailed in a list underneath the topic heading. Every `.html` document has a corresponding `.json` document presenting the same information in a structured manner. This feature is experimental, and added for the benefit of IDEs and other utilities that wish to do programmatic things with the documentation. Every `.html` and `.json` file is generated based on the corresponding `.markdown` file in the `doc/api/` folder in node's source tree. The documentation is generated using the `tools/doc/generate.js` program. The HTML template is located at `doc/template.html`. ## Stability Index Throughout the documentation, you will see indications of a section's stability. The Node.js API is still somewhat changing, and as it matures, certain parts are more reliable than others. Some are so proven, and so relied upon, that they are unlikely to ever change at all. Others are brand new and experimental, or known to be hazardous and in the process of being redesigned. The stability indices are as follows: ``` Stability: 0 - Deprecated This feature is known to be problematic, and changes are planned. Do not rely on it. Use of the feature may cause warnings. Backwards compatibility should not be expected. ``` ``` Stability: 1 - Experimental This feature was introduced recently, and may change or be removed in future versions. Please try it out and provide feedback. If it addresses a use-case that is important to you, tell the node core team. ``` ``` Stability: 2 - Unstable The API is in the process of settling, but has not yet had sufficient real-world testing to be considered stable. Backwards-compatibility will be maintained if reasonable. ``` ``` Stability: 3 - Stable The API has proven satisfactory, but cleanup in the underlying code may cause minor changes. Backwards-compatibility is guaranteed. ``` ``` Stability: 4 - API Frozen This API has been tested extensively in production and is unlikely to ever have to change. ``` ``` Stability: 5 - Locked Unless serious bugs are found, this code will not ever change. Please do not suggest changes in this area; they will be refused. ``` ## JSON Output Stability: 1 - Experimental Every HTML file in the markdown has a corresponding JSON file with the same data. This feature is new as of node v0.6.12. It is experimental. node-v0.10.25~dfsg2/doc/api/tls.markdown0000644000000000000000000004702512270121457016511 0ustar rootroot# TLS (SSL) Stability: 3 - Stable Use `require('tls')` to access this module. The `tls` module uses OpenSSL to provide Transport Layer Security and/or Secure Socket Layer: encrypted stream communication. TLS/SSL is a public/private key infrastructure. Each client and each server must have a private key. A private key is created like this openssl genrsa -out ryans-key.pem 1024 All severs and some clients need to have a certificate. Certificates are public keys signed by a Certificate Authority or self-signed. The first step to getting a certificate is to create a "Certificate Signing Request" (CSR) file. This is done with: openssl req -new -key ryans-key.pem -out ryans-csr.pem To create a self-signed certificate with the CSR, do this: openssl x509 -req -in ryans-csr.pem -signkey ryans-key.pem -out ryans-cert.pem Alternatively you can send the CSR to a Certificate Authority for signing. (TODO: docs on creating a CA, for now interested users should just look at `test/fixtures/keys/Makefile` in the Node source code) To create .pfx or .p12, do this: openssl pkcs12 -export -in agent5-cert.pem -inkey agent5-key.pem \ -certfile ca-cert.pem -out agent5.pfx - `in`: certificate - `inkey`: private key - `certfile`: all CA certs concatenated in one file like `cat ca1-cert.pem ca2-cert.pem > ca-cert.pem` ## Client-initiated renegotiation attack mitigation The TLS protocol lets the client renegotiate certain aspects of the TLS session. Unfortunately, session renegotiation requires a disproportional amount of server-side resources, which makes it a potential vector for denial-of-service attacks. To mitigate this, renegotiations are limited to three times every 10 minutes. An error is emitted on the [CleartextStream][] instance when the threshold is exceeded. The limits are configurable: - `tls.CLIENT_RENEG_LIMIT`: renegotiation limit, default is 3. - `tls.CLIENT_RENEG_WINDOW`: renegotiation window in seconds, default is 10 minutes. Don't change the defaults unless you know what you are doing. To test your server, connect to it with `openssl s_client -connect address:port` and tap `R` (that's the letter `R` followed by a carriage return) a few times. ## NPN and SNI NPN (Next Protocol Negotiation) and SNI (Server Name Indication) are TLS handshake extensions allowing you: * NPN - to use one TLS server for multiple protocols (HTTP, SPDY) * SNI - to use one TLS server for multiple hostnames with different SSL certificates. ## tls.getCiphers() Returns an array with the names of the supported SSL ciphers. Example: var ciphers = tls.getCiphers(); console.log(ciphers); // ['AES128-SHA', 'AES256-SHA', ...] ## tls.createServer(options, [secureConnectionListener]) Creates a new [tls.Server][]. The `connectionListener` argument is automatically set as a listener for the [secureConnection][] event. The `options` object has these possibilities: - `pfx`: A string or `Buffer` containing the private key, certificate and CA certs of the server in PFX or PKCS12 format. (Mutually exclusive with the `key`, `cert` and `ca` options.) - `key`: A string or `Buffer` containing the private key of the server in PEM format. (Required) - `passphrase`: A string of passphrase for the private key or pfx. - `cert`: A string or `Buffer` containing the certificate key of the server in PEM format. (Required) - `ca`: An array of strings or `Buffer`s of trusted certificates in PEM format. If this is omitted several well known "root" CAs will be used, like VeriSign. These are used to authorize connections. - `crl` : Either a string or list of strings of PEM encoded CRLs (Certificate Revocation List) - `ciphers`: A string describing the ciphers to use or exclude. To mitigate [BEAST attacks] it is recommended that you use this option in conjunction with the `honorCipherOrder` option described below to prioritize the non-CBC cipher. Defaults to `AES128-GCM-SHA256:RC4:HIGH:!MD5:!aNULL:!EDH`. Consult the [OpenSSL cipher list format documentation] for details on the format. ECDH (Elliptic Curve Diffie-Hellman) ciphers are not yet supported. `AES128-GCM-SHA256` is used when node.js is linked against OpenSSL 1.0.1 or newer and the client speaks TLS 1.2, RC4 is used as a secure fallback. **NOTE**: Previous revisions of this section suggested `AES256-SHA` as an acceptable cipher. Unfortunately, `AES256-SHA` is a CBC cipher and therefore susceptible to BEAST attacks. Do *not* use it. - `handshakeTimeout`: Abort the connection if the SSL/TLS handshake does not finish in this many milliseconds. The default is 120 seconds. A `'clientError'` is emitted on the `tls.Server` object whenever a handshake times out. - `honorCipherOrder` : When choosing a cipher, use the server's preferences instead of the client preferences. Note that if SSLv2 is used, the server will send its list of preferences to the client, and the client chooses the cipher. Although, this option is disabled by default, it is *recommended* that you use this option in conjunction with the `ciphers` option to mitigate BEAST attacks. - `requestCert`: If `true` the server will request a certificate from clients that connect and attempt to verify that certificate. Default: `false`. - `rejectUnauthorized`: If `true` the server will reject any connection which is not authorized with the list of supplied CAs. This option only has an effect if `requestCert` is `true`. Default: `false`. - `NPNProtocols`: An array or `Buffer` of possible NPN protocols. (Protocols should be ordered by their priority). - `SNICallback`: A function that will be called if client supports SNI TLS extension. Only one argument will be passed to it: `servername`. And `SNICallback` should return SecureContext instance. (You can use `crypto.createCredentials(...).context` to get proper SecureContext). If `SNICallback` wasn't provided - default callback with high-level API will be used (see below). - `sessionIdContext`: A string containing a opaque identifier for session resumption. If `requestCert` is `true`, the default is MD5 hash value generated from command-line. Otherwise, the default is not provided. - `secureProtocol`: The SSL method to use, e.g. `SSLv3_method` to force SSL version 3. The possible values depend on your installation of OpenSSL and are defined in the constant [SSL_METHODS][]. Here is a simple example echo server: var tls = require('tls'); var fs = require('fs'); var options = { key: fs.readFileSync('server-key.pem'), cert: fs.readFileSync('server-cert.pem'), // This is necessary only if using the client certificate authentication. requestCert: true, // This is necessary only if the client uses the self-signed certificate. ca: [ fs.readFileSync('client-cert.pem') ] }; var server = tls.createServer(options, function(cleartextStream) { console.log('server connected', cleartextStream.authorized ? 'authorized' : 'unauthorized'); cleartextStream.write("welcome!\n"); cleartextStream.setEncoding('utf8'); cleartextStream.pipe(cleartextStream); }); server.listen(8000, function() { console.log('server bound'); }); Or var tls = require('tls'); var fs = require('fs'); var options = { pfx: fs.readFileSync('server.pfx'), // This is necessary only if using the client certificate authentication. requestCert: true, }; var server = tls.createServer(options, function(cleartextStream) { console.log('server connected', cleartextStream.authorized ? 'authorized' : 'unauthorized'); cleartextStream.write("welcome!\n"); cleartextStream.setEncoding('utf8'); cleartextStream.pipe(cleartextStream); }); server.listen(8000, function() { console.log('server bound'); }); You can test this server by connecting to it with `openssl s_client`: openssl s_client -connect 127.0.0.1:8000 ## tls.SLAB_BUFFER_SIZE Size of slab buffer used by all tls servers and clients. Default: `10 * 1024 * 1024`. Don't change the defaults unless you know what you are doing. ## tls.connect(options, [callback]) ## tls.connect(port, [host], [options], [callback]) Creates a new client connection to the given `port` and `host` (old API) or `options.port` and `options.host`. (If `host` is omitted, it defaults to `localhost`.) `options` should be an object which specifies: - `host`: Host the client should connect to - `port`: Port the client should connect to - `socket`: Establish secure connection on a given socket rather than creating a new socket. If this option is specified, `host` and `port` are ignored. - `pfx`: A string or `Buffer` containing the private key, certificate and CA certs of the server in PFX or PKCS12 format. - `key`: A string or `Buffer` containing the private key of the client in PEM format. - `passphrase`: A string of passphrase for the private key or pfx. - `cert`: A string or `Buffer` containing the certificate key of the client in PEM format. - `ca`: An array of strings or `Buffer`s of trusted certificates in PEM format. If this is omitted several well known "root" CAs will be used, like VeriSign. These are used to authorize connections. - `rejectUnauthorized`: If `true`, the server certificate is verified against the list of supplied CAs. An `'error'` event is emitted if verification fails. Default: `true`. - `NPNProtocols`: An array of strings or `Buffer`s containing supported NPN protocols. `Buffer`s should have following format: `0x05hello0x05world`, where first byte is next protocol name's length. (Passing array should usually be much simpler: `['hello', 'world']`.) - `servername`: Servername for SNI (Server Name Indication) TLS extension. - `secureProtocol`: The SSL method to use, e.g. `SSLv3_method` to force SSL version 3. The possible values depend on your installation of OpenSSL and are defined in the constant [SSL_METHODS][]. The `callback` parameter will be added as a listener for the ['secureConnect'][] event. `tls.connect()` returns a [CleartextStream][] object. Here is an example of a client of echo server as described previously: var tls = require('tls'); var fs = require('fs'); var options = { // These are necessary only if using the client certificate authentication key: fs.readFileSync('client-key.pem'), cert: fs.readFileSync('client-cert.pem'), // This is necessary only if the server uses the self-signed certificate ca: [ fs.readFileSync('server-cert.pem') ] }; var cleartextStream = tls.connect(8000, options, function() { console.log('client connected', cleartextStream.authorized ? 'authorized' : 'unauthorized'); process.stdin.pipe(cleartextStream); process.stdin.resume(); }); cleartextStream.setEncoding('utf8'); cleartextStream.on('data', function(data) { console.log(data); }); cleartextStream.on('end', function() { server.close(); }); Or var tls = require('tls'); var fs = require('fs'); var options = { pfx: fs.readFileSync('client.pfx') }; var cleartextStream = tls.connect(8000, options, function() { console.log('client connected', cleartextStream.authorized ? 'authorized' : 'unauthorized'); process.stdin.pipe(cleartextStream); process.stdin.resume(); }); cleartextStream.setEncoding('utf8'); cleartextStream.on('data', function(data) { console.log(data); }); cleartextStream.on('end', function() { server.close(); }); ## tls.createSecurePair([credentials], [isServer], [requestCert], [rejectUnauthorized]) Creates a new secure pair object with two streams, one of which reads/writes encrypted data, and one reads/writes cleartext data. Generally the encrypted one is piped to/from an incoming encrypted data stream, and the cleartext one is used as a replacement for the initial encrypted stream. - `credentials`: A credentials object from crypto.createCredentials( ... ) - `isServer`: A boolean indicating whether this tls connection should be opened as a server or a client. - `requestCert`: A boolean indicating whether a server should request a certificate from a connecting client. Only applies to server connections. - `rejectUnauthorized`: A boolean indicating whether a server should automatically reject clients with invalid certificates. Only applies to servers with `requestCert` enabled. `tls.createSecurePair()` returns a SecurePair object with [cleartext][] and `encrypted` stream properties. ## Class: SecurePair Returned by tls.createSecurePair. ### Event: 'secure' The event is emitted from the SecurePair once the pair has successfully established a secure connection. Similarly to the checking for the server 'secureConnection' event, pair.cleartext.authorized should be checked to confirm whether the certificate used properly authorized. ## Class: tls.Server This class is a subclass of `net.Server` and has the same methods on it. Instead of accepting just raw TCP connections, this accepts encrypted connections using TLS or SSL. ### Event: 'secureConnection' `function (cleartextStream) {}` This event is emitted after a new connection has been successfully handshaked. The argument is a instance of [CleartextStream][]. It has all the common stream methods and events. `cleartextStream.authorized` is a boolean value which indicates if the client has verified by one of the supplied certificate authorities for the server. If `cleartextStream.authorized` is false, then `cleartextStream.authorizationError` is set to describe how authorization failed. Implied but worth mentioning: depending on the settings of the TLS server, you unauthorized connections may be accepted. `cleartextStream.npnProtocol` is a string containing selected NPN protocol. `cleartextStream.servername` is a string containing servername requested with SNI. ### Event: 'clientError' `function (exception, securePair) { }` When a client connection emits an 'error' event before secure connection is established - it will be forwarded here. `securePair` is the `tls.SecurePair` that the error originated from. ### Event: 'newSession' `function (sessionId, sessionData) { }` Emitted on creation of TLS session. May be used to store sessions in external storage. ### Event: 'resumeSession' `function (sessionId, callback) { }` Emitted when client wants to resume previous TLS session. Event listener may perform lookup in external storage using given `sessionId`, and invoke `callback(null, sessionData)` once finished. If session can't be resumed (i.e. doesn't exist in storage) one may call `callback(null, null)`. Calling `callback(err)` will terminate incoming connection and destroy socket. ### server.listen(port, [host], [callback]) Begin accepting connections on the specified `port` and `host`. If the `host` is omitted, the server will accept connections directed to any IPv4 address (`INADDR_ANY`). This function is asynchronous. The last parameter `callback` will be called when the server has been bound. See `net.Server` for more information. ### server.close() Stops the server from accepting new connections. This function is asynchronous, the server is finally closed when the server emits a `'close'` event. ### server.address() Returns the bound address, the address family name and port of the server as reported by the operating system. See [net.Server.address()][] for more information. ### server.addContext(hostname, credentials) Add secure context that will be used if client request's SNI hostname is matching passed `hostname` (wildcards can be used). `credentials` can contain `key`, `cert` and `ca`. ### server.maxConnections Set this property to reject connections when the server's connection count gets high. ### server.connections The number of concurrent connections on the server. ## Class: CryptoStream This is an encrypted stream. ### cryptoStream.bytesWritten A proxy to the underlying socket's bytesWritten accessor, this will return the total bytes written to the socket, *including the TLS overhead*. ## Class: tls.CleartextStream This is a stream on top of the *Encrypted* stream that makes it possible to read/write an encrypted data as a cleartext data. This instance implements a duplex [Stream][] interfaces. It has all the common stream methods and events. A ClearTextStream is the `clear` member of a SecurePair object. ### Event: 'secureConnect' This event is emitted after a new connection has been successfully handshaked. The listener will be called no matter if the server's certificate was authorized or not. It is up to the user to test `cleartextStream.authorized` to see if the server certificate was signed by one of the specified CAs. If `cleartextStream.authorized === false` then the error can be found in `cleartextStream.authorizationError`. Also if NPN was used - you can check `cleartextStream.npnProtocol` for negotiated protocol. ### cleartextStream.authorized A boolean that is `true` if the peer certificate was signed by one of the specified CAs, otherwise `false` ### cleartextStream.authorizationError The reason why the peer's certificate has not been verified. This property becomes available only when `cleartextStream.authorized === false`. ### cleartextStream.getPeerCertificate() Returns an object representing the peer's certificate. The returned object has some properties corresponding to the field of the certificate. Example: { subject: { C: 'UK', ST: 'Acknack Ltd', L: 'Rhys Jones', O: 'node.js', OU: 'Test TLS Certificate', CN: 'localhost' }, issuer: { C: 'UK', ST: 'Acknack Ltd', L: 'Rhys Jones', O: 'node.js', OU: 'Test TLS Certificate', CN: 'localhost' }, valid_from: 'Nov 11 09:52:22 2009 GMT', valid_to: 'Nov 6 09:52:22 2029 GMT', fingerprint: '2A:7A:C2:DD:E5:F9:CC:53:72:35:99:7A:02:5A:71:38:52:EC:8A:DF' } If the peer does not provide a certificate, it returns `null` or an empty object. ### cleartextStream.getCipher() Returns an object representing the cipher name and the SSL/TLS protocol version of the current connection. Example: { name: 'AES256-SHA', version: 'TLSv1/SSLv3' } See SSL_CIPHER_get_name() and SSL_CIPHER_get_version() in http://www.openssl.org/docs/ssl/ssl.html#DEALING_WITH_CIPHERS for more information. ### cleartextStream.address() Returns the bound address, the address family name and port of the underlying socket as reported by the operating system. Returns an object with three properties, e.g. `{ port: 12346, family: 'IPv4', address: '127.0.0.1' }` ### cleartextStream.remoteAddress The string representation of the remote IP address. For example, `'74.125.127.100'` or `'2001:4860:a005::68'`. ### cleartextStream.remotePort The numeric representation of the remote port. For example, `443`. [OpenSSL cipher list format documentation]: http://www.openssl.org/docs/apps/ciphers.html#CIPHER_LIST_FORMAT [BEAST attacks]: http://blog.ivanristic.com/2011/10/mitigating-the-beast-attack-on-tls.html [CleartextStream]: #tls_class_tls_cleartextstream [net.Server.address()]: net.html#net_server_address ['secureConnect']: #tls_event_secureconnect [secureConnection]: #tls_event_secureconnection [Stream]: stream.html#stream_stream [SSL_METHODS]: http://www.openssl.org/docs/ssl/ssl.html#DEALING_WITH_PROTOCOL_METHODS [tls.Server]: #tls_class_tls_server node-v0.10.25~dfsg2/doc/api/globals.markdown0000644000000000000000000001161212270121457017323 0ustar rootroot# Global Objects These objects are available in all modules. Some of these objects aren't actually in the global scope but in the module scope - this will be noted. ## global * {Object} The global namespace object. In browsers, the top-level scope is the global scope. That means that in browsers if you're in the global scope `var something` will define a global variable. In Node this is different. The top-level scope is not the global scope; `var something` inside a Node module will be local to that module. ## process * {Object} The process object. See the [process object][] section. ## console * {Object} Used to print to stdout and stderr. See the [console][] section. ## Class: Buffer * {Function} Used to handle binary data. See the [buffer section][] ## require() * {Function} To require modules. See the [Modules][] section. `require` isn't actually a global but rather local to each module. ### require.resolve() Use the internal `require()` machinery to look up the location of a module, but rather than loading the module, just return the resolved filename. ### require.cache * {Object} Modules are cached in this object when they are required. By deleting a key value from this object, the next `require` will reload the module. ### require.extensions Stability: 0 - Deprecated * {Object} Instruct `require` on how to handle certain file extensions. Process files with the extension `.sjs` as `.js`: require.extensions['.sjs'] = require.extensions['.js']; **Deprecated** In the past, this list has been used to load non-JavaScript modules into Node by compiling them on-demand. However, in practice, there are much better ways to do this, such as loading modules via some other Node program, or compiling them to JavaScript ahead of time. Since the Module system is locked, this feature will probably never go away. However, it may have subtle bugs and complexities that are best left untouched. ## __filename * {String} The filename of the code being executed. This is the resolved absolute path of this code file. For a main program this is not necessarily the same filename used in the command line. The value inside a module is the path to that module file. Example: running `node example.js` from `/Users/mjr` console.log(__filename); // /Users/mjr/example.js `__filename` isn't actually a global but rather local to each module. ## __dirname * {String} The name of the directory that the currently executing script resides in. Example: running `node example.js` from `/Users/mjr` console.log(__dirname); // /Users/mjr `__dirname` isn't actually a global but rather local to each module. ## module * {Object} A reference to the current module. In particular `module.exports` is used for defining what a module exports and makes available through `require()`. `module` isn't actually a global but rather local to each module. See the [module system documentation][] for more information. ## exports A reference to the `module.exports` that is shorter to type. See [module system documentation][] for details on when to use `exports` and when to use `module.exports`. `exports` isn't actually a global but rather local to each module. See the [module system documentation][] for more information. See the [module section][] for more information. ## setTimeout(cb, ms) Run callback `cb` after *at least* `ms` milliseconds. The actual delay depends on external factors like OS timer granularity and system load. The timeout must be in the range of 1-2,147,483,647 inclusive. If the value is outside that range, it's changed to 1 millisecond. Broadly speaking, a timer cannot span more than 24.8 days. Returns an opaque value that represents the timer. ## clearTimeout(t) Stop a timer that was previously created with `setTimeout()`. The callback will not execute. ## setInterval(cb, ms) Run callback `cb` repeatedly every `ms` milliseconds. Note that the actual interval may vary, depending on external factors like OS timer granularity and system load. It's never less than `ms` but it may be longer. The interval must be in the range of 1-2,147,483,647 inclusive. If the value is outside that range, it's changed to 1 millisecond. Broadly speaking, a timer cannot span more than 24.8 days. Returns an opaque value that represents the timer. ## clearInterval(t) Stop a timer that was previously created with `setInterval()`. The callback will not execute. The timer functions are global variables. See the [timers][] section. [buffer section]: buffer.html [module section]: modules.html [module system documentation]: modules.html [Modules]: modules.html#modules_modules [process object]: process.html#process_process [console]: console.html [timers]: timers.html node-v0.10.25~dfsg2/doc/api/repl.markdown0000644000000000000000000001367312270121457016653 0ustar rootroot# REPL A Read-Eval-Print-Loop (REPL) is available both as a standalone program and easily includable in other programs. The REPL provides a way to interactively run JavaScript and see the results. It can be used for debugging, testing, or just trying things out. By executing `node` without any arguments from the command-line you will be dropped into the REPL. It has simplistic emacs line-editing. mjr:~$ node Type '.help' for options. > a = [ 1, 2, 3]; [ 1, 2, 3 ] > a.forEach(function (v) { ... console.log(v); ... }); 1 2 3 For advanced line-editors, start node with the environmental variable `NODE_NO_READLINE=1`. This will start the main and debugger REPL in canonical terminal settings which will allow you to use with `rlwrap`. For example, you could add this to your bashrc file: alias node="env NODE_NO_READLINE=1 rlwrap node" ## repl.start(options) Returns and starts a `REPLServer` instance. Accepts an "options" Object that takes the following values: - `prompt` - the prompt and `stream` for all I/O. Defaults to `> `. - `input` - the readable stream to listen to. Defaults to `process.stdin`. - `output` - the writable stream to write readline data to. Defaults to `process.stdout`. - `terminal` - pass `true` if the `stream` should be treated like a TTY, and have ANSI/VT100 escape codes written to it. Defaults to checking `isTTY` on the `output` stream upon instantiation. - `eval` - function that will be used to eval each given line. Defaults to an async wrapper for `eval()`. See below for an example of a custom `eval`. - `useColors` - a boolean which specifies whether or not the `writer` function should output colors. If a different `writer` function is set then this does nothing. Defaults to the repl's `terminal` value. - `useGlobal` - if set to `true`, then the repl will use the `global` object, instead of running scripts in a separate context. Defaults to `false`. - `ignoreUndefined` - if set to `true`, then the repl will not output the return value of command if it's `undefined`. Defaults to `false`. - `writer` - the function to invoke for each command that gets evaluated which returns the formatting (including coloring) to display. Defaults to `util.inspect`. You can use your own `eval` function if it has following signature: function eval(cmd, context, filename, callback) { callback(null, result); } Multiple REPLs may be started against the same running instance of node. Each will share the same global object but will have unique I/O. Here is an example that starts a REPL on stdin, a Unix socket, and a TCP socket: var net = require("net"), repl = require("repl"); connections = 0; repl.start({ prompt: "node via stdin> ", input: process.stdin, output: process.stdout }); net.createServer(function (socket) { connections += 1; repl.start({ prompt: "node via Unix socket> ", input: socket, output: socket }).on('exit', function() { socket.end(); }) }).listen("/tmp/node-repl-sock"); net.createServer(function (socket) { connections += 1; repl.start({ prompt: "node via TCP socket> ", input: socket, output: socket }).on('exit', function() { socket.end(); }); }).listen(5001); Running this program from the command line will start a REPL on stdin. Other REPL clients may connect through the Unix socket or TCP socket. `telnet` is useful for connecting to TCP sockets, and `socat` can be used to connect to both Unix and TCP sockets. By starting a REPL from a Unix socket-based server instead of stdin, you can connect to a long-running node process without restarting it. For an example of running a "full-featured" (`terminal`) REPL over a `net.Server` and `net.Socket` instance, see: https://gist.github.com/2209310 For an example of running a REPL instance over `curl(1)`, see: https://gist.github.com/2053342 ### Event: 'exit' `function () {}` Emitted when the user exits the REPL in any of the defined ways. Namely, typing `.exit` at the repl, pressing Ctrl+C twice to signal SIGINT, or pressing Ctrl+D to signal "end" on the `input` stream. Example of listening for `exit`: r.on('exit', function () { console.log('Got "exit" event from repl!'); process.exit(); }); ## REPL Features Inside the REPL, Control+D will exit. Multi-line expressions can be input. Tab completion is supported for both global and local variables. The special variable `_` (underscore) contains the result of the last expression. > [ "a", "b", "c" ] [ 'a', 'b', 'c' ] > _.length 3 > _ += 1 4 The REPL provides access to any variables in the global scope. You can expose a variable to the REPL explicitly by assigning it to the `context` object associated with each `REPLServer`. For example: // repl_test.js var repl = require("repl"), msg = "message"; repl.start("> ").context.m = msg; Things in the `context` object appear as local within the REPL: mjr:~$ node repl_test.js > m 'message' There are a few special REPL commands: - `.break` - While inputting a multi-line expression, sometimes you get lost or just don't care about completing it. `.break` will start over. - `.clear` - Resets the `context` object to an empty object and clears any multi-line expression. - `.exit` - Close the I/O stream, which will cause the REPL to exit. - `.help` - Show this list of special commands. - `.save` - Save the current REPL session to a file >.save ./file/to/save.js - `.load` - Load a file into the current REPL session. >.load ./file/to/load.js The following key combinations in the REPL have these special effects: - `C` - Similar to the `.break` keyword. Terminates the current command. Press twice on a blank line to forcibly exit. - `D` - Similar to the `.exit` keyword. node-v0.10.25~dfsg2/doc/api/cluster.json0000644000000000000000000007107712270264601016522 0ustar rootroot{ "source": "doc/api/cluster.markdown", "modules": [ { "textRaw": "Cluster", "name": "cluster", "stability": 1, "stabilityText": "Experimental", "desc": "

    A single instance of Node runs in a single thread. To take advantage of\nmulti-core systems the user will sometimes want to launch a cluster of Node\nprocesses to handle the load.\n\n

    \n

    The cluster module allows you to easily create child processes that\nall share server ports.\n\n

    \n
    var cluster = require('cluster');\nvar http = require('http');\nvar numCPUs = require('os').cpus().length;\n\nif (cluster.isMaster) {\n  // Fork workers.\n  for (var i = 0; i < numCPUs; i++) {\n    cluster.fork();\n  }\n\n  cluster.on('exit', function(worker, code, signal) {\n    console.log('worker ' + worker.process.pid + ' died');\n  });\n} else {\n  // Workers can share any TCP connection\n  // In this case its a HTTP server\n  http.createServer(function(req, res) {\n    res.writeHead(200);\n    res.end("hello world\\n");\n  }).listen(8000);\n}
    \n

    Running node will now share port 8000 between the workers:\n\n

    \n
    % NODE_DEBUG=cluster node server.js\n23521,Master Worker 23524 online\n23521,Master Worker 23526 online\n23521,Master Worker 23523 online\n23521,Master Worker 23528 online
    \n

    This feature was introduced recently, and may change in future versions.\nPlease try it out and provide feedback.\n\n

    \n

    Also note that, on Windows, it is not yet possible to set up a named pipe\nserver in a worker.\n\n

    \n", "miscs": [ { "textRaw": "How It Works", "name": "How It Works", "type": "misc", "desc": "

    The worker processes are spawned using the child_process.fork method,\nso that they can communicate with the parent via IPC and pass server\nhandles back and forth.\n\n

    \n

    When you call server.listen(...) in a worker, it serializes the\narguments and passes the request to the master process. If the master\nprocess already has a listening server matching the worker's\nrequirements, then it passes the handle to the worker. If it does not\nalready have a listening server matching that requirement, then it will\ncreate one, and pass the handle to the worker.\n\n

    \n

    This causes potentially surprising behavior in three edge cases:\n\n

    \n
      \n
    1. server.listen({fd: 7}) Because the message is passed to the master,\nfile descriptor 7 in the parent will be listened on, and the\nhandle passed to the worker, rather than listening to the worker's\nidea of what the number 7 file descriptor references.
    2. \n
    3. server.listen(handle) Listening on handles explicitly will cause\nthe worker to use the supplied handle, rather than talk to the master\nprocess. If the worker already has the handle, then it's presumed\nthat you know what you are doing.
    4. \n
    5. server.listen(0) Normally, this will cause servers to listen on a\nrandom port. However, in a cluster, each worker will receive the\nsame "random" port each time they do listen(0). In essence, the\nport is random the first time, but predictable thereafter. If you\nwant to listen on a unique port, generate a port number based on the\ncluster worker ID.
    6. \n
    \n

    When multiple processes are all accept()ing on the same underlying\nresource, the operating system load-balances across them very\nefficiently. There is no routing logic in Node.js, or in your program,\nand no shared state between the workers. Therefore, it is important to\ndesign your program such that it does not rely too heavily on in-memory\ndata objects for things like sessions and login.\n\n

    \n

    Because workers are all separate processes, they can be killed or\nre-spawned depending on your program's needs, without affecting other\nworkers. As long as there are some workers still alive, the server will\ncontinue to accept connections. Node does not automatically manage the\nnumber of workers for you, however. It is your responsibility to manage\nthe worker pool for your application's needs.\n\n

    \n" } ], "properties": [ { "textRaw": "`settings` {Object} ", "name": "settings", "options": [ { "textRaw": "`execArgv` {Array} list of string arguments passed to the node executable. (Default=`process.execArgv`) ", "name": "execArgv", "default": "process.execArgv", "type": "Array", "desc": "list of string arguments passed to the node executable." }, { "textRaw": "`exec` {String} file path to worker file. (Default=`process.argv[1]`) ", "name": "exec", "default": "process.argv[1]", "type": "String", "desc": "file path to worker file." }, { "textRaw": "`args` {Array} string arguments passed to worker. (Default=`process.argv.slice(2)`) ", "name": "args", "default": "process.argv.slice(2)", "type": "Array", "desc": "string arguments passed to worker." }, { "textRaw": "`silent` {Boolean} whether or not to send output to parent's stdio. (Default=`false`) ", "name": "silent", "default": "false", "type": "Boolean", "desc": "whether or not to send output to parent's stdio." } ], "desc": "

    After calling .setupMaster() (or .fork()) this settings object will contain\nthe settings, including the default values.\n\n

    \n

    It is effectively frozen after being set, because .setupMaster() can\nonly be called once.\n\n

    \n

    This object is not supposed to be changed or set manually, by you.\n\n

    \n" }, { "textRaw": "`isMaster` {Boolean} ", "name": "isMaster", "desc": "

    True if the process is a master. This is determined\nby the process.env.NODE_UNIQUE_ID. If process.env.NODE_UNIQUE_ID is\nundefined, then isMaster is true.\n\n

    \n" }, { "textRaw": "`isWorker` {Boolean} ", "name": "isWorker", "desc": "

    True if the process is not a master (it is the negation of cluster.isMaster).\n\n

    \n" }, { "textRaw": "`worker` {Object} ", "name": "worker", "desc": "

    A reference to the current worker object. Not available in the master process.\n\n

    \n
    var cluster = require('cluster');\n\nif (cluster.isMaster) {\n  console.log('I am master');\n  cluster.fork();\n  cluster.fork();\n} else if (cluster.isWorker) {\n  console.log('I am worker #' + cluster.worker.id);\n}
    \n" }, { "textRaw": "`workers` {Object} ", "name": "workers", "desc": "

    A hash that stores the active worker objects, keyed by id field. Makes it\neasy to loop through all the workers. It is only available in the master\nprocess.\n\n

    \n

    A worker is removed from cluster.workers just before the 'disconnect' or\n'exit' event is emitted.\n\n

    \n
    // Go through all workers\nfunction eachWorker(callback) {\n  for (var id in cluster.workers) {\n    callback(cluster.workers[id]);\n  }\n}\neachWorker(function(worker) {\n  worker.send('big announcement to all workers');\n});
    \n

    Should you wish to reference a worker over a communication channel, using\nthe worker's unique id is the easiest way to find the worker.\n\n

    \n
    socket.on('data', function(id) {\n  var worker = cluster.workers[id];\n});
    \n" } ], "events": [ { "textRaw": "Event: 'fork'", "type": "event", "name": "fork", "params": [], "desc": "

    When a new worker is forked the cluster module will emit a 'fork' event.\nThis can be used to log worker activity, and create your own timeout.\n\n

    \n
    var timeouts = [];\nfunction errorMsg() {\n  console.error("Something must be wrong with the connection ...");\n}\n\ncluster.on('fork', function(worker) {\n  timeouts[worker.id] = setTimeout(errorMsg, 2000);\n});\ncluster.on('listening', function(worker, address) {\n  clearTimeout(timeouts[worker.id]);\n});\ncluster.on('exit', function(worker, code, signal) {\n  clearTimeout(timeouts[worker.id]);\n  errorMsg();\n});
    \n" }, { "textRaw": "Event: 'online'", "type": "event", "name": "online", "params": [], "desc": "

    After forking a new worker, the worker should respond with an online message.\nWhen the master receives an online message it will emit this event.\nThe difference between 'fork' and 'online' is that fork is emitted when the\nmaster forks a worker, and 'online' is emitted when the worker is running.\n\n

    \n
    cluster.on('online', function(worker) {\n  console.log("Yay, the worker responded after it was forked");\n});
    \n" }, { "textRaw": "Event: 'listening'", "type": "event", "name": "listening", "params": [], "desc": "

    After calling listen() from a worker, when the 'listening' event is emitted on\nthe server, a listening event will also be emitted on cluster in the master.\n\n

    \n

    The event handler is executed with two arguments, the worker contains the worker\nobject and the address object contains the following connection properties:\naddress, port and addressType. This is very useful if the worker is listening\non more than one address.\n\n

    \n
    cluster.on('listening', function(worker, address) {\n  console.log("A worker is now connected to " + address.address + ":" + address.port);\n});
    \n

    The addressType is one of:\n\n

    \n
      \n
    • 4 (TCPv4)
    • \n
    • 6 (TCPv6)
    • \n
    • -1 (unix domain socket)
    • \n
    • "udp4" or "udp6" (UDP v4 or v6)
    • \n
    \n" }, { "textRaw": "Event: 'disconnect'", "type": "event", "name": "disconnect", "params": [], "desc": "

    Emitted after the worker IPC channel has disconnected. This can occur when a\nworker exits gracefully, is killed, or is disconnected manually (such as with\nworker.disconnect()).\n\n

    \n

    There may be a delay between the disconnect and exit events. These events\ncan be used to detect if the process is stuck in a cleanup or if there are\nlong-living connections.\n\n

    \n
    cluster.on('disconnect', function(worker) {\n  console.log('The worker #' + worker.id + ' has disconnected');\n});
    \n" }, { "textRaw": "Event: 'exit'", "type": "event", "name": "exit", "params": [], "desc": "

    When any of the workers die the cluster module will emit the 'exit' event.\n\n

    \n

    This can be used to restart the worker by calling .fork() again.\n\n

    \n
    cluster.on('exit', function(worker, code, signal) {\n  console.log('worker %d died (%s). restarting...',\n    worker.process.pid, signal || code);\n  cluster.fork();\n});
    \n

    See child_process event: 'exit'.\n\n

    \n" }, { "textRaw": "Event: 'setup'", "type": "event", "name": "setup", "desc": "

    Emitted the first time that .setupMaster() is called.\n\n

    \n", "params": [] } ], "methods": [ { "textRaw": "cluster.setupMaster([settings])", "type": "method", "name": "setupMaster", "signatures": [ { "params": [ { "textRaw": "`settings` {Object} ", "options": [ { "textRaw": "`exec` {String} file path to worker file. (Default=`process.argv[1]`) ", "name": "exec", "default": "process.argv[1]", "type": "String", "desc": "file path to worker file." }, { "textRaw": "`args` {Array} string arguments passed to worker. (Default=`process.argv.slice(2)`) ", "name": "args", "default": "process.argv.slice(2)", "type": "Array", "desc": "string arguments passed to worker." }, { "textRaw": "`silent` {Boolean} whether or not to send output to parent's stdio. (Default=`false`) ", "name": "silent", "default": "false", "type": "Boolean", "desc": "whether or not to send output to parent's stdio." } ], "name": "settings", "type": "Object", "optional": true } ] }, { "params": [ { "name": "settings", "optional": true } ] } ], "desc": "

    setupMaster is used to change the default 'fork' behavior. Once called,\nthe settings will be present in cluster.settings.\n\n

    \n

    Note that:\n\n

    \n
      \n
    • Only the first call to .setupMaster() has any effect, subsequent calls are\nignored
    • \n
    • That because of the above, the only attribute of a worker that may be\ncustomized per-worker is the env passed to .fork()
    • \n
    • .fork() calls .setupMaster() internally to establish the defaults, so to\nhave any effect, .setupMaster() must be called before any calls to\n.fork()
    • \n
    \n

    Example:\n\n

    \n
    var cluster = require("cluster");\ncluster.setupMaster({\n  exec : "worker.js",\n  args : ["--use", "https"],\n  silent : true\n});\ncluster.fork();
    \n

    This can only be called from the master process.\n\n

    \n" }, { "textRaw": "cluster.fork([env])", "type": "method", "name": "fork", "signatures": [ { "return": { "textRaw": "return {Worker object} ", "name": "return", "type": "Worker object" }, "params": [ { "textRaw": "`env` {Object} Key/value pairs to add to worker process environment. ", "name": "env", "type": "Object", "desc": "Key/value pairs to add to worker process environment.", "optional": true } ] }, { "params": [ { "name": "env", "optional": true } ] } ], "desc": "

    Spawn a new worker process.\n\n

    \n

    This can only be called from the master process.\n\n

    \n" }, { "textRaw": "cluster.disconnect([callback])", "type": "method", "name": "disconnect", "signatures": [ { "params": [ { "textRaw": "`callback` {Function} called when all workers are disconnected and handles are closed ", "name": "callback", "type": "Function", "desc": "called when all workers are disconnected and handles are closed", "optional": true } ] }, { "params": [ { "name": "callback", "optional": true } ] } ], "desc": "

    Calls .disconnect() on each worker in cluster.workers.\n\n

    \n

    When they are disconnected all internal handles will be closed, allowing the\nmaster process to die gracefully if no other event is waiting.\n\n

    \n

    The method takes an optional callback argument which will be called when finished.\n\n

    \n

    This can only be called from the master process.\n\n

    \n" } ], "classes": [ { "textRaw": "Class: Worker", "type": "class", "name": "Worker", "desc": "

    A Worker object contains all public information and method about a worker.\nIn the master it can be obtained using cluster.workers. In a worker\nit can be obtained using cluster.worker.\n\n

    \n", "properties": [ { "textRaw": "`id` {String} ", "name": "id", "desc": "

    Each new worker is given its own unique id, this id is stored in the\nid.\n\n

    \n

    While a worker is alive, this is the key that indexes it in\ncluster.workers\n\n

    \n" }, { "textRaw": "`process` {ChildProcess object} ", "name": "process", "desc": "

    All workers are created using child_process.fork(), the returned object\nfrom this function is stored as .process. In a worker, the global process\nis stored.\n\n

    \n

    See: Child Process module\n\n

    \n

    Note that workers will call process.exit(0) if the 'disconnect' event occurs\non process and .suicide is not true. This protects against accidental\ndisconnection.\n\n

    \n" }, { "textRaw": "`suicide` {Boolean} ", "name": "suicide", "desc": "

    Set by calling .kill() or .disconnect(), until then it is undefined.\n\n

    \n

    The boolean worker.suicide lets you distinguish between voluntary and accidental\nexit, the master may choose not to respawn a worker based on this value.\n\n

    \n
    cluster.on('exit', function(worker, code, signal) {\n  if (worker.suicide === true) {\n    console.log('Oh, it was just suicide\\' – no need to worry').\n  }\n});\n\n// kill worker\nworker.kill();
    \n" } ], "methods": [ { "textRaw": "worker.send(message, [sendHandle])", "type": "method", "name": "send", "signatures": [ { "params": [ { "textRaw": "`message` {Object} ", "name": "message", "type": "Object" }, { "textRaw": "`sendHandle` {Handle object} ", "name": "sendHandle", "type": "Handle object", "optional": true } ] }, { "params": [ { "name": "message" }, { "name": "sendHandle", "optional": true } ] } ], "desc": "

    This function is equal to the send methods provided by\nchild_process.fork(). In the master you should use this function to\nsend a message to a specific worker.\n\n

    \n

    In a worker you can also use process.send(message), it is the same function.\n\n

    \n

    This example will echo back all messages from the master:\n\n

    \n
    if (cluster.isMaster) {\n  var worker = cluster.fork();\n  worker.send('hi there');\n\n} else if (cluster.isWorker) {\n  process.on('message', function(msg) {\n    process.send(msg);\n  });\n}
    \n" }, { "textRaw": "worker.kill([signal='SIGTERM'])", "type": "method", "name": "kill", "signatures": [ { "params": [ { "textRaw": "`signal` {String} Name of the kill signal to send to the worker process. ", "name": "signal", "type": "String", "desc": "Name of the kill signal to send to the worker process.", "optional": true, "default": "'SIGTERM'" } ] }, { "params": [ { "name": "signal", "optional": true, "default": "'SIGTERM'" } ] } ], "desc": "

    This function will kill the worker. In the master, it does this by disconnecting\nthe worker.process, and once disconnected, killing with signal. In the\nworker, it does it by disconnecting the channel, and then exiting with code 0.\n\n

    \n

    Causes .suicide to be set.\n\n

    \n

    This method is aliased as worker.destroy() for backwards compatibility.\n\n

    \n

    Note that in a worker, process.kill() exists, but it is not this function,\nit is kill.\n\n

    \n" }, { "textRaw": "worker.disconnect()", "type": "method", "name": "disconnect", "desc": "

    In a worker, this function will close all servers, wait for the 'close' event on\nthose servers, and then disconnect the IPC channel.\n\n

    \n

    In the master, an internal message is sent to the worker causing it to call\n.disconnect() on itself.\n\n

    \n

    Causes .suicide to be set.\n\n

    \n

    Note that after a server is closed, it will no longer accept new connections,\nbut connections may be accepted by any other listening worker. Existing\nconnections will be allowed to close as usual. When no more connections exist,\nsee server.close(), the IPC channel to the worker\nwill close allowing it to die gracefully.\n\n

    \n

    The above applies only to server connections, client connections are not\nautomatically closed by workers, and disconnect does not wait for them to close\nbefore exiting.\n\n

    \n

    Note that in a worker, process.disconnect exists, but it is not this function,\nit is disconnect.\n\n

    \n

    Because long living server connections may block workers from disconnecting, it\nmay be useful to send a message, so application specific actions may be taken to\nclose them. It also may be useful to implement a timeout, killing a worker if\nthe disconnect event has not been emitted after some time.\n\n

    \n
    if (cluster.isMaster) {\n  var worker = cluster.fork();\n  var timeout;\n\n  worker.on('listening', function(address) {\n    worker.send('shutdown');\n    worker.disconnect();\n    timeout = setTimeout(function() {\n      worker.kill();\n    }, 2000);\n  });\n\n  worker.on('disconnect', function() {\n    clearTimeout(timeout);\n  });\n\n} else if (cluster.isWorker) {\n  var net = require('net');\n  var server = net.createServer(function(socket) {\n    // connections never end\n  });\n\n  server.listen(8000);\n\n  process.on('message', function(msg) {\n    if(msg === 'shutdown') {\n      // initiate graceful close of any connections to server\n    }\n  });\n}
    \n", "signatures": [ { "params": [] } ] } ], "events": [ { "textRaw": "Event: 'message'", "type": "event", "name": "message", "params": [], "desc": "

    This event is the same as the one provided by child_process.fork().\n\n

    \n

    In a worker you can also use process.on('message').\n\n

    \n

    As an example, here is a cluster that keeps count of the number of requests\nin the master process using the message system:\n\n

    \n
    var cluster = require('cluster');\nvar http = require('http');\n\nif (cluster.isMaster) {\n\n  // Keep track of http requests\n  var numReqs = 0;\n  setInterval(function() {\n    console.log("numReqs =", numReqs);\n  }, 1000);\n\n  // Count requestes\n  function messageHandler(msg) {\n    if (msg.cmd && msg.cmd == 'notifyRequest') {\n      numReqs += 1;\n    }\n  }\n\n  // Start workers and listen for messages containing notifyRequest\n  var numCPUs = require('os').cpus().length;\n  for (var i = 0; i < numCPUs; i++) {\n    cluster.fork();\n  }\n\n  Object.keys(cluster.workers).forEach(function(id) {\n    cluster.workers[id].on('message', messageHandler);\n  });\n\n} else {\n\n  // Worker processes have a http server.\n  http.Server(function(req, res) {\n    res.writeHead(200);\n    res.end("hello world\\n");\n\n    // notify master about the request\n    process.send({ cmd: 'notifyRequest' });\n  }).listen(8000);\n}
    \n" }, { "textRaw": "Event: 'online'", "type": "event", "name": "online", "desc": "

    Similar to the cluster.on('online') event, but specific to this worker.\n\n

    \n
    cluster.fork().on('online', function() {\n  // Worker is online\n});
    \n

    It is not emitted in the worker.\n\n

    \n", "params": [] }, { "textRaw": "Event: 'listening'", "type": "event", "name": "listening", "params": [], "desc": "

    Similar to the cluster.on('listening') event, but specific to this worker.\n\n

    \n
    cluster.fork().on('listening', function(address) {\n  // Worker is listening\n});
    \n

    It is not emitted in the worker.\n\n

    \n" }, { "textRaw": "Event: 'disconnect'", "type": "event", "name": "disconnect", "desc": "

    Similar to the cluster.on('disconnect') event, but specfic to this worker.\n\n

    \n
    cluster.fork().on('disconnect', function() {\n  // Worker has disconnected\n});
    \n", "params": [] }, { "textRaw": "Event: 'exit'", "type": "event", "name": "exit", "params": [], "desc": "

    Similar to the cluster.on('exit') event, but specific to this worker.\n\n

    \n
    var worker = cluster.fork();\nworker.on('exit', function(code, signal) {\n  if( signal ) {\n    console.log("worker was killed by signal: "+signal);\n  } else if( code !== 0 ) {\n    console.log("worker exited with error code: "+code);\n  } else {\n    console.log("worker success!");\n  }\n});
    \n" }, { "textRaw": "Event: 'error'", "type": "event", "name": "error", "desc": "

    This event is the same as the one provided by child_process.fork().\n\n

    \n

    In a worker you can also use process.on('error').\n

    \n", "params": [] } ] } ], "type": "module", "displayName": "Cluster" } ] } node-v0.10.25~dfsg2/doc/api/repl.json0000644000000000000000000002043712270264601015775 0ustar rootroot{ "source": "doc/api/repl.markdown", "modules": [ { "textRaw": "REPL", "name": "repl", "desc": "

    A Read-Eval-Print-Loop (REPL) is available both as a standalone program and\neasily includable in other programs. The REPL provides a way to interactively\nrun JavaScript and see the results. It can be used for debugging, testing, or\njust trying things out.\n\n

    \n

    By executing node without any arguments from the command-line you will be\ndropped into the REPL. It has simplistic emacs line-editing.\n\n

    \n
    mjr:~$ node\nType '.help' for options.\n> a = [ 1, 2, 3];\n[ 1, 2, 3 ]\n> a.forEach(function (v) {\n...   console.log(v);\n...   });\n1\n2\n3
    \n

    For advanced line-editors, start node with the environmental variable\nNODE_NO_READLINE=1. This will start the main and debugger REPL in canonical\nterminal settings which will allow you to use with rlwrap.\n\n

    \n

    For example, you could add this to your bashrc file:\n\n

    \n
    alias node="env NODE_NO_READLINE=1 rlwrap node"
    \n", "methods": [ { "textRaw": "repl.start(options)", "type": "method", "name": "start", "desc": "

    Returns and starts a REPLServer instance. Accepts an "options" Object that\ntakes the following values:\n\n

    \n
      \n
    • prompt - the prompt and stream for all I/O. Defaults to > .

      \n
    • \n
    • input - the readable stream to listen to. Defaults to process.stdin.

      \n
    • \n
    • output - the writable stream to write readline data to. Defaults to\nprocess.stdout.

      \n
    • \n
    • terminal - pass true if the stream should be treated like a TTY, and\nhave ANSI/VT100 escape codes written to it. Defaults to checking isTTY\non the output stream upon instantiation.

      \n
    • \n
    • eval - function that will be used to eval each given line. Defaults to\nan async wrapper for eval(). See below for an example of a custom eval.

      \n
    • \n
    • useColors - a boolean which specifies whether or not the writer function\nshould output colors. If a different writer function is set then this does\nnothing. Defaults to the repl's terminal value.

      \n
    • \n
    • useGlobal - if set to true, then the repl will use the global object,\ninstead of running scripts in a separate context. Defaults to false.

      \n
    • \n
    • ignoreUndefined - if set to true, then the repl will not output the\nreturn value of command if it's undefined. Defaults to false.

      \n
    • \n
    • writer - the function to invoke for each command that gets evaluated which\nreturns the formatting (including coloring) to display. Defaults to\nutil.inspect.

      \n
    • \n
    \n

    You can use your own eval function if it has following signature:\n\n

    \n
    function eval(cmd, context, filename, callback) {\n  callback(null, result);\n}
    \n

    Multiple REPLs may be started against the same running instance of node. Each\nwill share the same global object but will have unique I/O.\n\n

    \n

    Here is an example that starts a REPL on stdin, a Unix socket, and a TCP socket:\n\n

    \n
    var net = require("net"),\n    repl = require("repl");\n\nconnections = 0;\n\nrepl.start({\n  prompt: "node via stdin> ",\n  input: process.stdin,\n  output: process.stdout\n});\n\nnet.createServer(function (socket) {\n  connections += 1;\n  repl.start({\n    prompt: "node via Unix socket> ",\n    input: socket,\n    output: socket\n  }).on('exit', function() {\n    socket.end();\n  })\n}).listen("/tmp/node-repl-sock");\n\nnet.createServer(function (socket) {\n  connections += 1;\n  repl.start({\n    prompt: "node via TCP socket> ",\n    input: socket,\n    output: socket\n  }).on('exit', function() {\n    socket.end();\n  });\n}).listen(5001);
    \n

    Running this program from the command line will start a REPL on stdin. Other\nREPL clients may connect through the Unix socket or TCP socket. telnet is useful\nfor connecting to TCP sockets, and socat can be used to connect to both Unix and\nTCP sockets.\n\n

    \n

    By starting a REPL from a Unix socket-based server instead of stdin, you can\nconnect to a long-running node process without restarting it.\n\n

    \n

    For an example of running a "full-featured" (terminal) REPL over\na net.Server and net.Socket instance, see: https://gist.github.com/2209310\n\n

    \n

    For an example of running a REPL instance over curl(1),\nsee: https://gist.github.com/2053342\n\n

    \n", "events": [ { "textRaw": "Event: 'exit'", "type": "event", "name": "exit", "desc": "

    function () {}\n\n

    \n

    Emitted when the user exits the REPL in any of the defined ways. Namely, typing\n.exit at the repl, pressing Ctrl+C twice to signal SIGINT, or pressing Ctrl+D\nto signal "end" on the input stream.\n\n

    \n

    Example of listening for exit:\n\n

    \n
    r.on('exit', function () {\n  console.log('Got "exit" event from repl!');\n  process.exit();\n});
    \n", "params": [] } ], "signatures": [ { "params": [ { "name": "options" } ] } ] } ], "miscs": [ { "textRaw": "REPL Features", "name": "REPL Features", "type": "misc", "desc": "

    Inside the REPL, Control+D will exit. Multi-line expressions can be input.\nTab completion is supported for both global and local variables.\n\n

    \n

    The special variable _ (underscore) contains the result of the last expression.\n\n

    \n
    > [ "a", "b", "c" ]\n[ 'a', 'b', 'c' ]\n> _.length\n3\n> _ += 1\n4
    \n

    The REPL provides access to any variables in the global scope. You can expose\na variable to the REPL explicitly by assigning it to the context object\nassociated with each REPLServer. For example:\n\n

    \n
    // repl_test.js\nvar repl = require("repl"),\n    msg = "message";\n\nrepl.start("> ").context.m = msg;
    \n

    Things in the context object appear as local within the REPL:\n\n

    \n
    mjr:~$ node repl_test.js\n> m\n'message'
    \n

    There are a few special REPL commands:\n\n

    \n
      \n
    • .break - While inputting a multi-line expression, sometimes you get lost\nor just don't care about completing it. .break will start over.
    • \n
    • .clear - Resets the context object to an empty object and clears any\nmulti-line expression.
    • \n
    • .exit - Close the I/O stream, which will cause the REPL to exit.
    • \n
    • .help - Show this list of special commands.
    • \n
    • .save - Save the current REPL session to a file
      \n

      .save ./file/to/save.js

      \n
      \n
    • \n
    • .load - Load a file into the current REPL session.
      \n

      .load ./file/to/load.js

      \n
      \n
    • \n
    \n

    The following key combinations in the REPL have these special effects:\n\n

    \n
      \n
    • <ctrl>C - Similar to the .break keyword. Terminates the current\ncommand. Press twice on a blank line to forcibly exit.
    • \n
    • <ctrl>D - Similar to the .exit keyword.
    • \n
    \n" } ], "type": "module", "displayName": "REPL" } ] } node-v0.10.25~dfsg2/doc/api/readline.markdown0000644000000000000000000001765012270121457017473 0ustar rootroot# Readline Stability: 2 - Unstable To use this module, do `require('readline')`. Readline allows reading of a stream (such as `process.stdin`) on a line-by-line basis. Note that once you've invoked this module, your node program will not terminate until you've closed the interface. Here's how to allow your program to gracefully exit: var readline = require('readline'); var rl = readline.createInterface({ input: process.stdin, output: process.stdout }); rl.question("What do you think of node.js? ", function(answer) { // TODO: Log the answer in a database console.log("Thank you for your valuable feedback:", answer); rl.close(); }); ## readline.createInterface(options) Creates a readline `Interface` instance. Accepts an "options" Object that takes the following values: - `input` - the readable stream to listen to (Required). - `output` - the writable stream to write readline data to (Required). - `completer` - an optional function that is used for Tab autocompletion. See below for an example of using this. - `terminal` - pass `true` if the `input` and `output` streams should be treated like a TTY, and have ANSI/VT100 escape codes written to it. Defaults to checking `isTTY` on the `output` stream upon instantiation. The `completer` function is given a the current line entered by the user, and is supposed to return an Array with 2 entries: 1. An Array with matching entries for the completion. 2. The substring that was used for the matching. Which ends up looking something like: `[[substr1, substr2, ...], originalsubstring]`. Example: function completer(line) { var completions = '.help .error .exit .quit .q'.split(' ') var hits = completions.filter(function(c) { return c.indexOf(line) == 0 }) // show all completions if none found return [hits.length ? hits : completions, line] } Also `completer` can be run in async mode if it accepts two arguments: function completer(linePartial, callback) { callback(null, [['123'], linePartial]); } `createInterface` is commonly used with `process.stdin` and `process.stdout` in order to accept user input: var readline = require('readline'); var rl = readline.createInterface({ input: process.stdin, output: process.stdout }); Once you have a readline instance, you most commonly listen for the `"line"` event. If `terminal` is `true` for this instance then the `output` stream will get the best compatibility if it defines an `output.columns` property, and fires a `"resize"` event on the `output` if/when the columns ever change (`process.stdout` does this automatically when it is a TTY). ## Class: Interface The class that represents a readline interface with an input and output stream. ### rl.setPrompt(prompt, length) Sets the prompt, for example when you run `node` on the command line, you see `> `, which is node's prompt. ### rl.prompt([preserveCursor]) Readies readline for input from the user, putting the current `setPrompt` options on a new line, giving the user a new spot to write. Set `preserveCursor` to `true` to prevent the cursor placement being reset to `0`. This will also resume the `input` stream used with `createInterface` if it has been paused. ### rl.question(query, callback) Prepends the prompt with `query` and invokes `callback` with the user's response. Displays the query to the user, and then invokes `callback` with the user's response after it has been typed. This will also resume the `input` stream used with `createInterface` if it has been paused. Example usage: interface.question('What is your favorite food?', function(answer) { console.log('Oh, so your favorite food is ' + answer); }); ### rl.pause() Pauses the readline `input` stream, allowing it to be resumed later if needed. ### rl.resume() Resumes the readline `input` stream. ### rl.close() Closes the `Interface` instance, relinquishing control on the `input` and `output` streams. The "close" event will also be emitted. ### rl.write(data, [key]) Writes `data` to `output` stream. `key` is an object literal to represent a key sequence; available if the terminal is a TTY. This will also resume the `input` stream if it has been paused. Example: rl.write('Delete me!'); // Simulate ctrl+u to delete the line written previously rl.write(null, {ctrl: true, name: 'u'}); ## Events ### Event: 'line' `function (line) {}` Emitted whenever the `input` stream receives a `\n`, usually received when the user hits enter, or return. This is a good hook to listen for user input. Example of listening for `line`: rl.on('line', function (cmd) { console.log('You just typed: '+cmd); }); ### Event: 'pause' `function () {}` Emitted whenever the `input` stream is paused. Also emitted whenever the `input` stream is not paused and receives the `SIGCONT` event. (See events `SIGTSTP` and `SIGCONT`) Example of listening for `pause`: rl.on('pause', function() { console.log('Readline paused.'); }); ### Event: 'resume' `function () {}` Emitted whenever the `input` stream is resumed. Example of listening for `resume`: rl.on('resume', function() { console.log('Readline resumed.'); }); ### Event: 'close' `function () {}` Emitted when `close()` is called. Also emitted when the `input` stream receives its "end" event. The `Interface` instance should be considered "finished" once this is emitted. For example, when the `input` stream receives `^D`, respectively known as `EOT`. This event is also called if there is no `SIGINT` event listener present when the `input` stream receives a `^C`, respectively known as `SIGINT`. ### Event: 'SIGINT' `function () {}` Emitted whenever the `input` stream receives a `^C`, respectively known as `SIGINT`. If there is no `SIGINT` event listener present when the `input` stream receives a `SIGINT`, `pause` will be triggered. Example of listening for `SIGINT`: rl.on('SIGINT', function() { rl.question('Are you sure you want to exit?', function(answer) { if (answer.match(/^y(es)?$/i)) rl.pause(); }); }); ### Event: 'SIGTSTP' `function () {}` **This does not work on Windows.** Emitted whenever the `input` stream receives a `^Z`, respectively known as `SIGTSTP`. If there is no `SIGTSTP` event listener present when the `input` stream receives a `SIGTSTP`, the program will be sent to the background. When the program is resumed with `fg`, the `pause` and `SIGCONT` events will be emitted. You can use either to resume the stream. The `pause` and `SIGCONT` events will not be triggered if the stream was paused before the program was sent to the background. Example of listening for `SIGTSTP`: rl.on('SIGTSTP', function() { // This will override SIGTSTP and prevent the program from going to the // background. console.log('Caught SIGTSTP.'); }); ### Event: 'SIGCONT' `function () {}` **This does not work on Windows.** Emitted whenever the `input` stream is sent to the background with `^Z`, respectively known as `SIGTSTP`, and then continued with `fg(1)`. This event only emits if the stream was not paused before sending the program to the background. Example of listening for `SIGCONT`: rl.on('SIGCONT', function() { // `prompt` will automatically resume the stream rl.prompt(); }); ## Example: Tiny CLI Here's an example of how to use all these together to craft a tiny command line interface: var readline = require('readline'), rl = readline.createInterface(process.stdin, process.stdout); rl.setPrompt('OHAI> '); rl.prompt(); rl.on('line', function(line) { switch(line.trim()) { case 'hello': console.log('world!'); break; default: console.log('Say what? I might have heard `' + line.trim() + '`'); break; } rl.prompt(); }).on('close', function() { console.log('Have a great day!'); process.exit(0); }); node-v0.10.25~dfsg2/doc/api/url.json0000644000000000000000000001423312270264601015632 0ustar rootroot{ "source": "doc/api/url.markdown", "modules": [ { "textRaw": "URL", "name": "url", "stability": 3, "stabilityText": "Stable", "desc": "

    This module has utilities for URL resolution and parsing.\nCall require('url') to use it.\n\n

    \n

    Parsed URL objects have some or all of the following fields, depending on\nwhether or not they exist in the URL string. Any parts that are not in the URL\nstring will not be in the parsed object. Examples are shown for the URL\n\n

    \n

    'http://user:pass@host.com:8080/p/a/t/h?query=string#hash'\n\n

    \n
      \n
    • href: The full URL that was originally parsed. Both the protocol and host are lowercased.

      \n

      Example: 'http://user:pass@host.com:8080/p/a/t/h?query=string#hash'

      \n
    • \n
    • protocol: The request protocol, lowercased.

      \n

      Example: 'http:'

      \n
    • \n
    • host: The full lowercased host portion of the URL, including port\ninformation.

      \n

      Example: 'host.com:8080'

      \n
    • \n
    • auth: The authentication information portion of a URL.

      \n

      Example: 'user:pass'

      \n
    • \n
    • hostname: Just the lowercased hostname portion of the host.

      \n

      Example: 'host.com'

      \n
    • \n
    • port: The port number portion of the host.

      \n

      Example: '8080'

      \n
    • \n
    • pathname: The path section of the URL, that comes after the host and\nbefore the query, including the initial slash if present.

      \n

      Example: '/p/a/t/h'

      \n
    • \n
    • search: The 'query string' portion of the URL, including the leading\nquestion mark.

      \n

      Example: '?query=string'

      \n
    • \n
    • path: Concatenation of pathname and search.

      \n

      Example: '/p/a/t/h?query=string'

      \n
    • \n
    • query: Either the 'params' portion of the query string, or a\nquerystring-parsed object.

      \n

      Example: 'query=string' or {'query':'string'}

      \n
    • \n
    • hash: The 'fragment' portion of the URL including the pound-sign.

      \n

      Example: '#hash'

      \n
    • \n
    \n

    The following methods are provided by the URL module:\n\n

    \n", "methods": [ { "textRaw": "url.parse(urlStr, [parseQueryString], [slashesDenoteHost])", "type": "method", "name": "parse", "desc": "

    Take a URL string, and return an object.\n\n

    \n

    Pass true as the second argument to also parse\nthe query string using the querystring module.\nDefaults to false.\n\n

    \n

    Pass true as the third argument to treat //foo/bar as\n{ host: 'foo', pathname: '/bar' } rather than\n{ pathname: '//foo/bar' }. Defaults to false.\n\n

    \n", "signatures": [ { "params": [ { "name": "urlStr" }, { "name": "parseQueryString", "optional": true }, { "name": "slashesDenoteHost", "optional": true } ] } ] }, { "textRaw": "url.format(urlObj)", "type": "method", "name": "format", "desc": "

    Take a parsed URL object, and return a formatted URL string.\n\n

    \n
      \n
    • href will be ignored.
    • \n
    • protocolis treated the same with or without the trailing : (colon).
        \n
      • The protocols http, https, ftp, gopher, file will be\npostfixed with :// (colon-slash-slash).
      • \n
      • All other protocols mailto, xmpp, aim, sftp, foo, etc will\nbe postfixed with : (colon)
      • \n
      \n
    • \n
    • auth will be used if present.
    • \n
    • hostname will only be used if host is absent.
    • \n
    • port will only be used if host is absent.
    • \n
    • host will be used in place of hostname and port
    • \n
    • pathname is treated the same with or without the leading / (slash)
    • \n
    • search will be used in place of query
    • \n
    • query (object; see querystring) will only be used if search is absent.
    • \n
    • search is treated the same with or without the leading ? (question mark)
    • \n
    • hash is treated the same with or without the leading # (pound sign, anchor)
    • \n
    \n", "signatures": [ { "params": [ { "name": "urlObj" } ] } ] }, { "textRaw": "url.resolve(from, to)", "type": "method", "name": "resolve", "desc": "

    Take a base URL, and a href URL, and resolve them as a browser would for\nan anchor tag. Examples:\n\n

    \n
    url.resolve('/one/two/three', 'four')         // '/one/two/four'\nurl.resolve('http://example.com/', '/one')    // 'http://example.com/one'\nurl.resolve('http://example.com/one', '/two') // 'http://example.com/two'
    \n", "signatures": [ { "params": [ { "name": "from" }, { "name": "to" } ] } ] } ], "type": "module", "displayName": "URL" } ] } node-v0.10.25~dfsg2/doc/api/querystring.markdown0000644000000000000000000000243212270121457020274 0ustar rootroot# Query String Stability: 3 - Stable This module provides utilities for dealing with query strings. It provides the following methods: ## querystring.stringify(obj, [sep], [eq]) Serialize an object to a query string. Optionally override the default separator (`'&'`) and assignment (`'='`) characters. Example: querystring.stringify({ foo: 'bar', baz: ['qux', 'quux'], corge: '' }) // returns 'foo=bar&baz=qux&baz=quux&corge=' querystring.stringify({foo: 'bar', baz: 'qux'}, ';', ':') // returns 'foo:bar;baz:qux' ## querystring.parse(str, [sep], [eq], [options]) Deserialize a query string to an object. Optionally override the default separator (`'&'`) and assignment (`'='`) characters. Options object may contain `maxKeys` property (equal to 1000 by default), it'll be used to limit processed keys. Set it to 0 to remove key count limitation. Example: querystring.parse('foo=bar&baz=qux&baz=quux&corge') // returns { foo: 'bar', baz: ['qux', 'quux'], corge: '' } ## querystring.escape The escape function used by `querystring.stringify`, provided so that it could be overridden if necessary. ## querystring.unescape The unescape function used by `querystring.parse`, provided so that it could be overridden if necessary. node-v0.10.25~dfsg2/doc/api/https.json0000644000000000000000000002472112270264601016175 0ustar rootroot{ "source": "doc/api/https.markdown", "modules": [ { "textRaw": "HTTPS", "name": "https", "stability": 3, "stabilityText": "Stable", "desc": "

    HTTPS is the HTTP protocol over TLS/SSL. In Node this is implemented as a\nseparate module.\n\n

    \n", "classes": [ { "textRaw": "Class: https.Server", "type": "class", "name": "https.Server", "desc": "

    This class is a subclass of tls.Server and emits events same as\nhttp.Server. See http.Server for more information.\n\n

    \n" }, { "textRaw": "Class: https.Agent", "type": "class", "name": "https.Agent", "desc": "

    An Agent object for HTTPS similar to [http.Agent][]. See [https.request()][]\nfor more information.\n\n\n

    \n" } ], "methods": [ { "textRaw": "https.createServer(options, [requestListener])", "type": "method", "name": "createServer", "desc": "

    Returns a new HTTPS web server object. The options is similar to\n[tls.createServer()][]. The requestListener is a function which is\nautomatically added to the 'request' event.\n\n

    \n

    Example:\n\n

    \n
    // curl -k https://localhost:8000/\nvar https = require('https');\nvar fs = require('fs');\n\nvar options = {\n  key: fs.readFileSync('test/fixtures/keys/agent2-key.pem'),\n  cert: fs.readFileSync('test/fixtures/keys/agent2-cert.pem')\n};\n\nhttps.createServer(options, function (req, res) {\n  res.writeHead(200);\n  res.end("hello world\\n");\n}).listen(8000);
    \n

    Or\n\n

    \n
    var https = require('https');\nvar fs = require('fs');\n\nvar options = {\n  pfx: fs.readFileSync('server.pfx')\n};\n\nhttps.createServer(options, function (req, res) {\n  res.writeHead(200);\n  res.end("hello world\\n");\n}).listen(8000);
    \n", "methods": [ { "textRaw": "server.listen(path, [callback])", "type": "method", "name": "listen", "desc": "

    See [http.listen()][] for details.\n\n

    \n", "signatures": [ { "params": [ { "name": "handle" }, { "name": "callback", "optional": true } ] }, { "params": [ { "name": "path" }, { "name": "callback", "optional": true } ] } ] }, { "textRaw": "server.listen(handle, [callback])", "type": "method", "name": "listen", "desc": "

    See [http.listen()][] for details.\n\n

    \n", "signatures": [ { "params": [ { "name": "handle" }, { "name": "callback", "optional": true } ] } ] }, { "textRaw": "server.close([callback])", "type": "method", "name": "close", "desc": "

    See [http.close()][] for details.\n\n

    \n", "signatures": [ { "params": [ { "name": "callback", "optional": true } ] } ] } ], "signatures": [ { "params": [ { "name": "options" }, { "name": "requestListener", "optional": true } ] } ] }, { "textRaw": "https.request(options, callback)", "type": "method", "name": "request", "desc": "

    Makes a request to a secure web server.\n\n

    \n

    options can be an object or a string. If options is a string, it is\nautomatically parsed with url.parse().\n\n

    \n

    All options from [http.request()][] are valid.\n\n

    \n

    Example:\n\n

    \n
    var https = require('https');\n\nvar options = {\n  hostname: 'encrypted.google.com',\n  port: 443,\n  path: '/',\n  method: 'GET'\n};\n\nvar req = https.request(options, function(res) {\n  console.log("statusCode: ", res.statusCode);\n  console.log("headers: ", res.headers);\n\n  res.on('data', function(d) {\n    process.stdout.write(d);\n  });\n});\nreq.end();\n\nreq.on('error', function(e) {\n  console.error(e);\n});
    \n

    The options argument has the following options\n\n

    \n
      \n
    • host: A domain name or IP address of the server to issue the request to.\nDefaults to 'localhost'.
    • \n
    • hostname: To support url.parse() hostname is preferred over host
    • \n
    • port: Port of remote server. Defaults to 443.
    • \n
    • method: A string specifying the HTTP request method. Defaults to 'GET'.
    • \n
    • path: Request path. Defaults to '/'. Should include query string if any.\nE.G. '/index.html?page=12'
    • \n
    • headers: An object containing request headers.
    • \n
    • auth: Basic authentication i.e. 'user:password' to compute an\nAuthorization header.
    • \n
    • agent: Controls [Agent][] behavior. When an Agent is used request will\ndefault to Connection: keep-alive. Possible values:
        \n
      • undefined (default): use [globalAgent][] for this host and port.
      • \n
      • Agent object: explicitly use the passed in Agent.
      • \n
      • false: opts out of connection pooling with an Agent, defaults request to\nConnection: close.
      • \n
      \n
    • \n
    \n

    The following options from [tls.connect()][] can also be specified. However, a\n[globalAgent][] silently ignores these.\n\n

    \n
      \n
    • pfx: Certificate, Private key and CA certificates to use for SSL. Default null.
    • \n
    • key: Private key to use for SSL. Default null.
    • \n
    • passphrase: A string of passphrase for the private key or pfx. Default null.
    • \n
    • cert: Public x509 certificate to use. Default null.
    • \n
    • ca: An authority certificate or array of authority certificates to check\nthe remote host against.
    • \n
    • ciphers: A string describing the ciphers to use or exclude. Consult\nhttp://www.openssl.org/docs/apps/ciphers.html#CIPHER_LIST_FORMAT for\ndetails on the format.
    • \n
    • rejectUnauthorized: If true, the server certificate is verified against\nthe list of supplied CAs. An 'error' event is emitted if verification\nfails. Verification happens at the connection level, before the HTTP\nrequest is sent. Default true.
    • \n
    • secureProtocol: The SSL method to use, e.g. SSLv3_method to force\nSSL version 3. The possible values depend on your installation of\nOpenSSL and are defined in the constant [SSL_METHODS][].
    • \n
    \n

    In order to specify these options, use a custom Agent.\n\n

    \n

    Example:\n\n

    \n
    var options = {\n  hostname: 'encrypted.google.com',\n  port: 443,\n  path: '/',\n  method: 'GET',\n  key: fs.readFileSync('test/fixtures/keys/agent2-key.pem'),\n  cert: fs.readFileSync('test/fixtures/keys/agent2-cert.pem')\n};\noptions.agent = new https.Agent(options);\n\nvar req = https.request(options, function(res) {\n  ...\n}
    \n

    Or does not use an Agent.\n\n

    \n

    Example:\n\n

    \n
    var options = {\n  hostname: 'encrypted.google.com',\n  port: 443,\n  path: '/',\n  method: 'GET',\n  key: fs.readFileSync('test/fixtures/keys/agent2-key.pem'),\n  cert: fs.readFileSync('test/fixtures/keys/agent2-cert.pem'),\n  agent: false\n};\n\nvar req = https.request(options, function(res) {\n  ...\n}
    \n", "signatures": [ { "params": [ { "name": "options" }, { "name": "callback" } ] } ] }, { "textRaw": "https.get(options, callback)", "type": "method", "name": "get", "desc": "

    Like http.get() but for HTTPS.\n\n

    \n

    options can be an object or a string. If options is a string, it is\nautomatically parsed with url.parse().\n\n

    \n

    Example:\n\n

    \n
    var https = require('https');\n\nhttps.get('https://encrypted.google.com/', function(res) {\n  console.log("statusCode: ", res.statusCode);\n  console.log("headers: ", res.headers);\n\n  res.on('data', function(d) {\n    process.stdout.write(d);\n  });\n\n}).on('error', function(e) {\n  console.error(e);\n});
    \n", "signatures": [ { "params": [ { "name": "options" }, { "name": "callback" } ] } ] } ], "properties": [ { "textRaw": "https.globalAgent", "name": "globalAgent", "desc": "

    Global instance of [https.Agent][] for all HTTPS client requests.\n\n

    \n" } ], "type": "module", "displayName": "HTTPS" } ] } node-v0.10.25~dfsg2/doc/api/vm.json0000644000000000000000000003214612270264601015455 0ustar rootroot{ "source": "doc/api/vm.markdown", "modules": [ { "textRaw": "Executing JavaScript", "name": "vm", "stability": 2, "stabilityText": "Unstable. See Caveats, below.", "desc": "

    You can access this module with:\n\n

    \n
    var vm = require('vm');
    \n

    JavaScript code can be compiled and run immediately or compiled, saved, and run later.\n\n

    \n", "modules": [ { "textRaw": "Caveats", "name": "caveats", "desc": "

    The vm module has many known issues and edge cases. If you run into\nissues or unexpected behavior, please consult the open issues on\nGitHub.\nSome of the biggest problems are described below.\n\n

    \n", "modules": [ { "textRaw": "Sandboxes", "name": "sandboxes", "desc": "

    The sandbox argument to vm.runInNewContext and vm.createContext,\nalong with the initSandbox argument to vm.createContext, do not\nbehave as one might normally expect and their behavior varies\nbetween different versions of Node.\n\n

    \n

    The key issue to be aware of is that V8 provides no way to directly\ncontrol the global object used within a context. As a result, while\nproperties of your sandbox object will be available in the context,\nany properties from the prototypes of the sandbox may not be\navailable. Furthermore, the this expression within the global scope\nof the context evaluates to the empty object ({}) instead of to\nyour sandbox.\n\n

    \n

    Your sandbox's properties are also not shared directly with the script.\nInstead, the properties of the sandbox are copied into the context at\nthe beginning of execution, and then after execution, the properties\nare copied back out in an attempt to propagate any changes.\n\n

    \n", "type": "module", "displayName": "Sandboxes" }, { "textRaw": "Globals", "name": "globals", "desc": "

    Properties of the global object, like Array and String, have\ndifferent values inside of a context. This means that common\nexpressions like [] instanceof Array or\nObject.getPrototypeOf([]) === Array.prototype may not produce\nexpected results when used inside of scripts evaluated via the vm module.\n\n

    \n

    Some of these problems have known workarounds listed in the issues for\nvm on GitHub. for example, Array.isArray works around\nthe example problem with Array.\n\n

    \n", "type": "module", "displayName": "Globals" } ], "type": "module", "displayName": "Caveats" } ], "methods": [ { "textRaw": "vm.runInThisContext(code, [filename])", "type": "method", "name": "runInThisContext", "desc": "

    vm.runInThisContext() compiles code, runs it and returns the result. Running\ncode does not have access to local scope. filename is optional, it's used only\nin stack traces.\n\n

    \n

    Example of using vm.runInThisContext and eval to run the same code:\n\n

    \n
    var localVar = 123,\n    usingscript, evaled,\n    vm = require('vm');\n\nusingscript = vm.runInThisContext('localVar = 1;',\n  'myfile.vm');\nconsole.log('localVar: ' + localVar + ', usingscript: ' +\n  usingscript);\nevaled = eval('localVar = 1;');\nconsole.log('localVar: ' + localVar + ', evaled: ' +\n  evaled);\n\n// localVar: 123, usingscript: 1\n// localVar: 1, evaled: 1
    \n

    vm.runInThisContext does not have access to the local scope, so localVar is unchanged.\neval does have access to the local scope, so localVar is changed.\n\n

    \n

    In case of syntax error in code, vm.runInThisContext emits the syntax error to stderr\nand throws an exception.\n\n\n

    \n", "signatures": [ { "params": [ { "name": "code" }, { "name": "filename", "optional": true } ] } ] }, { "textRaw": "vm.runInNewContext(code, [sandbox], [filename])", "type": "method", "name": "runInNewContext", "desc": "

    vm.runInNewContext compiles code, then runs it in sandbox and returns the\nresult. Running code does not have access to local scope. The object sandbox\nwill be used as the global object for code.\nsandbox and filename are optional, filename is only used in stack traces.\n\n

    \n

    Example: compile and execute code that increments a global variable and sets a new one.\nThese globals are contained in the sandbox.\n\n

    \n
    var util = require('util'),\n    vm = require('vm'),\n    sandbox = {\n      animal: 'cat',\n      count: 2\n    };\n\nvm.runInNewContext('count += 1; name = "kitty"', sandbox, 'myfile.vm');\nconsole.log(util.inspect(sandbox));\n\n// { animal: 'cat', count: 3, name: 'kitty' }
    \n

    Note that running untrusted code is a tricky business requiring great care. To prevent accidental\nglobal variable leakage, vm.runInNewContext is quite useful, but safely running untrusted code\nrequires a separate process.\n\n

    \n

    In case of syntax error in code, vm.runInNewContext emits the syntax error to stderr\nand throws an exception.\n\n

    \n", "signatures": [ { "params": [ { "name": "code" }, { "name": "sandbox", "optional": true }, { "name": "filename", "optional": true } ] } ] }, { "textRaw": "vm.runInContext(code, context, [filename])", "type": "method", "name": "runInContext", "desc": "

    vm.runInContext compiles code, then runs it in context and returns the\nresult. A (V8) context comprises a global object, together with a set of\nbuilt-in objects and functions. Running code does not have access to local scope\nand the global object held within context will be used as the global object\nfor code.\nfilename is optional, it's used only in stack traces.\n\n

    \n

    Example: compile and execute code in a existing context.\n\n

    \n
    var util = require('util'),\n    vm = require('vm'),\n    initSandbox = {\n      animal: 'cat',\n      count: 2\n    },\n    context = vm.createContext(initSandbox);\n\nvm.runInContext('count += 1; name = "CATT"', context, 'myfile.vm');\nconsole.log(util.inspect(context));\n\n// { animal: 'cat', count: 3, name: 'CATT' }
    \n

    Note that createContext will perform a shallow clone of the supplied sandbox object in order to\ninitialize the global object of the freshly constructed context.\n\n

    \n

    Note that running untrusted code is a tricky business requiring great care. To prevent accidental\nglobal variable leakage, vm.runInContext is quite useful, but safely running untrusted code\nrequires a separate process.\n\n

    \n

    In case of syntax error in code, vm.runInContext emits the syntax error to stderr\nand throws an exception.\n\n

    \n", "signatures": [ { "params": [ { "name": "code" }, { "name": "context" }, { "name": "filename", "optional": true } ] } ] }, { "textRaw": "vm.createContext([initSandbox])", "type": "method", "name": "createContext", "desc": "

    vm.createContext creates a new context which is suitable for use as the 2nd argument of a subsequent\ncall to vm.runInContext. A (V8) context comprises a global object together with a set of\nbuild-in objects and functions. The optional argument initSandbox will be shallow-copied\nto seed the initial contents of the global object used by the context.\n\n

    \n", "signatures": [ { "params": [ { "name": "initSandbox", "optional": true } ] } ] }, { "textRaw": "vm.createScript(code, [filename])", "type": "method", "name": "createScript", "desc": "

    createScript compiles code but does not run it. Instead, it returns a\nvm.Script object representing this compiled code. This script can be run\nlater many times using methods below. The returned script is not bound to any\nglobal object. It is bound before each run, just for that run. filename is\noptional, it's only used in stack traces.\n\n

    \n

    In case of syntax error in code, createScript prints the syntax error to stderr\nand throws an exception.\n\n\n

    \n", "signatures": [ { "params": [ { "name": "code" }, { "name": "filename", "optional": true } ] } ] } ], "classes": [ { "textRaw": "Class: Script", "type": "class", "name": "Script", "desc": "

    A class for running scripts. Returned by vm.createScript.\n\n

    \n", "methods": [ { "textRaw": "script.runInThisContext()", "type": "method", "name": "runInThisContext", "desc": "

    Similar to vm.runInThisContext but a method of a precompiled Script object.\nscript.runInThisContext runs the code of script and returns the result.\nRunning code does not have access to local scope, but does have access to the global object\n(v8: in actual context).\n\n

    \n

    Example of using script.runInThisContext to compile code once and run it multiple times:\n\n

    \n
    var vm = require('vm');\n\nglobalVar = 0;\n\nvar script = vm.createScript('globalVar += 1', 'myfile.vm');\n\nfor (var i = 0; i < 1000 ; i += 1) {\n  script.runInThisContext();\n}\n\nconsole.log(globalVar);\n\n// 1000
    \n", "signatures": [ { "params": [] } ] }, { "textRaw": "script.runInNewContext([sandbox])", "type": "method", "name": "runInNewContext", "desc": "

    Similar to vm.runInNewContext a method of a precompiled Script object.\nscript.runInNewContext runs the code of script with sandbox as the global object and returns the result.\nRunning code does not have access to local scope. sandbox is optional.\n\n

    \n

    Example: compile code that increments a global variable and sets one, then execute this code multiple times.\nThese globals are contained in the sandbox.\n\n

    \n
    var util = require('util'),\n    vm = require('vm'),\n    sandbox = {\n      animal: 'cat',\n      count: 2\n    };\n\nvar script = vm.createScript('count += 1; name = "kitty"', 'myfile.vm');\n\nfor (var i = 0; i < 10 ; i += 1) {\n  script.runInNewContext(sandbox);\n}\n\nconsole.log(util.inspect(sandbox));\n\n// { animal: 'cat', count: 12, name: 'kitty' }
    \n

    Note that running untrusted code is a tricky business requiring great care. To prevent accidental\nglobal variable leakage, script.runInNewContext is quite useful, but safely running untrusted code\nrequires a separate process.\n

    \n", "signatures": [ { "params": [ { "name": "sandbox", "optional": true } ] } ] } ] } ], "type": "module", "displayName": "vm" } ] } node-v0.10.25~dfsg2/doc/api/addons.html0000644000000000000000000006246212270264601016302 0ustar rootroot Addons Node.js v0.10.25 Manual & Documentation

    Node.js v0.10.25 Manual & Documentation


    Addons#

    Addons are dynamically linked shared objects. They can provide glue to C and C++ libraries. The API (at the moment) is rather complex, involving knowledge of several libraries:

    • V8 JavaScript, a C++ library. Used for interfacing with JavaScript: creating objects, calling functions, etc. Documented mostly in the v8.h header file (deps/v8/include/v8.h in the Node source tree), which is also available online.

    • libuv, C event loop library. Anytime one needs to wait for a file descriptor to become readable, wait for a timer, or wait for a signal to be received one will need to interface with libuv. That is, if you perform any I/O, libuv will need to be used.

    • Internal Node libraries. Most importantly is the node::ObjectWrap class which you will likely want to derive from.

    • Others. Look in deps/ for what else is available.

    Node statically compiles all its dependencies into the executable. When compiling your module, you don't need to worry about linking to any of these libraries.

    All of the following examples are available for download and may be used as a starting-point for your own Addon.

    Hello world#

    To get started let's make a small Addon which is the C++ equivalent of the following JavaScript code:

    module.exports.hello = function() { return 'world'; };

    First we create a file hello.cc:

    #include <node.h>
    #include <v8.h>
    
    using namespace v8;
    
    Handle<Value> Method(const Arguments& args) {
      HandleScope scope;
      return scope.Close(String::New("world"));
    }
    
    void init(Handle<Object> exports) {
      exports->Set(String::NewSymbol("hello"),
          FunctionTemplate::New(Method)->GetFunction());
    }
    
    NODE_MODULE(hello, init)

    Note that all Node addons must export an initialization function:

    void Initialize (Handle<Object> exports);
    NODE_MODULE(module_name, Initialize)

    There is no semi-colon after NODE_MODULE as it's not a function (see node.h).

    The module_name needs to match the filename of the final binary (minus the .node suffix).

    The source code needs to be built into hello.node, the binary Addon. To do this we create a file called binding.gyp which describes the configuration to build your module in a JSON-like format. This file gets compiled by node-gyp.

    {
      "targets": [
        {
          "target_name": "hello",
          "sources": [ "hello.cc" ]
        }
      ]
    }

    The next step is to generate the appropriate project build files for the current platform. Use node-gyp configure for that.

    Now you will have either a Makefile (on Unix platforms) or a vcxproj file (on Windows) in the build/ directory. Next invoke the node-gyp build command.

    Now you have your compiled .node bindings file! The compiled bindings end up in build/Release/.

    You can now use the binary addon in a Node project hello.js by pointing require to the recently built hello.node module:

    var addon = require('./build/Release/hello');
    
    console.log(addon.hello()); // 'world'

    Please see patterns below for further information or

    https://github.com/arturadib/node-qt for an example in production.

    Addon patterns#

    Below are some addon patterns to help you get started. Consult the online v8 reference for help with the various v8 calls, and v8's Embedder's Guide for an explanation of several concepts used such as handles, scopes, function templates, etc.

    In order to use these examples you need to compile them using node-gyp. Create the following binding.gyp file:

    {
      "targets": [
        {
          "target_name": "addon",
          "sources": [ "addon.cc" ]
        }
      ]
    }

    In cases where there is more than one .cc file, simply add the file name to the sources array, e.g.:

    "sources": ["addon.cc", "myexample.cc"]

    Now that you have your binding.gyp ready, you can configure and build the addon:

    $ node-gyp configure build

    Function arguments#

    The following pattern illustrates how to read arguments from JavaScript function calls and return a result. This is the main and only needed source addon.cc:

    #define BUILDING_NODE_EXTENSION
    #include <node.h>
    
    using namespace v8;
    
    Handle<Value> Add(const Arguments& args) {
      HandleScope scope;
    
      if (args.Length() < 2) {
        ThrowException(Exception::TypeError(String::New("Wrong number of arguments")));
        return scope.Close(Undefined());
      }
    
      if (!args[0]->IsNumber() || !args[1]->IsNumber()) {
        ThrowException(Exception::TypeError(String::New("Wrong arguments")));
        return scope.Close(Undefined());
      }
    
      Local<Number> num = Number::New(args[0]->NumberValue() +
          args[1]->NumberValue());
      return scope.Close(num);
    }
    
    void Init(Handle<Object> exports) {
      exports->Set(String::NewSymbol("add"),
          FunctionTemplate::New(Add)->GetFunction());
    }
    
    NODE_MODULE(addon, Init)

    You can test it with the following JavaScript snippet:

    var addon = require('./build/Release/addon');
    
    console.log( 'This should be eight:', addon.add(3,5) );

    Callbacks#

    You can pass JavaScript functions to a C++ function and execute them from there. Here's addon.cc:

    #define BUILDING_NODE_EXTENSION
    #include <node.h>
    
    using namespace v8;
    
    Handle<Value> RunCallback(const Arguments& args) {
      HandleScope scope;
    
      Local<Function> cb = Local<Function>::Cast(args[0]);
      const unsigned argc = 1;
      Local<Value> argv[argc] = { Local<Value>::New(String::New("hello world")) };
      cb->Call(Context::GetCurrent()->Global(), argc, argv);
    
      return scope.Close(Undefined());
    }
    
    void Init(Handle<Object> exports, Handle<Object> module) {
      module->Set(String::NewSymbol("exports"),
          FunctionTemplate::New(RunCallback)->GetFunction());
    }
    
    NODE_MODULE(addon, Init)

    Note that this example uses a two-argument form of Init() that receives the full module object as the second argument. This allows the addon to completely overwrite exports with a single function instead of adding the function as a property of exports.

    To test it run the following JavaScript snippet:

    var addon = require('./build/Release/addon');
    
    addon(function(msg){
      console.log(msg); // 'hello world'
    });

    Object factory#

    You can create and return new objects from within a C++ function with this addon.cc pattern, which returns an object with property msg that echoes the string passed to createObject():

    #define BUILDING_NODE_EXTENSION
    #include <node.h>
    
    using namespace v8;
    
    Handle<Value> CreateObject(const Arguments& args) {
      HandleScope scope;
    
      Local<Object> obj = Object::New();
      obj->Set(String::NewSymbol("msg"), args[0]->ToString());
    
      return scope.Close(obj);
    }
    
    void Init(Handle<Object> exports, Handle<Object> module) {
      module->Set(String::NewSymbol("exports"),
          FunctionTemplate::New(CreateObject)->GetFunction());
    }
    
    NODE_MODULE(addon, Init)

    To test it in JavaScript:

    var addon = require('./build/Release/addon');
    
    var obj1 = addon('hello');
    var obj2 = addon('world');
    console.log(obj1.msg+' '+obj2.msg); // 'hello world'

    Function factory#

    This pattern illustrates how to create and return a JavaScript function that wraps a C++ function:

    #define BUILDING_NODE_EXTENSION
    #include <node.h>
    
    using namespace v8;
    
    Handle<Value> MyFunction(const Arguments& args) {
      HandleScope scope;
      return scope.Close(String::New("hello world"));
    }
    
    Handle<Value> CreateFunction(const Arguments& args) {
      HandleScope scope;
    
      Local<FunctionTemplate> tpl = FunctionTemplate::New(MyFunction);
      Local<Function> fn = tpl->GetFunction();
      fn->SetName(String::NewSymbol("theFunction")); // omit this to make it anonymous
    
      return scope.Close(fn);
    }
    
    void Init(Handle<Object> exports, Handle<Object> module) {
      module->Set(String::NewSymbol("exports"),
          FunctionTemplate::New(CreateFunction)->GetFunction());
    }
    
    NODE_MODULE(addon, Init)

    To test:

    var addon = require('./build/Release/addon');
    
    var fn = addon();
    console.log(fn()); // 'hello world'

    Wrapping C++ objects#

    Here we will create a wrapper for a C++ object/class MyObject that can be instantiated in JavaScript through the new operator. First prepare the main module addon.cc:

    #define BUILDING_NODE_EXTENSION
    #include <node.h>
    #include "myobject.h"
    
    using namespace v8;
    
    void InitAll(Handle<Object> exports) {
      MyObject::Init(exports);
    }
    
    NODE_MODULE(addon, InitAll)

    Then in myobject.h make your wrapper inherit from node::ObjectWrap:

    #ifndef MYOBJECT_H
    #define MYOBJECT_H
    
    #include <node.h>
    
    class MyObject : public node::ObjectWrap {
     public:
      static void Init(v8::Handle<v8::Object> exports);
    
     private:
      explicit MyObject(double value = 0);
      ~MyObject();
    
      static v8::Handle<v8::Value> New(const v8::Arguments& args);
      static v8::Handle<v8::Value> PlusOne(const v8::Arguments& args);
      static v8::Persistent<v8::Function> constructor;
      double value_;
    };
    
    #endif

    And in myobject.cc implement the various methods that you want to expose. Here we expose the method plusOne by adding it to the constructor's prototype:

    #define BUILDING_NODE_EXTENSION
    #include <node.h>
    #include "myobject.h"
    
    using namespace v8;
    
    Persistent<Function> MyObject::constructor;
    
    MyObject::MyObject(double value) : value_(value) {
    }
    
    MyObject::~MyObject() {
    }
    
    void MyObject::Init(Handle<Object> exports) {
      // Prepare constructor template
      Local<FunctionTemplate> tpl = FunctionTemplate::New(New);
      tpl->SetClassName(String::NewSymbol("MyObject"));
      tpl->InstanceTemplate()->SetInternalFieldCount(1);
      // Prototype
      tpl->PrototypeTemplate()->Set(String::NewSymbol("plusOne"),
          FunctionTemplate::New(PlusOne)->GetFunction());
      constructor = Persistent<Function>::New(tpl->GetFunction());
      exports->Set(String::NewSymbol("MyObject"), constructor);
    }
    
    Handle<Value> MyObject::New(const Arguments& args) {
      HandleScope scope;
    
      if (args.IsConstructCall()) {
        // Invoked as constructor: `new MyObject(...)`
        double value = args[0]->IsUndefined() ? 0 : args[0]->NumberValue();
        MyObject* obj = new MyObject(value);
        obj->Wrap(args.This());
        return args.This();
      } else {
        // Invoked as plain function `MyObject(...)`, turn into construct call.
        const int argc = 1;
        Local<Value> argv[argc] = { args[0] };
        return scope.Close(constructor->NewInstance(argc, argv));
      }
    }
    
    Handle<Value> MyObject::PlusOne(const Arguments& args) {
      HandleScope scope;
    
      MyObject* obj = ObjectWrap::Unwrap<MyObject>(args.This());
      obj->value_ += 1;
    
      return scope.Close(Number::New(obj->value_));
    }

    Test it with:

    var addon = require('./build/Release/addon');
    
    var obj = new addon.MyObject(10);
    console.log( obj.plusOne() ); // 11
    console.log( obj.plusOne() ); // 12
    console.log( obj.plusOne() ); // 13

    Factory of wrapped objects#

    This is useful when you want to be able to create native objects without explicitly instantiating them with the new operator in JavaScript, e.g.

    var obj = addon.createObject();
    // instead of:
    // var obj = new addon.Object();

    Let's register our createObject method in addon.cc:

    #define BUILDING_NODE_EXTENSION
    #include <node.h>
    #include "myobject.h"
    
    using namespace v8;
    
    Handle<Value> CreateObject(const Arguments& args) {
      HandleScope scope;
      return scope.Close(MyObject::NewInstance(args));
    }
    
    void InitAll(Handle<Object> exports, Handle<Object> module) {
      MyObject::Init();
    
      module->Set(String::NewSymbol("exports"),
          FunctionTemplate::New(CreateObject)->GetFunction());
    }
    
    NODE_MODULE(addon, InitAll)

    In myobject.h we now introduce the static method NewInstance that takes care of instantiating the object (i.e. it does the job of new in JavaScript):

    #define BUILDING_NODE_EXTENSION
    #ifndef MYOBJECT_H
    #define MYOBJECT_H
    
    #include <node.h>
    
    class MyObject : public node::ObjectWrap {
     public:
      static void Init();
      static v8::Handle<v8::Value> NewInstance(const v8::Arguments& args);
    
     private:
      explicit MyObject(double value = 0);
      ~MyObject();
    
      static v8::Handle<v8::Value> New(const v8::Arguments& args);
      static v8::Handle<v8::Value> PlusOne(const v8::Arguments& args);
      static v8::Persistent<v8::Function> constructor;
      double value_;
    };
    
    #endif

    The implementation is similar to the above in myobject.cc:

    #define BUILDING_NODE_EXTENSION
    #include <node.h>
    #include "myobject.h"
    
    using namespace v8;
    
    Persistent<Function> MyObject::constructor;
    
    MyObject::MyObject(double value) : value_(value) {
    }
    
    MyObject::~MyObject() {
    }
    
    void MyObject::Init() {
      // Prepare constructor template
      Local<FunctionTemplate> tpl = FunctionTemplate::New(New);
      tpl->SetClassName(String::NewSymbol("MyObject"));
      tpl->InstanceTemplate()->SetInternalFieldCount(1);
      // Prototype
      tpl->PrototypeTemplate()->Set(String::NewSymbol("plusOne"),
          FunctionTemplate::New(PlusOne)->GetFunction());
      constructor = Persistent<Function>::New(tpl->GetFunction());
    }
    
    Handle<Value> MyObject::New(const Arguments& args) {
      HandleScope scope;
    
      if (args.IsConstructCall()) {
        // Invoked as constructor: `new MyObject(...)`
        double value = args[0]->IsUndefined() ? 0 : args[0]->NumberValue();
        MyObject* obj = new MyObject(value);
        obj->Wrap(args.This());
        return args.This();
      } else {
        // Invoked as plain function `MyObject(...)`, turn into construct call.
        const int argc = 1;
        Local<Value> argv[argc] = { args[0] };
        return scope.Close(constructor->NewInstance(argc, argv));
      }
    }
    
    Handle<Value> MyObject::NewInstance(const Arguments& args) {
      HandleScope scope;
    
      const unsigned argc = 1;
      Handle<Value> argv[argc] = { args[0] };
      Local<Object> instance = constructor->NewInstance(argc, argv);
    
      return scope.Close(instance);
    }
    
    Handle<Value> MyObject::PlusOne(const Arguments& args) {
      HandleScope scope;
    
      MyObject* obj = ObjectWrap::Unwrap<MyObject>(args.This());
      obj->value_ += 1;
    
      return scope.Close(Number::New(obj->value_));
    }

    Test it with:

    var createObject = require('./build/Release/addon');
    
    var obj = createObject(10);
    console.log( obj.plusOne() ); // 11
    console.log( obj.plusOne() ); // 12
    console.log( obj.plusOne() ); // 13
    
    var obj2 = createObject(20);
    console.log( obj2.plusOne() ); // 21
    console.log( obj2.plusOne() ); // 22
    console.log( obj2.plusOne() ); // 23

    Passing wrapped objects around#

    In addition to wrapping and returning C++ objects, you can pass them around by unwrapping them with Node's node::ObjectWrap::Unwrap helper function. In the following addon.cc we introduce a function add() that can take on two MyObject objects:

    #define BUILDING_NODE_EXTENSION
    #include <node.h>
    #include "myobject.h"
    
    using namespace v8;
    
    Handle<Value> CreateObject(const Arguments& args) {
      HandleScope scope;
      return scope.Close(MyObject::NewInstance(args));
    }
    
    Handle<Value> Add(const Arguments& args) {
      HandleScope scope;
    
      MyObject* obj1 = node::ObjectWrap::Unwrap<MyObject>(
          args[0]->ToObject());
      MyObject* obj2 = node::ObjectWrap::Unwrap<MyObject>(
          args[1]->ToObject());
    
      double sum = obj1->Value() + obj2->Value();
      return scope.Close(Number::New(sum));
    }
    
    void InitAll(Handle<Object> exports) {
      MyObject::Init();
    
      exports->Set(String::NewSymbol("createObject"),
          FunctionTemplate::New(CreateObject)->GetFunction());
    
      exports->Set(String::NewSymbol("add"),
          FunctionTemplate::New(Add)->GetFunction());
    }
    
    NODE_MODULE(addon, InitAll)

    To make things interesting we introduce a public method in myobject.h so we can probe private values after unwrapping the object:

    #define BUILDING_NODE_EXTENSION
    #ifndef MYOBJECT_H
    #define MYOBJECT_H
    
    #include <node.h>
    
    class MyObject : public node::ObjectWrap {
     public:
      static void Init();
      static v8::Handle<v8::Value> NewInstance(const v8::Arguments& args);
      double Value() const { return value_; }
    
     private:
      explicit MyObject(double value = 0);
      ~MyObject();
    
      static v8::Handle<v8::Value> New(const v8::Arguments& args);
      static v8::Persistent<v8::Function> constructor;
      double value_;
    };
    
    #endif

    The implementation of myobject.cc is similar as before:

    #define BUILDING_NODE_EXTENSION
    #include <node.h>
    #include "myobject.h"
    
    using namespace v8;
    
    Persistent<Function> MyObject::constructor;
    
    MyObject::MyObject(double value) : value_(value) {
    }
    
    MyObject::~MyObject() {
    }
    
    void MyObject::Init() {
      // Prepare constructor template
      Local<FunctionTemplate> tpl = FunctionTemplate::New(New);
      tpl->SetClassName(String::NewSymbol("MyObject"));
      tpl->InstanceTemplate()->SetInternalFieldCount(1);
      constructor = Persistent<Function>::New(tpl->GetFunction());
    }
    
    Handle<Value> MyObject::New(const Arguments& args) {
      HandleScope scope;
    
      if (args.IsConstructCall()) {
        // Invoked as constructor: `new MyObject(...)`
        double value = args[0]->IsUndefined() ? 0 : args[0]->NumberValue();
        MyObject* obj = new MyObject(value);
        obj->Wrap(args.This());
        return args.This();
      } else {
        // Invoked as plain function `MyObject(...)`, turn into construct call.
        const int argc = 1;
        Local<Value> argv[argc] = { args[0] };
        return scope.Close(constructor->NewInstance(argc, argv));
      }
    }
    
    Handle<Value> MyObject::NewInstance(const Arguments& args) {
      HandleScope scope;
    
      const unsigned argc = 1;
      Handle<Value> argv[argc] = { args[0] };
      Local<Object> instance = constructor->NewInstance(argc, argv);
    
      return scope.Close(instance);
    }

    Test it with:

    var addon = require('./build/Release/addon');
    
    var obj1 = addon.createObject(10);
    var obj2 = addon.createObject(20);
    var result = addon.add(obj1, obj2);
    
    console.log(result); // 30
    node-v0.10.25~dfsg2/doc/api/crypto.markdown0000644000000000000000000004527612270121457017235 0ustar rootroot# Crypto Stability: 2 - Unstable; API changes are being discussed for future versions. Breaking changes will be minimized. See below. Use `require('crypto')` to access this module. The crypto module offers a way of encapsulating secure credentials to be used as part of a secure HTTPS net or http connection. It also offers a set of wrappers for OpenSSL's hash, hmac, cipher, decipher, sign and verify methods. ## crypto.getCiphers() Returns an array with the names of the supported ciphers. Example: var ciphers = crypto.getCiphers(); console.log(ciphers); // ['AES-128-CBC', 'AES-128-CBC-HMAC-SHA1', ...] ## crypto.getHashes() Returns an array with the names of the supported hash algorithms. Example: var hashes = crypto.getHashes(); console.log(hashes); // ['sha', 'sha1', 'sha1WithRSAEncryption', ...] ## crypto.createCredentials(details) Creates a credentials object, with the optional details being a dictionary with keys: * `pfx` : A string or buffer holding the PFX or PKCS12 encoded private key, certificate and CA certificates * `key` : A string holding the PEM encoded private key * `passphrase` : A string of passphrase for the private key or pfx * `cert` : A string holding the PEM encoded certificate * `ca` : Either a string or list of strings of PEM encoded CA certificates to trust. * `crl` : Either a string or list of strings of PEM encoded CRLs (Certificate Revocation List) * `ciphers`: A string describing the ciphers to use or exclude. Consult for details on the format. If no 'ca' details are given, then node.js will use the default publicly trusted list of CAs as given in . ## crypto.createHash(algorithm) Creates and returns a hash object, a cryptographic hash with the given algorithm which can be used to generate hash digests. `algorithm` is dependent on the available algorithms supported by the version of OpenSSL on the platform. Examples are `'sha1'`, `'md5'`, `'sha256'`, `'sha512'`, etc. On recent releases, `openssl list-message-digest-algorithms` will display the available digest algorithms. Example: this program that takes the sha1 sum of a file var filename = process.argv[2]; var crypto = require('crypto'); var fs = require('fs'); var shasum = crypto.createHash('sha1'); var s = fs.ReadStream(filename); s.on('data', function(d) { shasum.update(d); }); s.on('end', function() { var d = shasum.digest('hex'); console.log(d + ' ' + filename); }); ## Class: Hash The class for creating hash digests of data. It is a [stream](stream.html) that is both readable and writable. The written data is used to compute the hash. Once the writable side of the stream is ended, use the `read()` method to get the computed hash digest. The legacy `update` and `digest` methods are also supported. Returned by `crypto.createHash`. ### hash.update(data, [input_encoding]) Updates the hash content with the given `data`, the encoding of which is given in `input_encoding` and can be `'utf8'`, `'ascii'` or `'binary'`. If no encoding is provided and the input is a string an encoding of `'binary'` is enforced. If `data` is a `Buffer` then `input_encoding` is ignored. This can be called many times with new data as it is streamed. ### hash.digest([encoding]) Calculates the digest of all of the passed data to be hashed. The `encoding` can be `'hex'`, `'binary'` or `'base64'`. If no encoding is provided, then a buffer is returned. Note: `hash` object can not be used after `digest()` method has been called. ## crypto.createHmac(algorithm, key) Creates and returns a hmac object, a cryptographic hmac with the given algorithm and key. It is a [stream](stream.html) that is both readable and writable. The written data is used to compute the hmac. Once the writable side of the stream is ended, use the `read()` method to get the computed digest. The legacy `update` and `digest` methods are also supported. `algorithm` is dependent on the available algorithms supported by OpenSSL - see createHash above. `key` is the hmac key to be used. ## Class: Hmac Class for creating cryptographic hmac content. Returned by `crypto.createHmac`. ### hmac.update(data) Update the hmac content with the given `data`. This can be called many times with new data as it is streamed. ### hmac.digest([encoding]) Calculates the digest of all of the passed data to the hmac. The `encoding` can be `'hex'`, `'binary'` or `'base64'`. If no encoding is provided, then a buffer is returned. Note: `hmac` object can not be used after `digest()` method has been called. ## crypto.createCipher(algorithm, password) Creates and returns a cipher object, with the given algorithm and password. `algorithm` is dependent on OpenSSL, examples are `'aes192'`, etc. On recent releases, `openssl list-cipher-algorithms` will display the available cipher algorithms. `password` is used to derive key and IV, which must be a `'binary'` encoded string or a [buffer](buffer.html). It is a [stream](stream.html) that is both readable and writable. The written data is used to compute the hash. Once the writable side of the stream is ended, use the `read()` method to get the computed hash digest. The legacy `update` and `digest` methods are also supported. ## crypto.createCipheriv(algorithm, key, iv) Creates and returns a cipher object, with the given algorithm, key and iv. `algorithm` is the same as the argument to `createCipher()`. `key` is the raw key used by the algorithm. `iv` is an [initialization vector](http://en.wikipedia.org/wiki/Initialization_vector). `key` and `iv` must be `'binary'` encoded strings or [buffers](buffer.html). ## Class: Cipher Class for encrypting data. Returned by `crypto.createCipher` and `crypto.createCipheriv`. Cipher objects are [streams](stream.html) that are both readable and writable. The written plain text data is used to produce the encrypted data on the readable side. The legacy `update` and `final` methods are also supported. ### cipher.update(data, [input_encoding], [output_encoding]) Updates the cipher with `data`, the encoding of which is given in `input_encoding` and can be `'utf8'`, `'ascii'` or `'binary'`. If no encoding is provided, then a buffer is expected. If `data` is a `Buffer` then `input_encoding` is ignored. The `output_encoding` specifies the output format of the enciphered data, and can be `'binary'`, `'base64'` or `'hex'`. If no encoding is provided, then a buffer is returned. Returns the enciphered contents, and can be called many times with new data as it is streamed. ### cipher.final([output_encoding]) Returns any remaining enciphered contents, with `output_encoding` being one of: `'binary'`, `'base64'` or `'hex'`. If no encoding is provided, then a buffer is returned. Note: `cipher` object can not be used after `final()` method has been called. ### cipher.setAutoPadding(auto_padding=true) You can disable automatic padding of the input data to block size. If `auto_padding` is false, the length of the entire input data must be a multiple of the cipher's block size or `final` will fail. Useful for non-standard padding, e.g. using `0x0` instead of PKCS padding. You must call this before `cipher.final`. ## crypto.createDecipher(algorithm, password) Creates and returns a decipher object, with the given algorithm and key. This is the mirror of the [createCipher()][] above. ## crypto.createDecipheriv(algorithm, key, iv) Creates and returns a decipher object, with the given algorithm, key and iv. This is the mirror of the [createCipheriv()][] above. ## Class: Decipher Class for decrypting data. Returned by `crypto.createDecipher` and `crypto.createDecipheriv`. Decipher objects are [streams](stream.html) that are both readable and writable. The written enciphered data is used to produce the plain-text data on the the readable side. The legacy `update` and `final` methods are also supported. ### decipher.update(data, [input_encoding], [output_encoding]) Updates the decipher with `data`, which is encoded in `'binary'`, `'base64'` or `'hex'`. If no encoding is provided, then a buffer is expected. If `data` is a `Buffer` then `input_encoding` is ignored. The `output_decoding` specifies in what format to return the deciphered plaintext: `'binary'`, `'ascii'` or `'utf8'`. If no encoding is provided, then a buffer is returned. ### decipher.final([output_encoding]) Returns any remaining plaintext which is deciphered, with `output_encoding` being one of: `'binary'`, `'ascii'` or `'utf8'`. If no encoding is provided, then a buffer is returned. Note: `decipher` object can not be used after `final()` method has been called. ### decipher.setAutoPadding(auto_padding=true) You can disable auto padding if the data has been encrypted without standard block padding to prevent `decipher.final` from checking and removing it. Can only work if the input data's length is a multiple of the ciphers block size. You must call this before streaming data to `decipher.update`. ## crypto.createSign(algorithm) Creates and returns a signing object, with the given algorithm. On recent OpenSSL releases, `openssl list-public-key-algorithms` will display the available signing algorithms. Examples are `'RSA-SHA256'`. ## Class: Sign Class for generating signatures. Returned by `crypto.createSign`. Sign objects are writable [streams](stream.html). The written data is used to generate the signature. Once all of the data has been written, the `sign` method will return the signature. The legacy `update` method is also supported. ### sign.update(data) Updates the sign object with data. This can be called many times with new data as it is streamed. ### sign.sign(private_key, [output_format]) Calculates the signature on all the updated data passed through the sign. `private_key` is a string containing the PEM encoded private key for signing. Returns the signature in `output_format` which can be `'binary'`, `'hex'` or `'base64'`. If no encoding is provided, then a buffer is returned. Note: `sign` object can not be used after `sign()` method has been called. ## crypto.createVerify(algorithm) Creates and returns a verification object, with the given algorithm. This is the mirror of the signing object above. ## Class: Verify Class for verifying signatures. Returned by `crypto.createVerify`. Verify objects are writable [streams](stream.html). The written data is used to validate against the supplied signature. Once all of the data has been written, the `verify` method will return true if the supplied signature is valid. The legacy `update` method is also supported. ### verifier.update(data) Updates the verifier object with data. This can be called many times with new data as it is streamed. ### verifier.verify(object, signature, [signature_format]) Verifies the signed data by using the `object` and `signature`. `object` is a string containing a PEM encoded object, which can be one of RSA public key, DSA public key, or X.509 certificate. `signature` is the previously calculated signature for the data, in the `signature_format` which can be `'binary'`, `'hex'` or `'base64'`. If no encoding is specified, then a buffer is expected. Returns true or false depending on the validity of the signature for the data and public key. Note: `verifier` object can not be used after `verify()` method has been called. ## crypto.createDiffieHellman(prime_length) Creates a Diffie-Hellman key exchange object and generates a prime of the given bit length. The generator used is `2`. ## crypto.createDiffieHellman(prime, [encoding]) Creates a Diffie-Hellman key exchange object using the supplied prime. The generator used is `2`. Encoding can be `'binary'`, `'hex'`, or `'base64'`. If no encoding is specified, then a buffer is expected. ## Class: DiffieHellman The class for creating Diffie-Hellman key exchanges. Returned by `crypto.createDiffieHellman`. ### diffieHellman.generateKeys([encoding]) Generates private and public Diffie-Hellman key values, and returns the public key in the specified encoding. This key should be transferred to the other party. Encoding can be `'binary'`, `'hex'`, or `'base64'`. If no encoding is provided, then a buffer is returned. ### diffieHellman.computeSecret(other_public_key, [input_encoding], [output_encoding]) Computes the shared secret using `other_public_key` as the other party's public key and returns the computed shared secret. Supplied key is interpreted using specified `input_encoding`, and secret is encoded using specified `output_encoding`. Encodings can be `'binary'`, `'hex'`, or `'base64'`. If the input encoding is not provided, then a buffer is expected. If no output encoding is given, then a buffer is returned. ### diffieHellman.getPrime([encoding]) Returns the Diffie-Hellman prime in the specified encoding, which can be `'binary'`, `'hex'`, or `'base64'`. If no encoding is provided, then a buffer is returned. ### diffieHellman.getGenerator([encoding]) Returns the Diffie-Hellman prime in the specified encoding, which can be `'binary'`, `'hex'`, or `'base64'`. If no encoding is provided, then a buffer is returned. ### diffieHellman.getPublicKey([encoding]) Returns the Diffie-Hellman public key in the specified encoding, which can be `'binary'`, `'hex'`, or `'base64'`. If no encoding is provided, then a buffer is returned. ### diffieHellman.getPrivateKey([encoding]) Returns the Diffie-Hellman private key in the specified encoding, which can be `'binary'`, `'hex'`, or `'base64'`. If no encoding is provided, then a buffer is returned. ### diffieHellman.setPublicKey(public_key, [encoding]) Sets the Diffie-Hellman public key. Key encoding can be `'binary'`, `'hex'` or `'base64'`. If no encoding is provided, then a buffer is expected. ### diffieHellman.setPrivateKey(private_key, [encoding]) Sets the Diffie-Hellman private key. Key encoding can be `'binary'`, `'hex'` or `'base64'`. If no encoding is provided, then a buffer is expected. ## crypto.getDiffieHellman(group_name) Creates a predefined Diffie-Hellman key exchange object. The supported groups are: `'modp1'`, `'modp2'`, `'modp5'` (defined in [RFC 2412][]) and `'modp14'`, `'modp15'`, `'modp16'`, `'modp17'`, `'modp18'` (defined in [RFC 3526][]). The returned object mimics the interface of objects created by [crypto.createDiffieHellman()][] above, but will not allow to change the keys (with [diffieHellman.setPublicKey()][] for example). The advantage of using this routine is that the parties don't have to generate nor exchange group modulus beforehand, saving both processor and communication time. Example (obtaining a shared secret): var crypto = require('crypto'); var alice = crypto.getDiffieHellman('modp5'); var bob = crypto.getDiffieHellman('modp5'); alice.generateKeys(); bob.generateKeys(); var alice_secret = alice.computeSecret(bob.getPublicKey(), null, 'hex'); var bob_secret = bob.computeSecret(alice.getPublicKey(), null, 'hex'); /* alice_secret and bob_secret should be the same */ console.log(alice_secret == bob_secret); ## crypto.pbkdf2(password, salt, iterations, keylen, callback) Asynchronous PBKDF2 applies pseudorandom function HMAC-SHA1 to derive a key of given length from the given password, salt and iterations. The callback gets two arguments `(err, derivedKey)`. ## crypto.pbkdf2Sync(password, salt, iterations, keylen) Synchronous PBKDF2 function. Returns derivedKey or throws error. ## crypto.randomBytes(size, [callback]) Generates cryptographically strong pseudo-random data. Usage: // async crypto.randomBytes(256, function(ex, buf) { if (ex) throw ex; console.log('Have %d bytes of random data: %s', buf.length, buf); }); // sync try { var buf = crypto.randomBytes(256); console.log('Have %d bytes of random data: %s', buf.length, buf); } catch (ex) { // handle error // most likely, entropy sources are drained } NOTE: Will throw error or invoke callback with error, if there is not enough accumulated entropy to generate cryptographically strong data. In other words, `crypto.randomBytes` without callback will not block even if all entropy sources are drained. ## crypto.pseudoRandomBytes(size, [callback]) Generates *non*-cryptographically strong pseudo-random data. The data returned will be unique if it is sufficiently long, but is not necessarily unpredictable. For this reason, the output of this function should never be used where unpredictability is important, such as in the generation of encryption keys. Usage is otherwise identical to `crypto.randomBytes`. ## crypto.DEFAULT_ENCODING The default encoding to use for functions that can take either strings or buffers. The default value is `'buffer'`, which makes it default to using Buffer objects. This is here to make the crypto module more easily compatible with legacy programs that expected `'binary'` to be the default encoding. Note that new programs will probably expect buffers, so only use this as a temporary measure. ## Recent API Changes The Crypto module was added to Node before there was the concept of a unified Stream API, and before there were Buffer objects for handling binary data. As such, the streaming classes don't have the typical methods found on other Node classes, and many methods accepted and returned Binary-encoded strings by default rather than Buffers. This was changed to use Buffers by default instead. This is a breaking change for some use cases, but not all. For example, if you currently use the default arguments to the Sign class, and then pass the results to the Verify class, without ever inspecting the data, then it will continue to work as before. Where you once got a binary string and then presented the binary string to the Verify object, you'll now get a Buffer, and present the Buffer to the Verify object. However, if you were doing things with the string data that will not work properly on Buffers (such as, concatenating them, storing in databases, etc.), or you are passing binary strings to the crypto functions without an encoding argument, then you will need to start providing encoding arguments to specify which encoding you'd like to use. To switch to the previous style of using binary strings by default, set the `crypto.DEFAULT_ENCODING` field to 'binary'. Note that new programs will probably expect buffers, so only use this as a temporary measure. [createCipher()]: #crypto_crypto_createcipher_algorithm_password [createCipheriv()]: #crypto_crypto_createcipheriv_algorithm_key_iv [crypto.createDiffieHellman()]: #crypto_crypto_creatediffiehellman_prime_encoding [diffieHellman.setPublicKey()]: #crypto_diffiehellman_setpublickey_public_key_encoding [RFC 2412]: http://www.rfc-editor.org/rfc/rfc2412.txt [RFC 3526]: http://www.rfc-editor.org/rfc/rfc3526.txt node-v0.10.25~dfsg2/doc/api/util.json0000644000000000000000000003224212270264601016005 0ustar rootroot{ "source": "doc/api/util.markdown", "modules": [ { "textRaw": "util", "name": "util", "stability": 4, "stabilityText": "API Frozen", "desc": "

    These functions are in the module 'util'. Use require('util') to access\nthem.\n\n\n

    \n", "methods": [ { "textRaw": "util.format(format, [...])", "type": "method", "name": "format", "desc": "

    Returns a formatted string using the first argument as a printf-like format.\n\n

    \n

    The first argument is a string that contains zero or more placeholders.\nEach placeholder is replaced with the converted value from its corresponding\nargument. Supported placeholders are:\n\n

    \n
      \n
    • %s - String.
    • \n
    • %d - Number (both integer and float).
    • \n
    • %j - JSON.
    • \n
    • % - single percent sign ('%'). This does not consume an argument.
    • \n
    \n

    If the placeholder does not have a corresponding argument, the placeholder is\nnot replaced.\n\n

    \n
    util.format('%s:%s', 'foo'); // 'foo:%s'
    \n

    If there are more arguments than placeholders, the extra arguments are\nconverted to strings with util.inspect() and these strings are concatenated,\ndelimited by a space.\n\n

    \n
    util.format('%s:%s', 'foo', 'bar', 'baz'); // 'foo:bar baz'
    \n

    If the first argument is not a format string then util.format() returns\na string that is the concatenation of all its arguments separated by spaces.\nEach argument is converted to a string with util.inspect().\n\n

    \n
    util.format(1, 2, 3); // '1 2 3'
    \n", "signatures": [ { "params": [ { "name": "format" }, { "name": "...", "optional": true } ] } ] }, { "textRaw": "util.debug(string)", "type": "method", "name": "debug", "desc": "

    A synchronous output function. Will block the process and\noutput string immediately to stderr.\n\n

    \n
    require('util').debug('message on stderr');
    \n", "signatures": [ { "params": [ { "name": "string" } ] } ] }, { "textRaw": "util.error([...])", "type": "method", "name": "error", "desc": "

    Same as util.debug() except this will output all arguments immediately to\nstderr.\n\n

    \n", "signatures": [ { "params": [ { "name": "...", "optional": true } ] } ] }, { "textRaw": "util.puts([...])", "type": "method", "name": "puts", "desc": "

    A synchronous output function. Will block the process and output all arguments\nto stdout with newlines after each argument.\n\n

    \n", "signatures": [ { "params": [ { "name": "...", "optional": true } ] } ] }, { "textRaw": "util.print([...])", "type": "method", "name": "print", "desc": "

    A synchronous output function. Will block the process, cast each argument to a\nstring then output to stdout. Does not place newlines after each argument.\n\n

    \n", "signatures": [ { "params": [ { "name": "...", "optional": true } ] } ] }, { "textRaw": "util.log(string)", "type": "method", "name": "log", "desc": "

    Output with timestamp on stdout.\n\n

    \n
    require('util').log('Timestamped message.');
    \n", "signatures": [ { "params": [ { "name": "string" } ] } ] }, { "textRaw": "util.inspect(object, [options])", "type": "method", "name": "inspect", "desc": "

    Return a string representation of object, which is useful for debugging.\n\n

    \n

    An optional options object may be passed that alters certain aspects of the\nformatted string:\n\n

    \n
      \n
    • showHidden - if true then the object's non-enumerable properties will be\nshown too. Defaults to false.

      \n
    • \n
    • depth - tells inspect how many times to recurse while formatting the\nobject. This is useful for inspecting large complicated objects. Defaults to\n2. To make it recurse indefinitely pass null.

      \n
    • \n
    • colors - if true, then the output will be styled with ANSI color codes.\nDefaults to false. Colors are customizable, see below.

      \n
    • \n
    • customInspect - if false, then custom inspect() functions defined on the\nobjects being inspected won't be called. Defaults to true.

      \n
    • \n
    \n

    Example of inspecting all properties of the util object:\n\n

    \n
    var util = require('util');\n\nconsole.log(util.inspect(util, { showHidden: true, depth: null }));
    \n", "modules": [ { "textRaw": "Customizing `util.inspect` colors", "name": "customizing_`util.inspect`_colors", "desc": "

    Color output (if enabled) of util.inspect is customizable globally\nvia util.inspect.styles and util.inspect.colors objects.\n\n

    \n

    util.inspect.styles is a map assigning each style a color\nfrom util.inspect.colors.\nHighlighted styles and their default values are:\n number (yellow)\n boolean (yellow)\n string (green)\n date (magenta)\n regexp (red)\n null (bold)\n undefined (grey)\n special - only function at this time (cyan)\n * name (intentionally no styling)\n\n

    \n

    Predefined color codes are: white, grey, black, blue, cyan, \ngreen, magenta, red and yellow.\nThere are also bold, italic, underline and inverse codes.\n\n

    \n

    Objects also may define their own inspect(depth) function which util.inspect()\nwill invoke and use the result of when inspecting the object:\n\n

    \n
    var util = require('util');\n\nvar obj = { name: 'nate' };\nobj.inspect = function(depth) {\n  return '{' + this.name + '}';\n};\n\nutil.inspect(obj);\n  // "{nate}"
    \n", "type": "module", "displayName": "Customizing `util.inspect` colors" } ], "signatures": [ { "params": [ { "name": "object" }, { "name": "options", "optional": true } ] } ] }, { "textRaw": "util.isArray(object)", "type": "method", "name": "isArray", "desc": "

    Returns true if the given "object" is an Array. false otherwise.\n\n

    \n
    var util = require('util');\n\nutil.isArray([])\n  // true\nutil.isArray(new Array)\n  // true\nutil.isArray({})\n  // false
    \n", "signatures": [ { "params": [ { "name": "object" } ] } ] }, { "textRaw": "util.isRegExp(object)", "type": "method", "name": "isRegExp", "desc": "

    Returns true if the given "object" is a RegExp. false otherwise.\n\n

    \n
    var util = require('util');\n\nutil.isRegExp(/some regexp/)\n  // true\nutil.isRegExp(new RegExp('another regexp'))\n  // true\nutil.isRegExp({})\n  // false
    \n", "signatures": [ { "params": [ { "name": "object" } ] } ] }, { "textRaw": "util.isDate(object)", "type": "method", "name": "isDate", "desc": "

    Returns true if the given "object" is a Date. false otherwise.\n\n

    \n
    var util = require('util');\n\nutil.isDate(new Date())\n  // true\nutil.isDate(Date())\n  // false (without 'new' returns a String)\nutil.isDate({})\n  // false
    \n", "signatures": [ { "params": [ { "name": "object" } ] } ] }, { "textRaw": "util.isError(object)", "type": "method", "name": "isError", "desc": "

    Returns true if the given "object" is an Error. false otherwise.\n\n

    \n
    var util = require('util');\n\nutil.isError(new Error())\n  // true\nutil.isError(new TypeError())\n  // true\nutil.isError({ name: 'Error', message: 'an error occurred' })\n  // false
    \n", "signatures": [ { "params": [ { "name": "object" } ] } ] }, { "textRaw": "util.pump(readableStream, writableStream, [callback])", "type": "method", "name": "pump", "stability": 0, "stabilityText": "Deprecated: Use readableStream.pipe(writableStream)", "desc": "

    Read the data from readableStream and send it to the writableStream.\nWhen writableStream.write(data) returns false readableStream will be\npaused until the drain event occurs on the writableStream. callback gets\nan error as its only argument and is called when writableStream is closed or\nwhen an error occurs.\n\n\n

    \n", "signatures": [ { "params": [ { "name": "readableStream" }, { "name": "writableStream" }, { "name": "callback", "optional": true } ] } ] }, { "textRaw": "util.inherits(constructor, superConstructor)", "type": "method", "name": "inherits", "desc": "

    Inherit the prototype methods from one\nconstructor\ninto another. The prototype of constructor will be set to a new\nobject created from superConstructor.\n\n

    \n

    As an additional convenience, superConstructor will be accessible\nthrough the constructor.super_ property.\n\n

    \n
    var util = require("util");\nvar events = require("events");\n\nfunction MyStream() {\n    events.EventEmitter.call(this);\n}\n\nutil.inherits(MyStream, events.EventEmitter);\n\nMyStream.prototype.write = function(data) {\n    this.emit("data", data);\n}\n\nvar stream = new MyStream();\n\nconsole.log(stream instanceof events.EventEmitter); // true\nconsole.log(MyStream.super_ === events.EventEmitter); // true\n\nstream.on("data", function(data) {\n    console.log('Received data: "' + data + '"');\n})\nstream.write("It works!"); // Received data: "It works!"
    \n", "signatures": [ { "params": [ { "name": "constructor" }, { "name": "superConstructor" } ] } ] } ], "type": "module", "displayName": "util" } ] } node-v0.10.25~dfsg2/doc/api/addons.markdown0000644000000000000000000004515612270121457017162 0ustar rootroot# Addons Addons are dynamically linked shared objects. They can provide glue to C and C++ libraries. The API (at the moment) is rather complex, involving knowledge of several libraries: - V8 JavaScript, a C++ library. Used for interfacing with JavaScript: creating objects, calling functions, etc. Documented mostly in the `v8.h` header file (`deps/v8/include/v8.h` in the Node source tree), which is also available [online](http://izs.me/v8-docs/main.html). - [libuv](https://github.com/joyent/libuv), C event loop library. Anytime one needs to wait for a file descriptor to become readable, wait for a timer, or wait for a signal to be received one will need to interface with libuv. That is, if you perform any I/O, libuv will need to be used. - Internal Node libraries. Most importantly is the `node::ObjectWrap` class which you will likely want to derive from. - Others. Look in `deps/` for what else is available. Node statically compiles all its dependencies into the executable. When compiling your module, you don't need to worry about linking to any of these libraries. All of the following examples are available for [download](https://github.com/rvagg/node-addon-examples) and may be used as a starting-point for your own Addon. ## Hello world To get started let's make a small Addon which is the C++ equivalent of the following JavaScript code: module.exports.hello = function() { return 'world'; }; First we create a file `hello.cc`: #include #include using namespace v8; Handle Method(const Arguments& args) { HandleScope scope; return scope.Close(String::New("world")); } void init(Handle exports) { exports->Set(String::NewSymbol("hello"), FunctionTemplate::New(Method)->GetFunction()); } NODE_MODULE(hello, init) Note that all Node addons must export an initialization function: void Initialize (Handle exports); NODE_MODULE(module_name, Initialize) There is no semi-colon after `NODE_MODULE` as it's not a function (see `node.h`). The `module_name` needs to match the filename of the final binary (minus the .node suffix). The source code needs to be built into `hello.node`, the binary Addon. To do this we create a file called `binding.gyp` which describes the configuration to build your module in a JSON-like format. This file gets compiled by [node-gyp](https://github.com/TooTallNate/node-gyp). { "targets": [ { "target_name": "hello", "sources": [ "hello.cc" ] } ] } The next step is to generate the appropriate project build files for the current platform. Use `node-gyp configure` for that. Now you will have either a `Makefile` (on Unix platforms) or a `vcxproj` file (on Windows) in the `build/` directory. Next invoke the `node-gyp build` command. Now you have your compiled `.node` bindings file! The compiled bindings end up in `build/Release/`. You can now use the binary addon in a Node project `hello.js` by pointing `require` to the recently built `hello.node` module: var addon = require('./build/Release/hello'); console.log(addon.hello()); // 'world' Please see patterns below for further information or for an example in production. ## Addon patterns Below are some addon patterns to help you get started. Consult the online [v8 reference](http://izs.me/v8-docs/main.html) for help with the various v8 calls, and v8's [Embedder's Guide](http://code.google.com/apis/v8/embed.html) for an explanation of several concepts used such as handles, scopes, function templates, etc. In order to use these examples you need to compile them using `node-gyp`. Create the following `binding.gyp` file: { "targets": [ { "target_name": "addon", "sources": [ "addon.cc" ] } ] } In cases where there is more than one `.cc` file, simply add the file name to the `sources` array, e.g.: "sources": ["addon.cc", "myexample.cc"] Now that you have your `binding.gyp` ready, you can configure and build the addon: $ node-gyp configure build ### Function arguments The following pattern illustrates how to read arguments from JavaScript function calls and return a result. This is the main and only needed source `addon.cc`: #define BUILDING_NODE_EXTENSION #include using namespace v8; Handle Add(const Arguments& args) { HandleScope scope; if (args.Length() < 2) { ThrowException(Exception::TypeError(String::New("Wrong number of arguments"))); return scope.Close(Undefined()); } if (!args[0]->IsNumber() || !args[1]->IsNumber()) { ThrowException(Exception::TypeError(String::New("Wrong arguments"))); return scope.Close(Undefined()); } Local num = Number::New(args[0]->NumberValue() + args[1]->NumberValue()); return scope.Close(num); } void Init(Handle exports) { exports->Set(String::NewSymbol("add"), FunctionTemplate::New(Add)->GetFunction()); } NODE_MODULE(addon, Init) You can test it with the following JavaScript snippet: var addon = require('./build/Release/addon'); console.log( 'This should be eight:', addon.add(3,5) ); ### Callbacks You can pass JavaScript functions to a C++ function and execute them from there. Here's `addon.cc`: #define BUILDING_NODE_EXTENSION #include using namespace v8; Handle RunCallback(const Arguments& args) { HandleScope scope; Local cb = Local::Cast(args[0]); const unsigned argc = 1; Local argv[argc] = { Local::New(String::New("hello world")) }; cb->Call(Context::GetCurrent()->Global(), argc, argv); return scope.Close(Undefined()); } void Init(Handle exports, Handle module) { module->Set(String::NewSymbol("exports"), FunctionTemplate::New(RunCallback)->GetFunction()); } NODE_MODULE(addon, Init) Note that this example uses a two-argument form of `Init()` that receives the full `module` object as the second argument. This allows the addon to completely overwrite `exports` with a single function instead of adding the function as a property of `exports`. To test it run the following JavaScript snippet: var addon = require('./build/Release/addon'); addon(function(msg){ console.log(msg); // 'hello world' }); ### Object factory You can create and return new objects from within a C++ function with this `addon.cc` pattern, which returns an object with property `msg` that echoes the string passed to `createObject()`: #define BUILDING_NODE_EXTENSION #include using namespace v8; Handle CreateObject(const Arguments& args) { HandleScope scope; Local obj = Object::New(); obj->Set(String::NewSymbol("msg"), args[0]->ToString()); return scope.Close(obj); } void Init(Handle exports, Handle module) { module->Set(String::NewSymbol("exports"), FunctionTemplate::New(CreateObject)->GetFunction()); } NODE_MODULE(addon, Init) To test it in JavaScript: var addon = require('./build/Release/addon'); var obj1 = addon('hello'); var obj2 = addon('world'); console.log(obj1.msg+' '+obj2.msg); // 'hello world' ### Function factory This pattern illustrates how to create and return a JavaScript function that wraps a C++ function: #define BUILDING_NODE_EXTENSION #include using namespace v8; Handle MyFunction(const Arguments& args) { HandleScope scope; return scope.Close(String::New("hello world")); } Handle CreateFunction(const Arguments& args) { HandleScope scope; Local tpl = FunctionTemplate::New(MyFunction); Local fn = tpl->GetFunction(); fn->SetName(String::NewSymbol("theFunction")); // omit this to make it anonymous return scope.Close(fn); } void Init(Handle exports, Handle module) { module->Set(String::NewSymbol("exports"), FunctionTemplate::New(CreateFunction)->GetFunction()); } NODE_MODULE(addon, Init) To test: var addon = require('./build/Release/addon'); var fn = addon(); console.log(fn()); // 'hello world' ### Wrapping C++ objects Here we will create a wrapper for a C++ object/class `MyObject` that can be instantiated in JavaScript through the `new` operator. First prepare the main module `addon.cc`: #define BUILDING_NODE_EXTENSION #include #include "myobject.h" using namespace v8; void InitAll(Handle exports) { MyObject::Init(exports); } NODE_MODULE(addon, InitAll) Then in `myobject.h` make your wrapper inherit from `node::ObjectWrap`: #ifndef MYOBJECT_H #define MYOBJECT_H #include class MyObject : public node::ObjectWrap { public: static void Init(v8::Handle exports); private: explicit MyObject(double value = 0); ~MyObject(); static v8::Handle New(const v8::Arguments& args); static v8::Handle PlusOne(const v8::Arguments& args); static v8::Persistent constructor; double value_; }; #endif And in `myobject.cc` implement the various methods that you want to expose. Here we expose the method `plusOne` by adding it to the constructor's prototype: #define BUILDING_NODE_EXTENSION #include #include "myobject.h" using namespace v8; Persistent MyObject::constructor; MyObject::MyObject(double value) : value_(value) { } MyObject::~MyObject() { } void MyObject::Init(Handle exports) { // Prepare constructor template Local tpl = FunctionTemplate::New(New); tpl->SetClassName(String::NewSymbol("MyObject")); tpl->InstanceTemplate()->SetInternalFieldCount(1); // Prototype tpl->PrototypeTemplate()->Set(String::NewSymbol("plusOne"), FunctionTemplate::New(PlusOne)->GetFunction()); constructor = Persistent::New(tpl->GetFunction()); exports->Set(String::NewSymbol("MyObject"), constructor); } Handle MyObject::New(const Arguments& args) { HandleScope scope; if (args.IsConstructCall()) { // Invoked as constructor: `new MyObject(...)` double value = args[0]->IsUndefined() ? 0 : args[0]->NumberValue(); MyObject* obj = new MyObject(value); obj->Wrap(args.This()); return args.This(); } else { // Invoked as plain function `MyObject(...)`, turn into construct call. const int argc = 1; Local argv[argc] = { args[0] }; return scope.Close(constructor->NewInstance(argc, argv)); } } Handle MyObject::PlusOne(const Arguments& args) { HandleScope scope; MyObject* obj = ObjectWrap::Unwrap(args.This()); obj->value_ += 1; return scope.Close(Number::New(obj->value_)); } Test it with: var addon = require('./build/Release/addon'); var obj = new addon.MyObject(10); console.log( obj.plusOne() ); // 11 console.log( obj.plusOne() ); // 12 console.log( obj.plusOne() ); // 13 ### Factory of wrapped objects This is useful when you want to be able to create native objects without explicitly instantiating them with the `new` operator in JavaScript, e.g. var obj = addon.createObject(); // instead of: // var obj = new addon.Object(); Let's register our `createObject` method in `addon.cc`: #define BUILDING_NODE_EXTENSION #include #include "myobject.h" using namespace v8; Handle CreateObject(const Arguments& args) { HandleScope scope; return scope.Close(MyObject::NewInstance(args)); } void InitAll(Handle exports, Handle module) { MyObject::Init(); module->Set(String::NewSymbol("exports"), FunctionTemplate::New(CreateObject)->GetFunction()); } NODE_MODULE(addon, InitAll) In `myobject.h` we now introduce the static method `NewInstance` that takes care of instantiating the object (i.e. it does the job of `new` in JavaScript): #define BUILDING_NODE_EXTENSION #ifndef MYOBJECT_H #define MYOBJECT_H #include class MyObject : public node::ObjectWrap { public: static void Init(); static v8::Handle NewInstance(const v8::Arguments& args); private: explicit MyObject(double value = 0); ~MyObject(); static v8::Handle New(const v8::Arguments& args); static v8::Handle PlusOne(const v8::Arguments& args); static v8::Persistent constructor; double value_; }; #endif The implementation is similar to the above in `myobject.cc`: #define BUILDING_NODE_EXTENSION #include #include "myobject.h" using namespace v8; Persistent MyObject::constructor; MyObject::MyObject(double value) : value_(value) { } MyObject::~MyObject() { } void MyObject::Init() { // Prepare constructor template Local tpl = FunctionTemplate::New(New); tpl->SetClassName(String::NewSymbol("MyObject")); tpl->InstanceTemplate()->SetInternalFieldCount(1); // Prototype tpl->PrototypeTemplate()->Set(String::NewSymbol("plusOne"), FunctionTemplate::New(PlusOne)->GetFunction()); constructor = Persistent::New(tpl->GetFunction()); } Handle MyObject::New(const Arguments& args) { HandleScope scope; if (args.IsConstructCall()) { // Invoked as constructor: `new MyObject(...)` double value = args[0]->IsUndefined() ? 0 : args[0]->NumberValue(); MyObject* obj = new MyObject(value); obj->Wrap(args.This()); return args.This(); } else { // Invoked as plain function `MyObject(...)`, turn into construct call. const int argc = 1; Local argv[argc] = { args[0] }; return scope.Close(constructor->NewInstance(argc, argv)); } } Handle MyObject::NewInstance(const Arguments& args) { HandleScope scope; const unsigned argc = 1; Handle argv[argc] = { args[0] }; Local instance = constructor->NewInstance(argc, argv); return scope.Close(instance); } Handle MyObject::PlusOne(const Arguments& args) { HandleScope scope; MyObject* obj = ObjectWrap::Unwrap(args.This()); obj->value_ += 1; return scope.Close(Number::New(obj->value_)); } Test it with: var createObject = require('./build/Release/addon'); var obj = createObject(10); console.log( obj.plusOne() ); // 11 console.log( obj.plusOne() ); // 12 console.log( obj.plusOne() ); // 13 var obj2 = createObject(20); console.log( obj2.plusOne() ); // 21 console.log( obj2.plusOne() ); // 22 console.log( obj2.plusOne() ); // 23 ### Passing wrapped objects around In addition to wrapping and returning C++ objects, you can pass them around by unwrapping them with Node's `node::ObjectWrap::Unwrap` helper function. In the following `addon.cc` we introduce a function `add()` that can take on two `MyObject` objects: #define BUILDING_NODE_EXTENSION #include #include "myobject.h" using namespace v8; Handle CreateObject(const Arguments& args) { HandleScope scope; return scope.Close(MyObject::NewInstance(args)); } Handle Add(const Arguments& args) { HandleScope scope; MyObject* obj1 = node::ObjectWrap::Unwrap( args[0]->ToObject()); MyObject* obj2 = node::ObjectWrap::Unwrap( args[1]->ToObject()); double sum = obj1->Value() + obj2->Value(); return scope.Close(Number::New(sum)); } void InitAll(Handle exports) { MyObject::Init(); exports->Set(String::NewSymbol("createObject"), FunctionTemplate::New(CreateObject)->GetFunction()); exports->Set(String::NewSymbol("add"), FunctionTemplate::New(Add)->GetFunction()); } NODE_MODULE(addon, InitAll) To make things interesting we introduce a public method in `myobject.h` so we can probe private values after unwrapping the object: #define BUILDING_NODE_EXTENSION #ifndef MYOBJECT_H #define MYOBJECT_H #include class MyObject : public node::ObjectWrap { public: static void Init(); static v8::Handle NewInstance(const v8::Arguments& args); double Value() const { return value_; } private: explicit MyObject(double value = 0); ~MyObject(); static v8::Handle New(const v8::Arguments& args); static v8::Persistent constructor; double value_; }; #endif The implementation of `myobject.cc` is similar as before: #define BUILDING_NODE_EXTENSION #include #include "myobject.h" using namespace v8; Persistent MyObject::constructor; MyObject::MyObject(double value) : value_(value) { } MyObject::~MyObject() { } void MyObject::Init() { // Prepare constructor template Local tpl = FunctionTemplate::New(New); tpl->SetClassName(String::NewSymbol("MyObject")); tpl->InstanceTemplate()->SetInternalFieldCount(1); constructor = Persistent::New(tpl->GetFunction()); } Handle MyObject::New(const Arguments& args) { HandleScope scope; if (args.IsConstructCall()) { // Invoked as constructor: `new MyObject(...)` double value = args[0]->IsUndefined() ? 0 : args[0]->NumberValue(); MyObject* obj = new MyObject(value); obj->Wrap(args.This()); return args.This(); } else { // Invoked as plain function `MyObject(...)`, turn into construct call. const int argc = 1; Local argv[argc] = { args[0] }; return scope.Close(constructor->NewInstance(argc, argv)); } } Handle MyObject::NewInstance(const Arguments& args) { HandleScope scope; const unsigned argc = 1; Handle argv[argc] = { args[0] }; Local instance = constructor->NewInstance(argc, argv); return scope.Close(instance); } Test it with: var addon = require('./build/Release/addon'); var obj1 = addon.createObject(10); var obj2 = addon.createObject(20); var result = addon.add(obj1, obj2); console.log(result); // 30 node-v0.10.25~dfsg2/doc/api/querystring.json0000644000000000000000000000626112270264601017426 0ustar rootroot{ "source": "doc/api/querystring.markdown", "modules": [ { "textRaw": "Query String", "name": "querystring", "stability": 3, "stabilityText": "Stable", "desc": "

    This module provides utilities for dealing with query strings.\nIt provides the following methods:\n\n

    \n", "methods": [ { "textRaw": "querystring.stringify(obj, [sep], [eq])", "type": "method", "name": "stringify", "desc": "

    Serialize an object to a query string.\nOptionally override the default separator ('&') and assignment ('=')\ncharacters.\n\n

    \n

    Example:\n\n

    \n
    querystring.stringify({ foo: 'bar', baz: ['qux', 'quux'], corge: '' })\n// returns\n'foo=bar&baz=qux&baz=quux&corge='\n\nquerystring.stringify({foo: 'bar', baz: 'qux'}, ';', ':')\n// returns\n'foo:bar;baz:qux'
    \n", "signatures": [ { "params": [ { "name": "obj" }, { "name": "sep", "optional": true }, { "name": "eq", "optional": true } ] } ] }, { "textRaw": "querystring.parse(str, [sep], [eq], [options])", "type": "method", "name": "parse", "desc": "

    Deserialize a query string to an object.\nOptionally override the default separator ('&') and assignment ('=')\ncharacters.\n\n

    \n

    Options object may contain maxKeys property (equal to 1000 by default), it'll\nbe used to limit processed keys. Set it to 0 to remove key count limitation.\n\n

    \n

    Example:\n\n

    \n
    querystring.parse('foo=bar&baz=qux&baz=quux&corge')\n// returns\n{ foo: 'bar', baz: ['qux', 'quux'], corge: '' }
    \n", "signatures": [ { "params": [ { "name": "str" }, { "name": "sep", "optional": true }, { "name": "eq", "optional": true }, { "name": "options", "optional": true } ] } ] } ], "properties": [ { "textRaw": "querystring.escape", "name": "escape", "desc": "

    The escape function used by querystring.stringify,\nprovided so that it could be overridden if necessary.\n\n

    \n" }, { "textRaw": "querystring.unescape", "name": "unescape", "desc": "

    The unescape function used by querystring.parse,\nprovided so that it could be overridden if necessary.\n

    \n" } ], "type": "module", "displayName": "querystring" } ] } node-v0.10.25~dfsg2/doc/api/punycode.json0000644000000000000000000001142612270264601016657 0ustar rootroot{ "source": "doc/api/punycode.markdown", "modules": [ { "textRaw": "punycode", "name": "punycode", "stability": 2, "stabilityText": "Unstable", "desc": "

    Punycode.js is bundled with Node.js v0.6.2+. Use\nrequire('punycode') to access it. (To use it with other Node.js versions,\nuse npm to install the punycode module first.)\n\n

    \n", "methods": [ { "textRaw": "punycode.decode(string)", "type": "method", "name": "decode", "desc": "

    Converts a Punycode string of ASCII code points to a string of Unicode code\npoints.\n\n

    \n
    // decode domain name parts\npunycode.decode('maana-pta'); // 'mañana'\npunycode.decode('--dqo34k'); // '☃-⌘'
    \n", "signatures": [ { "params": [ { "name": "string" } ] } ] }, { "textRaw": "punycode.encode(string)", "type": "method", "name": "encode", "desc": "

    Converts a string of Unicode code points to a Punycode string of ASCII code\npoints.\n\n

    \n
    // encode domain name parts\npunycode.encode('mañana'); // 'maana-pta'\npunycode.encode('☃-⌘'); // '--dqo34k'
    \n", "signatures": [ { "params": [ { "name": "string" } ] } ] }, { "textRaw": "punycode.toUnicode(domain)", "type": "method", "name": "toUnicode", "desc": "

    Converts a Punycode string representing a domain name to Unicode. Only the\nPunycoded parts of the domain name will be converted, i.e. it doesn't matter if\nyou call it on a string that has already been converted to Unicode.\n\n

    \n
    // decode domain names\npunycode.toUnicode('xn--maana-pta.com'); // 'mañana.com'\npunycode.toUnicode('xn----dqo34k.com'); // '☃-⌘.com'
    \n", "signatures": [ { "params": [ { "name": "domain" } ] } ] }, { "textRaw": "punycode.toASCII(domain)", "type": "method", "name": "toASCII", "desc": "

    Converts a Unicode string representing a domain name to Punycode. Only the\nnon-ASCII parts of the domain name will be converted, i.e. it doesn't matter if\nyou call it with a domain that's already in ASCII.\n\n

    \n
    // encode domain names\npunycode.toASCII('mañana.com'); // 'xn--maana-pta.com'\npunycode.toASCII('☃-⌘.com'); // 'xn----dqo34k.com'
    \n", "signatures": [ { "params": [ { "name": "domain" } ] } ] } ], "properties": [ { "textRaw": "punycode.ucs2", "name": "ucs2", "modules": [ { "textRaw": "punycode.ucs2.decode(string)", "name": "punycode.ucs2.decode(string)", "desc": "

    Creates an array containing the decimal code points of each Unicode character\nin the string. While JavaScript uses UCS-2\ninternally, this function\nwill convert a pair of surrogate halves (each of which UCS-2 exposes as\nseparate characters) into a single code point, matching UTF-16.\n\n

    \n
    punycode.ucs2.decode('abc'); // [97, 98, 99]\n// surrogate pair for U+1D306 tetragram for centre:\npunycode.ucs2.decode('\\uD834\\uDF06'); // [0x1D306]
    \n", "type": "module", "displayName": "punycode.ucs2.decode(string)" }, { "textRaw": "punycode.ucs2.encode(codePoints)", "name": "punycode.ucs2.encode(codepoints)", "desc": "

    Creates a string based on an array of decimal code points.\n\n

    \n
    punycode.ucs2.encode([97, 98, 99]); // 'abc'\npunycode.ucs2.encode([0x1D306]); // '\\uD834\\uDF06'
    \n", "type": "module", "displayName": "punycode.ucs2.encode(codePoints)" } ] }, { "textRaw": "punycode.version", "name": "version", "desc": "

    A string representing the current Punycode.js version number.\n

    \n" } ], "type": "module", "displayName": "punycode" } ] } node-v0.10.25~dfsg2/doc/api/_toc.markdown0000644000000000000000000000162312270121457016625 0ustar rootroot* [About these Docs](documentation.html) * [Synopsis](synopsis.html) * [Assertion Testing](assert.html) * [Buffer](buffer.html) * [C/C++ Addons](addons.html) * [Child Processes](child_process.html) * [Cluster](cluster.html) * [Console](console.html) * [Crypto](crypto.html) * [Debugger](debugger.html) * [DNS](dns.html) * [Domain](domain.html) * [Events](events.html) * [File System](fs.html) * [Globals](globals.html) * [HTTP](http.html) * [HTTPS](https.html) * [Modules](modules.html) * [Net](net.html) * [OS](os.html) * [Path](path.html) * [Process](process.html) * [Punycode](punycode.html) * [Query Strings](querystring.html) * [Readline](readline.html) * [REPL](repl.html) * [Stream](stream.html) * [String Decoder](string_decoder.html) * [Timers](timers.html) * [TLS/SSL](tls.html) * [TTY](tty.html) * [UDP/Datagram](dgram.html) * [URL](url.html) * [Utilities](util.html) * [VM](vm.html) * [ZLIB](zlib.html) node-v0.10.25~dfsg2/doc/api/url.html0000644000000000000000000002154712270264601015633 0ustar rootroot URL Node.js v0.10.25 Manual & Documentation

    Node.js v0.10.25 Manual & Documentation


    URL#

    Stability: 3 - Stable

    This module has utilities for URL resolution and parsing. Call require('url') to use it.

    Parsed URL objects have some or all of the following fields, depending on whether or not they exist in the URL string. Any parts that are not in the URL string will not be in the parsed object. Examples are shown for the URL

    'http://user:pass@host.com:8080/p/a/t/h?query=string#hash'

    • href: The full URL that was originally parsed. Both the protocol and host are lowercased.

      Example: 'http://user:pass@host.com:8080/p/a/t/h?query=string#hash'

    • protocol: The request protocol, lowercased.

      Example: 'http:'

    • host: The full lowercased host portion of the URL, including port information.

      Example: 'host.com:8080'

    • auth: The authentication information portion of a URL.

      Example: 'user:pass'

    • hostname: Just the lowercased hostname portion of the host.

      Example: 'host.com'

    • port: The port number portion of the host.

      Example: '8080'

    • pathname: The path section of the URL, that comes after the host and before the query, including the initial slash if present.

      Example: '/p/a/t/h'

    • search: The 'query string' portion of the URL, including the leading question mark.

      Example: '?query=string'

    • path: Concatenation of pathname and search.

      Example: '/p/a/t/h?query=string'

    • query: Either the 'params' portion of the query string, or a querystring-parsed object.

      Example: 'query=string' or {'query':'string'}

    • hash: The 'fragment' portion of the URL including the pound-sign.

      Example: '#hash'

    The following methods are provided by the URL module:

    url.parse(urlStr, [parseQueryString], [slashesDenoteHost])#

    Take a URL string, and return an object.

    Pass true as the second argument to also parse the query string using the querystring module. Defaults to false.

    Pass true as the third argument to treat //foo/bar as { host: 'foo', pathname: '/bar' } rather than { pathname: '//foo/bar' }. Defaults to false.

    url.format(urlObj)#

    Take a parsed URL object, and return a formatted URL string.

    • href will be ignored.
    • protocolis treated the same with or without the trailing : (colon).
      • The protocols http, https, ftp, gopher, file will be postfixed with :// (colon-slash-slash).
      • All other protocols mailto, xmpp, aim, sftp, foo, etc will be postfixed with : (colon)
    • auth will be used if present.
    • hostname will only be used if host is absent.
    • port will only be used if host is absent.
    • host will be used in place of hostname and port
    • pathname is treated the same with or without the leading / (slash)
    • search will be used in place of query
    • query (object; see querystring) will only be used if search is absent.
    • search is treated the same with or without the leading ? (question mark)
    • hash is treated the same with or without the leading # (pound sign, anchor)

    url.resolve(from, to)#

    Take a base URL, and a href URL, and resolve them as a browser would for an anchor tag. Examples:

    url.resolve('/one/two/three', 'four')         // '/one/two/four'
    url.resolve('http://example.com/', '/one')    // 'http://example.com/one'
    url.resolve('http://example.com/one', '/two') // 'http://example.com/two'
    node-v0.10.25~dfsg2/doc/api/tty.json0000644000000000000000000001141112270264601015643 0ustar rootroot{ "source": "doc/api/tty.markdown", "modules": [ { "textRaw": "TTY", "name": "tty", "stability": 2, "stabilityText": "Unstable", "desc": "

    The tty module houses the tty.ReadStream and tty.WriteStream classes. In\nmost cases, you will not need to use this module directly.\n\n

    \n

    When node detects that it is being run inside a TTY context, then process.stdin\nwill be a tty.ReadStream instance and process.stdout will be\na tty.WriteStream instance. The preferred way to check if node is being run in\na TTY context is to check process.stdout.isTTY:\n\n

    \n
    $ node -p -e "Boolean(process.stdout.isTTY)"\ntrue\n$ node -p -e "Boolean(process.stdout.isTTY)" | cat\nfalse
    \n", "methods": [ { "textRaw": "tty.isatty(fd)", "type": "method", "name": "isatty", "desc": "

    Returns true or false depending on if the fd is associated with a\nterminal.\n\n\n

    \n", "signatures": [ { "params": [ { "name": "fd" } ] } ] }, { "textRaw": "tty.setRawMode(mode)", "type": "method", "name": "setRawMode", "desc": "

    Deprecated. Use tty.ReadStream#setRawMode()\n(i.e. process.stdin.setRawMode()) instead.\n\n\n

    \n", "signatures": [ { "params": [ { "name": "mode" } ] } ] } ], "classes": [ { "textRaw": "Class: ReadStream", "type": "class", "name": "ReadStream", "desc": "

    A net.Socket subclass that represents the readable portion of a tty. In normal\ncircumstances, process.stdin will be the only tty.ReadStream instance in any\nnode program (only when isatty(0) is true).\n\n

    \n", "properties": [ { "textRaw": "rs.isRaw", "name": "isRaw", "desc": "

    A Boolean that is initialized to false. It represents the current "raw" state\nof the tty.ReadStream instance.\n\n

    \n" } ], "methods": [ { "textRaw": "rs.setRawMode(mode)", "type": "method", "name": "setRawMode", "desc": "

    mode should be true or false. This sets the properties of the\ntty.ReadStream to act either as a raw device or default. isRaw will be set\nto the resulting mode.\n\n\n

    \n", "signatures": [ { "params": [ { "name": "mode" } ] } ] } ] }, { "textRaw": "Class: WriteStream", "type": "class", "name": "WriteStream", "desc": "

    A net.Socket subclass that represents the writable portion of a tty. In normal\ncircumstances, process.stdout will be the only tty.WriteStream instance\never created (and only when isatty(1) is true).\n\n

    \n", "properties": [ { "textRaw": "ws.columns", "name": "columns", "desc": "

    A Number that gives the number of columns the TTY currently has. This property\ngets updated on "resize" events.\n\n

    \n" }, { "textRaw": "ws.rows", "name": "rows", "desc": "

    A Number that gives the number of rows the TTY currently has. This property\ngets updated on "resize" events.\n\n

    \n" } ], "events": [ { "textRaw": "Event: 'resize'", "type": "event", "name": "resize", "desc": "

    function () {}\n\n

    \n

    Emitted by refreshSize() when either of the columns or rows properties\nhas changed.\n\n

    \n
    process.stdout.on('resize', function() {\n  console.log('screen size has changed!');\n  console.log(process.stdout.columns + 'x' + process.stdout.rows);\n});
    \n", "params": [] } ] } ], "type": "module", "displayName": "TTY" } ] } node-v0.10.25~dfsg2/doc/api/documentation.json0000644000000000000000000000664212270264601017706 0ustar rootroot{ "source": "doc/api/documentation.markdown", "miscs": [ { "textRaw": "About this Documentation", "name": "About this Documentation", "type": "misc", "desc": "

    The goal of this documentation is to comprehensively explain the Node.js\nAPI, both from a reference as well as a conceptual point of view. Each\nsection describes a built-in module or high-level concept.\n\n

    \n

    Where appropriate, property types, method arguments, and the arguments\nprovided to event handlers are detailed in a list underneath the topic\nheading.\n\n

    \n

    Every .html document has a corresponding .json document presenting\nthe same information in a structured manner. This feature is\nexperimental, and added for the benefit of IDEs and other utilities that\nwish to do programmatic things with the documentation.\n\n

    \n

    Every .html and .json file is generated based on the corresponding\n.markdown file in the doc/api/ folder in node's source tree. The\ndocumentation is generated using the tools/doc/generate.js program.\nThe HTML template is located at doc/template.html.\n\n

    \n", "miscs": [ { "textRaw": "Stability Index", "name": "Stability Index", "type": "misc", "desc": "

    Throughout the documentation, you will see indications of a section's\nstability. The Node.js API is still somewhat changing, and as it\nmatures, certain parts are more reliable than others. Some are so\nproven, and so relied upon, that they are unlikely to ever change at\nall. Others are brand new and experimental, or known to be hazardous\nand in the process of being redesigned.\n\n

    \n

    The stability indices are as follows:\n\n

    \n
    Stability: 0 - Deprecated\nThis feature is known to be problematic, and changes are\nplanned.  Do not rely on it.  Use of the feature may cause warnings.  Backwards\ncompatibility should not be expected.
    \n
    Stability: 1 - Experimental\nThis feature was introduced recently, and may change\nor be removed in future versions.  Please try it out and provide feedback.\nIf it addresses a use-case that is important to you, tell the node core team.
    \n
    Stability: 2 - Unstable\nThe API is in the process of settling, but has not yet had\nsufficient real-world testing to be considered stable. Backwards-compatibility\nwill be maintained if reasonable.
    \n
    Stability: 3 - Stable\nThe API has proven satisfactory, but cleanup in the underlying\ncode may cause minor changes.  Backwards-compatibility is guaranteed.
    \n
    Stability: 4 - API Frozen\nThis API has been tested extensively in production and is\nunlikely to ever have to change.
    \n
    Stability: 5 - Locked\nUnless serious bugs are found, this code will not ever\nchange.  Please do not suggest changes in this area; they will be refused.
    \n" }, { "textRaw": "JSON Output", "name": "json_output", "stability": 1, "stabilityText": "Experimental", "desc": "

    Every HTML file in the markdown has a corresponding JSON file with the\nsame data.\n\n

    \n

    This feature is new as of node v0.6.12. It is experimental.\n

    \n", "type": "misc", "displayName": "JSON Output" } ] } ] } node-v0.10.25~dfsg2/doc/api/assert.markdown0000644000000000000000000000411212270121457017176 0ustar rootroot# Assert Stability: 5 - Locked This module is used for writing unit tests for your applications, you can access it with `require('assert')`. ## assert.fail(actual, expected, message, operator) Throws an exception that displays the values for `actual` and `expected` separated by the provided operator. ## assert(value, message), assert.ok(value, [message]) Tests if value is truthy, it is equivalent to `assert.equal(true, !!value, message);` ## assert.equal(actual, expected, [message]) Tests shallow, coercive equality with the equal comparison operator ( `==` ). ## assert.notEqual(actual, expected, [message]) Tests shallow, coercive non-equality with the not equal comparison operator ( `!=` ). ## assert.deepEqual(actual, expected, [message]) Tests for deep equality. ## assert.notDeepEqual(actual, expected, [message]) Tests for any deep inequality. ## assert.strictEqual(actual, expected, [message]) Tests strict equality, as determined by the strict equality operator ( `===` ) ## assert.notStrictEqual(actual, expected, [message]) Tests strict non-equality, as determined by the strict not equal operator ( `!==` ) ## assert.throws(block, [error], [message]) Expects `block` to throw an error. `error` can be constructor, regexp or validation function. Validate instanceof using constructor: assert.throws( function() { throw new Error("Wrong value"); }, Error ); Validate error message using RegExp: assert.throws( function() { throw new Error("Wrong value"); }, /value/ ); Custom error validation: assert.throws( function() { throw new Error("Wrong value"); }, function(err) { if ( (err instanceof Error) && /value/.test(err) ) { return true; } }, "unexpected error" ); ## assert.doesNotThrow(block, [message]) Expects `block` not to throw an error, see assert.throws for details. ## assert.ifError(value) Tests if value is not a false value, throws if it is a true value. Useful when testing the first argument, `error` in callbacks. node-v0.10.25~dfsg2/doc/api/zlib.json0000644000000000000000000004473512270264601016002 0ustar rootroot{ "source": "doc/api/zlib.markdown", "modules": [ { "textRaw": "Zlib", "name": "zlib", "stability": 3, "stabilityText": "Stable", "desc": "

    You can access this module with:\n\n

    \n
    var zlib = require('zlib');
    \n

    This provides bindings to Gzip/Gunzip, Deflate/Inflate, and\nDeflateRaw/InflateRaw classes. Each class takes the same options, and\nis a readable/writable Stream.\n\n

    \n

    Examples

    \n

    Compressing or decompressing a file can be done by piping an\nfs.ReadStream into a zlib stream, then into an fs.WriteStream.\n\n

    \n
    var gzip = zlib.createGzip();\nvar fs = require('fs');\nvar inp = fs.createReadStream('input.txt');\nvar out = fs.createWriteStream('input.txt.gz');\n\ninp.pipe(gzip).pipe(out);
    \n

    Compressing or decompressing data in one step can be done by using\nthe convenience methods.\n\n

    \n
    var input = '.................................';\nzlib.deflate(input, function(err, buffer) {\n  if (!err) {\n    console.log(buffer.toString('base64'));\n  }\n});\n\nvar buffer = new Buffer('eJzT0yMAAGTvBe8=', 'base64');\nzlib.unzip(buffer, function(err, buffer) {\n  if (!err) {\n    console.log(buffer.toString());\n  }\n});
    \n

    To use this module in an HTTP client or server, use the\naccept-encoding\non requests, and the\ncontent-encoding\nheader on responses.\n\n

    \n

    Note: these examples are drastically simplified to show\nthe basic concept. Zlib encoding can be expensive, and the results\nought to be cached. See Memory Usage Tuning\nbelow for more information on the speed/memory/compression\ntradeoffs involved in zlib usage.\n\n

    \n
    // client request example\nvar zlib = require('zlib');\nvar http = require('http');\nvar fs = require('fs');\nvar request = http.get({ host: 'izs.me',\n                         path: '/',\n                         port: 80,\n                         headers: { 'accept-encoding': 'gzip,deflate' } });\nrequest.on('response', function(response) {\n  var output = fs.createWriteStream('izs.me_index.html');\n\n  switch (response.headers['content-encoding']) {\n    // or, just use zlib.createUnzip() to handle both cases\n    case 'gzip':\n      response.pipe(zlib.createGunzip()).pipe(output);\n      break;\n    case 'deflate':\n      response.pipe(zlib.createInflate()).pipe(output);\n      break;\n    default:\n      response.pipe(output);\n      break;\n  }\n});\n\n// server example\n// Running a gzip operation on every request is quite expensive.\n// It would be much more efficient to cache the compressed buffer.\nvar zlib = require('zlib');\nvar http = require('http');\nvar fs = require('fs');\nhttp.createServer(function(request, response) {\n  var raw = fs.createReadStream('index.html');\n  var acceptEncoding = request.headers['accept-encoding'];\n  if (!acceptEncoding) {\n    acceptEncoding = '';\n  }\n\n  // Note: this is not a conformant accept-encoding parser.\n  // See http://www.w3.org/Protocols/rfc2616/rfc2616-sec14.html#sec14.3\n  if (acceptEncoding.match(/\\bdeflate\\b/)) {\n    response.writeHead(200, { 'content-encoding': 'deflate' });\n    raw.pipe(zlib.createDeflate()).pipe(response);\n  } else if (acceptEncoding.match(/\\bgzip\\b/)) {\n    response.writeHead(200, { 'content-encoding': 'gzip' });\n    raw.pipe(zlib.createGzip()).pipe(response);\n  } else {\n    response.writeHead(200, {});\n    raw.pipe(response);\n  }\n}).listen(1337);
    \n", "methods": [ { "textRaw": "zlib.createGzip([options])", "type": "method", "name": "createGzip", "desc": "

    Returns a new Gzip object with an\noptions.\n\n

    \n", "signatures": [ { "params": [ { "name": "options", "optional": true } ] } ] }, { "textRaw": "zlib.createGunzip([options])", "type": "method", "name": "createGunzip", "desc": "

    Returns a new Gunzip object with an\noptions.\n\n

    \n", "signatures": [ { "params": [ { "name": "options", "optional": true } ] } ] }, { "textRaw": "zlib.createDeflate([options])", "type": "method", "name": "createDeflate", "desc": "

    Returns a new Deflate object with an\noptions.\n\n

    \n", "signatures": [ { "params": [ { "name": "options", "optional": true } ] } ] }, { "textRaw": "zlib.createInflate([options])", "type": "method", "name": "createInflate", "desc": "

    Returns a new Inflate object with an\noptions.\n\n

    \n", "signatures": [ { "params": [ { "name": "options", "optional": true } ] } ] }, { "textRaw": "zlib.createDeflateRaw([options])", "type": "method", "name": "createDeflateRaw", "desc": "

    Returns a new DeflateRaw object with an\noptions.\n\n

    \n", "signatures": [ { "params": [ { "name": "options", "optional": true } ] } ] }, { "textRaw": "zlib.createInflateRaw([options])", "type": "method", "name": "createInflateRaw", "desc": "

    Returns a new InflateRaw object with an\noptions.\n\n

    \n", "signatures": [ { "params": [ { "name": "options", "optional": true } ] } ] }, { "textRaw": "zlib.createUnzip([options])", "type": "method", "name": "createUnzip", "desc": "

    Returns a new Unzip object with an\noptions.\n\n\n

    \n", "signatures": [ { "params": [ { "name": "options", "optional": true } ] } ] }, { "textRaw": "zlib.deflate(buf, callback)", "type": "method", "name": "deflate", "desc": "

    Compress a string with Deflate.\n\n

    \n", "signatures": [ { "params": [ { "name": "buf" }, { "name": "callback" } ] } ] }, { "textRaw": "zlib.deflateRaw(buf, callback)", "type": "method", "name": "deflateRaw", "desc": "

    Compress a string with DeflateRaw.\n\n

    \n", "signatures": [ { "params": [ { "name": "buf" }, { "name": "callback" } ] } ] }, { "textRaw": "zlib.gzip(buf, callback)", "type": "method", "name": "gzip", "desc": "

    Compress a string with Gzip.\n\n

    \n", "signatures": [ { "params": [ { "name": "buf" }, { "name": "callback" } ] } ] }, { "textRaw": "zlib.gunzip(buf, callback)", "type": "method", "name": "gunzip", "desc": "

    Decompress a raw Buffer with Gunzip.\n\n

    \n", "signatures": [ { "params": [ { "name": "buf" }, { "name": "callback" } ] } ] }, { "textRaw": "zlib.inflate(buf, callback)", "type": "method", "name": "inflate", "desc": "

    Decompress a raw Buffer with Inflate.\n\n

    \n", "signatures": [ { "params": [ { "name": "buf" }, { "name": "callback" } ] } ] }, { "textRaw": "zlib.inflateRaw(buf, callback)", "type": "method", "name": "inflateRaw", "desc": "

    Decompress a raw Buffer with InflateRaw.\n\n

    \n", "signatures": [ { "params": [ { "name": "buf" }, { "name": "callback" } ] } ] }, { "textRaw": "zlib.unzip(buf, callback)", "type": "method", "name": "unzip", "desc": "

    Decompress a raw Buffer with Unzip.\n\n

    \n", "signatures": [ { "params": [ { "name": "buf" }, { "name": "callback" } ] } ] } ], "classes": [ { "textRaw": "Class: zlib.Zlib", "type": "class", "name": "zlib.Zlib", "desc": "

    Not exported by the zlib module. It is documented here because it is the base\nclass of the compressor/decompressor classes.\n\n

    \n", "methods": [ { "textRaw": "zlib.flush(callback)", "type": "method", "name": "flush", "desc": "

    Flush pending data. Don't call this frivolously, premature flushes negatively\nimpact the effectiveness of the compression algorithm.\n\n

    \n", "signatures": [ { "params": [ { "name": "callback" } ] } ] }, { "textRaw": "zlib.reset()", "type": "method", "name": "reset", "desc": "

    Reset the compressor/decompressor to factory defaults. Only applicable to\nthe inflate and deflate algorithms.\n\n

    \n", "signatures": [ { "params": [] } ] } ] }, { "textRaw": "Class: zlib.Gzip", "type": "class", "name": "zlib.Gzip", "desc": "

    Compress data using gzip.\n\n

    \n" }, { "textRaw": "Class: zlib.Gunzip", "type": "class", "name": "zlib.Gunzip", "desc": "

    Decompress a gzip stream.\n\n

    \n" }, { "textRaw": "Class: zlib.Deflate", "type": "class", "name": "zlib.Deflate", "desc": "

    Compress data using deflate.\n\n

    \n" }, { "textRaw": "Class: zlib.Inflate", "type": "class", "name": "zlib.Inflate", "desc": "

    Decompress a deflate stream.\n\n

    \n" }, { "textRaw": "Class: zlib.DeflateRaw", "type": "class", "name": "zlib.DeflateRaw", "desc": "

    Compress data using deflate, and do not append a zlib header.\n\n

    \n" }, { "textRaw": "Class: zlib.InflateRaw", "type": "class", "name": "zlib.InflateRaw", "desc": "

    Decompress a raw deflate stream.\n\n

    \n" }, { "textRaw": "Class: zlib.Unzip", "type": "class", "name": "zlib.Unzip", "desc": "

    Decompress either a Gzip- or Deflate-compressed stream by auto-detecting\nthe header.\n\n

    \n" } ], "miscs": [ { "textRaw": "Convenience Methods", "name": "Convenience Methods", "type": "misc", "desc": "

    All of these take a string or buffer as the first argument, and call the\nsupplied callback with callback(error, result). The\ncompression/decompression engine is created using the default settings\nin all convenience methods. To supply different options, use the\nzlib classes directly.\n\n

    \n" }, { "textRaw": "Options", "name": "Options", "type": "misc", "desc": "

    Each class takes an options object. All options are optional. (The\nconvenience methods use the default settings for all options.)\n\n

    \n

    Note that some options are only relevant when compressing, and are\nignored by the decompression classes.\n\n

    \n
      \n
    • flush (default: zlib.Z_NO_FLUSH)
    • \n
    • chunkSize (default: 16*1024)
    • \n
    • windowBits
    • \n
    • level (compression only)
    • \n
    • memLevel (compression only)
    • \n
    • strategy (compression only)
    • \n
    • dictionary (deflate/inflate only, empty dictionary by default)
    • \n
    \n

    See the description of deflateInit2 and inflateInit2 at\n

    \n

    http://zlib.net/manual.html#Advanced for more information on these.\n\n

    \n" }, { "textRaw": "Memory Usage Tuning", "name": "Memory Usage Tuning", "type": "misc", "desc": "

    From zlib/zconf.h, modified to node's usage:\n\n

    \n

    The memory requirements for deflate are (in bytes):\n\n

    \n
    (1 << (windowBits+2)) +  (1 << (memLevel+9))
    \n

    that is: 128K for windowBits=15 + 128K for memLevel = 8\n(default values) plus a few kilobytes for small objects.\n\n

    \n

    For example, if you want to reduce\nthe default memory requirements from 256K to 128K, set the options to:\n\n

    \n
    { windowBits: 14, memLevel: 7 }
    \n

    Of course this will generally degrade compression (there's no free lunch).\n\n

    \n

    The memory requirements for inflate are (in bytes)\n\n

    \n
    1 << windowBits
    \n

    that is, 32K for windowBits=15 (default value) plus a few kilobytes\nfor small objects.\n\n

    \n

    This is in addition to a single internal output slab buffer of size\nchunkSize, which defaults to 16K.\n\n

    \n

    The speed of zlib compression is affected most dramatically by the\nlevel setting. A higher level will result in better compression, but\nwill take longer to complete. A lower level will result in less\ncompression, but will be much faster.\n\n

    \n

    In general, greater memory usage options will mean that node has to make\nfewer calls to zlib, since it'll be able to process more data in a\nsingle write operation. So, this is another factor that affects the\nspeed, at the cost of memory usage.\n\n

    \n" }, { "textRaw": "Constants", "name": "Constants", "type": "misc", "desc": "

    All of the constants defined in zlib.h are also defined on\nrequire('zlib').\nIn the normal course of operations, you will not need to ever set any of\nthese. They are documented here so that their presence is not\nsurprising. This section is taken almost directly from the zlib\ndocumentation. See\n

    \n

    http://zlib.net/manual.html#Constants for more details.\n\n

    \n

    Allowed flush values.\n\n

    \n
      \n
    • zlib.Z_NO_FLUSH
    • \n
    • zlib.Z_PARTIAL_FLUSH
    • \n
    • zlib.Z_SYNC_FLUSH
    • \n
    • zlib.Z_FULL_FLUSH
    • \n
    • zlib.Z_FINISH
    • \n
    • zlib.Z_BLOCK
    • \n
    • zlib.Z_TREES
    • \n
    \n

    Return codes for the compression/decompression functions. Negative\nvalues are errors, positive values are used for special but normal\nevents.\n\n

    \n
      \n
    • zlib.Z_OK
    • \n
    • zlib.Z_STREAM_END
    • \n
    • zlib.Z_NEED_DICT
    • \n
    • zlib.Z_ERRNO
    • \n
    • zlib.Z_STREAM_ERROR
    • \n
    • zlib.Z_DATA_ERROR
    • \n
    • zlib.Z_MEM_ERROR
    • \n
    • zlib.Z_BUF_ERROR
    • \n
    • zlib.Z_VERSION_ERROR
    • \n
    \n

    Compression levels.\n\n

    \n
      \n
    • zlib.Z_NO_COMPRESSION
    • \n
    • zlib.Z_BEST_SPEED
    • \n
    • zlib.Z_BEST_COMPRESSION
    • \n
    • zlib.Z_DEFAULT_COMPRESSION
    • \n
    \n

    Compression strategy.\n\n

    \n
      \n
    • zlib.Z_FILTERED
    • \n
    • zlib.Z_HUFFMAN_ONLY
    • \n
    • zlib.Z_RLE
    • \n
    • zlib.Z_FIXED
    • \n
    • zlib.Z_DEFAULT_STRATEGY
    • \n
    \n

    Possible values of the data_type field.\n\n

    \n
      \n
    • zlib.Z_BINARY
    • \n
    • zlib.Z_TEXT
    • \n
    • zlib.Z_ASCII
    • \n
    • zlib.Z_UNKNOWN
    • \n
    \n

    The deflate compression method (the only one supported in this version).\n\n

    \n
      \n
    • zlib.Z_DEFLATED
    • \n
    \n

    For initializing zalloc, zfree, opaque.\n\n

    \n
      \n
    • zlib.Z_NULL
    • \n
    \n" } ], "type": "module", "displayName": "Zlib" } ] } node-v0.10.25~dfsg2/doc/api/punycode.markdown0000644000000000000000000000445212270121457017532 0ustar rootroot# punycode Stability: 2 - Unstable [Punycode.js](http://mths.be/punycode) is bundled with Node.js v0.6.2+. Use `require('punycode')` to access it. (To use it with other Node.js versions, use npm to install the `punycode` module first.) ## punycode.decode(string) Converts a Punycode string of ASCII code points to a string of Unicode code points. // decode domain name parts punycode.decode('maana-pta'); // 'mañana' punycode.decode('--dqo34k'); // '☃-⌘' ## punycode.encode(string) Converts a string of Unicode code points to a Punycode string of ASCII code points. // encode domain name parts punycode.encode('mañana'); // 'maana-pta' punycode.encode('☃-⌘'); // '--dqo34k' ## punycode.toUnicode(domain) Converts a Punycode string representing a domain name to Unicode. Only the Punycoded parts of the domain name will be converted, i.e. it doesn't matter if you call it on a string that has already been converted to Unicode. // decode domain names punycode.toUnicode('xn--maana-pta.com'); // 'mañana.com' punycode.toUnicode('xn----dqo34k.com'); // '☃-⌘.com' ## punycode.toASCII(domain) Converts a Unicode string representing a domain name to Punycode. Only the non-ASCII parts of the domain name will be converted, i.e. it doesn't matter if you call it with a domain that's already in ASCII. // encode domain names punycode.toASCII('mañana.com'); // 'xn--maana-pta.com' punycode.toASCII('☃-⌘.com'); // 'xn----dqo34k.com' ## punycode.ucs2 ### punycode.ucs2.decode(string) Creates an array containing the decimal code points of each Unicode character in the string. While [JavaScript uses UCS-2 internally](http://mathiasbynens.be/notes/javascript-encoding), this function will convert a pair of surrogate halves (each of which UCS-2 exposes as separate characters) into a single code point, matching UTF-16. punycode.ucs2.decode('abc'); // [97, 98, 99] // surrogate pair for U+1D306 tetragram for centre: punycode.ucs2.decode('\uD834\uDF06'); // [0x1D306] ### punycode.ucs2.encode(codePoints) Creates a string based on an array of decimal code points. punycode.ucs2.encode([97, 98, 99]); // 'abc' punycode.ucs2.encode([0x1D306]); // '\uD834\uDF06' ## punycode.version A string representing the current Punycode.js version number. node-v0.10.25~dfsg2/doc/api/url.markdown0000644000000000000000000000647512270121457016515 0ustar rootroot# URL Stability: 3 - Stable This module has utilities for URL resolution and parsing. Call `require('url')` to use it. Parsed URL objects have some or all of the following fields, depending on whether or not they exist in the URL string. Any parts that are not in the URL string will not be in the parsed object. Examples are shown for the URL `'http://user:pass@host.com:8080/p/a/t/h?query=string#hash'` * `href`: The full URL that was originally parsed. Both the protocol and host are lowercased. Example: `'http://user:pass@host.com:8080/p/a/t/h?query=string#hash'` * `protocol`: The request protocol, lowercased. Example: `'http:'` * `host`: The full lowercased host portion of the URL, including port information. Example: `'host.com:8080'` * `auth`: The authentication information portion of a URL. Example: `'user:pass'` * `hostname`: Just the lowercased hostname portion of the host. Example: `'host.com'` * `port`: The port number portion of the host. Example: `'8080'` * `pathname`: The path section of the URL, that comes after the host and before the query, including the initial slash if present. Example: `'/p/a/t/h'` * `search`: The 'query string' portion of the URL, including the leading question mark. Example: `'?query=string'` * `path`: Concatenation of `pathname` and `search`. Example: `'/p/a/t/h?query=string'` * `query`: Either the 'params' portion of the query string, or a querystring-parsed object. Example: `'query=string'` or `{'query':'string'}` * `hash`: The 'fragment' portion of the URL including the pound-sign. Example: `'#hash'` The following methods are provided by the URL module: ## url.parse(urlStr, [parseQueryString], [slashesDenoteHost]) Take a URL string, and return an object. Pass `true` as the second argument to also parse the query string using the `querystring` module. Defaults to `false`. Pass `true` as the third argument to treat `//foo/bar` as `{ host: 'foo', pathname: '/bar' }` rather than `{ pathname: '//foo/bar' }`. Defaults to `false`. ## url.format(urlObj) Take a parsed URL object, and return a formatted URL string. * `href` will be ignored. * `protocol`is treated the same with or without the trailing `:` (colon). * The protocols `http`, `https`, `ftp`, `gopher`, `file` will be postfixed with `://` (colon-slash-slash). * All other protocols `mailto`, `xmpp`, `aim`, `sftp`, `foo`, etc will be postfixed with `:` (colon) * `auth` will be used if present. * `hostname` will only be used if `host` is absent. * `port` will only be used if `host` is absent. * `host` will be used in place of `hostname` and `port` * `pathname` is treated the same with or without the leading `/` (slash) * `search` will be used in place of `query` * `query` (object; see `querystring`) will only be used if `search` is absent. * `search` is treated the same with or without the leading `?` (question mark) * `hash` is treated the same with or without the leading `#` (pound sign, anchor) ## url.resolve(from, to) Take a base URL, and a href URL, and resolve them as a browser would for an anchor tag. Examples: url.resolve('/one/two/three', 'four') // '/one/two/four' url.resolve('http://example.com/', '/one') // 'http://example.com/one' url.resolve('http://example.com/one', '/two') // 'http://example.com/two' node-v0.10.25~dfsg2/doc/api/modules.markdown0000644000000000000000000003726312270121457017362 0ustar rootroot# Modules Stability: 5 - Locked Node has a simple module loading system. In Node, files and modules are in one-to-one correspondence. As an example, `foo.js` loads the module `circle.js` in the same directory. The contents of `foo.js`: var circle = require('./circle.js'); console.log( 'The area of a circle of radius 4 is ' + circle.area(4)); The contents of `circle.js`: var PI = Math.PI; exports.area = function (r) { return PI * r * r; }; exports.circumference = function (r) { return 2 * PI * r; }; The module `circle.js` has exported the functions `area()` and `circumference()`. To add functions and objects to the root of your module, you can add them to the special `exports` object. Variables local to the module will be private, as though the module was wrapped in a function. In this example the variable `PI` is private to `circle.js`. If you want the root of your module's export to be a function (such as a constructor) or if you want to export a complete object in one assignment instead of building it one property at a time, assign it to `module.exports` instead of `exports`. Below, `bar.js` makes use of the `square` module, which exports a constructor: var square = require('./square.js'); var mySquare = square(2); console.log('The area of my square is ' + mySquare.area()); The `square` module is defined in `square.js`: // assigning to exports will not modify module, must use module.exports module.exports = function(width) { return { area: function() { return width * width; } }; } The module system is implemented in the `require("module")` module. ## Cycles When there are circular `require()` calls, a module might not be done being executed when it is returned. Consider this situation: `a.js`: console.log('a starting'); exports.done = false; var b = require('./b.js'); console.log('in a, b.done = %j', b.done); exports.done = true; console.log('a done'); `b.js`: console.log('b starting'); exports.done = false; var a = require('./a.js'); console.log('in b, a.done = %j', a.done); exports.done = true; console.log('b done'); `main.js`: console.log('main starting'); var a = require('./a.js'); var b = require('./b.js'); console.log('in main, a.done=%j, b.done=%j', a.done, b.done); When `main.js` loads `a.js`, then `a.js` in turn loads `b.js`. At that point, `b.js` tries to load `a.js`. In order to prevent an infinite loop an **unfinished copy** of the `a.js` exports object is returned to the `b.js` module. `b.js` then finishes loading, and its `exports` object is provided to the `a.js` module. By the time `main.js` has loaded both modules, they're both finished. The output of this program would thus be: $ node main.js main starting a starting b starting in b, a.done = false b done in a, b.done = true a done in main, a.done=true, b.done=true If you have cyclic module dependencies in your program, make sure to plan accordingly. ## Core Modules Node has several modules compiled into the binary. These modules are described in greater detail elsewhere in this documentation. The core modules are defined in node's source in the `lib/` folder. Core modules are always preferentially loaded if their identifier is passed to `require()`. For instance, `require('http')` will always return the built in HTTP module, even if there is a file by that name. ## File Modules If the exact filename is not found, then node will attempt to load the required filename with the added extension of `.js`, `.json`, and then `.node`. `.js` files are interpreted as JavaScript text files, and `.json` files are parsed as JSON text files. `.node` files are interpreted as compiled addon modules loaded with `dlopen`. A module prefixed with `'/'` is an absolute path to the file. For example, `require('/home/marco/foo.js')` will load the file at `/home/marco/foo.js`. A module prefixed with `'./'` is relative to the file calling `require()`. That is, `circle.js` must be in the same directory as `foo.js` for `require('./circle')` to find it. Without a leading '/' or './' to indicate a file, the module is either a "core module" or is loaded from a `node_modules` folder. If the given path does not exist, `require()` will throw an Error with its `code` property set to `'MODULE_NOT_FOUND'`. ## Loading from `node_modules` Folders If the module identifier passed to `require()` is not a native module, and does not begin with `'/'`, `'../'`, or `'./'`, then node starts at the parent directory of the current module, and adds `/node_modules`, and attempts to load the module from that location. If it is not found there, then it moves to the parent directory, and so on, until the root of the tree is reached. For example, if the file at `'/home/ry/projects/foo.js'` called `require('bar.js')`, then node would look in the following locations, in this order: * `/home/ry/projects/node_modules/bar.js` * `/home/ry/node_modules/bar.js` * `/home/node_modules/bar.js` * `/node_modules/bar.js` This allows programs to localize their dependencies, so that they do not clash. ## Folders as Modules It is convenient to organize programs and libraries into self-contained directories, and then provide a single entry point to that library. There are three ways in which a folder may be passed to `require()` as an argument. The first is to create a `package.json` file in the root of the folder, which specifies a `main` module. An example package.json file might look like this: { "name" : "some-library", "main" : "./lib/some-library.js" } If this was in a folder at `./some-library`, then `require('./some-library')` would attempt to load `./some-library/lib/some-library.js`. This is the extent of Node's awareness of package.json files. If there is no package.json file present in the directory, then node will attempt to load an `index.js` or `index.node` file out of that directory. For example, if there was no package.json file in the above example, then `require('./some-library')` would attempt to load: * `./some-library/index.js` * `./some-library/index.node` ## Caching Modules are cached after the first time they are loaded. This means (among other things) that every call to `require('foo')` will get exactly the same object returned, if it would resolve to the same file. Multiple calls to `require('foo')` may not cause the module code to be executed multiple times. This is an important feature. With it, "partially done" objects can be returned, thus allowing transitive dependencies to be loaded even when they would cause cycles. If you want to have a module execute code multiple times, then export a function, and call that function. ### Module Caching Caveats Modules are cached based on their resolved filename. Since modules may resolve to a different filename based on the location of the calling module (loading from `node_modules` folders), it is not a *guarantee* that `require('foo')` will always return the exact same object, if it would resolve to different files. ## The `module` Object * {Object} In each module, the `module` free variable is a reference to the object representing the current module. For convenience, `module.exports` is also accessible via the `exports` module-global. `module` isn't actually a global but rather local to each module. ### module.exports * {Object} The `module.exports` object is created by the Module system. Sometimes this is not acceptable; many want their module to be an instance of some class. To do this assign the desired export object to `module.exports`. Note that assigning the desired object to `exports` will simply rebind the local `exports` variable, which is probably not what you want to do. For example suppose we were making a module called `a.js` var EventEmitter = require('events').EventEmitter; module.exports = new EventEmitter(); // Do some work, and after some time emit // the 'ready' event from the module itself. setTimeout(function() { module.exports.emit('ready'); }, 1000); Then in another file we could do var a = require('./a'); a.on('ready', function() { console.log('module a is ready'); }); Note that assignment to `module.exports` must be done immediately. It cannot be done in any callbacks. This does not work: x.js: setTimeout(function() { module.exports = { a: "hello" }; }, 0); y.js: var x = require('./x'); console.log(x.a); #### exports alias The `exports` variable that is available within a module starts as a reference to `module.exports`. As with any variable, if you assign a new value to it, it is no longer bound to the previous value. To illustrate the behaviour, imagine this hypothetical implementation of `require()`: function require(...) { // ... function (module, exports) { // Your module code here exports = some_func; // re-assigns exports, exports is no longer // a shortcut, and nothing is exported. module.exports = some_func; // makes your module export 0 } (module, module.exports); return module; } As a guideline, if the relationship between `exports` and `module.exports` seems like magic to you, ignore `exports` and only use `module.exports`. ### module.require(id) * `id` {String} * Return: {Object} `module.exports` from the resolved module The `module.require` method provides a way to load a module as if `require()` was called from the original module. Note that in order to do this, you must get a reference to the `module` object. Since `require()` returns the `module.exports`, and the `module` is typically *only* available within a specific module's code, it must be explicitly exported in order to be used. ### module.id * {String} The identifier for the module. Typically this is the fully resolved filename. ### module.filename * {String} The fully resolved filename to the module. ### module.loaded * {Boolean} Whether or not the module is done loading, or is in the process of loading. ### module.parent * {Module Object} The module that required this one. ### module.children * {Array} The module objects required by this one. ## All Together... To get the exact filename that will be loaded when `require()` is called, use the `require.resolve()` function. Putting together all of the above, here is the high-level algorithm in pseudocode of what require.resolve does: require(X) from module at path Y 1. If X is a core module, a. return the core module b. STOP 2. If X begins with './' or '/' or '../' a. LOAD_AS_FILE(Y + X) b. LOAD_AS_DIRECTORY(Y + X) 3. LOAD_NODE_MODULES(X, dirname(Y)) 4. THROW "not found" LOAD_AS_FILE(X) 1. If X is a file, load X as JavaScript text. STOP 2. If X.js is a file, load X.js as JavaScript text. STOP 3. If X.node is a file, load X.node as binary addon. STOP LOAD_AS_DIRECTORY(X) 1. If X/package.json is a file, a. Parse X/package.json, and look for "main" field. b. let M = X + (json main field) c. LOAD_AS_FILE(M) 2. If X/index.js is a file, load X/index.js as JavaScript text. STOP 3. If X/index.node is a file, load X/index.node as binary addon. STOP LOAD_NODE_MODULES(X, START) 1. let DIRS=NODE_MODULES_PATHS(START) 2. for each DIR in DIRS: a. LOAD_AS_FILE(DIR/X) b. LOAD_AS_DIRECTORY(DIR/X) NODE_MODULES_PATHS(START) 1. let PARTS = path split(START) 2. let ROOT = index of first instance of "node_modules" in PARTS, or 0 3. let I = count of PARTS - 1 4. let DIRS = [] 5. while I > ROOT, a. if PARTS[I] = "node_modules" CONTINUE c. DIR = path join(PARTS[0 .. I] + "node_modules") b. DIRS = DIRS + DIR c. let I = I - 1 6. return DIRS ## Loading from the global folders If the `NODE_PATH` environment variable is set to a colon-delimited list of absolute paths, then node will search those paths for modules if they are not found elsewhere. (Note: On Windows, `NODE_PATH` is delimited by semicolons instead of colons.) Additionally, node will search in the following locations: * 1: `$HOME/.node_modules` * 2: `$HOME/.node_libraries` * 3: `$PREFIX/lib/node` Where `$HOME` is the user's home directory, and `$PREFIX` is node's configured `node_prefix`. These are mostly for historic reasons. You are highly encouraged to place your dependencies locally in `node_modules` folders. They will be loaded faster, and more reliably. ## Accessing the main module When a file is run directly from Node, `require.main` is set to its `module`. That means that you can determine whether a file has been run directly by testing require.main === module For a file `foo.js`, this will be `true` if run via `node foo.js`, but `false` if run by `require('./foo')`. Because `module` provides a `filename` property (normally equivalent to `__filename`), the entry point of the current application can be obtained by checking `require.main.filename`. ## Addenda: Package Manager Tips The semantics of Node's `require()` function were designed to be general enough to support a number of sane directory structures. Package manager programs such as `dpkg`, `rpm`, and `npm` will hopefully find it possible to build native packages from Node modules without modification. Below we give a suggested directory structure that could work: Let's say that we wanted to have the folder at `/usr/lib/node//` hold the contents of a specific version of a package. Packages can depend on one another. In order to install package `foo`, you may have to install a specific version of package `bar`. The `bar` package may itself have dependencies, and in some cases, these dependencies may even collide or form cycles. Since Node looks up the `realpath` of any modules it loads (that is, resolves symlinks), and then looks for their dependencies in the `node_modules` folders as described above, this situation is very simple to resolve with the following architecture: * `/usr/lib/node/foo/1.2.3/` - Contents of the `foo` package, version 1.2.3. * `/usr/lib/node/bar/4.3.2/` - Contents of the `bar` package that `foo` depends on. * `/usr/lib/node/foo/1.2.3/node_modules/bar` - Symbolic link to `/usr/lib/node/bar/4.3.2/`. * `/usr/lib/node/bar/4.3.2/node_modules/*` - Symbolic links to the packages that `bar` depends on. Thus, even if a cycle is encountered, or if there are dependency conflicts, every module will be able to get a version of its dependency that it can use. When the code in the `foo` package does `require('bar')`, it will get the version that is symlinked into `/usr/lib/node/foo/1.2.3/node_modules/bar`. Then, when the code in the `bar` package calls `require('quux')`, it'll get the version that is symlinked into `/usr/lib/node/bar/4.3.2/node_modules/quux`. Furthermore, to make the module lookup process even more optimal, rather than putting packages directly in `/usr/lib/node`, we could put them in `/usr/lib/node_modules//`. Then node will not bother looking for missing dependencies in `/usr/node_modules` or `/node_modules`. In order to make modules available to the node REPL, it might be useful to also add the `/usr/lib/node_modules` folder to the `$NODE_PATH` environment variable. Since the module lookups using `node_modules` folders are all relative, and based on the real path of the files making the calls to `require()`, the packages themselves can be anywhere. node-v0.10.25~dfsg2/doc/api/debugger.json0000644000000000000000000001442612270264601016620 0ustar rootroot{ "source": "doc/api/debugger.markdown", "stability": 3, "stabilityText": "Stable", "miscs": [ { "textRaw": "Debugger", "name": "Debugger", "stability": 3, "stabilityText": "Stable", "type": "misc", "desc": "

    V8 comes with an extensive debugger which is accessible out-of-process via a\nsimple TCP protocol.\nNode has a built-in client for this debugger. To use this, start Node with the\ndebug argument; a prompt will appear:\n\n

    \n
    % node debug myscript.js\n< debugger listening on port 5858\nconnecting... ok\nbreak in /home/indutny/Code/git/indutny/myscript.js:1\n  1 x = 5;\n  2 setTimeout(function () {\n  3   debugger;\ndebug>
    \n

    Node's debugger client doesn't support the full range of commands, but\nsimple step and inspection is possible. By putting the statement debugger;\ninto the source code of your script, you will enable a breakpoint.\n\n

    \n

    For example, suppose myscript.js looked like this:\n\n

    \n
    // myscript.js\nx = 5;\nsetTimeout(function () {\n  debugger;\n  console.log("world");\n}, 1000);\nconsole.log("hello");
    \n

    Then once the debugger is run, it will break on line 4.\n\n

    \n
    % node debug myscript.js\n< debugger listening on port 5858\nconnecting... ok\nbreak in /home/indutny/Code/git/indutny/myscript.js:1\n  1 x = 5;\n  2 setTimeout(function () {\n  3   debugger;\ndebug> cont\n< hello\nbreak in /home/indutny/Code/git/indutny/myscript.js:3\n  1 x = 5;\n  2 setTimeout(function () {\n  3   debugger;\n  4   console.log("world");\n  5 }, 1000);\ndebug> next\nbreak in /home/indutny/Code/git/indutny/myscript.js:4\n  2 setTimeout(function () {\n  3   debugger;\n  4   console.log("world");\n  5 }, 1000);\n  6 console.log("hello");\ndebug> repl\nPress Ctrl + C to leave debug repl\n> x\n5\n> 2+2\n4\ndebug> next\n< world\nbreak in /home/indutny/Code/git/indutny/myscript.js:5\n  3   debugger;\n  4   console.log("world");\n  5 }, 1000);\n  6 console.log("hello");\n  7\ndebug> quit\n%
    \n

    The repl command allows you to evaluate code remotely. The next command\nsteps over to the next line. There are a few other commands available and more\nto come. Type help to see others.\n\n

    \n", "miscs": [ { "textRaw": "Watchers", "name": "watchers", "desc": "

    You can watch expression and variable values while debugging your code.\nOn every breakpoint each expression from the watchers list will be evaluated\nin the current context and displayed just before the breakpoint's source code\nlisting.\n\n

    \n

    To start watching an expression, type watch("my_expression"). watchers\nprints the active watchers. To remove a watcher, type\nunwatch("my_expression").\n\n

    \n", "type": "misc", "displayName": "Watchers" }, { "textRaw": "Commands reference", "name": "commands_reference", "modules": [ { "textRaw": "Stepping", "name": "Stepping", "desc": "

    It is also possible to set a breakpoint in a file (module) that\nisn't loaded yet:\n\n

    \n
    % ./node debug test/fixtures/break-in-module/main.js\n< debugger listening on port 5858\nconnecting to port 5858... ok\nbreak in test/fixtures/break-in-module/main.js:1\n  1 var mod = require('./mod.js');\n  2 mod.hello();\n  3 mod.hello();\ndebug> setBreakpoint('mod.js', 23)\nWarning: script 'mod.js' was not loaded yet.\n  1 var mod = require('./mod.js');\n  2 mod.hello();\n  3 mod.hello();\ndebug> c\nbreak in test/fixtures/break-in-module/mod.js:23\n 21\n 22 exports.hello = function() {\n 23   return 'hello from module';\n 24 };\n 25\ndebug>
    \n", "type": "module", "displayName": "Breakpoints" }, { "textRaw": "Breakpoints", "name": "breakpoints", "desc": "

    It is also possible to set a breakpoint in a file (module) that\nisn't loaded yet:\n\n

    \n
    % ./node debug test/fixtures/break-in-module/main.js\n< debugger listening on port 5858\nconnecting to port 5858... ok\nbreak in test/fixtures/break-in-module/main.js:1\n  1 var mod = require('./mod.js');\n  2 mod.hello();\n  3 mod.hello();\ndebug> setBreakpoint('mod.js', 23)\nWarning: script 'mod.js' was not loaded yet.\n  1 var mod = require('./mod.js');\n  2 mod.hello();\n  3 mod.hello();\ndebug> c\nbreak in test/fixtures/break-in-module/mod.js:23\n 21\n 22 exports.hello = function() {\n 23   return 'hello from module';\n 24 };\n 25\ndebug>
    \n", "type": "module", "displayName": "Breakpoints" }, { "textRaw": "Execution control", "name": "Execution control", "type": "module", "displayName": "Various" }, { "textRaw": "Various", "name": "various", "type": "module", "displayName": "Various" } ], "type": "misc", "displayName": "Commands reference" }, { "textRaw": "Advanced Usage", "name": "advanced_usage", "desc": "

    The V8 debugger can be enabled and accessed either by starting Node with\nthe --debug command-line flag or by signaling an existing Node process\nwith SIGUSR1.\n\n

    \n

    Once a process has been set in debug mode with this it can be connected to\nwith the node debugger. Either connect to the pid or the URI to the debugger.\nThe syntax is:\n\n

    \n
      \n
    • node debug -p <pid> - Connects to the process via the pid
    • \n
    • node debug <URI> - Connects to the process via the URI such as localhost:5858
    • \n
    \n", "type": "misc", "displayName": "Advanced Usage" } ] } ] } node-v0.10.25~dfsg2/doc/api/zlib.markdown0000644000000000000000000002242712270121457016646 0ustar rootroot# Zlib Stability: 3 - Stable You can access this module with: var zlib = require('zlib'); This provides bindings to Gzip/Gunzip, Deflate/Inflate, and DeflateRaw/InflateRaw classes. Each class takes the same options, and is a readable/writable Stream. ## Examples Compressing or decompressing a file can be done by piping an fs.ReadStream into a zlib stream, then into an fs.WriteStream. var gzip = zlib.createGzip(); var fs = require('fs'); var inp = fs.createReadStream('input.txt'); var out = fs.createWriteStream('input.txt.gz'); inp.pipe(gzip).pipe(out); Compressing or decompressing data in one step can be done by using the convenience methods. var input = '.................................'; zlib.deflate(input, function(err, buffer) { if (!err) { console.log(buffer.toString('base64')); } }); var buffer = new Buffer('eJzT0yMAAGTvBe8=', 'base64'); zlib.unzip(buffer, function(err, buffer) { if (!err) { console.log(buffer.toString()); } }); To use this module in an HTTP client or server, use the [accept-encoding](http://www.w3.org/Protocols/rfc2616/rfc2616-sec14.html#sec14.3) on requests, and the [content-encoding](http://www.w3.org/Protocols/rfc2616/rfc2616-sec14.html#sec14.11) header on responses. **Note: these examples are drastically simplified to show the basic concept.** Zlib encoding can be expensive, and the results ought to be cached. See [Memory Usage Tuning](#zlib_memory_usage_tuning) below for more information on the speed/memory/compression tradeoffs involved in zlib usage. // client request example var zlib = require('zlib'); var http = require('http'); var fs = require('fs'); var request = http.get({ host: 'izs.me', path: '/', port: 80, headers: { 'accept-encoding': 'gzip,deflate' } }); request.on('response', function(response) { var output = fs.createWriteStream('izs.me_index.html'); switch (response.headers['content-encoding']) { // or, just use zlib.createUnzip() to handle both cases case 'gzip': response.pipe(zlib.createGunzip()).pipe(output); break; case 'deflate': response.pipe(zlib.createInflate()).pipe(output); break; default: response.pipe(output); break; } }); // server example // Running a gzip operation on every request is quite expensive. // It would be much more efficient to cache the compressed buffer. var zlib = require('zlib'); var http = require('http'); var fs = require('fs'); http.createServer(function(request, response) { var raw = fs.createReadStream('index.html'); var acceptEncoding = request.headers['accept-encoding']; if (!acceptEncoding) { acceptEncoding = ''; } // Note: this is not a conformant accept-encoding parser. // See http://www.w3.org/Protocols/rfc2616/rfc2616-sec14.html#sec14.3 if (acceptEncoding.match(/\bdeflate\b/)) { response.writeHead(200, { 'content-encoding': 'deflate' }); raw.pipe(zlib.createDeflate()).pipe(response); } else if (acceptEncoding.match(/\bgzip\b/)) { response.writeHead(200, { 'content-encoding': 'gzip' }); raw.pipe(zlib.createGzip()).pipe(response); } else { response.writeHead(200, {}); raw.pipe(response); } }).listen(1337); ## zlib.createGzip([options]) Returns a new [Gzip](#zlib_class_zlib_gzip) object with an [options](#zlib_options). ## zlib.createGunzip([options]) Returns a new [Gunzip](#zlib_class_zlib_gunzip) object with an [options](#zlib_options). ## zlib.createDeflate([options]) Returns a new [Deflate](#zlib_class_zlib_deflate) object with an [options](#zlib_options). ## zlib.createInflate([options]) Returns a new [Inflate](#zlib_class_zlib_inflate) object with an [options](#zlib_options). ## zlib.createDeflateRaw([options]) Returns a new [DeflateRaw](#zlib_class_zlib_deflateraw) object with an [options](#zlib_options). ## zlib.createInflateRaw([options]) Returns a new [InflateRaw](#zlib_class_zlib_inflateraw) object with an [options](#zlib_options). ## zlib.createUnzip([options]) Returns a new [Unzip](#zlib_class_zlib_unzip) object with an [options](#zlib_options). ## Class: zlib.Zlib Not exported by the `zlib` module. It is documented here because it is the base class of the compressor/decompressor classes. ### zlib.flush(callback) Flush pending data. Don't call this frivolously, premature flushes negatively impact the effectiveness of the compression algorithm. ### zlib.reset() Reset the compressor/decompressor to factory defaults. Only applicable to the inflate and deflate algorithms. ## Class: zlib.Gzip Compress data using gzip. ## Class: zlib.Gunzip Decompress a gzip stream. ## Class: zlib.Deflate Compress data using deflate. ## Class: zlib.Inflate Decompress a deflate stream. ## Class: zlib.DeflateRaw Compress data using deflate, and do not append a zlib header. ## Class: zlib.InflateRaw Decompress a raw deflate stream. ## Class: zlib.Unzip Decompress either a Gzip- or Deflate-compressed stream by auto-detecting the header. ## Convenience Methods All of these take a string or buffer as the first argument, and call the supplied callback with `callback(error, result)`. The compression/decompression engine is created using the default settings in all convenience methods. To supply different options, use the zlib classes directly. ## zlib.deflate(buf, callback) Compress a string with Deflate. ## zlib.deflateRaw(buf, callback) Compress a string with DeflateRaw. ## zlib.gzip(buf, callback) Compress a string with Gzip. ## zlib.gunzip(buf, callback) Decompress a raw Buffer with Gunzip. ## zlib.inflate(buf, callback) Decompress a raw Buffer with Inflate. ## zlib.inflateRaw(buf, callback) Decompress a raw Buffer with InflateRaw. ## zlib.unzip(buf, callback) Decompress a raw Buffer with Unzip. ## Options Each class takes an options object. All options are optional. (The convenience methods use the default settings for all options.) Note that some options are only relevant when compressing, and are ignored by the decompression classes. * flush (default: `zlib.Z_NO_FLUSH`) * chunkSize (default: 16*1024) * windowBits * level (compression only) * memLevel (compression only) * strategy (compression only) * dictionary (deflate/inflate only, empty dictionary by default) See the description of `deflateInit2` and `inflateInit2` at for more information on these. ## Memory Usage Tuning From `zlib/zconf.h`, modified to node's usage: The memory requirements for deflate are (in bytes): (1 << (windowBits+2)) + (1 << (memLevel+9)) that is: 128K for windowBits=15 + 128K for memLevel = 8 (default values) plus a few kilobytes for small objects. For example, if you want to reduce the default memory requirements from 256K to 128K, set the options to: { windowBits: 14, memLevel: 7 } Of course this will generally degrade compression (there's no free lunch). The memory requirements for inflate are (in bytes) 1 << windowBits that is, 32K for windowBits=15 (default value) plus a few kilobytes for small objects. This is in addition to a single internal output slab buffer of size `chunkSize`, which defaults to 16K. The speed of zlib compression is affected most dramatically by the `level` setting. A higher level will result in better compression, but will take longer to complete. A lower level will result in less compression, but will be much faster. In general, greater memory usage options will mean that node has to make fewer calls to zlib, since it'll be able to process more data in a single `write` operation. So, this is another factor that affects the speed, at the cost of memory usage. ## Constants All of the constants defined in zlib.h are also defined on `require('zlib')`. In the normal course of operations, you will not need to ever set any of these. They are documented here so that their presence is not surprising. This section is taken almost directly from the [zlib documentation](http://zlib.net/manual.html#Constants). See for more details. Allowed flush values. * `zlib.Z_NO_FLUSH` * `zlib.Z_PARTIAL_FLUSH` * `zlib.Z_SYNC_FLUSH` * `zlib.Z_FULL_FLUSH` * `zlib.Z_FINISH` * `zlib.Z_BLOCK` * `zlib.Z_TREES` Return codes for the compression/decompression functions. Negative values are errors, positive values are used for special but normal events. * `zlib.Z_OK` * `zlib.Z_STREAM_END` * `zlib.Z_NEED_DICT` * `zlib.Z_ERRNO` * `zlib.Z_STREAM_ERROR` * `zlib.Z_DATA_ERROR` * `zlib.Z_MEM_ERROR` * `zlib.Z_BUF_ERROR` * `zlib.Z_VERSION_ERROR` Compression levels. * `zlib.Z_NO_COMPRESSION` * `zlib.Z_BEST_SPEED` * `zlib.Z_BEST_COMPRESSION` * `zlib.Z_DEFAULT_COMPRESSION` Compression strategy. * `zlib.Z_FILTERED` * `zlib.Z_HUFFMAN_ONLY` * `zlib.Z_RLE` * `zlib.Z_FIXED` * `zlib.Z_DEFAULT_STRATEGY` Possible values of the data_type field. * `zlib.Z_BINARY` * `zlib.Z_TEXT` * `zlib.Z_ASCII` * `zlib.Z_UNKNOWN` The deflate compression method (the only one supported in this version). * `zlib.Z_DEFLATED` For initializing zalloc, zfree, opaque. * `zlib.Z_NULL` node-v0.10.25~dfsg2/doc/api/domain.json0000644000000000000000000005310712270264601016302 0ustar rootroot{ "source": "doc/api/domain.markdown", "modules": [ { "textRaw": "Domain", "name": "domain", "stability": 2, "stabilityText": "Unstable", "desc": "

    Domains provide a way to handle multiple different IO operations as a\nsingle group. If any of the event emitters or callbacks registered to a\ndomain emit an error event, or throw an error, then the domain object\nwill be notified, rather than losing the context of the error in the\nprocess.on('uncaughtException') handler, or causing the program to\nexit immediately with an error code.\n\n

    \n", "miscs": [ { "textRaw": "Warning: Don't Ignore Errors!", "name": "Warning: Don't Ignore Errors!", "type": "misc", "desc": "

    Domain error handlers are not a substitute for closing down your\nprocess when an error occurs.\n\n

    \n

    By the very nature of how throw works in JavaScript, there is almost\nnever any way to safely "pick up where you left off", without leaking\nreferences, or creating some other sort of undefined brittle state.\n\n

    \n

    The safest way to respond to a thrown error is to shut down the\nprocess. Of course, in a normal web server, you might have many\nconnections open, and it is not reasonable to abruptly shut those down\nbecause an error was triggered by someone else.\n\n

    \n

    The better approach is send an error response to the request that\ntriggered the error, while letting the others finish in their normal\ntime, and stop listening for new requests in that worker.\n\n

    \n

    In this way, domain usage goes hand-in-hand with the cluster module,\nsince the master process can fork a new worker when a worker\nencounters an error. For node programs that scale to multiple\nmachines, the terminating proxy or service registry can take note of\nthe failure, and react accordingly.\n\n

    \n

    For example, this is not a good idea:\n\n

    \n
    // XXX WARNING!  BAD IDEA!\n\nvar d = require('domain').create();\nd.on('error', function(er) {\n  // The error won't crash the process, but what it does is worse!\n  // Though we've prevented abrupt process restarting, we are leaking\n  // resources like crazy if this ever happens.\n  // This is no better than process.on('uncaughtException')!\n  console.log('error, but oh well', er.message);\n});\nd.run(function() {\n  require('http').createServer(function(req, res) {\n    handleRequest(req, res);\n  }).listen(PORT);\n});
    \n

    By using the context of a domain, and the resilience of separating our\nprogram into multiple worker processes, we can react more\nappropriately, and handle errors with much greater safety.\n\n

    \n
    // Much better!\n\nvar cluster = require('cluster');\nvar PORT = +process.env.PORT || 1337;\n\nif (cluster.isMaster) {\n  // In real life, you'd probably use more than just 2 workers,\n  // and perhaps not put the master and worker in the same file.\n  //\n  // You can also of course get a bit fancier about logging, and\n  // implement whatever custom logic you need to prevent DoS\n  // attacks and other bad behavior.\n  //\n  // See the options in the cluster documentation.\n  //\n  // The important thing is that the master does very little,\n  // increasing our resilience to unexpected errors.\n\n  cluster.fork();\n  cluster.fork();\n\n  cluster.on('disconnect', function(worker) {\n    console.error('disconnect!');\n    cluster.fork();\n  });\n\n} else {\n  // the worker\n  //\n  // This is where we put our bugs!\n\n  var domain = require('domain');\n\n  // See the cluster documentation for more details about using\n  // worker processes to serve requests.  How it works, caveats, etc.\n\n  var server = require('http').createServer(function(req, res) {\n    var d = domain.create();\n    d.on('error', function(er) {\n      console.error('error', er.stack);\n\n      // Note: we're in dangerous territory!\n      // By definition, something unexpected occurred,\n      // which we probably didn't want.\n      // Anything can happen now!  Be very careful!\n\n      try {\n        // make sure we close down within 30 seconds\n        var killtimer = setTimeout(function() {\n          process.exit(1);\n        }, 30000);\n        // But don't keep the process open just for that!\n        killtimer.unref();\n\n        // stop taking new requests.\n        server.close();\n\n        // Let the master know we're dead.  This will trigger a\n        // 'disconnect' in the cluster master, and then it will fork\n        // a new worker.\n        cluster.worker.disconnect();\n\n        // try to send an error to the request that triggered the problem\n        res.statusCode = 500;\n        res.setHeader('content-type', 'text/plain');\n        res.end('Oops, there was a problem!\\n');\n      } catch (er2) {\n        // oh well, not much we can do at this point.\n        console.error('Error sending 500!', er2.stack);\n      }\n    });\n\n    // Because req and res were created before this domain existed,\n    // we need to explicitly add them.\n    // See the explanation of implicit vs explicit binding below.\n    d.add(req);\n    d.add(res);\n\n    // Now run the handler function in the domain.\n    d.run(function() {\n      handleRequest(req, res);\n    });\n  });\n  server.listen(PORT);\n}\n\n// This part isn't important.  Just an example routing thing.\n// You'd put your fancy application logic here.\nfunction handleRequest(req, res) {\n  switch(req.url) {\n    case '/error':\n      // We do some async stuff, and then...\n      setTimeout(function() {\n        // Whoops!\n        flerb.bark();\n      });\n      break;\n    default:\n      res.end('ok');\n  }\n}
    \n" }, { "textRaw": "Additions to Error objects", "name": "Additions to Error objects", "type": "misc", "desc": "

    Any time an Error object is routed through a domain, a few extra fields\nare added to it.\n\n

    \n
      \n
    • error.domain The domain that first handled the error.
    • \n
    • error.domainEmitter The event emitter that emitted an 'error' event\nwith the error object.
    • \n
    • error.domainBound The callback function which was bound to the\ndomain, and passed an error as its first argument.
    • \n
    • error.domainThrown A boolean indicating whether the error was\nthrown, emitted, or passed to a bound callback function.
    • \n
    \n" }, { "textRaw": "Implicit Binding", "name": "Implicit Binding", "type": "misc", "desc": "

    If domains are in use, then all new EventEmitter objects (including\nStream objects, requests, responses, etc.) will be implicitly bound to\nthe active domain at the time of their creation.\n\n

    \n

    Additionally, callbacks passed to lowlevel event loop requests (such as\nto fs.open, or other callback-taking methods) will automatically be\nbound to the active domain. If they throw, then the domain will catch\nthe error.\n\n

    \n

    In order to prevent excessive memory usage, Domain objects themselves\nare not implicitly added as children of the active domain. If they\nwere, then it would be too easy to prevent request and response objects\nfrom being properly garbage collected.\n\n

    \n

    If you want to nest Domain objects as children of a parent Domain,\nthen you must explicitly add them.\n\n

    \n

    Implicit binding routes thrown errors and 'error' events to the\nDomain's error event, but does not register the EventEmitter on the\nDomain, so domain.dispose() will not shut down the EventEmitter.\nImplicit binding only takes care of thrown errors and 'error' events.\n\n

    \n" }, { "textRaw": "Explicit Binding", "name": "Explicit Binding", "type": "misc", "desc": "

    Sometimes, the domain in use is not the one that ought to be used for a\nspecific event emitter. Or, the event emitter could have been created\nin the context of one domain, but ought to instead be bound to some\nother domain.\n\n

    \n

    For example, there could be one domain in use for an HTTP server, but\nperhaps we would like to have a separate domain to use for each request.\n\n

    \n

    That is possible via explicit binding.\n\n

    \n

    For example:\n\n

    \n
    // create a top-level domain for the server\nvar serverDomain = domain.create();\n\nserverDomain.run(function() {\n  // server is created in the scope of serverDomain\n  http.createServer(function(req, res) {\n    // req and res are also created in the scope of serverDomain\n    // however, we'd prefer to have a separate domain for each request.\n    // create it first thing, and add req and res to it.\n    var reqd = domain.create();\n    reqd.add(req);\n    reqd.add(res);\n    reqd.on('error', function(er) {\n      console.error('Error', er, req.url);\n      try {\n        res.writeHead(500);\n        res.end('Error occurred, sorry.');\n      } catch (er) {\n        console.error('Error sending 500', er, req.url);\n      }\n    });\n  }).listen(1337);\n});
    \n" } ], "methods": [ { "textRaw": "domain.create()", "type": "method", "name": "create", "signatures": [ { "return": { "textRaw": "return: {Domain} ", "name": "return", "type": "Domain" }, "params": [] }, { "params": [] } ], "desc": "

    Returns a new Domain object.\n\n

    \n" } ], "classes": [ { "textRaw": "Class: Domain", "type": "class", "name": "Domain", "desc": "

    The Domain class encapsulates the functionality of routing errors and\nuncaught exceptions to the active Domain object.\n\n

    \n

    Domain is a child class of [EventEmitter][]. To handle the errors that it\ncatches, listen to its error event.\n\n

    \n", "methods": [ { "textRaw": "domain.run(fn)", "type": "method", "name": "run", "signatures": [ { "params": [ { "textRaw": "`fn` {Function} ", "name": "fn", "type": "Function" } ] }, { "params": [ { "name": "fn" } ] } ], "desc": "

    Run the supplied function in the context of the domain, implicitly\nbinding all event emitters, timers, and lowlevel requests that are\ncreated in that context.\n\n

    \n

    This is the most basic way to use a domain.\n\n

    \n

    Example:\n\n

    \n
    var d = domain.create();\nd.on('error', function(er) {\n  console.error('Caught error!', er);\n});\nd.run(function() {\n  process.nextTick(function() {\n    setTimeout(function() { // simulating some various async stuff\n      fs.open('non-existent file', 'r', function(er, fd) {\n        if (er) throw er;\n        // proceed...\n      });\n    }, 100);\n  });\n});
    \n

    In this example, the d.on('error') handler will be triggered, rather\nthan crashing the program.\n\n

    \n" }, { "textRaw": "domain.add(emitter)", "type": "method", "name": "add", "signatures": [ { "params": [ { "textRaw": "`emitter` {EventEmitter | Timer} emitter or timer to be added to the domain ", "name": "emitter", "type": "EventEmitter | Timer", "desc": "emitter or timer to be added to the domain" } ] }, { "params": [ { "name": "emitter" } ] } ], "desc": "

    Explicitly adds an emitter to the domain. If any event handlers called by\nthe emitter throw an error, or if the emitter emits an error event, it\nwill be routed to the domain's error event, just like with implicit\nbinding.\n\n

    \n

    This also works with timers that are returned from setInterval and\nsetTimeout. If their callback function throws, it will be caught by\nthe domain 'error' handler.\n\n

    \n

    If the Timer or EventEmitter was already bound to a domain, it is removed\nfrom that one, and bound to this one instead.\n\n

    \n" }, { "textRaw": "domain.remove(emitter)", "type": "method", "name": "remove", "signatures": [ { "params": [ { "textRaw": "`emitter` {EventEmitter | Timer} emitter or timer to be removed from the domain ", "name": "emitter", "type": "EventEmitter | Timer", "desc": "emitter or timer to be removed from the domain" } ] }, { "params": [ { "name": "emitter" } ] } ], "desc": "

    The opposite of domain.add(emitter). Removes domain handling from the\nspecified emitter.\n\n

    \n" }, { "textRaw": "domain.bind(callback)", "type": "method", "name": "bind", "signatures": [ { "return": { "textRaw": "return: {Function} The bound function ", "name": "return", "type": "Function", "desc": "The bound function" }, "params": [ { "textRaw": "`callback` {Function} The callback function ", "name": "callback", "type": "Function", "desc": "The callback function" } ] }, { "params": [ { "name": "callback" } ] } ], "desc": "

    The returned function will be a wrapper around the supplied callback\nfunction. When the returned function is called, any errors that are\nthrown will be routed to the domain's error event.\n\n

    \n

    Example

    \n
    var d = domain.create();\n\nfunction readSomeFile(filename, cb) {\n  fs.readFile(filename, 'utf8', d.bind(function(er, data) {\n    // if this throws, it will also be passed to the domain\n    return cb(er, data ? JSON.parse(data) : null);\n  }));\n}\n\nd.on('error', function(er) {\n  // an error occurred somewhere.\n  // if we throw it now, it will crash the program\n  // with the normal line number and stack message.\n});
    \n" }, { "textRaw": "domain.intercept(callback)", "type": "method", "name": "intercept", "signatures": [ { "return": { "textRaw": "return: {Function} The intercepted function ", "name": "return", "type": "Function", "desc": "The intercepted function" }, "params": [ { "textRaw": "`callback` {Function} The callback function ", "name": "callback", "type": "Function", "desc": "The callback function" } ] }, { "params": [ { "name": "callback" } ] } ], "desc": "

    This method is almost identical to domain.bind(callback). However, in\naddition to catching thrown errors, it will also intercept Error\nobjects sent as the first argument to the function.\n\n

    \n

    In this way, the common if (er) return callback(er); pattern can be replaced\nwith a single error handler in a single place.\n\n

    \n

    Example

    \n
    var d = domain.create();\n\nfunction readSomeFile(filename, cb) {\n  fs.readFile(filename, 'utf8', d.intercept(function(data) {\n    // note, the first argument is never passed to the\n    // callback since it is assumed to be the 'Error' argument\n    // and thus intercepted by the domain.\n\n    // if this throws, it will also be passed to the domain\n    // so the error-handling logic can be moved to the 'error'\n    // event on the domain instead of being repeated throughout\n    // the program.\n    return cb(null, JSON.parse(data));\n  }));\n}\n\nd.on('error', function(er) {\n  // an error occurred somewhere.\n  // if we throw it now, it will crash the program\n  // with the normal line number and stack message.\n});
    \n" }, { "textRaw": "domain.enter()", "type": "method", "name": "enter", "desc": "

    The enter method is plumbing used by the run, bind, and intercept\nmethods to set the active domain. It sets domain.active and process.domain\nto the domain, and implicitly pushes the domain onto the domain stack managed\nby the domain module (see domain.exit() for details on the domain stack). The\ncall to enter delimits the beginning of a chain of asynchronous calls and I/O\noperations bound to a domain.\n\n

    \n

    Calling enter changes only the active domain, and does not alter the domain\nitself. Enter and exit can be called an arbitrary number of times on a\nsingle domain.\n\n

    \n

    If the domain on which enter is called has been disposed, enter will return\nwithout setting the domain.\n\n

    \n", "signatures": [ { "params": [] } ] }, { "textRaw": "domain.exit()", "type": "method", "name": "exit", "desc": "

    The exit method exits the current domain, popping it off the domain stack.\nAny time execution is going to switch to the context of a different chain of\nasynchronous calls, it's important to ensure that the current domain is exited.\nThe call to exit delimits either the end of or an interruption to the chain\nof asynchronous calls and I/O operations bound to a domain.\n\n

    \n

    If there are multiple, nested domains bound to the current execution context,\nexit will exit any domains nested within this domain.\n\n

    \n

    Calling exit changes only the active domain, and does not alter the domain\nitself. Enter and exit can be called an arbitrary number of times on a\nsingle domain.\n\n

    \n

    If the domain on which exit is called has been disposed, exit will return\nwithout exiting the domain.\n\n

    \n", "signatures": [ { "params": [] } ] }, { "textRaw": "domain.dispose()", "type": "method", "name": "dispose", "desc": "

    The dispose method destroys a domain, and makes a best effort attempt to\nclean up any and all IO that is associated with the domain. Streams are\naborted, ended, closed, and/or destroyed. Timers are cleared.\nExplicitly bound callbacks are no longer called. Any error events that\nare raised as a result of this are ignored.\n\n

    \n

    The intention of calling dispose is generally to prevent cascading\nerrors when a critical part of the Domain context is found to be in an\nerror state.\n\n

    \n

    Once the domain is disposed the dispose event will emit.\n\n

    \n

    Note that IO might still be performed. However, to the highest degree\npossible, once a domain is disposed, further errors from the emitters in\nthat set will be ignored. So, even if some remaining actions are still\nin flight, Node.js will not communicate further about them.\n\n

    \n", "signatures": [ { "params": [] } ] } ], "properties": [ { "textRaw": "`members` {Array} ", "name": "members", "desc": "

    An array of timers and event emitters that have been explicitly added\nto the domain.\n\n

    \n" } ] } ], "type": "module", "displayName": "Domain" } ] } node-v0.10.25~dfsg2/doc/api/assert.json0000644000000000000000000001736512270264601016342 0ustar rootroot{ "source": "doc/api/assert.markdown", "modules": [ { "textRaw": "Assert", "name": "assert", "stability": 5, "stabilityText": "Locked", "desc": "

    This module is used for writing unit tests for your applications, you can\naccess it with require('assert').\n\n

    \n", "methods": [ { "textRaw": "assert.fail(actual, expected, message, operator)", "type": "method", "name": "fail", "desc": "

    Throws an exception that displays the values for actual and expected separated by the provided operator.\n\n

    \n", "signatures": [ { "params": [ { "name": "actual" }, { "name": "expected" }, { "name": "message" }, { "name": "operator" } ] } ] }, { "textRaw": "assert(value, message), assert.ok(value, [message])", "type": "method", "name": "ok", "desc": "

    Tests if value is truthy, it is equivalent to assert.equal(true, !!value, message);\n\n

    \n", "signatures": [ { "params": [ { "name": "value" }, { "name": "message)" }, { "name": "assert.ok(value" }, { "name": "message", "optional": true } ] } ] }, { "textRaw": "assert.equal(actual, expected, [message])", "type": "method", "name": "equal", "desc": "

    Tests shallow, coercive equality with the equal comparison operator ( == ).\n\n

    \n", "signatures": [ { "params": [ { "name": "actual" }, { "name": "expected" }, { "name": "message", "optional": true } ] } ] }, { "textRaw": "assert.notEqual(actual, expected, [message])", "type": "method", "name": "notEqual", "desc": "

    Tests shallow, coercive non-equality with the not equal comparison operator ( != ).\n\n

    \n", "signatures": [ { "params": [ { "name": "actual" }, { "name": "expected" }, { "name": "message", "optional": true } ] } ] }, { "textRaw": "assert.deepEqual(actual, expected, [message])", "type": "method", "name": "deepEqual", "desc": "

    Tests for deep equality.\n\n

    \n", "signatures": [ { "params": [ { "name": "actual" }, { "name": "expected" }, { "name": "message", "optional": true } ] } ] }, { "textRaw": "assert.notDeepEqual(actual, expected, [message])", "type": "method", "name": "notDeepEqual", "desc": "

    Tests for any deep inequality.\n\n

    \n", "signatures": [ { "params": [ { "name": "actual" }, { "name": "expected" }, { "name": "message", "optional": true } ] } ] }, { "textRaw": "assert.strictEqual(actual, expected, [message])", "type": "method", "name": "strictEqual", "desc": "

    Tests strict equality, as determined by the strict equality operator ( === )\n\n

    \n", "signatures": [ { "params": [ { "name": "actual" }, { "name": "expected" }, { "name": "message", "optional": true } ] } ] }, { "textRaw": "assert.notStrictEqual(actual, expected, [message])", "type": "method", "name": "notStrictEqual", "desc": "

    Tests strict non-equality, as determined by the strict not equal operator ( !== )\n\n

    \n", "signatures": [ { "params": [ { "name": "actual" }, { "name": "expected" }, { "name": "message", "optional": true } ] } ] }, { "textRaw": "assert.throws(block, [error], [message])", "type": "method", "name": "throws", "desc": "

    Expects block to throw an error. error can be constructor, regexp or \nvalidation function.\n\n

    \n

    Validate instanceof using constructor:\n\n

    \n
    assert.throws(\n  function() {\n    throw new Error("Wrong value");\n  },\n  Error\n);
    \n

    Validate error message using RegExp:\n\n

    \n
    assert.throws(\n  function() {\n    throw new Error("Wrong value");\n  },\n  /value/\n);
    \n

    Custom error validation:\n\n

    \n
    assert.throws(\n  function() {\n    throw new Error("Wrong value");\n  },\n  function(err) {\n    if ( (err instanceof Error) && /value/.test(err) ) {\n      return true;\n    }\n  },\n  "unexpected error"\n);
    \n", "signatures": [ { "params": [ { "name": "block" }, { "name": "error", "optional": true }, { "name": "message", "optional": true } ] } ] }, { "textRaw": "assert.doesNotThrow(block, [message])", "type": "method", "name": "doesNotThrow", "desc": "

    Expects block not to throw an error, see assert.throws for details.\n\n

    \n", "signatures": [ { "params": [ { "name": "block" }, { "name": "message", "optional": true } ] } ] }, { "textRaw": "assert.ifError(value)", "type": "method", "name": "ifError", "desc": "

    Tests if value is not a false value, throws if it is a true value. Useful when\ntesting the first argument, error in callbacks.\n

    \n", "signatures": [ { "params": [ { "name": "value" } ] } ] } ], "type": "module", "displayName": "Assert" } ] } node-v0.10.25~dfsg2/doc/api/path.html0000644000000000000000000002465712270264601015772 0ustar rootroot Path Node.js v0.10.25 Manual & Documentation

    Node.js v0.10.25 Manual & Documentation


    Path#

    Stability: 3 - Stable

    This module contains utilities for handling and transforming file paths. Almost all these methods perform only string transformations. The file system is not consulted to check whether paths are valid.

    Use require('path') to use this module. The following methods are provided:

    path.normalize(p)#

    Normalize a string path, taking care of '..' and '.' parts.

    When multiple slashes are found, they're replaced by a single one; when the path contains a trailing slash, it is preserved. On Windows backslashes are used.

    Example:

    path.normalize('/foo/bar//baz/asdf/quux/..')
    // returns
    '/foo/bar/baz/asdf'

    path.join([path1], [path2], [...])#

    Join all arguments together and normalize the resulting path.

    Arguments must be strings. In v0.8, non-string arguments were silently ignored. In v0.10 and up, an exception is thrown.

    Example:

    path.join('/foo', 'bar', 'baz/asdf', 'quux', '..')
    // returns
    '/foo/bar/baz/asdf'
    
    path.join('foo', {}, 'bar')
    // throws exception
    TypeError: Arguments to path.join must be strings

    path.resolve([from ...], to)#

    Resolves to to an absolute path.

    If to isn't already absolute from arguments are prepended in right to left order, until an absolute path is found. If after using all from paths still no absolute path is found, the current working directory is used as well. The resulting path is normalized, and trailing slashes are removed unless the path gets resolved to the root directory. Non-string arguments are ignored.

    Another way to think of it is as a sequence of cd commands in a shell.

    path.resolve('foo/bar', '/tmp/file/', '..', 'a/../subfile')

    Is similar to:

    cd foo/bar
    cd /tmp/file/
    cd ..
    cd a/../subfile
    pwd

    The difference is that the different paths don't need to exist and may also be files.

    Examples:

    path.resolve('/foo/bar', './baz')
    // returns
    '/foo/bar/baz'
    
    path.resolve('/foo/bar', '/tmp/file/')
    // returns
    '/tmp/file'
    
    path.resolve('wwwroot', 'static_files/png/', '../gif/image.gif')
    // if currently in /home/myself/node, it returns
    '/home/myself/node/wwwroot/static_files/gif/image.gif'

    path.relative(from, to)#

    Solve the relative path from from to to.

    At times we have two absolute paths, and we need to derive the relative path from one to the other. This is actually the reverse transform of path.resolve, which means we see that:

    path.resolve(from, path.relative(from, to)) == path.resolve(to)

    Examples:

    path.relative('C:\\orandea\\test\\aaa', 'C:\\orandea\\impl\\bbb')
    // returns
    '..\\..\\impl\\bbb'
    
    path.relative('/data/orandea/test/aaa', '/data/orandea/impl/bbb')
    // returns
    '../../impl/bbb'

    path.dirname(p)#

    Return the directory name of a path. Similar to the Unix dirname command.

    Example:

    path.dirname('/foo/bar/baz/asdf/quux')
    // returns
    '/foo/bar/baz/asdf'

    path.basename(p, [ext])#

    Return the last portion of a path. Similar to the Unix basename command.

    Example:

    path.basename('/foo/bar/baz/asdf/quux.html')
    // returns
    'quux.html'
    
    path.basename('/foo/bar/baz/asdf/quux.html', '.html')
    // returns
    'quux'

    path.extname(p)#

    Return the extension of the path, from the last '.' to end of string in the last portion of the path. If there is no '.' in the last portion of the path or the first character of it is '.', then it returns an empty string. Examples:

    path.extname('index.html')
    // returns
    '.html'
    
    path.extname('index.')
    // returns
    '.'
    
    path.extname('index')
    // returns
    ''

    path.sep#

    The platform-specific file separator. '\\' or '/'.

    An example on *nix:

    'foo/bar/baz'.split(path.sep)
    // returns
    ['foo', 'bar', 'baz']

    An example on Windows:

    'foo\\bar\\baz'.split(path.sep)
    // returns
    ['foo', 'bar', 'baz']

    path.delimiter#

    The platform-specific path delimiter, ; or ':'.

    An example on *nix:

    console.log(process.env.PATH)
    // '/usr/bin:/bin:/usr/sbin:/sbin:/usr/local/bin'
    
    process.env.PATH.split(path.delimiter)
    // returns
    ['/usr/bin', '/bin', '/usr/sbin', '/sbin', '/usr/local/bin']

    An example on Windows:

    console.log(process.env.PATH)
    // 'C:\Windows\system32;C:\Windows;C:\Program Files\nodejs\'
    
    process.env.PATH.split(path.delimiter)
    // returns
    ['C:\Windows\system32', 'C:\Windows', 'C:\Program Files\nodejs\']
    node-v0.10.25~dfsg2/doc/api/all.markdown0000644000000000000000000000110112270121457016440 0ustar rootroot@include documentation @include synopsis @include globals @include console @include timers @include modules @include addons @include process @include util @include events @include domain @include buffer @include stream @include crypto @include tls @include string_decoder @include fs @include path @include net @include dgram @include dns @include http @include https @include url @include querystring @include punycode @include readline @include repl @include vm @include child_process @include assert @include tty @include zlib @include os @include debugger @include cluster node-v0.10.25~dfsg2/doc/api/process.json0000644000000000000000000006744012270264601016516 0ustar rootroot{ "source": "doc/api/process.markdown", "globals": [ { "textRaw": "process", "name": "process", "type": "global", "desc": "

    The process object is a global object and can be accessed from anywhere.\nIt is an instance of [EventEmitter][].\n\n\n

    \n", "events": [ { "textRaw": "Event: 'exit'", "type": "event", "name": "exit", "desc": "

    Emitted when the process is about to exit. There is no way to prevent the\nexiting of the event loop at this point, and once all exit listeners have\nfinished running the process will exit. Therefore you must only perform\nsynchronous operations in this handler. This is a good hook to perform\nchecks on the module's state (like for unit tests). The callback takes one\nargument, the code the process is exiting with.\n\n

    \n

    Example of listening for exit:\n\n

    \n
    process.on('exit', function(code) {\n  // do *NOT* do this\n  setTimeout(function() {\n    console.log('This will not run');\n  }, 0);\n  console.log('About to exit with code:', code);\n});
    \n", "params": [] }, { "textRaw": "Event: 'uncaughtException'", "type": "event", "name": "uncaughtException", "desc": "

    Emitted when an exception bubbles all the way back to the event loop. If a\nlistener is added for this exception, the default action (which is to print\na stack trace and exit) will not occur.\n\n

    \n

    Example of listening for uncaughtException:\n\n

    \n
    process.on('uncaughtException', function(err) {\n  console.log('Caught exception: ' + err);\n});\n\nsetTimeout(function() {\n  console.log('This will still run.');\n}, 500);\n\n// Intentionally cause an exception, but don't catch it.\nnonexistentFunc();\nconsole.log('This will not run.');
    \n

    Note that uncaughtException is a very crude mechanism for exception\nhandling and may be removed in the future.\n\n

    \n

    Don't use it, use domains instead. If you do use it, restart\nyour application after every unhandled exception!\n\n

    \n

    Do not use it as the node.js equivalent of On Error Resume Next. An\nunhandled exception means your application - and by extension node.js itself -\nis in an undefined state. Blindly resuming means anything could happen.\n\n

    \n

    Think of resuming as pulling the power cord when you are upgrading your system.\nNine out of ten times nothing happens - but the 10th time, your system is bust.\n\n

    \n

    You have been warned.\n\n

    \n", "params": [] }, { "textRaw": "Signal Events", "name": "SIGINT, SIGHUP, etc.", "type": "event", "desc": "

    Emitted when the processes receives a signal. See sigaction(2) for a list of\nstandard POSIX signal names such as SIGINT, SIGHUP, etc.\n\n

    \n

    Example of listening for SIGINT:\n\n

    \n
    // Start reading from stdin so we don't exit.\nprocess.stdin.resume();\n\nprocess.on('SIGINT', function() {\n  console.log('Got SIGINT.  Press Control-D to exit.');\n});
    \n

    An easy way to send the SIGINT signal is with Control-C in most terminal\nprograms.\n\n

    \n

    Note:\n\n

    \n
      \n
    • SIGUSR1 is reserved by node.js to start the debugger. It's possible to\ninstall a listener but that won't stop the debugger from starting.
    • \n
    • SIGTERM and SIGINT have default handlers on non-Windows platforms that resets\nthe terminal mode before exiting with code 128 + signal number. If one of\nthese signals has a listener installed, its default behaviour will be removed\n(node will no longer exit).
    • \n
    • SIGPIPE is ignored by default, it can have a listener installed.
    • \n
    • SIGHUP is generated on Windows when the console window is closed, and on other\nplatforms under various similar conditions, see signal(7). It can have a\nlistener installed, however node will be unconditionally terminated by Windows\nabout 10 seconds later. On non-Windows platforms, the default behaviour of\nSIGHUP is to terminate node, but once a listener has been installed its\ndefault behaviour will be removed.
    • \n
    • SIGTERM is not supported on Windows, it can be listened on.
    • \n
    • SIGINT from the terminal is supported on all platforms, and can usually be\ngenerated with CTRL+C (though this may be configurable). It is not generated\nwhen terminal raw mode is enabled.
    • \n
    • SIGBREAK is delivered on Windows when CTRL+BREAK is pressed, on non-Windows\nplatforms it can be listened on, but there is no way to send or generate it.
    • \n
    • SIGWINCH is delivered when the console has been resized. On Windows, this will\nonly happen on write to the console when the cursor is being moved, or when a\nreadable tty is used in raw mode.
    • \n
    • SIGKILL cannot have a listener installed, it will unconditionally terminate\nnode on all platforms.
    • \n
    • SIGSTOP cannot have a listener installed.
    • \n
    \n

    Note that Windows does not support sending Signals, but node offers some\nemulation with process.kill(), and child_process.kill():\n- Sending signal 0 can be used to search for the existence of a process\n- Sending SIGINT, SIGTERM, and SIGKILL cause the unconditional exit of the\n target process.\n\n

    \n", "params": [] } ], "properties": [ { "textRaw": "process.stdout", "name": "stdout", "desc": "

    A Writable Stream to stdout.\n\n

    \n

    Example: the definition of console.log\n\n

    \n
    console.log = function(d) {\n  process.stdout.write(d + '\\n');\n};
    \n

    process.stderr and process.stdout are unlike other streams in Node in\nthat writes to them are usually blocking. They are blocking in the case\nthat they refer to regular files or TTY file descriptors. In the case they\nrefer to pipes, they are non-blocking like other streams.\n\n

    \n

    To check if Node is being run in a TTY context, read the isTTY property\non process.stderr, process.stdout, or process.stdin:\n\n

    \n
    $ node -p "Boolean(process.stdin.isTTY)"\ntrue\n$ echo "foo" | node -p "Boolean(process.stdin.isTTY)"\nfalse\n\n$ node -p "Boolean(process.stdout.isTTY)"\ntrue\n$ node -p "Boolean(process.stdout.isTTY)" | cat\nfalse
    \n

    See the tty docs for more information.\n\n

    \n" }, { "textRaw": "process.stderr", "name": "stderr", "desc": "

    A writable stream to stderr.\n\n

    \n

    process.stderr and process.stdout are unlike other streams in Node in\nthat writes to them are usually blocking. They are blocking in the case\nthat they refer to regular files or TTY file descriptors. In the case they\nrefer to pipes, they are non-blocking like other streams.\n\n\n

    \n" }, { "textRaw": "process.stdin", "name": "stdin", "desc": "

    A Readable Stream for stdin. The stdin stream is paused by default, so one\nmust call process.stdin.resume() to read from it.\n\n

    \n

    Example of opening standard input and listening for both events:\n\n

    \n
    process.stdin.resume();\nprocess.stdin.setEncoding('utf8');\n\nprocess.stdin.on('data', function(chunk) {\n  process.stdout.write('data: ' + chunk);\n});\n\nprocess.stdin.on('end', function() {\n  process.stdout.write('end');\n});
    \n" }, { "textRaw": "process.argv", "name": "argv", "desc": "

    An array containing the command line arguments. The first element will be\n'node', the second element will be the name of the JavaScript file. The\nnext elements will be any additional command line arguments.\n\n

    \n
    // print process.argv\nprocess.argv.forEach(function(val, index, array) {\n  console.log(index + ': ' + val);\n});
    \n

    This will generate:\n\n

    \n
    $ node process-2.js one two=three four\n0: node\n1: /Users/mjr/work/node/process-2.js\n2: one\n3: two=three\n4: four
    \n" }, { "textRaw": "process.execPath", "name": "execPath", "desc": "

    This is the absolute pathname of the executable that started the process.\n\n

    \n

    Example:\n\n

    \n
    /usr/local/bin/node
    \n" }, { "textRaw": "process.execArgv", "name": "execArgv", "desc": "

    This is the set of node-specific command line options from the\nexecutable that started the process. These options do not show up in\nprocess.argv, and do not include the node executable, the name of\nthe script, or any options following the script name. These options\nare useful in order to spawn child processes with the same execution\nenvironment as the parent.\n\n

    \n

    Example:\n\n

    \n
    $ node --harmony script.js --version
    \n

    results in process.execArgv:\n\n

    \n
    ['--harmony']
    \n

    and process.argv:\n\n

    \n
    ['/usr/local/bin/node', 'script.js', '--version']
    \n" }, { "textRaw": "process.env", "name": "env", "desc": "

    An object containing the user environment. See environ(7).\n\n\n

    \n" }, { "textRaw": "process.version", "name": "version", "desc": "

    A compiled-in property that exposes NODE_VERSION.\n\n

    \n
    console.log('Version: ' + process.version);
    \n" }, { "textRaw": "process.versions", "name": "versions", "desc": "

    A property exposing version strings of node and its dependencies.\n\n

    \n
    console.log(process.versions);
    \n

    Will print something like:\n\n

    \n
    { http_parser: '1.0',\n  node: '0.10.4',\n  v8: '3.14.5.8',\n  ares: '1.9.0-DEV',\n  uv: '0.10.3',\n  zlib: '1.2.3',\n  modules: '11',\n  openssl: '1.0.1e' }
    \n" }, { "textRaw": "process.config", "name": "config", "desc": "

    An Object containing the JavaScript representation of the configure options\nthat were used to compile the current node executable. This is the same as\nthe "config.gypi" file that was produced when running the ./configure script.\n\n

    \n

    An example of the possible output looks like:\n\n

    \n
    { target_defaults:\n   { cflags: [],\n     default_configuration: 'Release',\n     defines: [],\n     include_dirs: [],\n     libraries: [] },\n  variables:\n   { host_arch: 'x64',\n     node_install_npm: 'true',\n     node_prefix: '',\n     node_shared_cares: 'false',\n     node_shared_http_parser: 'false',\n     node_shared_libuv: 'false',\n     node_shared_v8: 'false',\n     node_shared_zlib: 'false',\n     node_use_dtrace: 'false',\n     node_use_openssl: 'true',\n     node_shared_openssl: 'false',\n     strict_aliasing: 'true',\n     target_arch: 'x64',\n     v8_use_snapshot: 'true' } }
    \n" }, { "textRaw": "process.pid", "name": "pid", "desc": "

    The PID of the process.\n\n

    \n
    console.log('This process is pid ' + process.pid);
    \n" }, { "textRaw": "process.title", "name": "title", "desc": "

    Getter/setter to set what is displayed in 'ps'.\n\n

    \n

    When used as a setter, the maximum length is platform-specific and probably\nshort.\n\n

    \n

    On Linux and OS X, it's limited to the size of the binary name plus the\nlength of the command line arguments because it overwrites the argv memory.\n\n

    \n

    v0.8 allowed for longer process title strings by also overwriting the environ\nmemory but that was potentially insecure/confusing in some (rather obscure)\ncases.\n\n\n

    \n" }, { "textRaw": "process.arch", "name": "arch", "desc": "

    What processor architecture you're running on: 'arm', 'ia32', or 'x64'.\n\n

    \n
    console.log('This processor architecture is ' + process.arch);
    \n" }, { "textRaw": "process.platform", "name": "platform", "desc": "

    What platform you're running on:\n'darwin', 'freebsd', 'linux', 'sunos' or 'win32'\n\n

    \n
    console.log('This platform is ' + process.platform);
    \n" }, { "textRaw": "`maxTickDepth` {Number} Default = 1000 ", "name": "maxTickDepth", "desc": "

    Callbacks passed to process.nextTick will usually be called at the\nend of the current flow of execution, and are thus approximately as fast\nas calling a function synchronously. Left unchecked, this would starve\nthe event loop, preventing any I/O from occurring.\n\n

    \n

    Consider this code:\n\n

    \n
    process.nextTick(function foo() {\n  process.nextTick(foo);\n});
    \n

    In order to avoid the situation where Node is blocked by an infinite\nloop of recursive series of nextTick calls, it defers to allow some I/O\nto be done every so often.\n\n

    \n

    The process.maxTickDepth value is the maximum depth of\nnextTick-calling nextTick-callbacks that will be evaluated before\nallowing other forms of I/O to occur.\n\n

    \n", "shortDesc": "Default = 1000" } ], "methods": [ { "textRaw": "process.abort()", "type": "method", "name": "abort", "desc": "

    This causes node to emit an abort. This will cause node to exit and\ngenerate a core file.\n\n

    \n", "signatures": [ { "params": [] } ] }, { "textRaw": "process.chdir(directory)", "type": "method", "name": "chdir", "desc": "

    Changes the current working directory of the process or throws an exception if that fails.\n\n

    \n
    console.log('Starting directory: ' + process.cwd());\ntry {\n  process.chdir('/tmp');\n  console.log('New directory: ' + process.cwd());\n}\ncatch (err) {\n  console.log('chdir: ' + err);\n}
    \n", "signatures": [ { "params": [ { "name": "directory" } ] } ] }, { "textRaw": "process.cwd()", "type": "method", "name": "cwd", "desc": "

    Returns the current working directory of the process.\n\n

    \n
    console.log('Current directory: ' + process.cwd());
    \n", "signatures": [ { "params": [] } ] }, { "textRaw": "process.exit([code])", "type": "method", "name": "exit", "desc": "

    Ends the process with the specified code. If omitted, exit uses the\n'success' code 0.\n\n

    \n

    To exit with a 'failure' code:\n\n

    \n
    process.exit(1);
    \n

    The shell that executed node should see the exit code as 1.\n\n\n

    \n", "signatures": [ { "params": [ { "name": "code", "optional": true } ] } ] }, { "textRaw": "process.getgid()", "type": "method", "name": "getgid", "desc": "

    Note: this function is only available on POSIX platforms (i.e. not Windows)\n\n

    \n

    Gets the group identity of the process. (See getgid(2).)\nThis is the numerical group id, not the group name.\n\n

    \n
    if (process.getgid) {\n  console.log('Current gid: ' + process.getgid());\n}
    \n", "signatures": [ { "params": [] } ] }, { "textRaw": "process.setgid(id)", "type": "method", "name": "setgid", "desc": "

    Note: this function is only available on POSIX platforms (i.e. not Windows)\n\n

    \n

    Sets the group identity of the process. (See setgid(2).) This accepts either\na numerical ID or a groupname string. If a groupname is specified, this method\nblocks while resolving it to a numerical ID.\n\n

    \n
    if (process.getgid && process.setgid) {\n  console.log('Current gid: ' + process.getgid());\n  try {\n    process.setgid(501);\n    console.log('New gid: ' + process.getgid());\n  }\n  catch (err) {\n    console.log('Failed to set gid: ' + err);\n  }\n}
    \n", "signatures": [ { "params": [ { "name": "id" } ] } ] }, { "textRaw": "process.getuid()", "type": "method", "name": "getuid", "desc": "

    Note: this function is only available on POSIX platforms (i.e. not Windows)\n\n

    \n

    Gets the user identity of the process. (See getuid(2).)\nThis is the numerical userid, not the username.\n\n

    \n
    if (process.getuid) {\n  console.log('Current uid: ' + process.getuid());\n}
    \n", "signatures": [ { "params": [] } ] }, { "textRaw": "process.setuid(id)", "type": "method", "name": "setuid", "desc": "

    Note: this function is only available on POSIX platforms (i.e. not Windows)\n\n

    \n

    Sets the user identity of the process. (See setuid(2).) This accepts either\na numerical ID or a username string. If a username is specified, this method\nblocks while resolving it to a numerical ID.\n\n

    \n
    if (process.getuid && process.setuid) {\n  console.log('Current uid: ' + process.getuid());\n  try {\n    process.setuid(501);\n    console.log('New uid: ' + process.getuid());\n  }\n  catch (err) {\n    console.log('Failed to set uid: ' + err);\n  }\n}
    \n", "signatures": [ { "params": [ { "name": "id" } ] } ] }, { "textRaw": "process.getgroups()", "type": "method", "name": "getgroups", "desc": "

    Note: this function is only available on POSIX platforms (i.e. not Windows)\n\n

    \n

    Returns an array with the supplementary group IDs. POSIX leaves it unspecified\nif the effective group ID is included but node.js ensures it always is.\n\n\n

    \n", "signatures": [ { "params": [] } ] }, { "textRaw": "process.setgroups(groups)", "type": "method", "name": "setgroups", "desc": "

    Note: this function is only available on POSIX platforms (i.e. not Windows)\n\n

    \n

    Sets the supplementary group IDs. This is a privileged operation, meaning you\nneed to be root or have the CAP_SETGID capability.\n\n

    \n

    The list can contain group IDs, group names or both.\n\n\n

    \n", "signatures": [ { "params": [ { "name": "groups" } ] } ] }, { "textRaw": "process.initgroups(user, extra_group)", "type": "method", "name": "initgroups", "desc": "

    Note: this function is only available on POSIX platforms (i.e. not Windows)\n\n

    \n

    Reads /etc/group and initializes the group access list, using all groups of\nwhich the user is a member. This is a privileged operation, meaning you need\nto be root or have the CAP_SETGID capability.\n\n

    \n

    user is a user name or user ID. extra_group is a group name or group ID.\n\n

    \n

    Some care needs to be taken when dropping privileges. Example:\n\n

    \n
    console.log(process.getgroups());         // [ 0 ]\nprocess.initgroups('bnoordhuis', 1000);   // switch user\nconsole.log(process.getgroups());         // [ 27, 30, 46, 1000, 0 ]\nprocess.setgid(1000);                     // drop root gid\nconsole.log(process.getgroups());         // [ 27, 30, 46, 1000 ]
    \n", "signatures": [ { "params": [ { "name": "user" }, { "name": "extra_group" } ] } ] }, { "textRaw": "process.kill(pid, [signal])", "type": "method", "name": "kill", "desc": "

    Send a signal to a process. pid is the process id and signal is the\nstring describing the signal to send. Signal names are strings like\n'SIGINT' or 'SIGHUP'. If omitted, the signal will be 'SIGTERM'.\nSee Signal Events and kill(2) for more information.\n\n

    \n

    Will throw an error if target does not exist, and as a special case, a signal of\n0 can be used to test for the existence of a process.\n\n

    \n

    Note that just because the name of this function is process.kill, it is\nreally just a signal sender, like the kill system call. The signal sent\nmay do something other than kill the target process.\n\n

    \n

    Example of sending a signal to yourself:\n\n

    \n
    process.on('SIGHUP', function() {\n  console.log('Got SIGHUP signal.');\n});\n\nsetTimeout(function() {\n  console.log('Exiting.');\n  process.exit(0);\n}, 100);\n\nprocess.kill(process.pid, 'SIGHUP');
    \n

    Note: When SIGUSR1 is received by Node.js it starts the debugger, see\nSignal Events.\n\n

    \n", "signatures": [ { "params": [ { "name": "pid" }, { "name": "signal", "optional": true } ] } ] }, { "textRaw": "process.memoryUsage()", "type": "method", "name": "memoryUsage", "desc": "

    Returns an object describing the memory usage of the Node process\nmeasured in bytes.\n\n

    \n
    var util = require('util');\n\nconsole.log(util.inspect(process.memoryUsage()));
    \n

    This will generate:\n\n

    \n
    { rss: 4935680,\n  heapTotal: 1826816,\n  heapUsed: 650472 }
    \n

    heapTotal and heapUsed refer to V8's memory usage.\n\n\n

    \n", "signatures": [ { "params": [] } ] }, { "textRaw": "process.nextTick(callback)", "type": "method", "name": "nextTick", "desc": "

    On the next loop around the event loop call this callback.\nThis is not a simple alias to setTimeout(fn, 0), it's much more\nefficient. It typically runs before any other I/O events fire, but there\nare some exceptions. See process.maxTickDepth below.\n\n

    \n
    process.nextTick(function() {\n  console.log('nextTick callback');\n});
    \n

    This is important in developing APIs where you want to give the user the\nchance to assign event handlers after an object has been constructed,\nbut before any I/O has occurred.\n\n

    \n
    function MyThing(options) {\n  this.setupOptions(options);\n\n  process.nextTick(function() {\n    this.startDoingStuff();\n  }.bind(this));\n}\n\nvar thing = new MyThing();\nthing.getReadyForStuff();\n\n// thing.startDoingStuff() gets called now, not before.
    \n

    It is very important for APIs to be either 100% synchronous or 100%\nasynchronous. Consider this example:\n\n

    \n
    // WARNING!  DO NOT USE!  BAD UNSAFE HAZARD!\nfunction maybeSync(arg, cb) {\n  if (arg) {\n    cb();\n    return;\n  }\n\n  fs.stat('file', cb);\n}
    \n

    This API is hazardous. If you do this:\n\n

    \n
    maybeSync(true, function() {\n  foo();\n});\nbar();
    \n

    then it's not clear whether foo() or bar() will be called first.\n\n

    \n

    This approach is much better:\n\n

    \n
    function definitelyAsync(arg, cb) {\n  if (arg) {\n    process.nextTick(cb);\n    return;\n  }\n\n  fs.stat('file', cb);\n}
    \n", "signatures": [ { "params": [ { "name": "callback" } ] } ] }, { "textRaw": "process.umask([mask])", "type": "method", "name": "umask", "desc": "

    Sets or reads the process's file mode creation mask. Child processes inherit\nthe mask from the parent process. Returns the old mask if mask argument is\ngiven, otherwise returns the current mask.\n\n

    \n
    var oldmask, newmask = 0644;\n\noldmask = process.umask(newmask);\nconsole.log('Changed umask from: ' + oldmask.toString(8) +\n            ' to ' + newmask.toString(8));
    \n", "signatures": [ { "params": [ { "name": "mask", "optional": true } ] } ] }, { "textRaw": "process.uptime()", "type": "method", "name": "uptime", "desc": "

    Number of seconds Node has been running.\n\n\n

    \n", "signatures": [ { "params": [] } ] }, { "textRaw": "process.hrtime()", "type": "method", "name": "hrtime", "desc": "

    Returns the current high-resolution real time in a [seconds, nanoseconds]\ntuple Array. It is relative to an arbitrary time in the past. It is not\nrelated to the time of day and therefore not subject to clock drift. The\nprimary use is for measuring performance between intervals.\n\n

    \n

    You may pass in the result of a previous call to process.hrtime() to get\na diff reading, useful for benchmarks and measuring intervals:\n\n

    \n
    var time = process.hrtime();\n// [ 1800216, 25 ]\n\nsetTimeout(function() {\n  var diff = process.hrtime(time);\n  // [ 1, 552 ]\n\n  console.log('benchmark took %d nanoseconds', diff[0] * 1e9 + diff[1]);\n  // benchmark took 1000000527 nanoseconds\n}, 1000);
    \n", "signatures": [ { "params": [] } ] } ] } ] } node-v0.10.25~dfsg2/doc/api/globals.json0000644000000000000000000003644412270264601016463 0ustar rootroot{ "source": "doc/api/globals.markdown", "globals": [ { "textRaw": "global", "name": "global", "type": "global", "desc": "

    In browsers, the top-level scope is the global scope. That means that in\nbrowsers if you're in the global scope var something will define a global\nvariable. In Node this is different. The top-level scope is not the global\nscope; var something inside a Node module will be local to that module.\n\n

    \n" }, { "textRaw": "process", "name": "process", "type": "global", "desc": "

    The process object. See the [process object][] section.\n\n

    \n" }, { "textRaw": "console", "name": "console", "type": "global", "desc": "

    Used to print to stdout and stderr. See the [console][] section.\n\n

    \n" }, { "textRaw": "Class: Buffer", "type": "global", "name": "Buffer", "desc": "

    Used to handle binary data. See the [buffer section][]\n\n

    \n" }, { "textRaw": "clearInterval(t)", "type": "global", "name": "clearInterval", "desc": "

    Stop a timer that was previously created with setInterval(). The callback\nwill not execute.\n\n

    \n

    The timer functions are global variables. See the [timers][] section.\n\n

    \n" } ], "vars": [ { "textRaw": "require()", "type": "var", "name": "require", "desc": "

    To require modules. See the [Modules][] section. require isn't actually a\nglobal but rather local to each module.\n\n

    \n", "methods": [ { "textRaw": "require.resolve()", "type": "method", "name": "resolve", "desc": "

    Use the internal require() machinery to look up the location of a module,\nbut rather than loading the module, just return the resolved filename.\n\n

    \n", "signatures": [ { "params": [] } ] } ], "properties": [ { "textRaw": "`cache` {Object} ", "name": "cache", "desc": "

    Modules are cached in this object when they are required. By deleting a key\nvalue from this object, the next require will reload the module.\n\n

    \n" }, { "textRaw": "`extensions` {Object} ", "name": "extensions", "stability": 0, "stabilityText": "Deprecated", "desc": "

    Instruct require on how to handle certain file extensions.\n\n

    \n

    Process files with the extension .sjs as .js:\n\n

    \n
    require.extensions['.sjs'] = require.extensions['.js'];
    \n

    Deprecated In the past, this list has been used to load\nnon-JavaScript modules into Node by compiling them on-demand.\nHowever, in practice, there are much better ways to do this, such as\nloading modules via some other Node program, or compiling them to\nJavaScript ahead of time.\n\n

    \n

    Since the Module system is locked, this feature will probably never go\naway. However, it may have subtle bugs and complexities that are best\nleft untouched.\n\n

    \n" } ] }, { "textRaw": "__filename", "name": "__filename", "type": "var", "desc": "

    The filename of the code being executed. This is the resolved absolute path\nof this code file. For a main program this is not necessarily the same\nfilename used in the command line. The value inside a module is the path\nto that module file.\n\n

    \n

    Example: running node example.js from /Users/mjr\n\n

    \n
    console.log(__filename);\n// /Users/mjr/example.js
    \n

    __filename isn't actually a global but rather local to each module.\n\n

    \n" }, { "textRaw": "__dirname", "name": "__dirname", "type": "var", "desc": "

    The name of the directory that the currently executing script resides in.\n\n

    \n

    Example: running node example.js from /Users/mjr\n\n

    \n
    console.log(__dirname);\n// /Users/mjr
    \n

    __dirname isn't actually a global but rather local to each module.\n\n\n

    \n" }, { "textRaw": "module", "name": "module", "type": "var", "desc": "

    A reference to the current module. In particular\nmodule.exports is used for defining what a module exports and makes\navailable through require().\n\n

    \n

    module isn't actually a global but rather local to each module.\n\n

    \n

    See the [module system documentation][] for more information.\n\n

    \n" }, { "textRaw": "exports", "name": "exports", "type": "var", "desc": "

    A reference to the module.exports that is shorter to type.\nSee [module system documentation][] for details on when to use exports and\nwhen to use module.exports.\n\n

    \n

    exports isn't actually a global but rather local to each module.\n\n

    \n

    See the [module system documentation][] for more information.\n\n

    \n

    See the [module section][] for more information.\n\n

    \n" } ], "methods": [ { "textRaw": "setTimeout(cb, ms)", "type": "method", "name": "setTimeout", "desc": "

    Run callback cb after at least ms milliseconds. The actual delay depends\non external factors like OS timer granularity and system load.\n\n

    \n

    The timeout must be in the range of 1-2,147,483,647 inclusive. If the value is\noutside that range, it's changed to 1 millisecond. Broadly speaking, a timer\ncannot span more than 24.8 days.\n\n

    \n

    Returns an opaque value that represents the timer.\n\n

    \n", "signatures": [ { "params": [ { "name": "cb" }, { "name": "ms" } ] } ] }, { "textRaw": "clearTimeout(t)", "type": "method", "name": "clearTimeout", "desc": "

    Stop a timer that was previously created with setTimeout(). The callback will\nnot execute.\n\n

    \n", "signatures": [ { "params": [ { "name": "t" } ] } ] }, { "textRaw": "setInterval(cb, ms)", "type": "method", "name": "setInterval", "desc": "

    Run callback cb repeatedly every ms milliseconds. Note that the actual\ninterval may vary, depending on external factors like OS timer granularity and\nsystem load. It's never less than ms but it may be longer.\n\n

    \n

    The interval must be in the range of 1-2,147,483,647 inclusive. If the value is\noutside that range, it's changed to 1 millisecond. Broadly speaking, a timer\ncannot span more than 24.8 days.\n\n

    \n

    Returns an opaque value that represents the timer.\n\n

    \n", "signatures": [ { "params": [ { "name": "cb" }, { "name": "ms" } ] } ] } ], "miscs": [ { "textRaw": "Global Objects", "name": "Global Objects", "type": "misc", "desc": "

    These objects are available in all modules. Some of these objects aren't\nactually in the global scope but in the module scope - this will be noted.\n\n

    \n", "globals": [ { "textRaw": "global", "name": "global", "type": "global", "desc": "

    In browsers, the top-level scope is the global scope. That means that in\nbrowsers if you're in the global scope var something will define a global\nvariable. In Node this is different. The top-level scope is not the global\nscope; var something inside a Node module will be local to that module.\n\n

    \n" }, { "textRaw": "process", "name": "process", "type": "global", "desc": "

    The process object. See the [process object][] section.\n\n

    \n" }, { "textRaw": "console", "name": "console", "type": "global", "desc": "

    Used to print to stdout and stderr. See the [console][] section.\n\n

    \n" }, { "textRaw": "Class: Buffer", "type": "global", "name": "Buffer", "desc": "

    Used to handle binary data. See the [buffer section][]\n\n

    \n" }, { "textRaw": "clearInterval(t)", "type": "global", "name": "clearInterval", "desc": "

    Stop a timer that was previously created with setInterval(). The callback\nwill not execute.\n\n

    \n

    The timer functions are global variables. See the [timers][] section.\n\n

    \n" } ], "vars": [ { "textRaw": "require()", "type": "var", "name": "require", "desc": "

    To require modules. See the [Modules][] section. require isn't actually a\nglobal but rather local to each module.\n\n

    \n", "methods": [ { "textRaw": "require.resolve()", "type": "method", "name": "resolve", "desc": "

    Use the internal require() machinery to look up the location of a module,\nbut rather than loading the module, just return the resolved filename.\n\n

    \n", "signatures": [ { "params": [] } ] } ], "properties": [ { "textRaw": "`cache` {Object} ", "name": "cache", "desc": "

    Modules are cached in this object when they are required. By deleting a key\nvalue from this object, the next require will reload the module.\n\n

    \n" }, { "textRaw": "`extensions` {Object} ", "name": "extensions", "stability": 0, "stabilityText": "Deprecated", "desc": "

    Instruct require on how to handle certain file extensions.\n\n

    \n

    Process files with the extension .sjs as .js:\n\n

    \n
    require.extensions['.sjs'] = require.extensions['.js'];
    \n

    Deprecated In the past, this list has been used to load\nnon-JavaScript modules into Node by compiling them on-demand.\nHowever, in practice, there are much better ways to do this, such as\nloading modules via some other Node program, or compiling them to\nJavaScript ahead of time.\n\n

    \n

    Since the Module system is locked, this feature will probably never go\naway. However, it may have subtle bugs and complexities that are best\nleft untouched.\n\n

    \n" } ] }, { "textRaw": "__filename", "name": "__filename", "type": "var", "desc": "

    The filename of the code being executed. This is the resolved absolute path\nof this code file. For a main program this is not necessarily the same\nfilename used in the command line. The value inside a module is the path\nto that module file.\n\n

    \n

    Example: running node example.js from /Users/mjr\n\n

    \n
    console.log(__filename);\n// /Users/mjr/example.js
    \n

    __filename isn't actually a global but rather local to each module.\n\n

    \n" }, { "textRaw": "__dirname", "name": "__dirname", "type": "var", "desc": "

    The name of the directory that the currently executing script resides in.\n\n

    \n

    Example: running node example.js from /Users/mjr\n\n

    \n
    console.log(__dirname);\n// /Users/mjr
    \n

    __dirname isn't actually a global but rather local to each module.\n\n\n

    \n" }, { "textRaw": "module", "name": "module", "type": "var", "desc": "

    A reference to the current module. In particular\nmodule.exports is used for defining what a module exports and makes\navailable through require().\n\n

    \n

    module isn't actually a global but rather local to each module.\n\n

    \n

    See the [module system documentation][] for more information.\n\n

    \n" }, { "textRaw": "exports", "name": "exports", "type": "var", "desc": "

    A reference to the module.exports that is shorter to type.\nSee [module system documentation][] for details on when to use exports and\nwhen to use module.exports.\n\n

    \n

    exports isn't actually a global but rather local to each module.\n\n

    \n

    See the [module system documentation][] for more information.\n\n

    \n

    See the [module section][] for more information.\n\n

    \n" } ], "methods": [ { "textRaw": "setTimeout(cb, ms)", "type": "method", "name": "setTimeout", "desc": "

    Run callback cb after at least ms milliseconds. The actual delay depends\non external factors like OS timer granularity and system load.\n\n

    \n

    The timeout must be in the range of 1-2,147,483,647 inclusive. If the value is\noutside that range, it's changed to 1 millisecond. Broadly speaking, a timer\ncannot span more than 24.8 days.\n\n

    \n

    Returns an opaque value that represents the timer.\n\n

    \n", "signatures": [ { "params": [ { "name": "cb" }, { "name": "ms" } ] } ] }, { "textRaw": "clearTimeout(t)", "type": "method", "name": "clearTimeout", "desc": "

    Stop a timer that was previously created with setTimeout(). The callback will\nnot execute.\n\n

    \n", "signatures": [ { "params": [ { "name": "t" } ] } ] }, { "textRaw": "setInterval(cb, ms)", "type": "method", "name": "setInterval", "desc": "

    Run callback cb repeatedly every ms milliseconds. Note that the actual\ninterval may vary, depending on external factors like OS timer granularity and\nsystem load. It's never less than ms but it may be longer.\n\n

    \n

    The interval must be in the range of 1-2,147,483,647 inclusive. If the value is\noutside that range, it's changed to 1 millisecond. Broadly speaking, a timer\ncannot span more than 24.8 days.\n\n

    \n

    Returns an opaque value that represents the timer.\n\n

    \n", "signatures": [ { "params": [ { "name": "cb" }, { "name": "ms" } ] } ] } ] } ] } node-v0.10.25~dfsg2/doc/api/http.markdown0000644000000000000000000007315212270121457016666 0ustar rootroot# HTTP Stability: 3 - Stable To use the HTTP server and client one must `require('http')`. The HTTP interfaces in Node are designed to support many features of the protocol which have been traditionally difficult to use. In particular, large, possibly chunk-encoded, messages. The interface is careful to never buffer entire requests or responses--the user is able to stream data. HTTP message headers are represented by an object like this: { 'content-length': '123', 'content-type': 'text/plain', 'connection': 'keep-alive', 'accept': '*/*' } Keys are lowercased. Values are not modified. In order to support the full spectrum of possible HTTP applications, Node's HTTP API is very low-level. It deals with stream handling and message parsing only. It parses a message into headers and body but it does not parse the actual headers or the body. ## http.STATUS_CODES * {Object} A collection of all the standard HTTP response status codes, and the short description of each. For example, `http.STATUS_CODES[404] === 'Not Found'`. ## http.createServer([requestListener]) Returns a new web server object. The `requestListener` is a function which is automatically added to the `'request'` event. ## http.createClient([port], [host]) This function is **deprecated**; please use [http.request()][] instead. Constructs a new HTTP client. `port` and `host` refer to the server to be connected to. ## Class: http.Server This is an [EventEmitter][] with the following events: ### Event: 'request' `function (request, response) { }` Emitted each time there is a request. Note that there may be multiple requests per connection (in the case of keep-alive connections). `request` is an instance of [http.IncomingMessage][] and `response` is an instance of [http.ServerResponse][]. ### Event: 'connection' `function (socket) { }` When a new TCP stream is established. `socket` is an object of type `net.Socket`. Usually users will not want to access this event. In particular, the socket will not emit `readable` events because of how the protocol parser attaches to the socket. The `socket` can also be accessed at `request.connection`. ### Event: 'close' `function () { }` Emitted when the server closes. ### Event: 'checkContinue' `function (request, response) { }` Emitted each time a request with an http Expect: 100-continue is received. If this event isn't listened for, the server will automatically respond with a 100 Continue as appropriate. Handling this event involves calling [response.writeContinue()][] if the client should continue to send the request body, or generating an appropriate HTTP response (e.g., 400 Bad Request) if the client should not continue to send the request body. Note that when this event is emitted and handled, the `request` event will not be emitted. ### Event: 'connect' `function (request, socket, head) { }` Emitted each time a client requests a http CONNECT method. If this event isn't listened for, then clients requesting a CONNECT method will have their connections closed. * `request` is the arguments for the http request, as it is in the request event. * `socket` is the network socket between the server and client. * `head` is an instance of Buffer, the first packet of the tunneling stream, this may be empty. After this event is emitted, the request's socket will not have a `data` event listener, meaning you will need to bind to it in order to handle data sent to the server on that socket. ### Event: 'upgrade' `function (request, socket, head) { }` Emitted each time a client requests a http upgrade. If this event isn't listened for, then clients requesting an upgrade will have their connections closed. * `request` is the arguments for the http request, as it is in the request event. * `socket` is the network socket between the server and client. * `head` is an instance of Buffer, the first packet of the upgraded stream, this may be empty. After this event is emitted, the request's socket will not have a `data` event listener, meaning you will need to bind to it in order to handle data sent to the server on that socket. ### Event: 'clientError' `function (exception, socket) { }` If a client connection emits an 'error' event - it will forwarded here. `socket` is the `net.Socket` object that the error originated from. ### server.listen(port, [hostname], [backlog], [callback]) Begin accepting connections on the specified port and hostname. If the hostname is omitted, the server will accept connections directed to any IPv4 address (`INADDR_ANY`). To listen to a unix socket, supply a filename instead of port and hostname. Backlog is the maximum length of the queue of pending connections. The actual length will be determined by your OS through sysctl settings such as `tcp_max_syn_backlog` and `somaxconn` on linux. The default value of this parameter is 511 (not 512). This function is asynchronous. The last parameter `callback` will be added as a listener for the ['listening'][] event. See also [net.Server.listen(port)][]. ### server.listen(path, [callback]) Start a UNIX socket server listening for connections on the given `path`. This function is asynchronous. The last parameter `callback` will be added as a listener for the ['listening'][] event. See also [net.Server.listen(path)][]. ### server.listen(handle, [callback]) * `handle` {Object} * `callback` {Function} The `handle` object can be set to either a server or socket (anything with an underlying `_handle` member), or a `{fd: }` object. This will cause the server to accept connections on the specified handle, but it is presumed that the file descriptor or handle has already been bound to a port or domain socket. Listening on a file descriptor is not supported on Windows. This function is asynchronous. The last parameter `callback` will be added as a listener for the ['listening'](net.html#event_listening_) event. See also [net.Server.listen()](net.html#net_server_listen_handle_callback). ### server.close([callback]) Stops the server from accepting new connections. See [net.Server.close()][]. ### server.maxHeadersCount Limits maximum incoming headers count, equal to 1000 by default. If set to 0 - no limit will be applied. ### server.setTimeout(msecs, callback) * `msecs` {Number} * `callback` {Function} Sets the timeout value for sockets, and emits a `'timeout'` event on the Server object, passing the socket as an argument, if a timeout occurs. If there is a `'timeout'` event listener on the Server object, then it will be called with the timed-out socket as an argument. By default, the Server's timeout value is 2 minutes, and sockets are destroyed automatically if they time out. However, if you assign a callback to the Server's `'timeout'` event, then you are responsible for handling socket timeouts. ### server.timeout * {Number} Default = 120000 (2 minutes) The number of milliseconds of inactivity before a socket is presumed to have timed out. Note that the socket timeout logic is set up on connection, so changing this value only affects *new* connections to the server, not any existing connections. Set to 0 to disable any kind of automatic timeout behavior on incoming connections. ## Class: http.ServerResponse This object is created internally by a HTTP server--not by the user. It is passed as the second parameter to the `'request'` event. The response implements the [Writable Stream][] interface. This is an [EventEmitter][] with the following events: ### Event: 'close' `function () { }` Indicates that the underlying connection was terminated before [response.end()][] was called or able to flush. ### Event: 'finish' `function () { }` Emitted when the response has been sent. More specifically, this event is emitted when the last segment of the response headers and body have been handed off to the operating system for transmission over the network. It does not imply that the client has received anything yet. After this event, no more events will be emitted on the response object. ### response.writeContinue() Sends a HTTP/1.1 100 Continue message to the client, indicating that the request body should be sent. See the ['checkContinue'][] event on `Server`. ### response.writeHead(statusCode, [reasonPhrase], [headers]) Sends a response header to the request. The status code is a 3-digit HTTP status code, like `404`. The last argument, `headers`, are the response headers. Optionally one can give a human-readable `reasonPhrase` as the second argument. Example: var body = 'hello world'; response.writeHead(200, { 'Content-Length': body.length, 'Content-Type': 'text/plain' }); This method must only be called once on a message and it must be called before [response.end()][] is called. If you call [response.write()][] or [response.end()][] before calling this, the implicit/mutable headers will be calculated and call this function for you. Note: that Content-Length is given in bytes not characters. The above example works because the string `'hello world'` contains only single byte characters. If the body contains higher coded characters then `Buffer.byteLength()` should be used to determine the number of bytes in a given encoding. And Node does not check whether Content-Length and the length of the body which has been transmitted are equal or not. ### response.setTimeout(msecs, callback) * `msecs` {Number} * `callback` {Function} Sets the Socket's timeout value to `msecs`. If a callback is provided, then it is added as a listener on the `'timeout'` event on the response object. If no `'timeout'` listener is added to the request, the response, or the server, then sockets are destroyed when they time out. If you assign a handler on the request, the response, or the server's `'timeout'` events, then it is your responsibility to handle timed out sockets. ### response.statusCode When using implicit headers (not calling [response.writeHead()][] explicitly), this property controls the status code that will be sent to the client when the headers get flushed. Example: response.statusCode = 404; After response header was sent to the client, this property indicates the status code which was sent out. ### response.setHeader(name, value) Sets a single header value for implicit headers. If this header already exists in the to-be-sent headers, its value will be replaced. Use an array of strings here if you need to send multiple headers with the same name. Example: response.setHeader("Content-Type", "text/html"); or response.setHeader("Set-Cookie", ["type=ninja", "language=javascript"]); ### response.headersSent Boolean (read-only). True if headers were sent, false otherwise. ### response.sendDate When true, the Date header will be automatically generated and sent in the response if it is not already present in the headers. Defaults to true. This should only be disabled for testing; HTTP requires the Date header in responses. ### response.getHeader(name) Reads out a header that's already been queued but not sent to the client. Note that the name is case insensitive. This can only be called before headers get implicitly flushed. Example: var contentType = response.getHeader('content-type'); ### response.removeHeader(name) Removes a header that's queued for implicit sending. Example: response.removeHeader("Content-Encoding"); ### response.write(chunk, [encoding]) If this method is called and [response.writeHead()][] has not been called, it will switch to implicit header mode and flush the implicit headers. This sends a chunk of the response body. This method may be called multiple times to provide successive parts of the body. `chunk` can be a string or a buffer. If `chunk` is a string, the second parameter specifies how to encode it into a byte stream. By default the `encoding` is `'utf8'`. **Note**: This is the raw HTTP body and has nothing to do with higher-level multi-part body encodings that may be used. The first time `response.write()` is called, it will send the buffered header information and the first body to the client. The second time `response.write()` is called, Node assumes you're going to be streaming data, and sends that separately. That is, the response is buffered up to the first chunk of body. Returns `true` if the entire data was flushed successfully to the kernel buffer. Returns `false` if all or part of the data was queued in user memory. `'drain'` will be emitted when the buffer is again free. ### response.addTrailers(headers) This method adds HTTP trailing headers (a header but at the end of the message) to the response. Trailers will **only** be emitted if chunked encoding is used for the response; if it is not (e.g., if the request was HTTP/1.0), they will be silently discarded. Note that HTTP requires the `Trailer` header to be sent if you intend to emit trailers, with a list of the header fields in its value. E.g., response.writeHead(200, { 'Content-Type': 'text/plain', 'Trailer': 'Content-MD5' }); response.write(fileData); response.addTrailers({'Content-MD5': "7895bf4b8828b55ceaf47747b4bca667"}); response.end(); ### response.end([data], [encoding]) This method signals to the server that all of the response headers and body have been sent; that server should consider this message complete. The method, `response.end()`, MUST be called on each response. If `data` is specified, it is equivalent to calling `response.write(data, encoding)` followed by `response.end()`. ## http.request(options, [callback]) Node maintains several connections per server to make HTTP requests. This function allows one to transparently issue requests. `options` can be an object or a string. If `options` is a string, it is automatically parsed with [url.parse()][]. Options: - `host`: A domain name or IP address of the server to issue the request to. Defaults to `'localhost'`. - `hostname`: To support `url.parse()` `hostname` is preferred over `host` - `port`: Port of remote server. Defaults to 80. - `localAddress`: Local interface to bind for network connections. - `socketPath`: Unix Domain Socket (use one of host:port or socketPath) - `method`: A string specifying the HTTP request method. Defaults to `'GET'`. - `path`: Request path. Defaults to `'/'`. Should include query string if any. E.G. `'/index.html?page=12'` - `headers`: An object containing request headers. - `auth`: Basic authentication i.e. `'user:password'` to compute an Authorization header. - `agent`: Controls [Agent][] behavior. When an Agent is used request will default to `Connection: keep-alive`. Possible values: - `undefined` (default): use [global Agent][] for this host and port. - `Agent` object: explicitly use the passed in `Agent`. - `false`: opts out of connection pooling with an Agent, defaults request to `Connection: close`. The optional `callback` parameter will be added as a one time listener for the ['response'][] event. `http.request()` returns an instance of the [http.ClientRequest][] class. The `ClientRequest` instance is a writable stream. If one needs to upload a file with a POST request, then write to the `ClientRequest` object. Example: var options = { hostname: 'www.google.com', port: 80, path: '/upload', method: 'POST' }; var req = http.request(options, function(res) { console.log('STATUS: ' + res.statusCode); console.log('HEADERS: ' + JSON.stringify(res.headers)); res.setEncoding('utf8'); res.on('data', function (chunk) { console.log('BODY: ' + chunk); }); }); req.on('error', function(e) { console.log('problem with request: ' + e.message); }); // write data to request body req.write('data\n'); req.write('data\n'); req.end(); Note that in the example `req.end()` was called. With `http.request()` one must always call `req.end()` to signify that you're done with the request - even if there is no data being written to the request body. If any error is encountered during the request (be that with DNS resolution, TCP level errors, or actual HTTP parse errors) an `'error'` event is emitted on the returned request object. There are a few special headers that should be noted. * Sending a 'Connection: keep-alive' will notify Node that the connection to the server should be persisted until the next request. * Sending a 'Content-length' header will disable the default chunked encoding. * Sending an 'Expect' header will immediately send the request headers. Usually, when sending 'Expect: 100-continue', you should both set a timeout and listen for the `continue` event. See RFC2616 Section 8.2.3 for more information. * Sending an Authorization header will override using the `auth` option to compute basic authentication. ## http.get(options, [callback]) Since most requests are GET requests without bodies, Node provides this convenience method. The only difference between this method and `http.request()` is that it sets the method to GET and calls `req.end()` automatically. Example: http.get("http://www.google.com/index.html", function(res) { console.log("Got response: " + res.statusCode); }).on('error', function(e) { console.log("Got error: " + e.message); }); ## Class: http.Agent In node 0.5.3+ there is a new implementation of the HTTP Agent which is used for pooling sockets used in HTTP client requests. Previously, a single agent instance helped pool for a single host+port. The current implementation now holds sockets for any number of hosts. The current HTTP Agent also defaults client requests to using Connection:keep-alive. If no pending HTTP requests are waiting on a socket to become free the socket is closed. This means that node's pool has the benefit of keep-alive when under load but still does not require developers to manually close the HTTP clients using keep-alive. Sockets are removed from the agent's pool when the socket emits either a "close" event or a special "agentRemove" event. This means that if you intend to keep one HTTP request open for a long time and don't want it to stay in the pool you can do something along the lines of: http.get(options, function(res) { // Do stuff }).on("socket", function (socket) { socket.emit("agentRemove"); }); Alternatively, you could just opt out of pooling entirely using `agent:false`: http.get({hostname:'localhost', port:80, path:'/', agent:false}, function (res) { // Do stuff }) ### agent.maxSockets By default set to 5. Determines how many concurrent sockets the agent can have open per host. ### agent.sockets An object which contains arrays of sockets currently in use by the Agent. Do not modify. ### agent.requests An object which contains queues of requests that have not yet been assigned to sockets. Do not modify. ## http.globalAgent Global instance of Agent which is used as the default for all http client requests. ## Class: http.ClientRequest This object is created internally and returned from `http.request()`. It represents an _in-progress_ request whose header has already been queued. The header is still mutable using the `setHeader(name, value)`, `getHeader(name)`, `removeHeader(name)` API. The actual header will be sent along with the first data chunk or when closing the connection. To get the response, add a listener for `'response'` to the request object. `'response'` will be emitted from the request object when the response headers have been received. The `'response'` event is executed with one argument which is an instance of [http.IncomingMessage][]. During the `'response'` event, one can add listeners to the response object; particularly to listen for the `'data'` event. If no `'response'` handler is added, then the response will be entirely discarded. However, if you add a `'response'` event handler, then you **must** consume the data from the response object, either by calling `response.read()` whenever there is a `'readable'` event, or by adding a `'data'` handler, or by calling the `.resume()` method. Until the data is consumed, the `'end'` event will not fire. Also, until the data is read it will consume memory that can eventually lead to a 'process out of memory' error. Note: Node does not check whether Content-Length and the length of the body which has been transmitted are equal or not. The request implements the [Writable Stream][] interface. This is an [EventEmitter][] with the following events: ### Event 'response' `function (response) { }` Emitted when a response is received to this request. This event is emitted only once. The `response` argument will be an instance of [http.IncomingMessage][]. Options: - `host`: A domain name or IP address of the server to issue the request to. - `port`: Port of remote server. - `socketPath`: Unix Domain Socket (use one of host:port or socketPath) ### Event: 'socket' `function (socket) { }` Emitted after a socket is assigned to this request. ### Event: 'connect' `function (response, socket, head) { }` Emitted each time a server responds to a request with a CONNECT method. If this event isn't being listened for, clients receiving a CONNECT method will have their connections closed. A client server pair that show you how to listen for the `connect` event. var http = require('http'); var net = require('net'); var url = require('url'); // Create an HTTP tunneling proxy var proxy = http.createServer(function (req, res) { res.writeHead(200, {'Content-Type': 'text/plain'}); res.end('okay'); }); proxy.on('connect', function(req, cltSocket, head) { // connect to an origin server var srvUrl = url.parse('http://' + req.url); var srvSocket = net.connect(srvUrl.port, srvUrl.hostname, function() { cltSocket.write('HTTP/1.1 200 Connection Established\r\n' + 'Proxy-agent: Node-Proxy\r\n' + '\r\n'); srvSocket.write(head); srvSocket.pipe(cltSocket); cltSocket.pipe(srvSocket); }); }); // now that proxy is running proxy.listen(1337, '127.0.0.1', function() { // make a request to a tunneling proxy var options = { port: 1337, hostname: '127.0.0.1', method: 'CONNECT', path: 'www.google.com:80' }; var req = http.request(options); req.end(); req.on('connect', function(res, socket, head) { console.log('got connected!'); // make a request over an HTTP tunnel socket.write('GET / HTTP/1.1\r\n' + 'Host: www.google.com:80\r\n' + 'Connection: close\r\n' + '\r\n'); socket.on('data', function(chunk) { console.log(chunk.toString()); }); socket.on('end', function() { proxy.close(); }); }); }); ### Event: 'upgrade' `function (response, socket, head) { }` Emitted each time a server responds to a request with an upgrade. If this event isn't being listened for, clients receiving an upgrade header will have their connections closed. A client server pair that show you how to listen for the `upgrade` event. var http = require('http'); // Create an HTTP server var srv = http.createServer(function (req, res) { res.writeHead(200, {'Content-Type': 'text/plain'}); res.end('okay'); }); srv.on('upgrade', function(req, socket, head) { socket.write('HTTP/1.1 101 Web Socket Protocol Handshake\r\n' + 'Upgrade: WebSocket\r\n' + 'Connection: Upgrade\r\n' + '\r\n'); socket.pipe(socket); // echo back }); // now that server is running srv.listen(1337, '127.0.0.1', function() { // make a request var options = { port: 1337, hostname: '127.0.0.1', headers: { 'Connection': 'Upgrade', 'Upgrade': 'websocket' } }; var req = http.request(options); req.end(); req.on('upgrade', function(res, socket, upgradeHead) { console.log('got upgraded!'); socket.end(); process.exit(0); }); }); ### Event: 'continue' `function () { }` Emitted when the server sends a '100 Continue' HTTP response, usually because the request contained 'Expect: 100-continue'. This is an instruction that the client should send the request body. ### request.write(chunk, [encoding]) Sends a chunk of the body. By calling this method many times, the user can stream a request body to a server--in that case it is suggested to use the `['Transfer-Encoding', 'chunked']` header line when creating the request. The `chunk` argument should be a [Buffer][] or a string. The `encoding` argument is optional and only applies when `chunk` is a string. Defaults to `'utf8'`. ### request.end([data], [encoding]) Finishes sending the request. If any parts of the body are unsent, it will flush them to the stream. If the request is chunked, this will send the terminating `'0\r\n\r\n'`. If `data` is specified, it is equivalent to calling `request.write(data, encoding)` followed by `request.end()`. ### request.abort() Aborts a request. (New since v0.3.8.) ### request.setTimeout(timeout, [callback]) Once a socket is assigned to this request and is connected [socket.setTimeout()][] will be called. ### request.setNoDelay([noDelay]) Once a socket is assigned to this request and is connected [socket.setNoDelay()][] will be called. ### request.setSocketKeepAlive([enable], [initialDelay]) Once a socket is assigned to this request and is connected [socket.setKeepAlive()][] will be called. ## http.IncomingMessage An `IncomingMessage` object is created by [http.Server][] or [http.ClientRequest][] and passed as the first argument to the `'request'` and `'response'` event respectively. It may be used to access response status, headers and data. It implements the [Readable Stream][] interface, as well as the following additional events, methods, and properties. ### Event: 'close' `function () { }` Indicates that the underlaying connection was closed. Just like `'end'`, this event occurs only once per response. ### message.httpVersion In case of server request, the HTTP version sent by the client. In the case of client response, the HTTP version of the connected-to server. Probably either `'1.1'` or `'1.0'`. Also `response.httpVersionMajor` is the first integer and `response.httpVersionMinor` is the second. ### message.headers The request/response headers object. Read only map of header names and values. Header names are lower-cased. Example: // Prints something like: // // { 'user-agent': 'curl/7.22.0', // host: '127.0.0.1:8000', // accept: '*/*' } console.log(request.headers); ### message.trailers The request/response trailers object. Only populated after the 'end' event. ### message.setTimeout(msecs, callback) * `msecs` {Number} * `callback` {Function} Calls `message.connection.setTimeout(msecs, callback)`. ### message.method **Only valid for request obtained from [http.Server][].** The request method as a string. Read only. Example: `'GET'`, `'DELETE'`. ### message.url **Only valid for request obtained from [http.Server][].** Request URL string. This contains only the URL that is present in the actual HTTP request. If the request is: GET /status?name=ryan HTTP/1.1\r\n Accept: text/plain\r\n \r\n Then `request.url` will be: '/status?name=ryan' If you would like to parse the URL into its parts, you can use `require('url').parse(request.url)`. Example: node> require('url').parse('/status?name=ryan') { href: '/status?name=ryan', search: '?name=ryan', query: 'name=ryan', pathname: '/status' } If you would like to extract the params from the query string, you can use the `require('querystring').parse` function, or pass `true` as the second argument to `require('url').parse`. Example: node> require('url').parse('/status?name=ryan', true) { href: '/status?name=ryan', search: '?name=ryan', query: { name: 'ryan' }, pathname: '/status' } ### message.statusCode **Only valid for response obtained from `http.ClientRequest`.** The 3-digit HTTP response status code. E.G. `404`. ### message.socket The `net.Socket` object associated with the connection. With HTTPS support, use request.connection.verifyPeer() and request.connection.getPeerCertificate() to obtain the client's authentication details. ['checkContinue']: #http_event_checkcontinue ['listening']: net.html#net_event_listening ['response']: #http_event_response [Agent]: #http_class_http_agent [Buffer]: buffer.html#buffer_buffer [EventEmitter]: events.html#events_class_events_eventemitter [Readable Stream]: stream.html#stream_readable_stream [Writable Stream]: stream.html#stream_writable_stream [global Agent]: #http_http_globalagent [http.ClientRequest]: #http_class_http_clientrequest [http.IncomingMessage]: #http_http_incomingmessage [http.ServerResponse]: #http_class_http_serverresponse [http.Server]: #http_class_http_server [http.request()]: #http_http_request_options_callback [http.request()]: #http_http_request_options_callback [net.Server.close()]: net.html#net_server_close_callback [net.Server.listen(path)]: net.html#net_server_listen_path_callback [net.Server.listen(port)]: net.html#net_server_listen_port_host_backlog_callback [response.end()]: #http_response_end_data_encoding [response.write()]: #http_response_write_chunk_encoding [response.writeContinue()]: #http_response_writecontinue [response.writeHead()]: #http_response_writehead_statuscode_reasonphrase_headers [socket.setKeepAlive()]: net.html#net_socket_setkeepalive_enable_initialdelay [socket.setNoDelay()]: net.html#net_socket_setnodelay_nodelay [socket.setTimeout()]: net.html#net_socket_settimeout_timeout_callback [stream.setEncoding()]: stream.html#stream_stream_setencoding_encoding [url.parse()]: url.html#url_url_parse_urlstr_parsequerystring_slashesdenotehost node-v0.10.25~dfsg2/doc/api/tls.html0000644000000000000000000010057112270264601015626 0ustar rootroot TLS (SSL) Node.js v0.10.25 Manual & Documentation

    Node.js v0.10.25 Manual & Documentation


    TLS (SSL)#

    Stability: 3 - Stable

    Use require('tls') to access this module.

    The tls module uses OpenSSL to provide Transport Layer Security and/or Secure Socket Layer: encrypted stream communication.

    TLS/SSL is a public/private key infrastructure. Each client and each server must have a private key. A private key is created like this

    openssl genrsa -out ryans-key.pem 1024

    All severs and some clients need to have a certificate. Certificates are public keys signed by a Certificate Authority or self-signed. The first step to getting a certificate is to create a "Certificate Signing Request" (CSR) file. This is done with:

    openssl req -new -key ryans-key.pem -out ryans-csr.pem

    To create a self-signed certificate with the CSR, do this:

    openssl x509 -req -in ryans-csr.pem -signkey ryans-key.pem -out ryans-cert.pem

    Alternatively you can send the CSR to a Certificate Authority for signing.

    (TODO: docs on creating a CA, for now interested users should just look at test/fixtures/keys/Makefile in the Node source code)

    To create .pfx or .p12, do this:

    openssl pkcs12 -export -in agent5-cert.pem -inkey agent5-key.pem \
        -certfile ca-cert.pem -out agent5.pfx
    • in: certificate
    • inkey: private key
    • certfile: all CA certs concatenated in one file like cat ca1-cert.pem ca2-cert.pem > ca-cert.pem

    Client-initiated renegotiation attack mitigation#

    The TLS protocol lets the client renegotiate certain aspects of the TLS session. Unfortunately, session renegotiation requires a disproportional amount of server-side resources, which makes it a potential vector for denial-of-service attacks.

    To mitigate this, renegotiations are limited to three times every 10 minutes. An error is emitted on the CleartextStream instance when the threshold is exceeded. The limits are configurable:

    • tls.CLIENT_RENEG_LIMIT: renegotiation limit, default is 3.

    • tls.CLIENT_RENEG_WINDOW: renegotiation window in seconds, default is 10 minutes.

    Don't change the defaults unless you know what you are doing.

    To test your server, connect to it with openssl s_client -connect address:port and tap R<CR> (that's the letter R followed by a carriage return) a few times.

    NPN and SNI#

    NPN (Next Protocol Negotiation) and SNI (Server Name Indication) are TLS handshake extensions allowing you:

    • NPN - to use one TLS server for multiple protocols (HTTP, SPDY)
    • SNI - to use one TLS server for multiple hostnames with different SSL certificates.

    tls.getCiphers()#

    Returns an array with the names of the supported SSL ciphers.

    Example:

    var ciphers = tls.getCiphers();
    console.log(ciphers); // ['AES128-SHA', 'AES256-SHA', ...]

    tls.createServer(options, [secureConnectionListener])#

    Creates a new tls.Server. The connectionListener argument is automatically set as a listener for the secureConnection event. The options object has these possibilities:

    • pfx: A string or Buffer containing the private key, certificate and CA certs of the server in PFX or PKCS12 format. (Mutually exclusive with the key, cert and ca options.)

    • key: A string or Buffer containing the private key of the server in PEM format. (Required)

    • passphrase: A string of passphrase for the private key or pfx.

    • cert: A string or Buffer containing the certificate key of the server in PEM format. (Required)

    • ca: An array of strings or Buffers of trusted certificates in PEM format. If this is omitted several well known "root" CAs will be used, like VeriSign. These are used to authorize connections.

    • crl : Either a string or list of strings of PEM encoded CRLs (Certificate Revocation List)

    • ciphers: A string describing the ciphers to use or exclude.

      To mitigate BEAST attacks it is recommended that you use this option in conjunction with the honorCipherOrder option described below to prioritize the non-CBC cipher.

      Defaults to AES128-GCM-SHA256:RC4:HIGH:!MD5:!aNULL:!EDH. Consult the OpenSSL cipher list format documentation for details on the format. ECDH (Elliptic Curve Diffie-Hellman) ciphers are not yet supported.

    `AES128-GCM-SHA256` is used when node.js is linked against OpenSSL 1.0.1
    or newer and the client speaks TLS 1.2, RC4 is used as a secure fallback.
    
    **NOTE**: Previous revisions of this section suggested `AES256-SHA` as an
    acceptable cipher. Unfortunately, `AES256-SHA` is a CBC cipher and therefore
    susceptible to BEAST attacks. Do *not* use it.
    • handshakeTimeout: Abort the connection if the SSL/TLS handshake does not finish in this many milliseconds. The default is 120 seconds.

      A 'clientError' is emitted on the tls.Server object whenever a handshake times out.

    • honorCipherOrder : When choosing a cipher, use the server's preferences instead of the client preferences.

      Note that if SSLv2 is used, the server will send its list of preferences to the client, and the client chooses the cipher.

      Although, this option is disabled by default, it is recommended that you use this option in conjunction with the ciphers option to mitigate BEAST attacks.

    • requestCert: If true the server will request a certificate from clients that connect and attempt to verify that certificate. Default: false.

    • rejectUnauthorized: If true the server will reject any connection which is not authorized with the list of supplied CAs. This option only has an effect if requestCert is true. Default: false.

    • NPNProtocols: An array or Buffer of possible NPN protocols. (Protocols should be ordered by their priority).

    • SNICallback: A function that will be called if client supports SNI TLS extension. Only one argument will be passed to it: servername. And SNICallback should return SecureContext instance. (You can use crypto.createCredentials(...).context to get proper SecureContext). If SNICallback wasn't provided - default callback with high-level API will be used (see below).

    • sessionIdContext: A string containing a opaque identifier for session resumption. If requestCert is true, the default is MD5 hash value generated from command-line. Otherwise, the default is not provided.

    • secureProtocol: The SSL method to use, e.g. SSLv3_method to force SSL version 3. The possible values depend on your installation of OpenSSL and are defined in the constant SSL_METHODS.

    Here is a simple example echo server:

    var tls = require('tls');
    var fs = require('fs');
    
    var options = {
      key: fs.readFileSync('server-key.pem'),
      cert: fs.readFileSync('server-cert.pem'),
    
      // This is necessary only if using the client certificate authentication.
      requestCert: true,
    
      // This is necessary only if the client uses the self-signed certificate.
      ca: [ fs.readFileSync('client-cert.pem') ]
    };
    
    var server = tls.createServer(options, function(cleartextStream) {
      console.log('server connected',
                  cleartextStream.authorized ? 'authorized' : 'unauthorized');
      cleartextStream.write("welcome!\n");
      cleartextStream.setEncoding('utf8');
      cleartextStream.pipe(cleartextStream);
    });
    server.listen(8000, function() {
      console.log('server bound');
    });

    Or

    var tls = require('tls');
    var fs = require('fs');
    
    var options = {
      pfx: fs.readFileSync('server.pfx'),
    
      // This is necessary only if using the client certificate authentication.
      requestCert: true,
    
    };
    
    var server = tls.createServer(options, function(cleartextStream) {
      console.log('server connected',
                  cleartextStream.authorized ? 'authorized' : 'unauthorized');
      cleartextStream.write("welcome!\n");
      cleartextStream.setEncoding('utf8');
      cleartextStream.pipe(cleartextStream);
    });
    server.listen(8000, function() {
      console.log('server bound');
    });

    You can test this server by connecting to it with openssl s_client:

    openssl s_client -connect 127.0.0.1:8000

    tls.SLAB_BUFFER_SIZE#

    Size of slab buffer used by all tls servers and clients. Default: 10 * 1024 * 1024.

    Don't change the defaults unless you know what you are doing.

    tls.connect(options, [callback])#

    tls.connect(port, [host], [options], [callback])#

    Creates a new client connection to the given port and host (old API) or options.port and options.host. (If host is omitted, it defaults to localhost.) options should be an object which specifies:

    • host: Host the client should connect to

    • port: Port the client should connect to

    • socket: Establish secure connection on a given socket rather than creating a new socket. If this option is specified, host and port are ignored.

    • pfx: A string or Buffer containing the private key, certificate and CA certs of the server in PFX or PKCS12 format.

    • key: A string or Buffer containing the private key of the client in PEM format.

    • passphrase: A string of passphrase for the private key or pfx.

    • cert: A string or Buffer containing the certificate key of the client in PEM format.

    • ca: An array of strings or Buffers of trusted certificates in PEM format. If this is omitted several well known "root" CAs will be used, like VeriSign. These are used to authorize connections.

    • rejectUnauthorized: If true, the server certificate is verified against the list of supplied CAs. An 'error' event is emitted if verification fails. Default: true.

    • NPNProtocols: An array of strings or Buffers containing supported NPN protocols. Buffers should have following format: 0x05hello0x05world, where first byte is next protocol name's length. (Passing array should usually be much simpler: ['hello', 'world'].)

    • servername: Servername for SNI (Server Name Indication) TLS extension.

    • secureProtocol: The SSL method to use, e.g. SSLv3_method to force SSL version 3. The possible values depend on your installation of OpenSSL and are defined in the constant SSL_METHODS.

    The callback parameter will be added as a listener for the 'secureConnect' event.

    tls.connect() returns a CleartextStream object.

    Here is an example of a client of echo server as described previously:

    var tls = require('tls');
    var fs = require('fs');
    
    var options = {
      // These are necessary only if using the client certificate authentication
      key: fs.readFileSync('client-key.pem'),
      cert: fs.readFileSync('client-cert.pem'),
    
      // This is necessary only if the server uses the self-signed certificate
      ca: [ fs.readFileSync('server-cert.pem') ]
    };
    
    var cleartextStream = tls.connect(8000, options, function() {
      console.log('client connected',
                  cleartextStream.authorized ? 'authorized' : 'unauthorized');
      process.stdin.pipe(cleartextStream);
      process.stdin.resume();
    });
    cleartextStream.setEncoding('utf8');
    cleartextStream.on('data', function(data) {
      console.log(data);
    });
    cleartextStream.on('end', function() {
      server.close();
    });

    Or

    var tls = require('tls');
    var fs = require('fs');
    
    var options = {
      pfx: fs.readFileSync('client.pfx')
    };
    
    var cleartextStream = tls.connect(8000, options, function() {
      console.log('client connected',
                  cleartextStream.authorized ? 'authorized' : 'unauthorized');
      process.stdin.pipe(cleartextStream);
      process.stdin.resume();
    });
    cleartextStream.setEncoding('utf8');
    cleartextStream.on('data', function(data) {
      console.log(data);
    });
    cleartextStream.on('end', function() {
      server.close();
    });

    tls.createSecurePair([credentials], [isServer], [requestCert], [rejectUnauthorized])#

    Creates a new secure pair object with two streams, one of which reads/writes encrypted data, and one reads/writes cleartext data. Generally the encrypted one is piped to/from an incoming encrypted data stream, and the cleartext one is used as a replacement for the initial encrypted stream.

    • credentials: A credentials object from crypto.createCredentials( ... )

    • isServer: A boolean indicating whether this tls connection should be opened as a server or a client.

    • requestCert: A boolean indicating whether a server should request a certificate from a connecting client. Only applies to server connections.

    • rejectUnauthorized: A boolean indicating whether a server should automatically reject clients with invalid certificates. Only applies to servers with requestCert enabled.

    tls.createSecurePair() returns a SecurePair object with [cleartext][] and encrypted stream properties.

    Class: SecurePair#

    Returned by tls.createSecurePair.

    Event: 'secure'#

    The event is emitted from the SecurePair once the pair has successfully established a secure connection.

    Similarly to the checking for the server 'secureConnection' event, pair.cleartext.authorized should be checked to confirm whether the certificate used properly authorized.

    Class: tls.Server#

    This class is a subclass of net.Server and has the same methods on it. Instead of accepting just raw TCP connections, this accepts encrypted connections using TLS or SSL.

    Event: 'secureConnection'#

    function (cleartextStream) {}

    This event is emitted after a new connection has been successfully handshaked. The argument is a instance of CleartextStream. It has all the common stream methods and events.

    cleartextStream.authorized is a boolean value which indicates if the client has verified by one of the supplied certificate authorities for the server. If cleartextStream.authorized is false, then cleartextStream.authorizationError is set to describe how authorization failed. Implied but worth mentioning: depending on the settings of the TLS server, you unauthorized connections may be accepted. cleartextStream.npnProtocol is a string containing selected NPN protocol. cleartextStream.servername is a string containing servername requested with SNI.

    Event: 'clientError'#

    function (exception, securePair) { }

    When a client connection emits an 'error' event before secure connection is established - it will be forwarded here.

    securePair is the tls.SecurePair that the error originated from.

    Event: 'newSession'#

    function (sessionId, sessionData) { }

    Emitted on creation of TLS session. May be used to store sessions in external storage.

    Event: 'resumeSession'#

    function (sessionId, callback) { }

    Emitted when client wants to resume previous TLS session. Event listener may perform lookup in external storage using given sessionId, and invoke callback(null, sessionData) once finished. If session can't be resumed (i.e. doesn't exist in storage) one may call callback(null, null). Calling callback(err) will terminate incoming connection and destroy socket.

    server.listen(port, [host], [callback])#

    Begin accepting connections on the specified port and host. If the host is omitted, the server will accept connections directed to any IPv4 address (INADDR_ANY).

    This function is asynchronous. The last parameter callback will be called when the server has been bound.

    See net.Server for more information.

    server.close()#

    Stops the server from accepting new connections. This function is asynchronous, the server is finally closed when the server emits a 'close' event.

    server.address()#

    Returns the bound address, the address family name and port of the server as reported by the operating system. See net.Server.address() for more information.

    server.addContext(hostname, credentials)#

    Add secure context that will be used if client request's SNI hostname is matching passed hostname (wildcards can be used). credentials can contain key, cert and ca.

    server.maxConnections#

    Set this property to reject connections when the server's connection count gets high.

    server.connections#

    The number of concurrent connections on the server.

    Class: CryptoStream#

    This is an encrypted stream.

    cryptoStream.bytesWritten#

    A proxy to the underlying socket's bytesWritten accessor, this will return the total bytes written to the socket, including the TLS overhead.

    Class: tls.CleartextStream#

    This is a stream on top of the Encrypted stream that makes it possible to read/write an encrypted data as a cleartext data.

    This instance implements a duplex Stream interfaces. It has all the common stream methods and events.

    A ClearTextStream is the clear member of a SecurePair object.

    Event: 'secureConnect'#

    This event is emitted after a new connection has been successfully handshaked. The listener will be called no matter if the server's certificate was authorized or not. It is up to the user to test cleartextStream.authorized to see if the server certificate was signed by one of the specified CAs. If cleartextStream.authorized === false then the error can be found in cleartextStream.authorizationError. Also if NPN was used - you can check cleartextStream.npnProtocol for negotiated protocol.

    cleartextStream.authorized#

    A boolean that is true if the peer certificate was signed by one of the specified CAs, otherwise false

    cleartextStream.authorizationError#

    The reason why the peer's certificate has not been verified. This property becomes available only when cleartextStream.authorized === false.

    cleartextStream.getPeerCertificate()#

    Returns an object representing the peer's certificate. The returned object has some properties corresponding to the field of the certificate.

    Example:

    { subject: 
       { C: 'UK',
         ST: 'Acknack Ltd',
         L: 'Rhys Jones',
         O: 'node.js',
         OU: 'Test TLS Certificate',
         CN: 'localhost' },
      issuer: 
       { C: 'UK',
         ST: 'Acknack Ltd',
         L: 'Rhys Jones',
         O: 'node.js',
         OU: 'Test TLS Certificate',
         CN: 'localhost' },
      valid_from: 'Nov 11 09:52:22 2009 GMT',
      valid_to: 'Nov  6 09:52:22 2029 GMT',
      fingerprint: '2A:7A:C2:DD:E5:F9:CC:53:72:35:99:7A:02:5A:71:38:52:EC:8A:DF' }

    If the peer does not provide a certificate, it returns null or an empty object.

    cleartextStream.getCipher()#

    Returns an object representing the cipher name and the SSL/TLS protocol version of the current connection.

    Example: { name: 'AES256-SHA', version: 'TLSv1/SSLv3' }

    See SSL_CIPHER_get_name() and SSL_CIPHER_get_version() in http://www.openssl.org/docs/ssl/ssl.html#DEALING_WITH_CIPHERS for more information.

    cleartextStream.address()#

    Returns the bound address, the address family name and port of the underlying socket as reported by the operating system. Returns an object with three properties, e.g. { port: 12346, family: 'IPv4', address: '127.0.0.1' }

    cleartextStream.remoteAddress#

    The string representation of the remote IP address. For example, '74.125.127.100' or '2001:4860:a005::68'.

    cleartextStream.remotePort#

    The numeric representation of the remote port. For example, 443.

    node-v0.10.25~dfsg2/doc/api/_toc.json0000644000000000000000000001356512270264601015763 0ustar rootroot{ "source": "doc/api/_toc.markdown", "desc": [ { "type": "list_start", "ordered": false }, { "type": "list_item_start" }, { "type": "text", "text": "[About these Docs](documentation.html)" }, { "type": "list_item_end" }, { "type": "list_item_start" }, { "type": "text", "text": "[Synopsis](synopsis.html)" }, { "type": "list_item_end" }, { "type": "list_item_start" }, { "type": "text", "text": "[Assertion Testing](assert.html)" }, { "type": "list_item_end" }, { "type": "list_item_start" }, { "type": "text", "text": "[Buffer](buffer.html)" }, { "type": "list_item_end" }, { "type": "list_item_start" }, { "type": "text", "text": "[C/C++ Addons](addons.html)" }, { "type": "list_item_end" }, { "type": "list_item_start" }, { "type": "text", "text": "[Child Processes](child_process.html)" }, { "type": "list_item_end" }, { "type": "list_item_start" }, { "type": "text", "text": "[Cluster](cluster.html)" }, { "type": "list_item_end" }, { "type": "list_item_start" }, { "type": "text", "text": "[Console](console.html)" }, { "type": "list_item_end" }, { "type": "list_item_start" }, { "type": "text", "text": "[Crypto](crypto.html)" }, { "type": "list_item_end" }, { "type": "list_item_start" }, { "type": "text", "text": "[Debugger](debugger.html)" }, { "type": "list_item_end" }, { "type": "list_item_start" }, { "type": "text", "text": "[DNS](dns.html)" }, { "type": "list_item_end" }, { "type": "list_item_start" }, { "type": "text", "text": "[Domain](domain.html)" }, { "type": "list_item_end" }, { "type": "list_item_start" }, { "type": "text", "text": "[Events](events.html)" }, { "type": "list_item_end" }, { "type": "list_item_start" }, { "type": "text", "text": "[File System](fs.html)" }, { "type": "list_item_end" }, { "type": "list_item_start" }, { "type": "text", "text": "[Globals](globals.html)" }, { "type": "list_item_end" }, { "type": "list_item_start" }, { "type": "text", "text": "[HTTP](http.html)" }, { "type": "list_item_end" }, { "type": "list_item_start" }, { "type": "text", "text": "[HTTPS](https.html)" }, { "type": "list_item_end" }, { "type": "list_item_start" }, { "type": "text", "text": "[Modules](modules.html)" }, { "type": "list_item_end" }, { "type": "list_item_start" }, { "type": "text", "text": "[Net](net.html)" }, { "type": "list_item_end" }, { "type": "list_item_start" }, { "type": "text", "text": "[OS](os.html)" }, { "type": "list_item_end" }, { "type": "list_item_start" }, { "type": "text", "text": "[Path](path.html)" }, { "type": "list_item_end" }, { "type": "list_item_start" }, { "type": "text", "text": "[Process](process.html)" }, { "type": "list_item_end" }, { "type": "list_item_start" }, { "type": "text", "text": "[Punycode](punycode.html)" }, { "type": "list_item_end" }, { "type": "list_item_start" }, { "type": "text", "text": "[Query Strings](querystring.html)" }, { "type": "list_item_end" }, { "type": "list_item_start" }, { "type": "text", "text": "[Readline](readline.html)" }, { "type": "list_item_end" }, { "type": "list_item_start" }, { "type": "text", "text": "[REPL](repl.html)" }, { "type": "list_item_end" }, { "type": "list_item_start" }, { "type": "text", "text": "[Stream](stream.html)" }, { "type": "list_item_end" }, { "type": "list_item_start" }, { "type": "text", "text": "[String Decoder](string_decoder.html)" }, { "type": "list_item_end" }, { "type": "list_item_start" }, { "type": "text", "text": "[Timers](timers.html)" }, { "type": "list_item_end" }, { "type": "list_item_start" }, { "type": "text", "text": "[TLS/SSL](tls.html)" }, { "type": "list_item_end" }, { "type": "list_item_start" }, { "type": "text", "text": "[TTY](tty.html)" }, { "type": "list_item_end" }, { "type": "list_item_start" }, { "type": "text", "text": "[UDP/Datagram](dgram.html)" }, { "type": "list_item_end" }, { "type": "list_item_start" }, { "type": "text", "text": "[URL](url.html)" }, { "type": "list_item_end" }, { "type": "list_item_start" }, { "type": "text", "text": "[Utilities](util.html)" }, { "type": "list_item_end" }, { "type": "list_item_start" }, { "type": "text", "text": "[VM](vm.html)" }, { "type": "list_item_end" }, { "type": "list_item_start" }, { "type": "text", "text": "[ZLIB](zlib.html)" }, { "type": "list_item_end" }, { "type": "list_end" } ] } node-v0.10.25~dfsg2/doc/api/modules.html0000644000000000000000000006424412270264601016502 0ustar rootroot Modules Node.js v0.10.25 Manual & Documentation

    Node.js v0.10.25 Manual & Documentation


    Modules#

    Stability: 5 - Locked

    Node has a simple module loading system. In Node, files and modules are in one-to-one correspondence. As an example, foo.js loads the module circle.js in the same directory.

    The contents of foo.js:

    var circle = require('./circle.js');
    console.log( 'The area of a circle of radius 4 is '
               + circle.area(4));

    The contents of circle.js:

    var PI = Math.PI;
    
    exports.area = function (r) {
      return PI * r * r;
    };
    
    exports.circumference = function (r) {
      return 2 * PI * r;
    };

    The module circle.js has exported the functions area() and circumference(). To add functions and objects to the root of your module, you can add them to the special exports object.

    Variables local to the module will be private, as though the module was wrapped in a function. In this example the variable PI is private to circle.js.

    If you want the root of your module's export to be a function (such as a constructor) or if you want to export a complete object in one assignment instead of building it one property at a time, assign it to module.exports instead of exports.

    Below, bar.js makes use of the square module, which exports a constructor:

    var square = require('./square.js');
    var mySquare = square(2);
    console.log('The area of my square is ' + mySquare.area());

    The square module is defined in square.js:

    // assigning to exports will not modify module, must use module.exports
    module.exports = function(width) {
      return {
        area: function() {
          return width * width;
        }
      };
    }

    The module system is implemented in the require("module") module.

    Cycles#

    When there are circular require() calls, a module might not be done being executed when it is returned.

    Consider this situation:

    a.js:

    console.log('a starting');
    exports.done = false;
    var b = require('./b.js');
    console.log('in a, b.done = %j', b.done);
    exports.done = true;
    console.log('a done');

    b.js:

    console.log('b starting');
    exports.done = false;
    var a = require('./a.js');
    console.log('in b, a.done = %j', a.done);
    exports.done = true;
    console.log('b done');

    main.js:

    console.log('main starting');
    var a = require('./a.js');
    var b = require('./b.js');
    console.log('in main, a.done=%j, b.done=%j', a.done, b.done);

    When main.js loads a.js, then a.js in turn loads b.js. At that point, b.js tries to load a.js. In order to prevent an infinite loop an unfinished copy of the a.js exports object is returned to the b.js module. b.js then finishes loading, and its exports object is provided to the a.js module.

    By the time main.js has loaded both modules, they're both finished. The output of this program would thus be:

    $ node main.js
    main starting
    a starting
    b starting
    in b, a.done = false
    b done
    in a, b.done = true
    a done
    in main, a.done=true, b.done=true

    If you have cyclic module dependencies in your program, make sure to plan accordingly.

    Core Modules#

    Node has several modules compiled into the binary. These modules are described in greater detail elsewhere in this documentation.

    The core modules are defined in node's source in the lib/ folder.

    Core modules are always preferentially loaded if their identifier is passed to require(). For instance, require('http') will always return the built in HTTP module, even if there is a file by that name.

    File Modules#

    If the exact filename is not found, then node will attempt to load the required filename with the added extension of .js, .json, and then .node.

    .js files are interpreted as JavaScript text files, and .json files are parsed as JSON text files. .node files are interpreted as compiled addon modules loaded with dlopen.

    A module prefixed with '/' is an absolute path to the file. For example, require('/home/marco/foo.js') will load the file at /home/marco/foo.js.

    A module prefixed with './' is relative to the file calling require(). That is, circle.js must be in the same directory as foo.js for require('./circle') to find it.

    Without a leading '/' or './' to indicate a file, the module is either a "core module" or is loaded from a node_modules folder.

    If the given path does not exist, require() will throw an Error with its code property set to 'MODULE_NOT_FOUND'.

    Loading from node_modules Folders#

    If the module identifier passed to require() is not a native module, and does not begin with '/', '../', or './', then node starts at the parent directory of the current module, and adds /node_modules, and attempts to load the module from that location.

    If it is not found there, then it moves to the parent directory, and so on, until the root of the tree is reached.

    For example, if the file at '/home/ry/projects/foo.js' called require('bar.js'), then node would look in the following locations, in this order:

    • /home/ry/projects/node_modules/bar.js
    • /home/ry/node_modules/bar.js
    • /home/node_modules/bar.js
    • /node_modules/bar.js

    This allows programs to localize their dependencies, so that they do not clash.

    Folders as Modules#

    It is convenient to organize programs and libraries into self-contained directories, and then provide a single entry point to that library. There are three ways in which a folder may be passed to require() as an argument.

    The first is to create a package.json file in the root of the folder, which specifies a main module. An example package.json file might look like this:

    { "name" : "some-library",
      "main" : "./lib/some-library.js" }

    If this was in a folder at ./some-library, then require('./some-library') would attempt to load ./some-library/lib/some-library.js.

    This is the extent of Node's awareness of package.json files.

    If there is no package.json file present in the directory, then node will attempt to load an index.js or index.node file out of that directory. For example, if there was no package.json file in the above example, then require('./some-library') would attempt to load:

    • ./some-library/index.js
    • ./some-library/index.node

    Caching#

    Modules are cached after the first time they are loaded. This means (among other things) that every call to require('foo') will get exactly the same object returned, if it would resolve to the same file.

    Multiple calls to require('foo') may not cause the module code to be executed multiple times. This is an important feature. With it, "partially done" objects can be returned, thus allowing transitive dependencies to be loaded even when they would cause cycles.

    If you want to have a module execute code multiple times, then export a function, and call that function.

    Module Caching Caveats#

    Modules are cached based on their resolved filename. Since modules may resolve to a different filename based on the location of the calling module (loading from node_modules folders), it is not a guarantee that require('foo') will always return the exact same object, if it would resolve to different files.

    The module Object#

    • {Object}

    In each module, the module free variable is a reference to the object representing the current module. For convenience, module.exports is also accessible via the exports module-global. module isn't actually a global but rather local to each module.

    module.exports#

    • Object

    The module.exports object is created by the Module system. Sometimes this is not acceptable; many want their module to be an instance of some class. To do this assign the desired export object to module.exports. Note that assigning the desired object to exports will simply rebind the local exports variable, which is probably not what you want to do.

    For example suppose we were making a module called a.js

    var EventEmitter = require('events').EventEmitter;
    
    module.exports = new EventEmitter();
    
    // Do some work, and after some time emit
    // the 'ready' event from the module itself.
    setTimeout(function() {
      module.exports.emit('ready');
    }, 1000);

    Then in another file we could do

    var a = require('./a');
    a.on('ready', function() {
      console.log('module a is ready');
    });

    Note that assignment to module.exports must be done immediately. It cannot be done in any callbacks. This does not work:

    x.js:

    setTimeout(function() {
      module.exports = { a: "hello" };
    }, 0);

    y.js:

    var x = require('./x');
    console.log(x.a);

    exports alias#

    The exports variable that is available within a module starts as a reference to module.exports. As with any variable, if you assign a new value to it, it is no longer bound to the previous value.

    To illustrate the behaviour, imagine this hypothetical implementation of require():

    function require(...) {
      // ...
      function (module, exports) {
        // Your module code here
        exports = some_func;        // re-assigns exports, exports is no longer
                                    // a shortcut, and nothing is exported.
        module.exports = some_func; // makes your module export 0
      } (module, module.exports);
      return module;
    }

    As a guideline, if the relationship between exports and module.exports seems like magic to you, ignore exports and only use module.exports.

    module.require(id)#

    • id String
    • Return: Object module.exports from the resolved module

    The module.require method provides a way to load a module as if require() was called from the original module.

    Note that in order to do this, you must get a reference to the module object. Since require() returns the module.exports, and the module is typically only available within a specific module's code, it must be explicitly exported in order to be used.

    module.id#

    • String

    The identifier for the module. Typically this is the fully resolved filename.

    module.filename#

    • String

    The fully resolved filename to the module.

    module.loaded#

    • Boolean

    Whether or not the module is done loading, or is in the process of loading.

    module.parent#

    • Module Object

    The module that required this one.

    module.children#

    • Array

    The module objects required by this one.

    All Together...#

    To get the exact filename that will be loaded when require() is called, use the require.resolve() function.

    Putting together all of the above, here is the high-level algorithm in pseudocode of what require.resolve does:

    require(X) from module at path Y
    1. If X is a core module,
       a. return the core module
       b. STOP
    2. If X begins with './' or '/' or '../'
       a. LOAD_AS_FILE(Y + X)
       b. LOAD_AS_DIRECTORY(Y + X)
    3. LOAD_NODE_MODULES(X, dirname(Y))
    4. THROW "not found"
    
    LOAD_AS_FILE(X)
    1. If X is a file, load X as JavaScript text.  STOP
    2. If X.js is a file, load X.js as JavaScript text.  STOP
    3. If X.node is a file, load X.node as binary addon.  STOP
    
    LOAD_AS_DIRECTORY(X)
    1. If X/package.json is a file,
       a. Parse X/package.json, and look for "main" field.
       b. let M = X + (json main field)
       c. LOAD_AS_FILE(M)
    2. If X/index.js is a file, load X/index.js as JavaScript text.  STOP
    3. If X/index.node is a file, load X/index.node as binary addon.  STOP
    
    LOAD_NODE_MODULES(X, START)
    1. let DIRS=NODE_MODULES_PATHS(START)
    2. for each DIR in DIRS:
       a. LOAD_AS_FILE(DIR/X)
       b. LOAD_AS_DIRECTORY(DIR/X)
    
    NODE_MODULES_PATHS(START)
    1. let PARTS = path split(START)
    2. let ROOT = index of first instance of "node_modules" in PARTS, or 0
    3. let I = count of PARTS - 1
    4. let DIRS = []
    5. while I > ROOT,
       a. if PARTS[I] = "node_modules" CONTINUE
       c. DIR = path join(PARTS[0 .. I] + "node_modules")
       b. DIRS = DIRS + DIR
       c. let I = I - 1
    6. return DIRS

    Loading from the global folders#

    If the NODE_PATH environment variable is set to a colon-delimited list of absolute paths, then node will search those paths for modules if they are not found elsewhere. (Note: On Windows, NODE_PATH is delimited by semicolons instead of colons.)

    Additionally, node will search in the following locations:

    • 1: $HOME/.node_modules
    • 2: $HOME/.node_libraries
    • 3: $PREFIX/lib/node

    Where $HOME is the user's home directory, and $PREFIX is node's configured node_prefix.

    These are mostly for historic reasons. You are highly encouraged to place your dependencies locally in node_modules folders. They will be loaded faster, and more reliably.

    Accessing the main module#

    When a file is run directly from Node, require.main is set to its module. That means that you can determine whether a file has been run directly by testing

    require.main === module

    For a file foo.js, this will be true if run via node foo.js, but false if run by require('./foo').

    Because module provides a filename property (normally equivalent to __filename), the entry point of the current application can be obtained by checking require.main.filename.

    Addenda: Package Manager Tips#

    The semantics of Node's require() function were designed to be general enough to support a number of sane directory structures. Package manager programs such as dpkg, rpm, and npm will hopefully find it possible to build native packages from Node modules without modification.

    Below we give a suggested directory structure that could work:

    Let's say that we wanted to have the folder at /usr/lib/node/<some-package>/<some-version> hold the contents of a specific version of a package.

    Packages can depend on one another. In order to install package foo, you may have to install a specific version of package bar. The bar package may itself have dependencies, and in some cases, these dependencies may even collide or form cycles.

    Since Node looks up the realpath of any modules it loads (that is, resolves symlinks), and then looks for their dependencies in the node_modules folders as described above, this situation is very simple to resolve with the following architecture:

    • /usr/lib/node/foo/1.2.3/ - Contents of the foo package, version 1.2.3.
    • /usr/lib/node/bar/4.3.2/ - Contents of the bar package that foo depends on.
    • /usr/lib/node/foo/1.2.3/node_modules/bar - Symbolic link to /usr/lib/node/bar/4.3.2/.
    • /usr/lib/node/bar/4.3.2/node_modules/* - Symbolic links to the packages that bar depends on.

    Thus, even if a cycle is encountered, or if there are dependency conflicts, every module will be able to get a version of its dependency that it can use.

    When the code in the foo package does require('bar'), it will get the version that is symlinked into /usr/lib/node/foo/1.2.3/node_modules/bar. Then, when the code in the bar package calls require('quux'), it'll get the version that is symlinked into /usr/lib/node/bar/4.3.2/node_modules/quux.

    Furthermore, to make the module lookup process even more optimal, rather than putting packages directly in /usr/lib/node, we could put them in /usr/lib/node_modules/<name>/<version>. Then node will not bother looking for missing dependencies in /usr/node_modules or /node_modules.

    In order to make modules available to the node REPL, it might be useful to also add the /usr/lib/node_modules folder to the $NODE_PATH environment variable. Since the module lookups using node_modules folders are all relative, and based on the real path of the files making the calls to require(), the packages themselves can be anywhere.

    node-v0.10.25~dfsg2/doc/api/child_process.html0000644000000000000000000010516712270264601017653 0ustar rootroot Child Process Node.js v0.10.25 Manual & Documentation

    Node.js v0.10.25 Manual & Documentation


    Child Process#

    Stability: 3 - Stable

    Node provides a tri-directional popen(3) facility through the child_process module.

    It is possible to stream data through a child's stdin, stdout, and stderr in a fully non-blocking way. (Note that some programs use line-buffered I/O internally. That doesn't affect node.js but it means data you send to the child process is not immediately consumed.)

    To create a child process use require('child_process').spawn() or require('child_process').fork(). The semantics of each are slightly different, and explained below.

    Class: ChildProcess#

    ChildProcess is an EventEmitter.

    Child processes always have three streams associated with them. child.stdin, child.stdout, and child.stderr. These may be shared with the stdio streams of the parent process, or they may be separate stream objects which can be piped to and from.

    The ChildProcess class is not intended to be used directly. Use the spawn() or fork() methods to create a Child Process instance.

    Event: 'error'#

    • err Error Object the error.

    Emitted when:

    1. The process could not be spawned, or
    2. The process could not be killed, or
    3. Sending a message to the child process failed for whatever reason.

    Note that the exit-event may or may not fire after an error has occured. If you are listening on both events to fire a function, remember to guard against calling your function twice.

    See also ChildProcess#kill() and ChildProcess#send().

    Event: 'exit'#

    • code Number the exit code, if it exited normally.
    • signal String the signal passed to kill the child process, if it was killed by the parent.

    This event is emitted after the child process ends. If the process terminated normally, code is the final exit code of the process, otherwise null. If the process terminated due to receipt of a signal, signal is the string name of the signal, otherwise null.

    Note that the child process stdio streams might still be open.

    Also, note that node establishes signal handlers for 'SIGINT' and 'SIGTERM', so it will not terminate due to receipt of those signals, it will exit.

    See waitpid(2).

    Event: 'close'#

    • code Number the exit code, if it exited normally.
    • signal String the signal passed to kill the child process, if it was killed by the parent.

    This event is emitted when the stdio streams of a child process have all terminated. This is distinct from 'exit', since multiple processes might share the same stdio streams.

    Event: 'disconnect'#

    This event is emitted after calling the .disconnect() method in the parent or in the child. After disconnecting it is no longer possible to send messages, and the .connected property is false.

    Event: 'message'#

    • message Object a parsed JSON object or primitive value
    • sendHandle Handle object a Socket or Server object

    Messages send by .send(message, [sendHandle]) are obtained using the message event.

    child.stdin#

    • Stream object

    A Writable Stream that represents the child process's stdin. Closing this stream via end() often causes the child process to terminate.

    If the child stdio streams are shared with the parent, then this will not be set.

    child.stdout#

    • Stream object

    A Readable Stream that represents the child process's stdout.

    If the child stdio streams are shared with the parent, then this will not be set.

    child.stderr#

    • Stream object

    A Readable Stream that represents the child process's stderr.

    If the child stdio streams are shared with the parent, then this will not be set.

    child.pid#

    • Integer

    The PID of the child process.

    Example:

    var spawn = require('child_process').spawn,
        grep  = spawn('grep', ['ssh']);
    
    console.log('Spawned child pid: ' + grep.pid);
    grep.stdin.end();

    child.connected#

    • Boolean Set to false after `.disconnect' is called

    If .connected is false, it is no longer possible to send messages.

    child.kill([signal])#

    • signal String

    Send a signal to the child process. If no argument is given, the process will be sent 'SIGTERM'. See signal(7) for a list of available signals.

    var spawn = require('child_process').spawn,
        grep  = spawn('grep', ['ssh']);
    
    grep.on('close', function (code, signal) {
      console.log('child process terminated due to receipt of signal '+signal);
    });
    
    // send SIGHUP to process
    grep.kill('SIGHUP');

    May emit an 'error' event when the signal cannot be delivered. Sending a signal to a child process that has already exited is not an error but may have unforeseen consequences: if the PID (the process ID) has been reassigned to another process, the signal will be delivered to that process instead. What happens next is anyone's guess.

    Note that while the function is called kill, the signal delivered to the child process may not actually kill it. kill really just sends a signal to a process.

    See kill(2)

    child.send(message, [sendHandle])#

    • message Object
    • sendHandle Handle object

    When using child_process.fork() you can write to the child using child.send(message, [sendHandle]) and messages are received by a 'message' event on the child.

    For example:

    var cp = require('child_process');
    
    var n = cp.fork(__dirname + '/sub.js');
    
    n.on('message', function(m) {
      console.log('PARENT got message:', m);
    });
    
    n.send({ hello: 'world' });

    And then the child script, 'sub.js' might look like this:

    process.on('message', function(m) {
      console.log('CHILD got message:', m);
    });
    
    process.send({ foo: 'bar' });

    In the child the process object will have a send() method, and process will emit objects each time it receives a message on its channel.

    Please note that the send() method on both the parent and child are synchronous - sending large chunks of data is not advised (pipes can be used instead, see child_process.spawn).

    There is a special case when sending a {cmd: 'NODE_foo'} message. All messages containing a NODE_ prefix in its cmd property will not be emitted in the message event, since they are internal messages used by node core. Messages containing the prefix are emitted in the internalMessage event, you should by all means avoid using this feature, it is subject to change without notice.

    The sendHandle option to child.send() is for sending a TCP server or socket object to another process. The child will receive the object as its second argument to the message event.

    Emits an 'error' event if the message cannot be sent, for example because the child process has already exited.

    Example: sending server object#

    Here is an example of sending a server:

    var child = require('child_process').fork('child.js');
    
    // Open up the server object and send the handle.
    var server = require('net').createServer();
    server.on('connection', function (socket) {
      socket.end('handled by parent');
    });
    server.listen(1337, function() {
      child.send('server', server);
    });

    And the child would the receive the server object as:

    process.on('message', function(m, server) {
      if (m === 'server') {
        server.on('connection', function (socket) {
          socket.end('handled by child');
        });
      }
    });

    Note that the server is now shared between the parent and child, this means that some connections will be handled by the parent and some by the child.

    For dgram servers the workflow is exactly the same. Here you listen on a message event instead of connection and use server.bind instead of server.listen. (Currently only supported on UNIX platforms.)

    Example: sending socket object#

    Here is an example of sending a socket. It will spawn two children and handle connections with the remote address 74.125.127.100 as VIP by sending the socket to a "special" child process. Other sockets will go to a "normal" process.

    var normal = require('child_process').fork('child.js', ['normal']);
    var special = require('child_process').fork('child.js', ['special']);
    
    // Open up the server and send sockets to child
    var server = require('net').createServer();
    server.on('connection', function (socket) {
    
      // if this is a VIP
      if (socket.remoteAddress === '74.125.127.100') {
        special.send('socket', socket);
        return;
      }
      // just the usual dudes
      normal.send('socket', socket);
    });
    server.listen(1337);

    The child.js could look like this:

    process.on('message', function(m, socket) {
      if (m === 'socket') {
        socket.end('You were handled as a ' + process.argv[2] + ' person');
      }
    });

    Note that once a single socket has been sent to a child the parent can no longer keep track of when the socket is destroyed. To indicate this condition the .connections property becomes null. It is also recommended not to use .maxConnections in this condition.

    child.disconnect()#

    Close the IPC channel between parent and child, allowing the child to exit gracefully once there are no other connections keeping it alive. After calling this method the .connected flag will be set to false in both the parent and child, and it is no longer possible to send messages.

    The 'disconnect' event will be emitted when there are no messages in the process of being received, most likely immediately.

    Note that you can also call process.disconnect() in the child process.

    child_process.spawn(command, [args], [options])#

    • command String The command to run
    • args Array List of string arguments
    • options Object
      • cwd String Current working directory of the child process
      • stdio Array|String Child's stdio configuration. (See below)
      • customFds Array Deprecated File descriptors for the child to use for stdio. (See below)
      • env Object Environment key-value pairs
      • detached Boolean The child will be a process group leader. (See below)
      • uid Number Sets the user identity of the process. (See setuid(2).)
      • gid Number Sets the group identity of the process. (See setgid(2).)
    • return: ChildProcess object

    Launches a new process with the given command, with command line arguments in args. If omitted, args defaults to an empty Array.

    The third argument is used to specify additional options, which defaults to:

    { cwd: undefined,
      env: process.env
    }

    cwd allows you to specify the working directory from which the process is spawned. Use env to specify environment variables that will be visible to the new process.

    Example of running ls -lh /usr, capturing stdout, stderr, and the exit code:

    var spawn = require('child_process').spawn,
        ls    = spawn('ls', ['-lh', '/usr']);
    
    ls.stdout.on('data', function (data) {
      console.log('stdout: ' + data);
    });
    
    ls.stderr.on('data', function (data) {
      console.log('stderr: ' + data);
    });
    
    ls.on('close', function (code) {
      console.log('child process exited with code ' + code);
    });

    Example: A very elaborate way to run 'ps ax | grep ssh'

    var spawn = require('child_process').spawn,
        ps    = spawn('ps', ['ax']),
        grep  = spawn('grep', ['ssh']);
    
    ps.stdout.on('data', function (data) {
      grep.stdin.write(data);
    });
    
    ps.stderr.on('data', function (data) {
      console.log('ps stderr: ' + data);
    });
    
    ps.on('close', function (code) {
      if (code !== 0) {
        console.log('ps process exited with code ' + code);
      }
      grep.stdin.end();
    });
    
    grep.stdout.on('data', function (data) {
      console.log('' + data);
    });
    
    grep.stderr.on('data', function (data) {
      console.log('grep stderr: ' + data);
    });
    
    grep.on('close', function (code) {
      if (code !== 0) {
        console.log('grep process exited with code ' + code);
      }
    });

    Example of checking for failed exec:

    var spawn = require('child_process').spawn,
        child = spawn('bad_command');
    
    child.stderr.setEncoding('utf8');
    child.stderr.on('data', function (data) {
      if (/^execvp\(\)/.test(data)) {
        console.log('Failed to start child process.');
      }
    });

    Note that if spawn receives an empty options object, it will result in spawning the process with an empty environment rather than using process.env. This due to backwards compatibility issues with a deprecated API.

    The 'stdio' option to child_process.spawn() is an array where each index corresponds to a fd in the child. The value is one of the following:

    1. 'pipe' - Create a pipe between the child process and the parent process. The parent end of the pipe is exposed to the parent as a property on the child_process object as ChildProcess.stdio[fd]. Pipes created for fds 0 - 2 are also available as ChildProcess.stdin, ChildProcess.stdout and ChildProcess.stderr, respectively.
    2. 'ipc' - Create an IPC channel for passing messages/file descriptors between parent and child. A ChildProcess may have at most one IPC stdio file descriptor. Setting this option enables the ChildProcess.send() method. If the child writes JSON messages to this file descriptor, then this will trigger ChildProcess.on('message'). If the child is a Node.js program, then the presence of an IPC channel will enable process.send() and process.on('message').
    3. 'ignore' - Do not set this file descriptor in the child. Note that Node will always open fd 0 - 2 for the processes it spawns. When any of these is ignored node will open /dev/null and attach it to the child's fd.
    4. Stream object - Share a readable or writable stream that refers to a tty, file, socket, or a pipe with the child process. The stream's underlying file descriptor is duplicated in the child process to the fd that corresponds to the index in the stdio array. Note that the stream must have an underlying descriptor (file streams do not until the 'open' event has occurred).
    5. Positive integer - The integer value is interpreted as a file descriptor that is is currently open in the parent process. It is shared with the child process, similar to how Stream objects can be shared.
    6. null, undefined - Use default value. For stdio fds 0, 1 and 2 (in other words, stdin, stdout, and stderr) a pipe is created. For fd 3 and up, the default is 'ignore'.

    As a shorthand, the stdio argument may also be one of the following strings, rather than an array:

    • ignore - ['ignore', 'ignore', 'ignore']
    • pipe - ['pipe', 'pipe', 'pipe']
    • inherit - [process.stdin, process.stdout, process.stderr] or [0,1,2]

    Example:

    var spawn = require('child_process').spawn;
    
    // Child will use parent's stdios
    spawn('prg', [], { stdio: 'inherit' });
    
    // Spawn child sharing only stderr
    spawn('prg', [], { stdio: ['pipe', 'pipe', process.stderr] });
    
    // Open an extra fd=4, to interact with programs present a
    // startd-style interface.
    spawn('prg', [], { stdio: ['pipe', null, null, null, 'pipe'] });

    If the detached option is set, the child process will be made the leader of a new process group. This makes it possible for the child to continue running after the parent exits.

    By default, the parent will wait for the detached child to exit. To prevent the parent from waiting for a given child, use the child.unref() method, and the parent's event loop will not include the child in its reference count.

    Example of detaching a long-running process and redirecting its output to a file:

     var fs = require('fs'),
         spawn = require('child_process').spawn,
         out = fs.openSync('./out.log', 'a'),
         err = fs.openSync('./out.log', 'a');
    
     var child = spawn('prg', [], {
       detached: true,
       stdio: [ 'ignore', out, err ]
     });
    
     child.unref();

    When using the detached option to start a long-running process, the process will not stay running in the background unless it is provided with a stdio configuration that is not connected to the parent. If the parent's stdio is inherited, the child will remain attached to the controlling terminal.

    There is a deprecated option called customFds which allows one to specify specific file descriptors for the stdio of the child process. This API was not portable to all platforms and therefore removed. With customFds it was possible to hook up the new process' [stdin, stdout, stderr] to existing streams; -1 meant that a new stream should be created. Use at your own risk.

    See also: child_process.exec() and child_process.fork()

    child_process.exec(command, [options], callback)#

    • command String The command to run, with space-separated arguments
    • options Object
      • cwd String Current working directory of the child process
      • env Object Environment key-value pairs
      • encoding String (Default: 'utf8')
      • timeout Number (Default: 0)
      • maxBuffer Number (Default: 200*1024)
      • killSignal String (Default: 'SIGTERM')
    • callback Function called with the output when process terminates
      • error Error
      • stdout Buffer
      • stderr Buffer
    • Return: ChildProcess object

    Runs a command in a shell and buffers the output.

    var exec = require('child_process').exec,
        child;
    
    child = exec('cat *.js bad_file | wc -l',
      function (error, stdout, stderr) {
        console.log('stdout: ' + stdout);
        console.log('stderr: ' + stderr);
        if (error !== null) {
          console.log('exec error: ' + error);
        }
    });

    The callback gets the arguments (error, stdout, stderr). On success, error will be null. On error, error will be an instance of Error and err.code will be the exit code of the child process, and err.signal will be set to the signal that terminated the process.

    There is a second optional argument to specify several options. The default options are

    { encoding: 'utf8',
      timeout: 0,
      maxBuffer: 200*1024,
      killSignal: 'SIGTERM',
      cwd: null,
      env: null }

    If timeout is greater than 0, then it will kill the child process if it runs longer than timeout milliseconds. The child process is killed with killSignal (default: 'SIGTERM'). maxBuffer specifies the largest amount of data allowed on stdout or stderr - if this value is exceeded then the child process is killed.

    child_process.execFile(file, [args], [options], [callback])#

    • file String The filename of the program to run
    • args Array List of string arguments
    • options Object
      • cwd String Current working directory of the child process
      • env Object Environment key-value pairs
      • encoding String (Default: 'utf8')
      • timeout Number (Default: 0)
      • maxBuffer Number (Default: 200*1024)
      • killSignal String (Default: 'SIGTERM')
    • callback Function called with the output when process terminates
      • error Error
      • stdout Buffer
      • stderr Buffer
    • Return: ChildProcess object

    This is similar to child_process.exec() except it does not execute a subshell but rather the specified file directly. This makes it slightly leaner than child_process.exec. It has the same options.

    child_process.fork(modulePath, [args], [options])#

    • modulePath String The module to run in the child
    • args Array List of string arguments
    • options Object
      • cwd String Current working directory of the child process
      • env Object Environment key-value pairs
      • encoding String (Default: 'utf8')
      • execPath String Executable used to create the child process
      • execArgv Array List of string arguments passed to the executable (Default: process.execArgv)
      • silent Boolean If true, stdin, stdout, and stderr of the child will be piped to the parent, otherwise they will be inherited from the parent, see the "pipe" and "inherit" options for spawn()'s stdio for more details (default is false)
    • Return: ChildProcess object

    This is a special case of the spawn() functionality for spawning Node processes. In addition to having all the methods in a normal ChildProcess instance, the returned object has a communication channel built-in. See child.send(message, [sendHandle]) for details.

    These child Nodes are still whole new instances of V8. Assume at least 30ms startup and 10mb memory for each new Node. That is, you cannot create many thousands of them.

    The execPath property in the options object allows for a process to be created for the child rather than the current node executable. This should be done with care and by default will talk over the fd represented an environmental variable NODE_CHANNEL_FD on the child process. The input and output on this fd is expected to be line delimited JSON objects.

    node-v0.10.25~dfsg2/doc/api/dgram.markdown0000644000000000000000000002203012270121457016766 0ustar rootroot# UDP / Datagram Sockets Stability: 3 - Stable Datagram sockets are available through `require('dgram')`. Important note: the behavior of `dgram.Socket#bind()` has changed in v0.10 and is always asynchronous now. If you have code that looks like this: var s = dgram.createSocket('udp4'); s.bind(1234); s.addMembership('224.0.0.114'); You have to change it to this: var s = dgram.createSocket('udp4'); s.bind(1234, function() { s.addMembership('224.0.0.114'); }); ## dgram.createSocket(type, [callback]) * `type` String. Either 'udp4' or 'udp6' * `callback` Function. Attached as a listener to `message` events. Optional * Returns: Socket object Creates a datagram Socket of the specified types. Valid types are `udp4` and `udp6`. Takes an optional callback which is added as a listener for `message` events. Call `socket.bind` if you want to receive datagrams. `socket.bind()` will bind to the "all interfaces" address on a random port (it does the right thing for both `udp4` and `udp6` sockets). You can then retrieve the address and port with `socket.address().address` and `socket.address().port`. ## Class: dgram.Socket The dgram Socket class encapsulates the datagram functionality. It should be created via `dgram.createSocket(type, [callback])`. ### Event: 'message' * `msg` Buffer object. The message * `rinfo` Object. Remote address information Emitted when a new datagram is available on a socket. `msg` is a `Buffer` and `rinfo` is an object with the sender's address information and the number of bytes in the datagram. ### Event: 'listening' Emitted when a socket starts listening for datagrams. This happens as soon as UDP sockets are created. ### Event: 'close' Emitted when a socket is closed with `close()`. No new `message` events will be emitted on this socket. ### Event: 'error' * `exception` Error object Emitted when an error occurs. ### socket.send(buf, offset, length, port, address, [callback]) * `buf` Buffer object. Message to be sent * `offset` Integer. Offset in the buffer where the message starts. * `length` Integer. Number of bytes in the message. * `port` Integer. Destination port. * `address` String. Destination hostname or IP address. * `callback` Function. Called when the message has been sent. Optional. For UDP sockets, the destination port and address must be specified. A string may be supplied for the `address` parameter, and it will be resolved with DNS. If the address is omitted or is an empty string, `'0.0.0.0'` or `'::0'` is used instead. Depending on the network configuration, those defaults may or may not work; it's best to be explicit about the destination address. If the socket has not been previously bound with a call to `bind`, it gets assigned a random port number and is bound to the "all interfaces" address (`'0.0.0.0'` for `udp4` sockets, `'::0'` for `udp6` sockets.) An optional callback may be specified to detect DNS errors or for determining when it's safe to reuse the `buf` object. Note that DNS lookups delay the time to send for at least one tick. The only way to know for sure that the datagram has been sent is by using a callback. Example of sending a UDP packet to a random port on `localhost`; var dgram = require('dgram'); var message = new Buffer("Some bytes"); var client = dgram.createSocket("udp4"); client.send(message, 0, message.length, 41234, "localhost", function(err, bytes) { client.close(); }); **A Note about UDP datagram size** The maximum size of an `IPv4/v6` datagram depends on the `MTU` (_Maximum Transmission Unit_) and on the `Payload Length` field size. - The `Payload Length` field is `16 bits` wide, which means that a normal payload cannot be larger than 64K octets including internet header and data (65,507 bytes = 65,535 − 8 bytes UDP header − 20 bytes IP header); this is generally true for loopback interfaces, but such long datagrams are impractical for most hosts and networks. - The `MTU` is the largest size a given link layer technology can support for datagrams. For any link, `IPv4` mandates a minimum `MTU` of `68` octets, while the recommended `MTU` for IPv4 is `576` (typically recommended as the `MTU` for dial-up type applications), whether they arrive whole or in fragments. For `IPv6`, the minimum `MTU` is `1280` octets, however, the mandatory minimum fragment reassembly buffer size is `1500` octets. The value of `68` octets is very small, since most current link layer technologies have a minimum `MTU` of `1500` (like Ethernet). Note that it's impossible to know in advance the MTU of each link through which a packet might travel, and that generally sending a datagram greater than the (receiver) `MTU` won't work (the packet gets silently dropped, without informing the source that the data did not reach its intended recipient). ### socket.bind(port, [address], [callback]) * `port` Integer * `address` String, Optional * `callback` Function with no parameters, Optional. Callback when binding is done. For UDP sockets, listen for datagrams on a named `port` and optional `address`. If `address` is not specified, the OS will try to listen on all addresses. After binding is done, a "listening" event is emitted and the `callback`(if specified) is called. Specifying both a "listening" event listener and `callback` is not harmful but not very useful. A bound datagram socket keeps the node process running to receive datagrams. If binding fails, an "error" event is generated. In rare case (e.g. binding a closed socket), an `Error` may be thrown by this method. Example of a UDP server listening on port 41234: var dgram = require("dgram"); var server = dgram.createSocket("udp4"); server.on("error", function (err) { console.log("server error:\n" + err.stack); server.close(); }); server.on("message", function (msg, rinfo) { console.log("server got: " + msg + " from " + rinfo.address + ":" + rinfo.port); }); server.on("listening", function () { var address = server.address(); console.log("server listening " + address.address + ":" + address.port); }); server.bind(41234); // server listening 0.0.0.0:41234 ### socket.close() Close the underlying socket and stop listening for data on it. ### socket.address() Returns an object containing the address information for a socket. For UDP sockets, this object will contain `address` , `family` and `port`. ### socket.setBroadcast(flag) * `flag` Boolean Sets or clears the `SO_BROADCAST` socket option. When this option is set, UDP packets may be sent to a local interface's broadcast address. ### socket.setTTL(ttl) * `ttl` Integer Sets the `IP_TTL` socket option. TTL stands for "Time to Live," but in this context it specifies the number of IP hops that a packet is allowed to go through. Each router or gateway that forwards a packet decrements the TTL. If the TTL is decremented to 0 by a router, it will not be forwarded. Changing TTL values is typically done for network probes or when multicasting. The argument to `setTTL()` is a number of hops between 1 and 255. The default on most systems is 64. ### socket.setMulticastTTL(ttl) * `ttl` Integer Sets the `IP_MULTICAST_TTL` socket option. TTL stands for "Time to Live," but in this context it specifies the number of IP hops that a packet is allowed to go through, specifically for multicast traffic. Each router or gateway that forwards a packet decrements the TTL. If the TTL is decremented to 0 by a router, it will not be forwarded. The argument to `setMulticastTTL()` is a number of hops between 0 and 255. The default on most systems is 1. ### socket.setMulticastLoopback(flag) * `flag` Boolean Sets or clears the `IP_MULTICAST_LOOP` socket option. When this option is set, multicast packets will also be received on the local interface. ### socket.addMembership(multicastAddress, [multicastInterface]) * `multicastAddress` String * `multicastInterface` String, Optional Tells the kernel to join a multicast group with `IP_ADD_MEMBERSHIP` socket option. If `multicastInterface` is not specified, the OS will try to add membership to all valid interfaces. ### socket.dropMembership(multicastAddress, [multicastInterface]) * `multicastAddress` String * `multicastInterface` String, Optional Opposite of `addMembership` - tells the kernel to leave a multicast group with `IP_DROP_MEMBERSHIP` socket option. This is automatically called by the kernel when the socket is closed or process terminates, so most apps will never need to call this. If `multicastInterface` is not specified, the OS will try to drop membership to all valid interfaces. ### socket.unref() Calling `unref` on a socket will allow the program to exit if this is the only active socket in the event system. If the socket is already `unref`d calling `unref` again will have no effect. ### socket.ref() Opposite of `unref`, calling `ref` on a previously `unref`d socket will *not* let the program exit if it's the only socket left (the default behavior). If the socket is `ref`d calling `ref` again will have no effect. node-v0.10.25~dfsg2/doc/api/cluster.markdown0000644000000000000000000004311712270121457017366 0ustar rootroot# Cluster Stability: 1 - Experimental A single instance of Node runs in a single thread. To take advantage of multi-core systems the user will sometimes want to launch a cluster of Node processes to handle the load. The cluster module allows you to easily create child processes that all share server ports. var cluster = require('cluster'); var http = require('http'); var numCPUs = require('os').cpus().length; if (cluster.isMaster) { // Fork workers. for (var i = 0; i < numCPUs; i++) { cluster.fork(); } cluster.on('exit', function(worker, code, signal) { console.log('worker ' + worker.process.pid + ' died'); }); } else { // Workers can share any TCP connection // In this case its a HTTP server http.createServer(function(req, res) { res.writeHead(200); res.end("hello world\n"); }).listen(8000); } Running node will now share port 8000 between the workers: % NODE_DEBUG=cluster node server.js 23521,Master Worker 23524 online 23521,Master Worker 23526 online 23521,Master Worker 23523 online 23521,Master Worker 23528 online This feature was introduced recently, and may change in future versions. Please try it out and provide feedback. Also note that, on Windows, it is not yet possible to set up a named pipe server in a worker. ## How It Works The worker processes are spawned using the `child_process.fork` method, so that they can communicate with the parent via IPC and pass server handles back and forth. When you call `server.listen(...)` in a worker, it serializes the arguments and passes the request to the master process. If the master process already has a listening server matching the worker's requirements, then it passes the handle to the worker. If it does not already have a listening server matching that requirement, then it will create one, and pass the handle to the worker. This causes potentially surprising behavior in three edge cases: 1. `server.listen({fd: 7})` Because the message is passed to the master, file descriptor 7 **in the parent** will be listened on, and the handle passed to the worker, rather than listening to the worker's idea of what the number 7 file descriptor references. 2. `server.listen(handle)` Listening on handles explicitly will cause the worker to use the supplied handle, rather than talk to the master process. If the worker already has the handle, then it's presumed that you know what you are doing. 3. `server.listen(0)` Normally, this will cause servers to listen on a random port. However, in a cluster, each worker will receive the same "random" port each time they do `listen(0)`. In essence, the port is random the first time, but predictable thereafter. If you want to listen on a unique port, generate a port number based on the cluster worker ID. When multiple processes are all `accept()`ing on the same underlying resource, the operating system load-balances across them very efficiently. There is no routing logic in Node.js, or in your program, and no shared state between the workers. Therefore, it is important to design your program such that it does not rely too heavily on in-memory data objects for things like sessions and login. Because workers are all separate processes, they can be killed or re-spawned depending on your program's needs, without affecting other workers. As long as there are some workers still alive, the server will continue to accept connections. Node does not automatically manage the number of workers for you, however. It is your responsibility to manage the worker pool for your application's needs. ## cluster.settings * {Object} * `execArgv` {Array} list of string arguments passed to the node executable. (Default=`process.execArgv`) * `exec` {String} file path to worker file. (Default=`process.argv[1]`) * `args` {Array} string arguments passed to worker. (Default=`process.argv.slice(2)`) * `silent` {Boolean} whether or not to send output to parent's stdio. (Default=`false`) After calling `.setupMaster()` (or `.fork()`) this settings object will contain the settings, including the default values. It is effectively frozen after being set, because `.setupMaster()` can only be called once. This object is not supposed to be changed or set manually, by you. ## cluster.isMaster * {Boolean} True if the process is a master. This is determined by the `process.env.NODE_UNIQUE_ID`. If `process.env.NODE_UNIQUE_ID` is undefined, then `isMaster` is `true`. ## cluster.isWorker * {Boolean} True if the process is not a master (it is the negation of `cluster.isMaster`). ## Event: 'fork' * `worker` {Worker object} When a new worker is forked the cluster module will emit a 'fork' event. This can be used to log worker activity, and create your own timeout. var timeouts = []; function errorMsg() { console.error("Something must be wrong with the connection ..."); } cluster.on('fork', function(worker) { timeouts[worker.id] = setTimeout(errorMsg, 2000); }); cluster.on('listening', function(worker, address) { clearTimeout(timeouts[worker.id]); }); cluster.on('exit', function(worker, code, signal) { clearTimeout(timeouts[worker.id]); errorMsg(); }); ## Event: 'online' * `worker` {Worker object} After forking a new worker, the worker should respond with an online message. When the master receives an online message it will emit this event. The difference between 'fork' and 'online' is that fork is emitted when the master forks a worker, and 'online' is emitted when the worker is running. cluster.on('online', function(worker) { console.log("Yay, the worker responded after it was forked"); }); ## Event: 'listening' * `worker` {Worker object} * `address` {Object} After calling `listen()` from a worker, when the 'listening' event is emitted on the server, a listening event will also be emitted on `cluster` in the master. The event handler is executed with two arguments, the `worker` contains the worker object and the `address` object contains the following connection properties: `address`, `port` and `addressType`. This is very useful if the worker is listening on more than one address. cluster.on('listening', function(worker, address) { console.log("A worker is now connected to " + address.address + ":" + address.port); }); The `addressType` is one of: * `4` (TCPv4) * `6` (TCPv6) * `-1` (unix domain socket) * `"udp4"` or `"udp6"` (UDP v4 or v6) ## Event: 'disconnect' * `worker` {Worker object} Emitted after the worker IPC channel has disconnected. This can occur when a worker exits gracefully, is killed, or is disconnected manually (such as with worker.disconnect()). There may be a delay between the `disconnect` and `exit` events. These events can be used to detect if the process is stuck in a cleanup or if there are long-living connections. cluster.on('disconnect', function(worker) { console.log('The worker #' + worker.id + ' has disconnected'); }); ## Event: 'exit' * `worker` {Worker object} * `code` {Number} the exit code, if it exited normally. * `signal` {String} the name of the signal (eg. `'SIGHUP'`) that caused the process to be killed. When any of the workers die the cluster module will emit the 'exit' event. This can be used to restart the worker by calling `.fork()` again. cluster.on('exit', function(worker, code, signal) { console.log('worker %d died (%s). restarting...', worker.process.pid, signal || code); cluster.fork(); }); See [child_process event: 'exit'](child_process.html#child_process_event_exit). ## Event: 'setup' Emitted the first time that `.setupMaster()` is called. ## cluster.setupMaster([settings]) * `settings` {Object} * `exec` {String} file path to worker file. (Default=`process.argv[1]`) * `args` {Array} string arguments passed to worker. (Default=`process.argv.slice(2)`) * `silent` {Boolean} whether or not to send output to parent's stdio. (Default=`false`) `setupMaster` is used to change the default 'fork' behavior. Once called, the settings will be present in `cluster.settings`. Note that: * Only the first call to `.setupMaster()` has any effect, subsequent calls are ignored * That because of the above, the *only* attribute of a worker that may be customized per-worker is the `env` passed to `.fork()` * `.fork()` calls `.setupMaster()` internally to establish the defaults, so to have any effect, `.setupMaster()` must be called *before* any calls to `.fork()` Example: var cluster = require("cluster"); cluster.setupMaster({ exec : "worker.js", args : ["--use", "https"], silent : true }); cluster.fork(); This can only be called from the master process. ## cluster.fork([env]) * `env` {Object} Key/value pairs to add to worker process environment. * return {Worker object} Spawn a new worker process. This can only be called from the master process. ## cluster.disconnect([callback]) * `callback` {Function} called when all workers are disconnected and handles are closed Calls `.disconnect()` on each worker in `cluster.workers`. When they are disconnected all internal handles will be closed, allowing the master process to die gracefully if no other event is waiting. The method takes an optional callback argument which will be called when finished. This can only be called from the master process. ## cluster.worker * {Object} A reference to the current worker object. Not available in the master process. var cluster = require('cluster'); if (cluster.isMaster) { console.log('I am master'); cluster.fork(); cluster.fork(); } else if (cluster.isWorker) { console.log('I am worker #' + cluster.worker.id); } ## cluster.workers * {Object} A hash that stores the active worker objects, keyed by `id` field. Makes it easy to loop through all the workers. It is only available in the master process. A worker is removed from cluster.workers just before the `'disconnect'` or `'exit'` event is emitted. // Go through all workers function eachWorker(callback) { for (var id in cluster.workers) { callback(cluster.workers[id]); } } eachWorker(function(worker) { worker.send('big announcement to all workers'); }); Should you wish to reference a worker over a communication channel, using the worker's unique id is the easiest way to find the worker. socket.on('data', function(id) { var worker = cluster.workers[id]; }); ## Class: Worker A Worker object contains all public information and method about a worker. In the master it can be obtained using `cluster.workers`. In a worker it can be obtained using `cluster.worker`. ### worker.id * {String} Each new worker is given its own unique id, this id is stored in the `id`. While a worker is alive, this is the key that indexes it in cluster.workers ### worker.process * {ChildProcess object} All workers are created using `child_process.fork()`, the returned object from this function is stored as `.process`. In a worker, the global `process` is stored. See: [Child Process module]( child_process.html#child_process_child_process_fork_modulepath_args_options) Note that workers will call `process.exit(0)` if the `'disconnect'` event occurs on `process` and `.suicide` is not `true`. This protects against accidental disconnection. ### worker.suicide * {Boolean} Set by calling `.kill()` or `.disconnect()`, until then it is `undefined`. The boolean `worker.suicide` lets you distinguish between voluntary and accidental exit, the master may choose not to respawn a worker based on this value. cluster.on('exit', function(worker, code, signal) { if (worker.suicide === true) { console.log('Oh, it was just suicide\' – no need to worry'). } }); // kill worker worker.kill(); ### worker.send(message, [sendHandle]) * `message` {Object} * `sendHandle` {Handle object} This function is equal to the send methods provided by `child_process.fork()`. In the master you should use this function to send a message to a specific worker. In a worker you can also use `process.send(message)`, it is the same function. This example will echo back all messages from the master: if (cluster.isMaster) { var worker = cluster.fork(); worker.send('hi there'); } else if (cluster.isWorker) { process.on('message', function(msg) { process.send(msg); }); } ### worker.kill([signal='SIGTERM']) * `signal` {String} Name of the kill signal to send to the worker process. This function will kill the worker. In the master, it does this by disconnecting the `worker.process`, and once disconnected, killing with `signal`. In the worker, it does it by disconnecting the channel, and then exiting with code `0`. Causes `.suicide` to be set. This method is aliased as `worker.destroy()` for backwards compatibility. Note that in a worker, `process.kill()` exists, but it is not this function, it is [kill](process.html#process_process_kill_pid_signal). ### worker.disconnect() In a worker, this function will close all servers, wait for the 'close' event on those servers, and then disconnect the IPC channel. In the master, an internal message is sent to the worker causing it to call `.disconnect()` on itself. Causes `.suicide` to be set. Note that after a server is closed, it will no longer accept new connections, but connections may be accepted by any other listening worker. Existing connections will be allowed to close as usual. When no more connections exist, see [server.close()](net.html#net_event_close), the IPC channel to the worker will close allowing it to die gracefully. The above applies *only* to server connections, client connections are not automatically closed by workers, and disconnect does not wait for them to close before exiting. Note that in a worker, `process.disconnect` exists, but it is not this function, it is [disconnect](child_process.html#child_process_child_disconnect). Because long living server connections may block workers from disconnecting, it may be useful to send a message, so application specific actions may be taken to close them. It also may be useful to implement a timeout, killing a worker if the `disconnect` event has not been emitted after some time. if (cluster.isMaster) { var worker = cluster.fork(); var timeout; worker.on('listening', function(address) { worker.send('shutdown'); worker.disconnect(); timeout = setTimeout(function() { worker.kill(); }, 2000); }); worker.on('disconnect', function() { clearTimeout(timeout); }); } else if (cluster.isWorker) { var net = require('net'); var server = net.createServer(function(socket) { // connections never end }); server.listen(8000); process.on('message', function(msg) { if(msg === 'shutdown') { // initiate graceful close of any connections to server } }); } ### Event: 'message' * `message` {Object} This event is the same as the one provided by `child_process.fork()`. In a worker you can also use `process.on('message')`. As an example, here is a cluster that keeps count of the number of requests in the master process using the message system: var cluster = require('cluster'); var http = require('http'); if (cluster.isMaster) { // Keep track of http requests var numReqs = 0; setInterval(function() { console.log("numReqs =", numReqs); }, 1000); // Count requestes function messageHandler(msg) { if (msg.cmd && msg.cmd == 'notifyRequest') { numReqs += 1; } } // Start workers and listen for messages containing notifyRequest var numCPUs = require('os').cpus().length; for (var i = 0; i < numCPUs; i++) { cluster.fork(); } Object.keys(cluster.workers).forEach(function(id) { cluster.workers[id].on('message', messageHandler); }); } else { // Worker processes have a http server. http.Server(function(req, res) { res.writeHead(200); res.end("hello world\n"); // notify master about the request process.send({ cmd: 'notifyRequest' }); }).listen(8000); } ### Event: 'online' Similar to the `cluster.on('online')` event, but specific to this worker. cluster.fork().on('online', function() { // Worker is online }); It is not emitted in the worker. ### Event: 'listening' * `address` {Object} Similar to the `cluster.on('listening')` event, but specific to this worker. cluster.fork().on('listening', function(address) { // Worker is listening }); It is not emitted in the worker. ### Event: 'disconnect' Similar to the `cluster.on('disconnect')` event, but specfic to this worker. cluster.fork().on('disconnect', function() { // Worker has disconnected }); ### Event: 'exit' * `code` {Number} the exit code, if it exited normally. * `signal` {String} the name of the signal (eg. `'SIGHUP'`) that caused the process to be killed. Similar to the `cluster.on('exit')` event, but specific to this worker. var worker = cluster.fork(); worker.on('exit', function(code, signal) { if( signal ) { console.log("worker was killed by signal: "+signal); } else if( code !== 0 ) { console.log("worker exited with error code: "+code); } else { console.log("worker success!"); } }); ### Event: 'error' This event is the same as the one provided by `child_process.fork()`. In a worker you can also use `process.on('error')`. node-v0.10.25~dfsg2/doc/api/vm.markdown0000644000000000000000000001757512270121457016340 0ustar rootroot# Executing JavaScript Stability: 2 - Unstable. See Caveats, below. You can access this module with: var vm = require('vm'); JavaScript code can be compiled and run immediately or compiled, saved, and run later. ## Caveats The `vm` module has many known issues and edge cases. If you run into issues or unexpected behavior, please consult [the open issues on GitHub](https://github.com/joyent/node/issues?labels=vm&state=open). Some of the biggest problems are described below. ### Sandboxes The `sandbox` argument to `vm.runInNewContext` and `vm.createContext`, along with the `initSandbox` argument to `vm.createContext`, do not behave as one might normally expect and their behavior varies between different versions of Node. The key issue to be aware of is that V8 provides no way to directly control the global object used within a context. As a result, while properties of your `sandbox` object will be available in the context, any properties from the `prototype`s of the `sandbox` may not be available. Furthermore, the `this` expression within the global scope of the context evaluates to the empty object (`{}`) instead of to your sandbox. Your sandbox's properties are also not shared directly with the script. Instead, the properties of the sandbox are copied into the context at the beginning of execution, and then after execution, the properties are copied back out in an attempt to propagate any changes. ### Globals Properties of the global object, like `Array` and `String`, have different values inside of a context. This means that common expressions like `[] instanceof Array` or `Object.getPrototypeOf([]) === Array.prototype` may not produce expected results when used inside of scripts evaluated via the `vm` module. Some of these problems have known workarounds listed in the issues for `vm` on GitHub. for example, `Array.isArray` works around the example problem with `Array`. ## vm.runInThisContext(code, [filename]) `vm.runInThisContext()` compiles `code`, runs it and returns the result. Running code does not have access to local scope. `filename` is optional, it's used only in stack traces. Example of using `vm.runInThisContext` and `eval` to run the same code: var localVar = 123, usingscript, evaled, vm = require('vm'); usingscript = vm.runInThisContext('localVar = 1;', 'myfile.vm'); console.log('localVar: ' + localVar + ', usingscript: ' + usingscript); evaled = eval('localVar = 1;'); console.log('localVar: ' + localVar + ', evaled: ' + evaled); // localVar: 123, usingscript: 1 // localVar: 1, evaled: 1 `vm.runInThisContext` does not have access to the local scope, so `localVar` is unchanged. `eval` does have access to the local scope, so `localVar` is changed. In case of syntax error in `code`, `vm.runInThisContext` emits the syntax error to stderr and throws an exception. ## vm.runInNewContext(code, [sandbox], [filename]) `vm.runInNewContext` compiles `code`, then runs it in `sandbox` and returns the result. Running code does not have access to local scope. The object `sandbox` will be used as the global object for `code`. `sandbox` and `filename` are optional, `filename` is only used in stack traces. Example: compile and execute code that increments a global variable and sets a new one. These globals are contained in the sandbox. var util = require('util'), vm = require('vm'), sandbox = { animal: 'cat', count: 2 }; vm.runInNewContext('count += 1; name = "kitty"', sandbox, 'myfile.vm'); console.log(util.inspect(sandbox)); // { animal: 'cat', count: 3, name: 'kitty' } Note that running untrusted code is a tricky business requiring great care. To prevent accidental global variable leakage, `vm.runInNewContext` is quite useful, but safely running untrusted code requires a separate process. In case of syntax error in `code`, `vm.runInNewContext` emits the syntax error to stderr and throws an exception. ## vm.runInContext(code, context, [filename]) `vm.runInContext` compiles `code`, then runs it in `context` and returns the result. A (V8) context comprises a global object, together with a set of built-in objects and functions. Running code does not have access to local scope and the global object held within `context` will be used as the global object for `code`. `filename` is optional, it's used only in stack traces. Example: compile and execute code in a existing context. var util = require('util'), vm = require('vm'), initSandbox = { animal: 'cat', count: 2 }, context = vm.createContext(initSandbox); vm.runInContext('count += 1; name = "CATT"', context, 'myfile.vm'); console.log(util.inspect(context)); // { animal: 'cat', count: 3, name: 'CATT' } Note that `createContext` will perform a shallow clone of the supplied sandbox object in order to initialize the global object of the freshly constructed context. Note that running untrusted code is a tricky business requiring great care. To prevent accidental global variable leakage, `vm.runInContext` is quite useful, but safely running untrusted code requires a separate process. In case of syntax error in `code`, `vm.runInContext` emits the syntax error to stderr and throws an exception. ## vm.createContext([initSandbox]) `vm.createContext` creates a new context which is suitable for use as the 2nd argument of a subsequent call to `vm.runInContext`. A (V8) context comprises a global object together with a set of build-in objects and functions. The optional argument `initSandbox` will be shallow-copied to seed the initial contents of the global object used by the context. ## vm.createScript(code, [filename]) `createScript` compiles `code` but does not run it. Instead, it returns a `vm.Script` object representing this compiled code. This script can be run later many times using methods below. The returned script is not bound to any global object. It is bound before each run, just for that run. `filename` is optional, it's only used in stack traces. In case of syntax error in `code`, `createScript` prints the syntax error to stderr and throws an exception. ## Class: Script A class for running scripts. Returned by vm.createScript. ### script.runInThisContext() Similar to `vm.runInThisContext` but a method of a precompiled `Script` object. `script.runInThisContext` runs the code of `script` and returns the result. Running code does not have access to local scope, but does have access to the `global` object (v8: in actual context). Example of using `script.runInThisContext` to compile code once and run it multiple times: var vm = require('vm'); globalVar = 0; var script = vm.createScript('globalVar += 1', 'myfile.vm'); for (var i = 0; i < 1000 ; i += 1) { script.runInThisContext(); } console.log(globalVar); // 1000 ### script.runInNewContext([sandbox]) Similar to `vm.runInNewContext` a method of a precompiled `Script` object. `script.runInNewContext` runs the code of `script` with `sandbox` as the global object and returns the result. Running code does not have access to local scope. `sandbox` is optional. Example: compile code that increments a global variable and sets one, then execute this code multiple times. These globals are contained in the sandbox. var util = require('util'), vm = require('vm'), sandbox = { animal: 'cat', count: 2 }; var script = vm.createScript('count += 1; name = "kitty"', 'myfile.vm'); for (var i = 0; i < 10 ; i += 1) { script.runInNewContext(sandbox); } console.log(util.inspect(sandbox)); // { animal: 'cat', count: 12, name: 'kitty' } Note that running untrusted code is a tricky business requiring great care. To prevent accidental global variable leakage, `script.runInNewContext` is quite useful, but safely running untrusted code requires a separate process. node-v0.10.25~dfsg2/doc/api/zlib.html0000644000000000000000000004710312270264601015765 0ustar rootroot Zlib Node.js v0.10.25 Manual & Documentation

    Node.js v0.10.25 Manual & Documentation


    Zlib#

    Stability: 3 - Stable

    You can access this module with:

    var zlib = require('zlib');

    This provides bindings to Gzip/Gunzip, Deflate/Inflate, and DeflateRaw/InflateRaw classes. Each class takes the same options, and is a readable/writable Stream.

    Examples#

    Compressing or decompressing a file can be done by piping an fs.ReadStream into a zlib stream, then into an fs.WriteStream.

    var gzip = zlib.createGzip();
    var fs = require('fs');
    var inp = fs.createReadStream('input.txt');
    var out = fs.createWriteStream('input.txt.gz');
    
    inp.pipe(gzip).pipe(out);

    Compressing or decompressing data in one step can be done by using the convenience methods.

    var input = '.................................';
    zlib.deflate(input, function(err, buffer) {
      if (!err) {
        console.log(buffer.toString('base64'));
      }
    });
    
    var buffer = new Buffer('eJzT0yMAAGTvBe8=', 'base64');
    zlib.unzip(buffer, function(err, buffer) {
      if (!err) {
        console.log(buffer.toString());
      }
    });

    To use this module in an HTTP client or server, use the accept-encoding on requests, and the content-encoding header on responses.

    Note: these examples are drastically simplified to show the basic concept. Zlib encoding can be expensive, and the results ought to be cached. See Memory Usage Tuning below for more information on the speed/memory/compression tradeoffs involved in zlib usage.

    // client request example
    var zlib = require('zlib');
    var http = require('http');
    var fs = require('fs');
    var request = http.get({ host: 'izs.me',
                             path: '/',
                             port: 80,
                             headers: { 'accept-encoding': 'gzip,deflate' } });
    request.on('response', function(response) {
      var output = fs.createWriteStream('izs.me_index.html');
    
      switch (response.headers['content-encoding']) {
        // or, just use zlib.createUnzip() to handle both cases
        case 'gzip':
          response.pipe(zlib.createGunzip()).pipe(output);
          break;
        case 'deflate':
          response.pipe(zlib.createInflate()).pipe(output);
          break;
        default:
          response.pipe(output);
          break;
      }
    });
    
    // server example
    // Running a gzip operation on every request is quite expensive.
    // It would be much more efficient to cache the compressed buffer.
    var zlib = require('zlib');
    var http = require('http');
    var fs = require('fs');
    http.createServer(function(request, response) {
      var raw = fs.createReadStream('index.html');
      var acceptEncoding = request.headers['accept-encoding'];
      if (!acceptEncoding) {
        acceptEncoding = '';
      }
    
      // Note: this is not a conformant accept-encoding parser.
      // See http://www.w3.org/Protocols/rfc2616/rfc2616-sec14.html#sec14.3
      if (acceptEncoding.match(/\bdeflate\b/)) {
        response.writeHead(200, { 'content-encoding': 'deflate' });
        raw.pipe(zlib.createDeflate()).pipe(response);
      } else if (acceptEncoding.match(/\bgzip\b/)) {
        response.writeHead(200, { 'content-encoding': 'gzip' });
        raw.pipe(zlib.createGzip()).pipe(response);
      } else {
        response.writeHead(200, {});
        raw.pipe(response);
      }
    }).listen(1337);

    zlib.createGzip([options])#

    Returns a new Gzip object with an options.

    zlib.createGunzip([options])#

    Returns a new Gunzip object with an options.

    zlib.createDeflate([options])#

    Returns a new Deflate object with an options.

    zlib.createInflate([options])#

    Returns a new Inflate object with an options.

    zlib.createDeflateRaw([options])#

    Returns a new DeflateRaw object with an options.

    zlib.createInflateRaw([options])#

    Returns a new InflateRaw object with an options.

    zlib.createUnzip([options])#

    Returns a new Unzip object with an options.

    Class: zlib.Zlib#

    Not exported by the zlib module. It is documented here because it is the base class of the compressor/decompressor classes.

    zlib.flush(callback)#

    Flush pending data. Don't call this frivolously, premature flushes negatively impact the effectiveness of the compression algorithm.

    zlib.reset()#

    Reset the compressor/decompressor to factory defaults. Only applicable to the inflate and deflate algorithms.

    Class: zlib.Gzip#

    Compress data using gzip.

    Class: zlib.Gunzip#

    Decompress a gzip stream.

    Class: zlib.Deflate#

    Compress data using deflate.

    Class: zlib.Inflate#

    Decompress a deflate stream.

    Class: zlib.DeflateRaw#

    Compress data using deflate, and do not append a zlib header.

    Class: zlib.InflateRaw#

    Decompress a raw deflate stream.

    Class: zlib.Unzip#

    Decompress either a Gzip- or Deflate-compressed stream by auto-detecting the header.

    Convenience Methods#

    All of these take a string or buffer as the first argument, and call the supplied callback with callback(error, result). The compression/decompression engine is created using the default settings in all convenience methods. To supply different options, use the zlib classes directly.

    zlib.deflate(buf, callback)#

    Compress a string with Deflate.

    zlib.deflateRaw(buf, callback)#

    Compress a string with DeflateRaw.

    zlib.gzip(buf, callback)#

    Compress a string with Gzip.

    zlib.gunzip(buf, callback)#

    Decompress a raw Buffer with Gunzip.

    zlib.inflate(buf, callback)#

    Decompress a raw Buffer with Inflate.

    zlib.inflateRaw(buf, callback)#

    Decompress a raw Buffer with InflateRaw.

    zlib.unzip(buf, callback)#

    Decompress a raw Buffer with Unzip.

    Options#

    Each class takes an options object. All options are optional. (The convenience methods use the default settings for all options.)

    Note that some options are only relevant when compressing, and are ignored by the decompression classes.

    • flush (default: zlib.Z_NO_FLUSH)
    • chunkSize (default: 16*1024)
    • windowBits
    • level (compression only)
    • memLevel (compression only)
    • strategy (compression only)
    • dictionary (deflate/inflate only, empty dictionary by default)

    See the description of deflateInit2 and inflateInit2 at

    http://zlib.net/manual.html#Advanced for more information on these.

    Memory Usage Tuning#

    From zlib/zconf.h, modified to node's usage:

    The memory requirements for deflate are (in bytes):

    (1 << (windowBits+2)) +  (1 << (memLevel+9))

    that is: 128K for windowBits=15 + 128K for memLevel = 8 (default values) plus a few kilobytes for small objects.

    For example, if you want to reduce the default memory requirements from 256K to 128K, set the options to:

    { windowBits: 14, memLevel: 7 }

    Of course this will generally degrade compression (there's no free lunch).

    The memory requirements for inflate are (in bytes)

    1 << windowBits

    that is, 32K for windowBits=15 (default value) plus a few kilobytes for small objects.

    This is in addition to a single internal output slab buffer of size chunkSize, which defaults to 16K.

    The speed of zlib compression is affected most dramatically by the level setting. A higher level will result in better compression, but will take longer to complete. A lower level will result in less compression, but will be much faster.

    In general, greater memory usage options will mean that node has to make fewer calls to zlib, since it'll be able to process more data in a single write operation. So, this is another factor that affects the speed, at the cost of memory usage.

    Constants#

    All of the constants defined in zlib.h are also defined on require('zlib'). In the normal course of operations, you will not need to ever set any of these. They are documented here so that their presence is not surprising. This section is taken almost directly from the zlib documentation. See

    http://zlib.net/manual.html#Constants for more details.

    Allowed flush values.

    • zlib.Z_NO_FLUSH
    • zlib.Z_PARTIAL_FLUSH
    • zlib.Z_SYNC_FLUSH
    • zlib.Z_FULL_FLUSH
    • zlib.Z_FINISH
    • zlib.Z_BLOCK
    • zlib.Z_TREES

    Return codes for the compression/decompression functions. Negative values are errors, positive values are used for special but normal events.

    • zlib.Z_OK
    • zlib.Z_STREAM_END
    • zlib.Z_NEED_DICT
    • zlib.Z_ERRNO
    • zlib.Z_STREAM_ERROR
    • zlib.Z_DATA_ERROR
    • zlib.Z_MEM_ERROR
    • zlib.Z_BUF_ERROR
    • zlib.Z_VERSION_ERROR

    Compression levels.

    • zlib.Z_NO_COMPRESSION
    • zlib.Z_BEST_SPEED
    • zlib.Z_BEST_COMPRESSION
    • zlib.Z_DEFAULT_COMPRESSION

    Compression strategy.

    • zlib.Z_FILTERED
    • zlib.Z_HUFFMAN_ONLY
    • zlib.Z_RLE
    • zlib.Z_FIXED
    • zlib.Z_DEFAULT_STRATEGY

    Possible values of the data_type field.

    • zlib.Z_BINARY
    • zlib.Z_TEXT
    • zlib.Z_ASCII
    • zlib.Z_UNKNOWN

    The deflate compression method (the only one supported in this version).

    • zlib.Z_DEFLATED

    For initializing zalloc, zfree, opaque.

    • zlib.Z_NULL
    node-v0.10.25~dfsg2/doc/api/string_decoder.json0000644000000000000000000000352712270264601020027 0ustar rootroot{ "source": "doc/api/string_decoder.markdown", "modules": [ { "textRaw": "StringDecoder", "name": "stringdecoder", "stability": 3, "stabilityText": "Stable", "desc": "

    To use this module, do require('string_decoder'). StringDecoder decodes a\nbuffer to a string. It is a simple interface to buffer.toString() but provides\nadditional support for utf8.\n\n

    \n
    var StringDecoder = require('string_decoder').StringDecoder;\nvar decoder = new StringDecoder('utf8');\n\nvar cent = new Buffer([0xC2, 0xA2]);\nconsole.log(decoder.write(cent));\n\nvar euro = new Buffer([0xE2, 0x82, 0xAC]);\nconsole.log(decoder.write(euro));
    \n", "classes": [ { "textRaw": "Class: StringDecoder", "type": "class", "name": "StringDecoder", "desc": "

    Accepts a single argument, encoding which defaults to utf8.\n\n

    \n", "methods": [ { "textRaw": "decoder.write(buffer)", "type": "method", "name": "write", "desc": "

    Returns a decoded string.\n\n

    \n", "signatures": [ { "params": [ { "name": "buffer" } ] } ] }, { "textRaw": "decoder.end()", "type": "method", "name": "end", "desc": "

    Returns any trailing bytes that were left in the buffer.\n

    \n", "signatures": [ { "params": [] } ] } ] } ], "type": "module", "displayName": "StringDecoder" } ] } node-v0.10.25~dfsg2/doc/api/dns.json0000644000000000000000000002701612270264601015617 0ustar rootroot{ "source": "doc/api/dns.markdown", "modules": [ { "textRaw": "DNS", "name": "dns", "stability": 3, "stabilityText": "Stable", "desc": "

    Use require('dns') to access this module. All methods in the dns module\nuse C-Ares except for dns.lookup which uses getaddrinfo(3) in a thread\npool. C-Ares is much faster than getaddrinfo but the system resolver is\nmore consistent with how other programs operate. When a user does\nnet.connect(80, 'google.com') or http.get({ host: 'google.com' }) the\ndns.lookup method is used. Users who need to do a large number of lookups\nquickly should use the methods that go through C-Ares.\n\n

    \n

    Here is an example which resolves 'www.google.com' then reverse\nresolves the IP addresses which are returned.\n\n

    \n
    var dns = require('dns');\n\ndns.resolve4('www.google.com', function (err, addresses) {\n  if (err) throw err;\n\n  console.log('addresses: ' + JSON.stringify(addresses));\n\n  addresses.forEach(function (a) {\n    dns.reverse(a, function (err, domains) {\n      if (err) {\n        throw err;\n      }\n\n      console.log('reverse for ' + a + ': ' + JSON.stringify(domains));\n    });\n  });\n});
    \n", "methods": [ { "textRaw": "dns.lookup(domain, [family], callback)", "type": "method", "name": "lookup", "desc": "

    Resolves a domain (e.g. 'google.com') into the first found A (IPv4) or\nAAAA (IPv6) record.\nThe family can be the integer 4 or 6. Defaults to null that indicates\nboth Ip v4 and v6 address family.\n\n

    \n

    The callback has arguments (err, address, family). The address argument\nis a string representation of a IP v4 or v6 address. The family argument\nis either the integer 4 or 6 and denotes the family of address (not\nnecessarily the value initially passed to lookup).\n\n

    \n

    On error, err is an Error object, where err.code is the error code.\nKeep in mind that err.code will be set to 'ENOENT' not only when\nthe domain does not exist but also when the lookup fails in other ways\nsuch as no available file descriptors.\n\n\n

    \n", "signatures": [ { "params": [ { "name": "domain" }, { "name": "family", "optional": true }, { "name": "callback" } ] } ] }, { "textRaw": "dns.resolve(domain, [rrtype], callback)", "type": "method", "name": "resolve", "desc": "

    Resolves a domain (e.g. 'google.com') into an array of the record types\nspecified by rrtype. Valid rrtypes are 'A' (IPV4 addresses, default),\n'AAAA' (IPV6 addresses), 'MX' (mail exchange records), 'TXT' (text\nrecords), 'SRV' (SRV records), 'PTR' (used for reverse IP lookups),\n'NS' (name server records) and 'CNAME' (canonical name records).\n\n

    \n

    The callback has arguments (err, addresses). The type of each item\nin addresses is determined by the record type, and described in the\ndocumentation for the corresponding lookup methods below.\n\n

    \n

    On error, err is an Error object, where err.code is\none of the error codes listed below.\n\n\n

    \n", "signatures": [ { "params": [ { "name": "domain" }, { "name": "rrtype", "optional": true }, { "name": "callback" } ] } ] }, { "textRaw": "dns.resolve4(domain, callback)", "type": "method", "name": "resolve4", "desc": "

    The same as dns.resolve(), but only for IPv4 queries (A records).\naddresses is an array of IPv4 addresses (e.g.\n['74.125.79.104', '74.125.79.105', '74.125.79.106']).\n\n

    \n", "signatures": [ { "params": [ { "name": "domain" }, { "name": "callback" } ] } ] }, { "textRaw": "dns.resolve6(domain, callback)", "type": "method", "name": "resolve6", "desc": "

    The same as dns.resolve4() except for IPv6 queries (an AAAA query).\n\n\n

    \n", "signatures": [ { "params": [ { "name": "domain" }, { "name": "callback" } ] } ] }, { "textRaw": "dns.resolveMx(domain, callback)", "type": "method", "name": "resolveMx", "desc": "

    The same as dns.resolve(), but only for mail exchange queries (MX records).\n\n

    \n

    addresses is an array of MX records, each with a priority and an exchange\nattribute (e.g. [{'priority': 10, 'exchange': 'mx.example.com'},...]).\n\n

    \n", "signatures": [ { "params": [ { "name": "domain" }, { "name": "callback" } ] } ] }, { "textRaw": "dns.resolveTxt(domain, callback)", "type": "method", "name": "resolveTxt", "desc": "

    The same as dns.resolve(), but only for text queries (TXT records).\naddresses is an array of the text records available for domain (e.g.,\n['v=spf1 ip4:0.0.0.0 ~all']).\n\n

    \n", "signatures": [ { "params": [ { "name": "domain" }, { "name": "callback" } ] } ] }, { "textRaw": "dns.resolveSrv(domain, callback)", "type": "method", "name": "resolveSrv", "desc": "

    The same as dns.resolve(), but only for service records (SRV records).\naddresses is an array of the SRV records available for domain. Properties\nof SRV records are priority, weight, port, and name (e.g.,\n[{'priority': 10, {'weight': 5, 'port': 21223, 'name': 'service.example.com'}, ...]).\n\n

    \n", "signatures": [ { "params": [ { "name": "domain" }, { "name": "callback" } ] } ] }, { "textRaw": "dns.resolveNs(domain, callback)", "type": "method", "name": "resolveNs", "desc": "

    The same as dns.resolve(), but only for name server records (NS records).\naddresses is an array of the name server records available for domain\n(e.g., ['ns1.example.com', 'ns2.example.com']).\n\n

    \n", "signatures": [ { "params": [ { "name": "domain" }, { "name": "callback" } ] } ] }, { "textRaw": "dns.resolveCname(domain, callback)", "type": "method", "name": "resolveCname", "desc": "

    The same as dns.resolve(), but only for canonical name records (CNAME\nrecords). addresses is an array of the canonical name records available for\ndomain (e.g., ['bar.example.com']).\n\n

    \n", "signatures": [ { "params": [ { "name": "domain" }, { "name": "callback" } ] } ] }, { "textRaw": "dns.reverse(ip, callback)", "type": "method", "name": "reverse", "desc": "

    Reverse resolves an ip address to an array of domain names.\n\n

    \n

    The callback has arguments (err, domains).\n\n

    \n

    On error, err is an Error object, where err.code is\none of the error codes listed below.\n\n

    \n", "signatures": [ { "params": [ { "name": "ip" }, { "name": "callback" } ] } ] } ], "modules": [ { "textRaw": "Error codes", "name": "error_codes", "desc": "

    Each DNS query can return one of the following error codes:\n\n

    \n
      \n
    • dns.NODATA: DNS server returned answer with no data.
    • \n
    • dns.FORMERR: DNS server claims query was misformatted.
    • \n
    • dns.SERVFAIL: DNS server returned general failure.
    • \n
    • dns.NOTFOUND: Domain name not found.
    • \n
    • dns.NOTIMP: DNS server does not implement requested operation.
    • \n
    • dns.REFUSED: DNS server refused query.
    • \n
    • dns.BADQUERY: Misformatted DNS query.
    • \n
    • dns.BADNAME: Misformatted domain name.
    • \n
    • dns.BADFAMILY: Unsupported address family.
    • \n
    • dns.BADRESP: Misformatted DNS reply.
    • \n
    • dns.CONNREFUSED: Could not contact DNS servers.
    • \n
    • dns.TIMEOUT: Timeout while contacting DNS servers.
    • \n
    • dns.EOF: End of file.
    • \n
    • dns.FILE: Error reading file.
    • \n
    • dns.NOMEM: Out of memory.
    • \n
    • dns.DESTRUCTION: Channel is being destroyed.
    • \n
    • dns.BADSTR: Misformatted string.
    • \n
    • dns.BADFLAGS: Illegal flags specified.
    • \n
    • dns.NONAME: Given hostname is not numeric.
    • \n
    • dns.BADHINTS: Illegal hints flags specified.
    • \n
    • dns.NOTINITIALIZED: c-ares library initialization not yet performed.
    • \n
    • dns.LOADIPHLPAPI: Error loading iphlpapi.dll.
    • \n
    • dns.ADDRGETNETWORKPARAMS: Could not find GetNetworkParams function.
    • \n
    • dns.CANCELLED: DNS query cancelled.
    • \n
    \n", "type": "module", "displayName": "Error codes" } ], "type": "module", "displayName": "DNS" } ] } node-v0.10.25~dfsg2/doc/api/child_process.markdown0000644000000000000000000005127312270121457020530 0ustar rootroot# Child Process Stability: 3 - Stable Node provides a tri-directional `popen(3)` facility through the `child_process` module. It is possible to stream data through a child's `stdin`, `stdout`, and `stderr` in a fully non-blocking way. (Note that some programs use line-buffered I/O internally. That doesn't affect node.js but it means data you send to the child process is not immediately consumed.) To create a child process use `require('child_process').spawn()` or `require('child_process').fork()`. The semantics of each are slightly different, and explained below. ## Class: ChildProcess `ChildProcess` is an [EventEmitter][]. Child processes always have three streams associated with them. `child.stdin`, `child.stdout`, and `child.stderr`. These may be shared with the stdio streams of the parent process, or they may be separate stream objects which can be piped to and from. The ChildProcess class is not intended to be used directly. Use the `spawn()` or `fork()` methods to create a Child Process instance. ### Event: 'error' * `err` {Error Object} the error. Emitted when: 1. The process could not be spawned, or 2. The process could not be killed, or 3. Sending a message to the child process failed for whatever reason. Note that the `exit`-event may or may not fire after an error has occured. If you are listening on both events to fire a function, remember to guard against calling your function twice. See also [`ChildProcess#kill()`](#child_process_child_kill_signal) and [`ChildProcess#send()`](#child_process_child_send_message_sendhandle). ### Event: 'exit' * `code` {Number} the exit code, if it exited normally. * `signal` {String} the signal passed to kill the child process, if it was killed by the parent. This event is emitted after the child process ends. If the process terminated normally, `code` is the final exit code of the process, otherwise `null`. If the process terminated due to receipt of a signal, `signal` is the string name of the signal, otherwise `null`. Note that the child process stdio streams might still be open. Also, note that node establishes signal handlers for `'SIGINT'` and `'SIGTERM`', so it will not terminate due to receipt of those signals, it will exit. See `waitpid(2)`. ### Event: 'close' * `code` {Number} the exit code, if it exited normally. * `signal` {String} the signal passed to kill the child process, if it was killed by the parent. This event is emitted when the stdio streams of a child process have all terminated. This is distinct from 'exit', since multiple processes might share the same stdio streams. ### Event: 'disconnect' This event is emitted after calling the `.disconnect()` method in the parent or in the child. After disconnecting it is no longer possible to send messages, and the `.connected` property is false. ### Event: 'message' * `message` {Object} a parsed JSON object or primitive value * `sendHandle` {Handle object} a Socket or Server object Messages send by `.send(message, [sendHandle])` are obtained using the `message` event. ### child.stdin * {Stream object} A `Writable Stream` that represents the child process's `stdin`. Closing this stream via `end()` often causes the child process to terminate. If the child stdio streams are shared with the parent, then this will not be set. ### child.stdout * {Stream object} A `Readable Stream` that represents the child process's `stdout`. If the child stdio streams are shared with the parent, then this will not be set. ### child.stderr * {Stream object} A `Readable Stream` that represents the child process's `stderr`. If the child stdio streams are shared with the parent, then this will not be set. ### child.pid * {Integer} The PID of the child process. Example: var spawn = require('child_process').spawn, grep = spawn('grep', ['ssh']); console.log('Spawned child pid: ' + grep.pid); grep.stdin.end(); ### child.connected * {Boolean} Set to false after `.disconnect' is called If `.connected` is false, it is no longer possible to send messages. ### child.kill([signal]) * `signal` {String} Send a signal to the child process. If no argument is given, the process will be sent `'SIGTERM'`. See `signal(7)` for a list of available signals. var spawn = require('child_process').spawn, grep = spawn('grep', ['ssh']); grep.on('close', function (code, signal) { console.log('child process terminated due to receipt of signal '+signal); }); // send SIGHUP to process grep.kill('SIGHUP'); May emit an `'error'` event when the signal cannot be delivered. Sending a signal to a child process that has already exited is not an error but may have unforeseen consequences: if the PID (the process ID) has been reassigned to another process, the signal will be delivered to that process instead. What happens next is anyone's guess. Note that while the function is called `kill`, the signal delivered to the child process may not actually kill it. `kill` really just sends a signal to a process. See `kill(2)` ### child.send(message, [sendHandle]) * `message` {Object} * `sendHandle` {Handle object} When using `child_process.fork()` you can write to the child using `child.send(message, [sendHandle])` and messages are received by a `'message'` event on the child. For example: var cp = require('child_process'); var n = cp.fork(__dirname + '/sub.js'); n.on('message', function(m) { console.log('PARENT got message:', m); }); n.send({ hello: 'world' }); And then the child script, `'sub.js'` might look like this: process.on('message', function(m) { console.log('CHILD got message:', m); }); process.send({ foo: 'bar' }); In the child the `process` object will have a `send()` method, and `process` will emit objects each time it receives a message on its channel. Please note that the `send()` method on both the parent and child are synchronous - sending large chunks of data is not advised (pipes can be used instead, see [`child_process.spawn`](#child_process_child_process_spawn_command_args_options)). There is a special case when sending a `{cmd: 'NODE_foo'}` message. All messages containing a `NODE_` prefix in its `cmd` property will not be emitted in the `message` event, since they are internal messages used by node core. Messages containing the prefix are emitted in the `internalMessage` event, you should by all means avoid using this feature, it is subject to change without notice. The `sendHandle` option to `child.send()` is for sending a TCP server or socket object to another process. The child will receive the object as its second argument to the `message` event. Emits an `'error'` event if the message cannot be sent, for example because the child process has already exited. #### Example: sending server object Here is an example of sending a server: var child = require('child_process').fork('child.js'); // Open up the server object and send the handle. var server = require('net').createServer(); server.on('connection', function (socket) { socket.end('handled by parent'); }); server.listen(1337, function() { child.send('server', server); }); And the child would the receive the server object as: process.on('message', function(m, server) { if (m === 'server') { server.on('connection', function (socket) { socket.end('handled by child'); }); } }); Note that the server is now shared between the parent and child, this means that some connections will be handled by the parent and some by the child. For `dgram` servers the workflow is exactly the same. Here you listen on a `message` event instead of `connection` and use `server.bind` instead of `server.listen`. (Currently only supported on UNIX platforms.) #### Example: sending socket object Here is an example of sending a socket. It will spawn two children and handle connections with the remote address `74.125.127.100` as VIP by sending the socket to a "special" child process. Other sockets will go to a "normal" process. var normal = require('child_process').fork('child.js', ['normal']); var special = require('child_process').fork('child.js', ['special']); // Open up the server and send sockets to child var server = require('net').createServer(); server.on('connection', function (socket) { // if this is a VIP if (socket.remoteAddress === '74.125.127.100') { special.send('socket', socket); return; } // just the usual dudes normal.send('socket', socket); }); server.listen(1337); The `child.js` could look like this: process.on('message', function(m, socket) { if (m === 'socket') { socket.end('You were handled as a ' + process.argv[2] + ' person'); } }); Note that once a single socket has been sent to a child the parent can no longer keep track of when the socket is destroyed. To indicate this condition the `.connections` property becomes `null`. It is also recommended not to use `.maxConnections` in this condition. ### child.disconnect() Close the IPC channel between parent and child, allowing the child to exit gracefully once there are no other connections keeping it alive. After calling this method the `.connected` flag will be set to `false` in both the parent and child, and it is no longer possible to send messages. The 'disconnect' event will be emitted when there are no messages in the process of being received, most likely immediately. Note that you can also call `process.disconnect()` in the child process. ## child_process.spawn(command, [args], [options]) * `command` {String} The command to run * `args` {Array} List of string arguments * `options` {Object} * `cwd` {String} Current working directory of the child process * `stdio` {Array|String} Child's stdio configuration. (See below) * `customFds` {Array} **Deprecated** File descriptors for the child to use for stdio. (See below) * `env` {Object} Environment key-value pairs * `detached` {Boolean} The child will be a process group leader. (See below) * `uid` {Number} Sets the user identity of the process. (See setuid(2).) * `gid` {Number} Sets the group identity of the process. (See setgid(2).) * return: {ChildProcess object} Launches a new process with the given `command`, with command line arguments in `args`. If omitted, `args` defaults to an empty Array. The third argument is used to specify additional options, which defaults to: { cwd: undefined, env: process.env } `cwd` allows you to specify the working directory from which the process is spawned. Use `env` to specify environment variables that will be visible to the new process. Example of running `ls -lh /usr`, capturing `stdout`, `stderr`, and the exit code: var spawn = require('child_process').spawn, ls = spawn('ls', ['-lh', '/usr']); ls.stdout.on('data', function (data) { console.log('stdout: ' + data); }); ls.stderr.on('data', function (data) { console.log('stderr: ' + data); }); ls.on('close', function (code) { console.log('child process exited with code ' + code); }); Example: A very elaborate way to run 'ps ax | grep ssh' var spawn = require('child_process').spawn, ps = spawn('ps', ['ax']), grep = spawn('grep', ['ssh']); ps.stdout.on('data', function (data) { grep.stdin.write(data); }); ps.stderr.on('data', function (data) { console.log('ps stderr: ' + data); }); ps.on('close', function (code) { if (code !== 0) { console.log('ps process exited with code ' + code); } grep.stdin.end(); }); grep.stdout.on('data', function (data) { console.log('' + data); }); grep.stderr.on('data', function (data) { console.log('grep stderr: ' + data); }); grep.on('close', function (code) { if (code !== 0) { console.log('grep process exited with code ' + code); } }); Example of checking for failed exec: var spawn = require('child_process').spawn, child = spawn('bad_command'); child.stderr.setEncoding('utf8'); child.stderr.on('data', function (data) { if (/^execvp\(\)/.test(data)) { console.log('Failed to start child process.'); } }); Note that if spawn receives an empty options object, it will result in spawning the process with an empty environment rather than using `process.env`. This due to backwards compatibility issues with a deprecated API. The 'stdio' option to `child_process.spawn()` is an array where each index corresponds to a fd in the child. The value is one of the following: 1. `'pipe'` - Create a pipe between the child process and the parent process. The parent end of the pipe is exposed to the parent as a property on the `child_process` object as `ChildProcess.stdio[fd]`. Pipes created for fds 0 - 2 are also available as ChildProcess.stdin, ChildProcess.stdout and ChildProcess.stderr, respectively. 2. `'ipc'` - Create an IPC channel for passing messages/file descriptors between parent and child. A ChildProcess may have at most *one* IPC stdio file descriptor. Setting this option enables the ChildProcess.send() method. If the child writes JSON messages to this file descriptor, then this will trigger ChildProcess.on('message'). If the child is a Node.js program, then the presence of an IPC channel will enable process.send() and process.on('message'). 3. `'ignore'` - Do not set this file descriptor in the child. Note that Node will always open fd 0 - 2 for the processes it spawns. When any of these is ignored node will open `/dev/null` and attach it to the child's fd. 4. `Stream` object - Share a readable or writable stream that refers to a tty, file, socket, or a pipe with the child process. The stream's underlying file descriptor is duplicated in the child process to the fd that corresponds to the index in the `stdio` array. Note that the stream must have an underlying descriptor (file streams do not until the `'open'` event has occurred). 5. Positive integer - The integer value is interpreted as a file descriptor that is is currently open in the parent process. It is shared with the child process, similar to how `Stream` objects can be shared. 6. `null`, `undefined` - Use default value. For stdio fds 0, 1 and 2 (in other words, stdin, stdout, and stderr) a pipe is created. For fd 3 and up, the default is `'ignore'`. As a shorthand, the `stdio` argument may also be one of the following strings, rather than an array: * `ignore` - `['ignore', 'ignore', 'ignore']` * `pipe` - `['pipe', 'pipe', 'pipe']` * `inherit` - `[process.stdin, process.stdout, process.stderr]` or `[0,1,2]` Example: var spawn = require('child_process').spawn; // Child will use parent's stdios spawn('prg', [], { stdio: 'inherit' }); // Spawn child sharing only stderr spawn('prg', [], { stdio: ['pipe', 'pipe', process.stderr] }); // Open an extra fd=4, to interact with programs present a // startd-style interface. spawn('prg', [], { stdio: ['pipe', null, null, null, 'pipe'] }); If the `detached` option is set, the child process will be made the leader of a new process group. This makes it possible for the child to continue running after the parent exits. By default, the parent will wait for the detached child to exit. To prevent the parent from waiting for a given `child`, use the `child.unref()` method, and the parent's event loop will not include the child in its reference count. Example of detaching a long-running process and redirecting its output to a file: var fs = require('fs'), spawn = require('child_process').spawn, out = fs.openSync('./out.log', 'a'), err = fs.openSync('./out.log', 'a'); var child = spawn('prg', [], { detached: true, stdio: [ 'ignore', out, err ] }); child.unref(); When using the `detached` option to start a long-running process, the process will not stay running in the background unless it is provided with a `stdio` configuration that is not connected to the parent. If the parent's `stdio` is inherited, the child will remain attached to the controlling terminal. There is a deprecated option called `customFds` which allows one to specify specific file descriptors for the stdio of the child process. This API was not portable to all platforms and therefore removed. With `customFds` it was possible to hook up the new process' `[stdin, stdout, stderr]` to existing streams; `-1` meant that a new stream should be created. Use at your own risk. See also: `child_process.exec()` and `child_process.fork()` ## child_process.exec(command, [options], callback) * `command` {String} The command to run, with space-separated arguments * `options` {Object} * `cwd` {String} Current working directory of the child process * `env` {Object} Environment key-value pairs * `encoding` {String} (Default: 'utf8') * `timeout` {Number} (Default: 0) * `maxBuffer` {Number} (Default: `200*1024`) * `killSignal` {String} (Default: 'SIGTERM') * `callback` {Function} called with the output when process terminates * `error` {Error} * `stdout` {Buffer} * `stderr` {Buffer} * Return: ChildProcess object Runs a command in a shell and buffers the output. var exec = require('child_process').exec, child; child = exec('cat *.js bad_file | wc -l', function (error, stdout, stderr) { console.log('stdout: ' + stdout); console.log('stderr: ' + stderr); if (error !== null) { console.log('exec error: ' + error); } }); The callback gets the arguments `(error, stdout, stderr)`. On success, `error` will be `null`. On error, `error` will be an instance of `Error` and `err.code` will be the exit code of the child process, and `err.signal` will be set to the signal that terminated the process. There is a second optional argument to specify several options. The default options are { encoding: 'utf8', timeout: 0, maxBuffer: 200*1024, killSignal: 'SIGTERM', cwd: null, env: null } If `timeout` is greater than 0, then it will kill the child process if it runs longer than `timeout` milliseconds. The child process is killed with `killSignal` (default: `'SIGTERM'`). `maxBuffer` specifies the largest amount of data allowed on stdout or stderr - if this value is exceeded then the child process is killed. ## child_process.execFile(file, [args], [options], [callback]) * `file` {String} The filename of the program to run * `args` {Array} List of string arguments * `options` {Object} * `cwd` {String} Current working directory of the child process * `env` {Object} Environment key-value pairs * `encoding` {String} (Default: 'utf8') * `timeout` {Number} (Default: 0) * `maxBuffer` {Number} (Default: 200\*1024) * `killSignal` {String} (Default: 'SIGTERM') * `callback` {Function} called with the output when process terminates * `error` {Error} * `stdout` {Buffer} * `stderr` {Buffer} * Return: ChildProcess object This is similar to `child_process.exec()` except it does not execute a subshell but rather the specified file directly. This makes it slightly leaner than `child_process.exec`. It has the same options. ## child_process.fork(modulePath, [args], [options]) * `modulePath` {String} The module to run in the child * `args` {Array} List of string arguments * `options` {Object} * `cwd` {String} Current working directory of the child process * `env` {Object} Environment key-value pairs * `encoding` {String} (Default: 'utf8') * `execPath` {String} Executable used to create the child process * `execArgv` {Array} List of string arguments passed to the executable (Default: `process.execArgv`) * `silent` {Boolean} If true, stdin, stdout, and stderr of the child will be piped to the parent, otherwise they will be inherited from the parent, see the "pipe" and "inherit" options for `spawn()`'s `stdio` for more details (default is false) * Return: ChildProcess object This is a special case of the `spawn()` functionality for spawning Node processes. In addition to having all the methods in a normal ChildProcess instance, the returned object has a communication channel built-in. See `child.send(message, [sendHandle])` for details. These child Nodes are still whole new instances of V8. Assume at least 30ms startup and 10mb memory for each new Node. That is, you cannot create many thousands of them. The `execPath` property in the `options` object allows for a process to be created for the child rather than the current `node` executable. This should be done with care and by default will talk over the fd represented an environmental variable `NODE_CHANNEL_FD` on the child process. The input and output on this fd is expected to be line delimited JSON objects. [EventEmitter]: events.html#events_class_events_eventemitter node-v0.10.25~dfsg2/doc/api/net.json0000644000000000000000000012302312270264601015614 0ustar rootroot{ "source": "doc/api/net.markdown", "modules": [ { "textRaw": "net", "name": "net", "stability": 3, "stabilityText": "Stable", "desc": "

    The net module provides you with an asynchronous network wrapper. It contains\nmethods for creating both servers and clients (called streams). You can include\nthis module with require('net');\n\n

    \n", "methods": [ { "textRaw": "net.createServer([options], [connectionListener])", "type": "method", "name": "createServer", "desc": "

    Creates a new TCP server. The connectionListener argument is\nautomatically set as a listener for the ['connection'][] event.\n\n

    \n

    options is an object with the following defaults:\n\n

    \n
    { allowHalfOpen: false\n}
    \n

    If allowHalfOpen is true, then the socket won't automatically send a FIN\npacket when the other end of the socket sends a FIN packet. The socket becomes\nnon-readable, but still writable. You should call the end() method explicitly.\nSee ['end'][] event for more information.\n\n

    \n

    Here is an example of an echo server which listens for connections\non port 8124:\n\n

    \n
    var net = require('net');\nvar server = net.createServer(function(c) { //'connection' listener\n  console.log('server connected');\n  c.on('end', function() {\n    console.log('server disconnected');\n  });\n  c.write('hello\\r\\n');\n  c.pipe(c);\n});\nserver.listen(8124, function() { //'listening' listener\n  console.log('server bound');\n});
    \n

    Test this by using telnet:\n\n

    \n
    telnet localhost 8124
    \n

    To listen on the socket /tmp/echo.sock the third line from the last would\njust be changed to\n\n

    \n
    server.listen('/tmp/echo.sock', function() { //'listening' listener
    \n

    Use nc to connect to a UNIX domain socket server:\n\n

    \n
    nc -U /tmp/echo.sock
    \n", "signatures": [ { "params": [ { "name": "options", "optional": true }, { "name": "connectionListener", "optional": true } ] } ] }, { "textRaw": "net.connect(options, [connectionListener])", "type": "method", "name": "connect", "desc": "

    Constructs a new socket object and opens the socket to the given location.\nWhen the socket is established, the ['connect'][] event will be emitted.\n\n

    \n

    For TCP sockets, options argument should be an object which specifies:\n\n

    \n
      \n
    • port: Port the client should connect to (Required).

      \n
    • \n
    • host: Host the client should connect to. Defaults to 'localhost'.

      \n
    • \n
    • localAddress: Local interface to bind to for network connections.

      \n
    • \n
    \n

    For UNIX domain sockets, options argument should be an object which specifies:\n\n

    \n
      \n
    • path: Path the client should connect to (Required).
    • \n
    \n

    Common options are:\n\n

    \n
      \n
    • allowHalfOpen: if true, the socket won't automatically send\na FIN packet when the other end of the socket sends a FIN packet.\nDefaults to false. See ['end'][] event for more information.
    • \n
    \n

    The connectListener parameter will be added as an listener for the\n['connect'][] event.\n\n

    \n

    Here is an example of a client of echo server as described previously:\n\n

    \n
    var net = require('net');\nvar client = net.connect({port: 8124},\n    function() { //'connect' listener\n  console.log('client connected');\n  client.write('world!\\r\\n');\n});\nclient.on('data', function(data) {\n  console.log(data.toString());\n  client.end();\n});\nclient.on('end', function() {\n  console.log('client disconnected');\n});
    \n

    To connect on the socket /tmp/echo.sock the second line would just be\nchanged to\n\n

    \n
    var client = net.connect({path: '/tmp/echo.sock'});
    \n", "signatures": [ { "params": [ { "name": "options" }, { "name": "connectionListener", "optional": true } ] }, { "params": [ { "name": "options" }, { "name": "connectionListener", "optional": true } ] } ] }, { "textRaw": "net.createConnection(options, [connectionListener])", "type": "method", "name": "createConnection", "desc": "

    Constructs a new socket object and opens the socket to the given location.\nWhen the socket is established, the ['connect'][] event will be emitted.\n\n

    \n

    For TCP sockets, options argument should be an object which specifies:\n\n

    \n
      \n
    • port: Port the client should connect to (Required).

      \n
    • \n
    • host: Host the client should connect to. Defaults to 'localhost'.

      \n
    • \n
    • localAddress: Local interface to bind to for network connections.

      \n
    • \n
    \n

    For UNIX domain sockets, options argument should be an object which specifies:\n\n

    \n
      \n
    • path: Path the client should connect to (Required).
    • \n
    \n

    Common options are:\n\n

    \n
      \n
    • allowHalfOpen: if true, the socket won't automatically send\na FIN packet when the other end of the socket sends a FIN packet.\nDefaults to false. See ['end'][] event for more information.
    • \n
    \n

    The connectListener parameter will be added as an listener for the\n['connect'][] event.\n\n

    \n

    Here is an example of a client of echo server as described previously:\n\n

    \n
    var net = require('net');\nvar client = net.connect({port: 8124},\n    function() { //'connect' listener\n  console.log('client connected');\n  client.write('world!\\r\\n');\n});\nclient.on('data', function(data) {\n  console.log(data.toString());\n  client.end();\n});\nclient.on('end', function() {\n  console.log('client disconnected');\n});
    \n

    To connect on the socket /tmp/echo.sock the second line would just be\nchanged to\n\n

    \n
    var client = net.connect({path: '/tmp/echo.sock'});
    \n", "signatures": [ { "params": [ { "name": "options" }, { "name": "connectionListener", "optional": true } ] } ] }, { "textRaw": "net.connect(port, [host], [connectListener])", "type": "method", "name": "connect", "desc": "

    Creates a TCP connection to port on host. If host is omitted,\n'localhost' will be assumed.\nThe connectListener parameter will be added as an listener for the\n['connect'][] event.\n\n

    \n", "signatures": [ { "params": [ { "name": "port" }, { "name": "host", "optional": true }, { "name": "connectListener", "optional": true } ] }, { "params": [ { "name": "port" }, { "name": "host", "optional": true }, { "name": "connectListener", "optional": true } ] } ] }, { "textRaw": "net.createConnection(port, [host], [connectListener])", "type": "method", "name": "createConnection", "desc": "

    Creates a TCP connection to port on host. If host is omitted,\n'localhost' will be assumed.\nThe connectListener parameter will be added as an listener for the\n['connect'][] event.\n\n

    \n", "signatures": [ { "params": [ { "name": "port" }, { "name": "host", "optional": true }, { "name": "connectListener", "optional": true } ] } ] }, { "textRaw": "net.connect(path, [connectListener])", "type": "method", "name": "connect", "desc": "

    Creates unix socket connection to path.\nThe connectListener parameter will be added as an listener for the\n['connect'][] event.\n\n

    \n", "signatures": [ { "params": [ { "name": "path" }, { "name": "connectListener", "optional": true } ] }, { "params": [ { "name": "path" }, { "name": "connectListener", "optional": true } ] } ] }, { "textRaw": "net.createConnection(path, [connectListener])", "type": "method", "name": "createConnection", "desc": "

    Creates unix socket connection to path.\nThe connectListener parameter will be added as an listener for the\n['connect'][] event.\n\n

    \n", "signatures": [ { "params": [ { "name": "path" }, { "name": "connectListener", "optional": true } ] } ] }, { "textRaw": "net.isIP(input)", "type": "method", "name": "isIP", "desc": "

    Tests if input is an IP address. Returns 0 for invalid strings,\nreturns 4 for IP version 4 addresses, and returns 6 for IP version 6 addresses.\n\n\n

    \n", "signatures": [ { "params": [ { "name": "input" } ] } ] }, { "textRaw": "net.isIPv4(input)", "type": "method", "name": "isIPv4", "desc": "

    Returns true if input is a version 4 IP address, otherwise returns false.\n\n\n

    \n", "signatures": [ { "params": [ { "name": "input" } ] } ] }, { "textRaw": "net.isIPv6(input)", "type": "method", "name": "isIPv6", "desc": "

    Returns true if input is a version 6 IP address, otherwise returns false.\n\n

    \n", "signatures": [ { "params": [ { "name": "input" } ] } ] } ], "classes": [ { "textRaw": "Class: net.Server", "type": "class", "name": "net.Server", "desc": "

    This class is used to create a TCP or UNIX server.\n\n

    \n", "methods": [ { "textRaw": "server.listen(port, [host], [backlog], [callback])", "type": "method", "name": "listen", "desc": "

    Begin accepting connections on the specified port and host. If the\nhost is omitted, the server will accept connections directed to any\nIPv4 address (INADDR_ANY). A port value of zero will assign a random port.\n\n

    \n

    Backlog is the maximum length of the queue of pending connections.\nThe actual length will be determined by your OS through sysctl settings such as\ntcp_max_syn_backlog and somaxconn on linux. The default value of this\nparameter is 511 (not 512).\n\n

    \n

    This function is asynchronous. When the server has been bound,\n['listening'][] event will be emitted. The last parameter callback\nwill be added as an listener for the ['listening'][] event.\n\n

    \n

    One issue some users run into is getting EADDRINUSE errors. This means that\nanother server is already running on the requested port. One way of handling this\nwould be to wait a second and then try again. This can be done with\n\n

    \n
    server.on('error', function (e) {\n  if (e.code == 'EADDRINUSE') {\n    console.log('Address in use, retrying...');\n    setTimeout(function () {\n      server.close();\n      server.listen(PORT, HOST);\n    }, 1000);\n  }\n});
    \n

    (Note: All sockets in Node set SO_REUSEADDR already)\n\n\n

    \n", "signatures": [ { "params": [ { "name": "port" }, { "name": "host", "optional": true }, { "name": "backlog", "optional": true }, { "name": "callback", "optional": true } ] } ] }, { "textRaw": "server.listen(path, [callback])", "type": "method", "name": "listen", "desc": "

    Start a UNIX socket server listening for connections on the given path.\n\n

    \n

    This function is asynchronous. When the server has been bound,\n['listening'][] event will be emitted. The last parameter callback\nwill be added as an listener for the ['listening'][] event.\n\n

    \n", "signatures": [ { "params": [ { "name": "path" }, { "name": "callback", "optional": true } ] } ] }, { "textRaw": "server.listen(handle, [callback])", "type": "method", "name": "listen", "signatures": [ { "params": [ { "textRaw": "`handle` {Object} ", "name": "handle", "type": "Object" }, { "textRaw": "`callback` {Function} ", "name": "callback", "type": "Function", "optional": true } ] }, { "params": [ { "name": "handle" }, { "name": "callback", "optional": true } ] } ], "desc": "

    The handle object can be set to either a server or socket (anything\nwith an underlying _handle member), or a {fd: <n>} object.\n\n

    \n

    This will cause the server to accept connections on the specified\nhandle, but it is presumed that the file descriptor or handle has\nalready been bound to a port or domain socket.\n\n

    \n

    Listening on a file descriptor is not supported on Windows.\n\n

    \n

    This function is asynchronous. When the server has been bound,\n'listening' event will be emitted.\nthe last parameter callback will be added as an listener for the\n'listening' event.\n\n

    \n" }, { "textRaw": "server.close([callback])", "type": "method", "name": "close", "desc": "

    Stops the server from accepting new connections and keeps existing\nconnections. This function is asynchronous, the server is finally\nclosed when all connections are ended and the server emits a 'close'\nevent. Optionally, you can pass a callback to listen for the 'close'\nevent.\n\n

    \n", "signatures": [ { "params": [ { "name": "callback", "optional": true } ] } ] }, { "textRaw": "server.address()", "type": "method", "name": "address", "desc": "

    Returns the bound address, the address family name and port of the server\nas reported by the operating system.\nUseful to find which port was assigned when giving getting an OS-assigned address.\nReturns an object with three properties, e.g.\n{ port: 12346, family: 'IPv4', address: '127.0.0.1' }\n\n

    \n

    Example:\n\n

    \n
    var server = net.createServer(function (socket) {\n  socket.end("goodbye\\n");\n});\n\n// grab a random port.\nserver.listen(function() {\n  address = server.address();\n  console.log("opened server on %j", address);\n});
    \n

    Don't call server.address() until the 'listening' event has been emitted.\n\n

    \n", "signatures": [ { "params": [] } ] }, { "textRaw": "server.unref()", "type": "method", "name": "unref", "desc": "

    Calling unref on a server will allow the program to exit if this is the only\nactive server in the event system. If the server is already unrefd calling\nunref again will have no effect.\n\n

    \n", "signatures": [ { "params": [] } ] }, { "textRaw": "server.ref()", "type": "method", "name": "ref", "desc": "

    Opposite of unref, calling ref on a previously unrefd server will not\nlet the program exit if it's the only server left (the default behavior). If\nthe server is refd calling ref again will have no effect.\n\n

    \n", "signatures": [ { "params": [] } ] }, { "textRaw": "server.getConnections(callback)", "type": "method", "name": "getConnections", "desc": "

    Asynchronously get the number of concurrent connections on the server. Works\nwhen sockets were sent to forks.\n\n

    \n

    Callback should take two arguments err and count.\n\n

    \n", "signatures": [ { "params": [ { "name": "callback" } ] } ] } ], "properties": [ { "textRaw": "server.maxConnections", "name": "maxConnections", "desc": "

    Set this property to reject connections when the server's connection count gets\nhigh.\n\n

    \n

    It is not recommended to use this option once a socket has been sent to a child\nwith child_process.fork().\n\n

    \n" }, { "textRaw": "server.connections", "name": "connections", "desc": "

    This function is deprecated; please use [server.getConnections()][] instead.\nThe number of concurrent connections on the server.\n\n

    \n

    This becomes null when sending a socket to a child with\nchild_process.fork(). To poll forks and get current number of active\nconnections use asynchronous server.getConnections instead.\n\n

    \n

    net.Server is an [EventEmitter][] with the following events:\n\n

    \n" } ], "events": [ { "textRaw": "Event: 'listening'", "type": "event", "name": "listening", "desc": "

    Emitted when the server has been bound after calling server.listen.\n\n

    \n", "params": [] }, { "textRaw": "Event: 'connection'", "type": "event", "name": "connection", "params": [], "desc": "

    Emitted when a new connection is made. socket is an instance of\nnet.Socket.\n\n

    \n" }, { "textRaw": "Event: 'close'", "type": "event", "name": "close", "desc": "

    Emitted when the server closes. Note that if connections exist, this\nevent is not emitted until all connections are ended.\n\n

    \n", "params": [] }, { "textRaw": "Event: 'error'", "type": "event", "name": "error", "params": [], "desc": "

    Emitted when an error occurs. The 'close' event will be called directly\nfollowing this event. See example in discussion of server.listen.\n\n

    \n" } ] }, { "textRaw": "Class: net.Socket", "type": "class", "name": "net.Socket", "desc": "

    This object is an abstraction of a TCP or UNIX socket. net.Socket\ninstances implement a duplex Stream interface. They can be created by the\nuser and used as a client (with connect()) or they can be created by Node\nand passed to the user through the 'connection' event of a server.\n\n

    \n", "methods": [ { "textRaw": "new net.Socket([options])", "type": "method", "name": "Socket", "desc": "

    Construct a new socket object.\n\n

    \n

    options is an object with the following defaults:\n\n

    \n
    { fd: null\n  allowHalfOpen: false,\n  readable: false,\n  writable: false\n}
    \n

    fd allows you to specify the existing file descriptor of socket.\nSet readable and/or writable to true to allow reads and/or writes on this\nsocket (NOTE: Works only when fd is passed).\nAbout allowHalfOpen, refer to createServer() and 'end' event.\n\n

    \n", "signatures": [ { "params": [ { "name": "options", "optional": true } ] } ] }, { "textRaw": "socket.connect(port, [host], [connectListener])", "type": "method", "name": "connect", "desc": "

    Opens the connection for a given socket. If port and host are given,\nthen the socket will be opened as a TCP socket, if host is omitted,\nlocalhost will be assumed. If a path is given, the socket will be\nopened as a unix socket to that path.\n\n

    \n

    Normally this method is not needed, as net.createConnection opens the\nsocket. Use this only if you are implementing a custom Socket.\n\n

    \n

    This function is asynchronous. When the ['connect'][] event is emitted the\nsocket is established. If there is a problem connecting, the 'connect' event\nwill not be emitted, the 'error' event will be emitted with the exception.\n\n

    \n

    The connectListener parameter will be added as an listener for the\n['connect'][] event.\n\n\n

    \n", "signatures": [ { "params": [ { "name": "path" }, { "name": "connectListener", "optional": true } ] }, { "params": [ { "name": "port" }, { "name": "host", "optional": true }, { "name": "connectListener", "optional": true } ] } ] }, { "textRaw": "socket.connect(path, [connectListener])", "type": "method", "name": "connect", "desc": "

    Opens the connection for a given socket. If port and host are given,\nthen the socket will be opened as a TCP socket, if host is omitted,\nlocalhost will be assumed. If a path is given, the socket will be\nopened as a unix socket to that path.\n\n

    \n

    Normally this method is not needed, as net.createConnection opens the\nsocket. Use this only if you are implementing a custom Socket.\n\n

    \n

    This function is asynchronous. When the ['connect'][] event is emitted the\nsocket is established. If there is a problem connecting, the 'connect' event\nwill not be emitted, the 'error' event will be emitted with the exception.\n\n

    \n

    The connectListener parameter will be added as an listener for the\n['connect'][] event.\n\n\n

    \n", "signatures": [ { "params": [ { "name": "path" }, { "name": "connectListener", "optional": true } ] } ] }, { "textRaw": "socket.setEncoding([encoding])", "type": "method", "name": "setEncoding", "desc": "

    Set the encoding for the socket as a Readable Stream. See\n[stream.setEncoding()][] for more information.\n\n

    \n", "signatures": [ { "params": [ { "name": "encoding", "optional": true } ] } ] }, { "textRaw": "socket.write(data, [encoding], [callback])", "type": "method", "name": "write", "desc": "

    Sends data on the socket. The second parameter specifies the encoding in the\ncase of a string--it defaults to UTF8 encoding.\n\n

    \n

    Returns true if the entire data was flushed successfully to the kernel\nbuffer. Returns false if all or part of the data was queued in user memory.\n'drain' will be emitted when the buffer is again free.\n\n

    \n

    The optional callback parameter will be executed when the data is finally\nwritten out - this may not be immediately.\n\n

    \n", "signatures": [ { "params": [ { "name": "data" }, { "name": "encoding", "optional": true }, { "name": "callback", "optional": true } ] } ] }, { "textRaw": "socket.end([data], [encoding])", "type": "method", "name": "end", "desc": "

    Half-closes the socket. i.e., it sends a FIN packet. It is possible the\nserver will still send some data.\n\n

    \n

    If data is specified, it is equivalent to calling\nsocket.write(data, encoding) followed by socket.end().\n\n

    \n", "signatures": [ { "params": [ { "name": "data", "optional": true }, { "name": "encoding", "optional": true } ] } ] }, { "textRaw": "socket.destroy()", "type": "method", "name": "destroy", "desc": "

    Ensures that no more I/O activity happens on this socket. Only necessary in\ncase of errors (parse error or so).\n\n

    \n", "signatures": [ { "params": [] } ] }, { "textRaw": "socket.pause()", "type": "method", "name": "pause", "desc": "

    Pauses the reading of data. That is, 'data' events will not be emitted.\nUseful to throttle back an upload.\n\n

    \n", "signatures": [ { "params": [] } ] }, { "textRaw": "socket.resume()", "type": "method", "name": "resume", "desc": "

    Resumes reading after a call to pause().\n\n

    \n", "signatures": [ { "params": [] } ] }, { "textRaw": "socket.setTimeout(timeout, [callback])", "type": "method", "name": "setTimeout", "desc": "

    Sets the socket to timeout after timeout milliseconds of inactivity on\nthe socket. By default net.Socket do not have a timeout.\n\n

    \n

    When an idle timeout is triggered the socket will receive a 'timeout'\nevent but the connection will not be severed. The user must manually end()\nor destroy() the socket.\n\n

    \n

    If timeout is 0, then the existing idle timeout is disabled.\n\n

    \n

    The optional callback parameter will be added as a one time listener for the\n'timeout' event.\n\n

    \n", "signatures": [ { "params": [ { "name": "timeout" }, { "name": "callback", "optional": true } ] } ] }, { "textRaw": "socket.setNoDelay([noDelay])", "type": "method", "name": "setNoDelay", "desc": "

    Disables the Nagle algorithm. By default TCP connections use the Nagle\nalgorithm, they buffer data before sending it off. Setting true for\nnoDelay will immediately fire off data each time socket.write() is called.\nnoDelay defaults to true.\n\n

    \n", "signatures": [ { "params": [ { "name": "noDelay", "optional": true } ] } ] }, { "textRaw": "socket.setKeepAlive([enable], [initialDelay])", "type": "method", "name": "setKeepAlive", "desc": "

    Enable/disable keep-alive functionality, and optionally set the initial\ndelay before the first keepalive probe is sent on an idle socket.\nenable defaults to false.\n\n

    \n

    Set initialDelay (in milliseconds) to set the delay between the last\ndata packet received and the first keepalive probe. Setting 0 for\ninitialDelay will leave the value unchanged from the default\n(or previous) setting. Defaults to 0.\n\n

    \n", "signatures": [ { "params": [ { "name": "enable", "optional": true }, { "name": "initialDelay", "optional": true } ] } ] }, { "textRaw": "socket.address()", "type": "method", "name": "address", "desc": "

    Returns the bound address, the address family name and port of the\nsocket as reported by the operating system. Returns an object with\nthree properties, e.g.\n{ port: 12346, family: 'IPv4', address: '127.0.0.1' }\n\n

    \n", "signatures": [ { "params": [] } ] }, { "textRaw": "socket.unref()", "type": "method", "name": "unref", "desc": "

    Calling unref on a socket will allow the program to exit if this is the only\nactive socket in the event system. If the socket is already unrefd calling\nunref again will have no effect.\n\n

    \n", "signatures": [ { "params": [] } ] }, { "textRaw": "socket.ref()", "type": "method", "name": "ref", "desc": "

    Opposite of unref, calling ref on a previously unrefd socket will not\nlet the program exit if it's the only socket left (the default behavior). If\nthe socket is refd calling ref again will have no effect.\n\n

    \n", "signatures": [ { "params": [] } ] } ], "properties": [ { "textRaw": "socket.bufferSize", "name": "bufferSize", "desc": "

    net.Socket has the property that socket.write() always works. This is to\nhelp users get up and running quickly. The computer cannot always keep up\nwith the amount of data that is written to a socket - the network connection\nsimply might be too slow. Node will internally queue up the data written to a\nsocket and send it out over the wire when it is possible. (Internally it is\npolling on the socket's file descriptor for being writable).\n\n

    \n

    The consequence of this internal buffering is that memory may grow. This\nproperty shows the number of characters currently buffered to be written.\n(Number of characters is approximately equal to the number of bytes to be\nwritten, but the buffer may contain strings, and the strings are lazily\nencoded, so the exact number of bytes is not known.)\n\n

    \n

    Users who experience large or growing bufferSize should attempt to\n"throttle" the data flows in their program with pause() and resume().\n\n\n

    \n" }, { "textRaw": "socket.remoteAddress", "name": "remoteAddress", "desc": "

    The string representation of the remote IP address. For example,\n'74.125.127.100' or '2001:4860:a005::68'.\n\n

    \n" }, { "textRaw": "socket.remotePort", "name": "remotePort", "desc": "

    The numeric representation of the remote port. For example,\n80 or 21.\n\n

    \n" }, { "textRaw": "socket.localAddress", "name": "localAddress", "desc": "

    The string representation of the local IP address the remote client is\nconnecting on. For example, if you are listening on '0.0.0.0' and the\nclient connects on '192.168.1.1', the value would be '192.168.1.1'.\n\n

    \n" }, { "textRaw": "socket.localPort", "name": "localPort", "desc": "

    The numeric representation of the local port. For example,\n80 or 21.\n\n

    \n" }, { "textRaw": "socket.bytesRead", "name": "bytesRead", "desc": "

    The amount of received bytes.\n\n

    \n" }, { "textRaw": "socket.bytesWritten", "name": "bytesWritten", "desc": "

    The amount of bytes sent.\n\n\n

    \n

    net.Socket instances are [EventEmitter][] with the following events:\n\n

    \n" } ], "events": [ { "textRaw": "Event: 'connect'", "type": "event", "name": "connect", "desc": "

    Emitted when a socket connection is successfully established.\nSee connect().\n\n

    \n", "params": [] }, { "textRaw": "Event: 'data'", "type": "event", "name": "data", "params": [], "desc": "

    Emitted when data is received. The argument data will be a Buffer or\nString. Encoding of data is set by socket.setEncoding().\n(See the [Readable Stream][] section for more information.)\n\n

    \n

    Note that the data will be lost if there is no listener when a Socket\nemits a 'data' event.\n\n

    \n" }, { "textRaw": "Event: 'end'", "type": "event", "name": "end", "desc": "

    Emitted when the other end of the socket sends a FIN packet.\n\n

    \n

    By default (allowHalfOpen == false) the socket will destroy its file\ndescriptor once it has written out its pending write queue. However, by\nsetting allowHalfOpen == true the socket will not automatically end()\nits side allowing the user to write arbitrary amounts of data, with the\ncaveat that the user is required to end() their side now.\n\n\n

    \n", "params": [] }, { "textRaw": "Event: 'timeout'", "type": "event", "name": "timeout", "desc": "

    Emitted if the socket times out from inactivity. This is only to notify that\nthe socket has been idle. The user must manually close the connection.\n\n

    \n

    See also: socket.setTimeout()\n\n\n

    \n", "params": [] }, { "textRaw": "Event: 'drain'", "type": "event", "name": "drain", "desc": "

    Emitted when the write buffer becomes empty. Can be used to throttle uploads.\n\n

    \n

    See also: the return values of socket.write()\n\n

    \n", "params": [] }, { "textRaw": "Event: 'error'", "type": "event", "name": "error", "params": [], "desc": "

    Emitted when an error occurs. The 'close' event will be called directly\nfollowing this event.\n\n

    \n" }, { "textRaw": "Event: 'close'", "type": "event", "name": "close", "params": [], "desc": "

    Emitted once the socket is fully closed. The argument had_error is a boolean\nwhich says if the socket was closed due to a transmission error.\n\n

    \n" } ] } ], "type": "module", "displayName": "net" } ] } node-v0.10.25~dfsg2/doc/api/synopsis.html0000644000000000000000000001047112270264601016712 0ustar rootroot Synopsis Node.js v0.10.25 Manual & Documentation

    Node.js v0.10.25 Manual & Documentation


    Table of Contents

    Synopsis#

    An example of a web server written with Node which responds with 'Hello World':

    var http = require('http');
    
    http.createServer(function (request, response) {
      response.writeHead(200, {'Content-Type': 'text/plain'});
      response.end('Hello World\n');
    }).listen(8124);
    
    console.log('Server running at http://127.0.0.1:8124/');

    To run the server, put the code into a file called example.js and execute it with the node program

    > node example.js
    Server running at http://127.0.0.1:8124/

    All of the examples in the documentation can be run similarly.

    node-v0.10.25~dfsg2/doc/api/events.json0000644000000000000000000002265312270264601016341 0ustar rootroot{ "source": "doc/api/events.markdown", "modules": [ { "textRaw": "Events", "name": "Events", "stability": 4, "stabilityText": "API Frozen", "type": "module", "desc": "

    Many objects in Node emit events: a net.Server emits an event each time\na peer connects to it, a fs.readStream emits an event when the file is\nopened. All objects which emit events are instances of events.EventEmitter.\nYou can access this module by doing: require("events");\n\n

    \n

    Typically, event names are represented by a camel-cased string, however,\nthere aren't any strict restrictions on that, as any string will be accepted.\n\n

    \n

    Functions can then be attached to objects, to be executed when an event\nis emitted. These functions are called listeners. Inside a listener\nfunction, this refers to the EventEmitter that the listener was\nattached to.\n\n\n

    \n", "classes": [ { "textRaw": "Class: events.EventEmitter", "type": "class", "name": "events.EventEmitter", "desc": "

    To access the EventEmitter class, require('events').EventEmitter.\n\n

    \n

    When an EventEmitter instance experiences an error, the typical action is\nto emit an 'error' event. Error events are treated as a special case in node.\nIf there is no listener for it, then the default action is to print a stack\ntrace and exit the program.\n\n

    \n

    All EventEmitters emit the event 'newListener' when new listeners are\nadded and 'removeListener' when a listener is removed.\n\n

    \n", "methods": [ { "textRaw": "emitter.addListener(event, listener)", "type": "method", "name": "addListener", "desc": "

    Adds a listener to the end of the listeners array for the specified event.\n\n

    \n
    server.on('connection', function (stream) {\n  console.log('someone connected!');\n});
    \n

    Returns emitter, so calls can be chained.\n\n

    \n", "signatures": [ { "params": [ { "name": "event" }, { "name": "listener" } ] }, { "params": [ { "name": "event" }, { "name": "listener" } ] } ] }, { "textRaw": "emitter.on(event, listener)", "type": "method", "name": "on", "desc": "

    Adds a listener to the end of the listeners array for the specified event.\n\n

    \n
    server.on('connection', function (stream) {\n  console.log('someone connected!');\n});
    \n

    Returns emitter, so calls can be chained.\n\n

    \n", "signatures": [ { "params": [ { "name": "event" }, { "name": "listener" } ] } ] }, { "textRaw": "emitter.once(event, listener)", "type": "method", "name": "once", "desc": "

    Adds a one time listener for the event. This listener is\ninvoked only the next time the event is fired, after which\nit is removed.\n\n

    \n
    server.once('connection', function (stream) {\n  console.log('Ah, we have our first user!');\n});
    \n

    Returns emitter, so calls can be chained.\n\n

    \n", "signatures": [ { "params": [ { "name": "event" }, { "name": "listener" } ] } ] }, { "textRaw": "emitter.removeListener(event, listener)", "type": "method", "name": "removeListener", "desc": "

    Remove a listener from the listener array for the specified event.\nCaution: changes array indices in the listener array behind the listener.\n\n

    \n
    var callback = function(stream) {\n  console.log('someone connected!');\n};\nserver.on('connection', callback);\n// ...\nserver.removeListener('connection', callback);
    \n

    Returns emitter, so calls can be chained.\n\n

    \n", "signatures": [ { "params": [ { "name": "event" }, { "name": "listener" } ] } ] }, { "textRaw": "emitter.removeAllListeners([event])", "type": "method", "name": "removeAllListeners", "desc": "

    Removes all listeners, or those of the specified event.\n\n

    \n

    Returns emitter, so calls can be chained.\n\n

    \n", "signatures": [ { "params": [ { "name": "event", "optional": true } ] } ] }, { "textRaw": "emitter.setMaxListeners(n)", "type": "method", "name": "setMaxListeners", "desc": "

    By default EventEmitters will print a warning if more than 10 listeners are\nadded for a particular event. This is a useful default which helps finding memory leaks.\nObviously not all Emitters should be limited to 10. This function allows\nthat to be increased. Set to zero for unlimited.\n\n\n

    \n", "signatures": [ { "params": [ { "name": "n" } ] } ] }, { "textRaw": "emitter.listeners(event)", "type": "method", "name": "listeners", "desc": "

    Returns an array of listeners for the specified event.\n\n

    \n
    server.on('connection', function (stream) {\n  console.log('someone connected!');\n});\nconsole.log(util.inspect(server.listeners('connection'))); // [ [Function] ]
    \n", "signatures": [ { "params": [ { "name": "event" } ] } ] }, { "textRaw": "emitter.emit(event, [arg1], [arg2], [...])", "type": "method", "name": "emit", "desc": "

    Execute each of the listeners in order with the supplied arguments.\n\n

    \n

    Returns true if event had listeners, false otherwise.\n\n\n

    \n", "signatures": [ { "params": [ { "name": "event" }, { "name": "arg1", "optional": true }, { "name": "arg2", "optional": true }, { "name": "...", "optional": true } ] } ] } ], "classMethods": [ { "textRaw": "Class Method: EventEmitter.listenerCount(emitter, event)", "type": "classMethod", "name": "listenerCount", "desc": "

    Return the number of listeners for a given event.\n\n\n

    \n", "signatures": [ { "params": [ { "name": "emitter" }, { "name": "event" } ] } ] } ], "events": [ { "textRaw": "Event: 'newListener'", "type": "event", "name": "newListener", "params": [], "desc": "

    This event is emitted any time someone adds a new listener. It is unspecified\nif listener is in the list returned by emitter.listeners(event).\n\n\n

    \n" }, { "textRaw": "Event: 'removeListener'", "type": "event", "name": "removeListener", "params": [], "desc": "

    This event is emitted any time someone removes a listener. It is unspecified\nif listener is in the list returned by emitter.listeners(event).\n

    \n" } ] } ] } ] } node-v0.10.25~dfsg2/doc/api/debugger.markdown0000644000000000000000000001161412270121457017466 0ustar rootroot# Debugger Stability: 3 - Stable V8 comes with an extensive debugger which is accessible out-of-process via a simple [TCP protocol](http://code.google.com/p/v8/wiki/DebuggerProtocol). Node has a built-in client for this debugger. To use this, start Node with the `debug` argument; a prompt will appear: % node debug myscript.js < debugger listening on port 5858 connecting... ok break in /home/indutny/Code/git/indutny/myscript.js:1 1 x = 5; 2 setTimeout(function () { 3 debugger; debug> Node's debugger client doesn't support the full range of commands, but simple step and inspection is possible. By putting the statement `debugger;` into the source code of your script, you will enable a breakpoint. For example, suppose `myscript.js` looked like this: // myscript.js x = 5; setTimeout(function () { debugger; console.log("world"); }, 1000); console.log("hello"); Then once the debugger is run, it will break on line 4. % node debug myscript.js < debugger listening on port 5858 connecting... ok break in /home/indutny/Code/git/indutny/myscript.js:1 1 x = 5; 2 setTimeout(function () { 3 debugger; debug> cont < hello break in /home/indutny/Code/git/indutny/myscript.js:3 1 x = 5; 2 setTimeout(function () { 3 debugger; 4 console.log("world"); 5 }, 1000); debug> next break in /home/indutny/Code/git/indutny/myscript.js:4 2 setTimeout(function () { 3 debugger; 4 console.log("world"); 5 }, 1000); 6 console.log("hello"); debug> repl Press Ctrl + C to leave debug repl > x 5 > 2+2 4 debug> next < world break in /home/indutny/Code/git/indutny/myscript.js:5 3 debugger; 4 console.log("world"); 5 }, 1000); 6 console.log("hello"); 7 debug> quit % The `repl` command allows you to evaluate code remotely. The `next` command steps over to the next line. There are a few other commands available and more to come. Type `help` to see others. ## Watchers You can watch expression and variable values while debugging your code. On every breakpoint each expression from the watchers list will be evaluated in the current context and displayed just before the breakpoint's source code listing. To start watching an expression, type `watch("my_expression")`. `watchers` prints the active watchers. To remove a watcher, type `unwatch("my_expression")`. ## Commands reference ### Stepping * `cont`, `c` - Continue execution * `next`, `n` - Step next * `step`, `s` - Step in * `out`, `o` - Step out * `pause` - Pause running code (like pause button in Developer Tools) ### Breakpoints * `setBreakpoint()`, `sb()` - Set breakpoint on current line * `setBreakpoint(line)`, `sb(line)` - Set breakpoint on specific line * `setBreakpoint('fn()')`, `sb(...)` - Set breakpoint on a first statement in functions body * `setBreakpoint('script.js', 1)`, `sb(...)` - Set breakpoint on first line of script.js * `clearBreakpoint`, `cb(...)` - Clear breakpoint It is also possible to set a breakpoint in a file (module) that isn't loaded yet: % ./node debug test/fixtures/break-in-module/main.js < debugger listening on port 5858 connecting to port 5858... ok break in test/fixtures/break-in-module/main.js:1 1 var mod = require('./mod.js'); 2 mod.hello(); 3 mod.hello(); debug> setBreakpoint('mod.js', 23) Warning: script 'mod.js' was not loaded yet. 1 var mod = require('./mod.js'); 2 mod.hello(); 3 mod.hello(); debug> c break in test/fixtures/break-in-module/mod.js:23 21 22 exports.hello = function() { 23 return 'hello from module'; 24 }; 25 debug> ### Info * `backtrace`, `bt` - Print backtrace of current execution frame * `list(5)` - List scripts source code with 5 line context (5 lines before and after) * `watch(expr)` - Add expression to watch list * `unwatch(expr)` - Remove expression from watch list * `watchers` - List all watchers and their values (automatically listed on each breakpoint) * `repl` - Open debugger's repl for evaluation in debugging script's context ### Execution control * `run` - Run script (automatically runs on debugger's start) * `restart` - Restart script * `kill` - Kill script ### Various * `scripts` - List all loaded scripts * `version` - Display v8's version ## Advanced Usage The V8 debugger can be enabled and accessed either by starting Node with the `--debug` command-line flag or by signaling an existing Node process with `SIGUSR1`. Once a process has been set in debug mode with this it can be connected to with the node debugger. Either connect to the `pid` or the URI to the debugger. The syntax is: * `node debug -p ` - Connects to the process via the `pid` * `node debug ` - Connects to the process via the URI such as localhost:5858 node-v0.10.25~dfsg2/doc/api/buffer.html0000644000000000000000000011720212270264601016274 0ustar rootroot Buffer Node.js v0.10.25 Manual & Documentation

    Node.js v0.10.25 Manual & Documentation


    Table of Contents

    Buffer#

    Stability: 3 - Stable

    Pure JavaScript is Unicode friendly but not nice to binary data. When dealing with TCP streams or the file system, it's necessary to handle octet streams. Node has several strategies for manipulating, creating, and consuming octet streams.

    Raw data is stored in instances of the Buffer class. A Buffer is similar to an array of integers but corresponds to a raw memory allocation outside the V8 heap. A Buffer cannot be resized.

    The Buffer class is a global, making it very rare that one would need to ever require('buffer').

    Converting between Buffers and JavaScript string objects requires an explicit encoding method. Here are the different string encodings.

    • 'ascii' - for 7 bit ASCII data only. This encoding method is very fast, and will strip the high bit if set.

      Note that when converting from string to buffer, this encoding converts a null character ('\0' or '\u0000') into 0x20 (character code of a space). If you want to convert a null character into 0x00, you should use 'utf8'.

    • 'utf8' - Multibyte encoded Unicode characters. Many web pages and other document formats use UTF-8.

    • 'utf16le' - 2 or 4 bytes, little endian encoded Unicode characters. Surrogate pairs (U+10000 to U+10FFFF) are supported.

    • 'ucs2' - Alias of 'utf16le'.

    • 'base64' - Base64 string encoding.

    • 'binary' - A way of encoding raw binary data into strings by using only the first 8 bits of each character. This encoding method is deprecated and should be avoided in favor of Buffer objects where possible. This encoding will be removed in future versions of Node.

    • 'hex' - Encode each byte as two hexadecimal characters.

    A Buffer object can also be used with typed arrays. The buffer object is cloned to an ArrayBuffer that is used as the backing store for the typed array. The memory of the buffer and the ArrayBuffer is not shared.

    NOTE: Node.js v0.8 simply retained a reference to the buffer in array.buffer instead of cloning it.

    While more efficient, it introduces subtle incompatibilities with the typed arrays specification. ArrayBuffer#slice() makes a copy of the slice while Buffer#slice() creates a view.

    Class: Buffer#

    The Buffer class is a global type for dealing with binary data directly. It can be constructed in a variety of ways.

    new Buffer(size)#

    • size Number

    Allocates a new buffer of size octets.

    new Buffer(array)#

    • array Array

    Allocates a new buffer using an array of octets.

    new Buffer(str, [encoding])#

    • str String - string to encode.
    • encoding String - encoding to use, Optional.

    Allocates a new buffer containing the given str. encoding defaults to 'utf8'.

    Class Method: Buffer.isEncoding(encoding)#

    • encoding String The encoding string to test

    Returns true if the encoding is a valid encoding argument, or false otherwise.

    buf.write(string, [offset], [length], [encoding])#

    • string String - data to be written to buffer
    • offset Number, Optional, Default: 0
    • length Number, Optional, Default: buffer.length - offset
    • encoding String, Optional, Default: 'utf8'

    Writes string to the buffer at offset using the given encoding. offset defaults to 0, encoding defaults to 'utf8'. length is the number of bytes to write. Returns number of octets written. If buffer did not contain enough space to fit the entire string, it will write a partial amount of the string. length defaults to buffer.length - offset. The method will not write partial characters.

    buf = new Buffer(256);
    len = buf.write('\u00bd + \u00bc = \u00be', 0);
    console.log(len + " bytes: " + buf.toString('utf8', 0, len));

    The number of characters written (which may be different than the number of bytes written) is set in Buffer._charsWritten and will be overwritten the next time buf.write() is called.

    buf.toString([encoding], [start], [end])#

    • encoding String, Optional, Default: 'utf8'
    • start Number, Optional, Default: 0
    • end Number, Optional, Default: buffer.length

    Decodes and returns a string from buffer data encoded with encoding (defaults to 'utf8') beginning at start (defaults to 0) and ending at end (defaults to buffer.length).

    See buffer.write() example, above.

    buf.toJSON()#

    Returns a JSON-representation of the Buffer instance, which is identical to the output for JSON Arrays. JSON.stringify implicitly calls this function when stringifying a Buffer instance.

    Example:

    var buf = new Buffer('test');
    var json = JSON.stringify(buf);
    
    console.log(json);
    // '[116,101,115,116]'
    
    var copy = new Buffer(JSON.parse(json));
    
    console.log(copy);
    // <Buffer 74 65 73 74>

    buf[index]#

    Get and set the octet at index. The values refer to individual bytes, so the legal range is between 0x00 and 0xFF hex or 0 and 255.

    Example: copy an ASCII string into a buffer, one byte at a time:

    str = "node.js";
    buf = new Buffer(str.length);
    
    for (var i = 0; i < str.length ; i++) {
      buf[i] = str.charCodeAt(i);
    }
    
    console.log(buf);
    
    // node.js

    Class Method: Buffer.isBuffer(obj)#

    • obj Object
    • Return: Boolean

    Tests if obj is a Buffer.

    Class Method: Buffer.byteLength(string, [encoding])#

    • string String
    • encoding String, Optional, Default: 'utf8'
    • Return: Number

    Gives the actual byte length of a string. encoding defaults to 'utf8'. This is not the same as String.prototype.length since that returns the number of characters in a string.

    Example:

    str = '\u00bd + \u00bc = \u00be';
    
    console.log(str + ": " + str.length + " characters, " +
      Buffer.byteLength(str, 'utf8') + " bytes");
    
    // ½ + ¼ = ¾: 9 characters, 12 bytes

    Class Method: Buffer.concat(list, [totalLength])#

    • list Array List of Buffer objects to concat
    • totalLength Number Total length of the buffers when concatenated

    Returns a buffer which is the result of concatenating all the buffers in the list together.

    If the list has no items, or if the totalLength is 0, then it returns a zero-length buffer.

    If the list has exactly one item, then the first item of the list is returned.

    If the list has more than one item, then a new Buffer is created.

    If totalLength is not provided, it is read from the buffers in the list. However, this adds an additional loop to the function, so it is faster to provide the length explicitly.

    buf.length#

    • Number

    The size of the buffer in bytes. Note that this is not necessarily the size of the contents. length refers to the amount of memory allocated for the buffer object. It does not change when the contents of the buffer are changed.

    buf = new Buffer(1234);
    
    console.log(buf.length);
    buf.write("some string", 0, "ascii");
    console.log(buf.length);
    
    // 1234
    // 1234

    buf.copy(targetBuffer, [targetStart], [sourceStart], [sourceEnd])#

    • targetBuffer Buffer object - Buffer to copy into
    • targetStart Number, Optional, Default: 0
    • sourceStart Number, Optional, Default: 0
    • sourceEnd Number, Optional, Default: buffer.length

    Does copy between buffers. The source and target regions can be overlapped. targetStart and sourceStart default to 0. sourceEnd defaults to buffer.length.

    All values passed that are undefined/NaN or are out of bounds are set equal to their respective defaults.

    Example: build two Buffers, then copy buf1 from byte 16 through byte 19 into buf2, starting at the 8th byte in buf2.

    buf1 = new Buffer(26);
    buf2 = new Buffer(26);
    
    for (var i = 0 ; i < 26 ; i++) {
      buf1[i] = i + 97; // 97 is ASCII a
      buf2[i] = 33; // ASCII !
    }
    
    buf1.copy(buf2, 8, 16, 20);
    console.log(buf2.toString('ascii', 0, 25));
    
    // !!!!!!!!qrst!!!!!!!!!!!!!

    buf.slice([start], [end])#

    • start Number, Optional, Default: 0
    • end Number, Optional, Default: buffer.length

    Returns a new buffer which references the same memory as the old, but offset and cropped by the start (defaults to 0) and end (defaults to buffer.length) indexes. Negative indexes start from the end of the buffer.

    Modifying the new buffer slice will modify memory in the original buffer!

    Example: build a Buffer with the ASCII alphabet, take a slice, then modify one byte from the original Buffer.

    var buf1 = new Buffer(26);
    
    for (var i = 0 ; i < 26 ; i++) {
      buf1[i] = i + 97; // 97 is ASCII a
    }
    
    var buf2 = buf1.slice(0, 3);
    console.log(buf2.toString('ascii', 0, buf2.length));
    buf1[0] = 33;
    console.log(buf2.toString('ascii', 0, buf2.length));
    
    // abc
    // !bc

    buf.readUInt8(offset, [noAssert])#

    • offset Number
    • noAssert Boolean, Optional, Default: false
    • Return: Number

    Reads an unsigned 8 bit integer from the buffer at the specified offset.

    Set noAssert to true to skip validation of offset. This means that offset may be beyond the end of the buffer. Defaults to false.

    Example:

    var buf = new Buffer(4);
    
    buf[0] = 0x3;
    buf[1] = 0x4;
    buf[2] = 0x23;
    buf[3] = 0x42;
    
    for (ii = 0; ii < buf.length; ii++) {
      console.log(buf.readUInt8(ii));
    }
    
    // 0x3
    // 0x4
    // 0x23
    // 0x42

    buf.readUInt16LE(offset, [noAssert])#

    buf.readUInt16BE(offset, [noAssert])#

    • offset Number
    • noAssert Boolean, Optional, Default: false
    • Return: Number

    Reads an unsigned 16 bit integer from the buffer at the specified offset with specified endian format.

    Set noAssert to true to skip validation of offset. This means that offset may be beyond the end of the buffer. Defaults to false.

    Example:

    var buf = new Buffer(4);
    
    buf[0] = 0x3;
    buf[1] = 0x4;
    buf[2] = 0x23;
    buf[3] = 0x42;
    
    console.log(buf.readUInt16BE(0));
    console.log(buf.readUInt16LE(0));
    console.log(buf.readUInt16BE(1));
    console.log(buf.readUInt16LE(1));
    console.log(buf.readUInt16BE(2));
    console.log(buf.readUInt16LE(2));
    
    // 0x0304
    // 0x0403
    // 0x0423
    // 0x2304
    // 0x2342
    // 0x4223

    buf.readUInt32LE(offset, [noAssert])#

    buf.readUInt32BE(offset, [noAssert])#

    • offset Number
    • noAssert Boolean, Optional, Default: false
    • Return: Number

    Reads an unsigned 32 bit integer from the buffer at the specified offset with specified endian format.

    Set noAssert to true to skip validation of offset. This means that offset may be beyond the end of the buffer. Defaults to false.

    Example:

    var buf = new Buffer(4);
    
    buf[0] = 0x3;
    buf[1] = 0x4;
    buf[2] = 0x23;
    buf[3] = 0x42;
    
    console.log(buf.readUInt32BE(0));
    console.log(buf.readUInt32LE(0));
    
    // 0x03042342
    // 0x42230403

    buf.readInt8(offset, [noAssert])#

    • offset Number
    • noAssert Boolean, Optional, Default: false
    • Return: Number

    Reads a signed 8 bit integer from the buffer at the specified offset.

    Set noAssert to true to skip validation of offset. This means that offset may be beyond the end of the buffer. Defaults to false.

    Works as buffer.readUInt8, except buffer contents are treated as two's complement signed values.

    buf.readInt16LE(offset, [noAssert])#

    buf.readInt16BE(offset, [noAssert])#

    • offset Number
    • noAssert Boolean, Optional, Default: false
    • Return: Number

    Reads a signed 16 bit integer from the buffer at the specified offset with specified endian format.

    Set noAssert to true to skip validation of offset. This means that offset may be beyond the end of the buffer. Defaults to false.

    Works as buffer.readUInt16*, except buffer contents are treated as two's complement signed values.

    buf.readInt32LE(offset, [noAssert])#

    buf.readInt32BE(offset, [noAssert])#

    • offset Number
    • noAssert Boolean, Optional, Default: false
    • Return: Number

    Reads a signed 32 bit integer from the buffer at the specified offset with specified endian format.

    Set noAssert to true to skip validation of offset. This means that offset may be beyond the end of the buffer. Defaults to false.

    Works as buffer.readUInt32*, except buffer contents are treated as two's complement signed values.

    buf.readFloatLE(offset, [noAssert])#

    buf.readFloatBE(offset, [noAssert])#

    • offset Number
    • noAssert Boolean, Optional, Default: false
    • Return: Number

    Reads a 32 bit float from the buffer at the specified offset with specified endian format.

    Set noAssert to true to skip validation of offset. This means that offset may be beyond the end of the buffer. Defaults to false.

    Example:

    var buf = new Buffer(4);
    
    buf[0] = 0x00;
    buf[1] = 0x00;
    buf[2] = 0x80;
    buf[3] = 0x3f;
    
    console.log(buf.readFloatLE(0));
    
    // 0x01

    buf.readDoubleLE(offset, [noAssert])#

    buf.readDoubleBE(offset, [noAssert])#

    • offset Number
    • noAssert Boolean, Optional, Default: false
    • Return: Number

    Reads a 64 bit double from the buffer at the specified offset with specified endian format.

    Set noAssert to true to skip validation of offset. This means that offset may be beyond the end of the buffer. Defaults to false.

    Example:

    var buf = new Buffer(8);
    
    buf[0] = 0x55;
    buf[1] = 0x55;
    buf[2] = 0x55;
    buf[3] = 0x55;
    buf[4] = 0x55;
    buf[5] = 0x55;
    buf[6] = 0xd5;
    buf[7] = 0x3f;
    
    console.log(buf.readDoubleLE(0));
    
    // 0.3333333333333333

    buf.writeUInt8(value, offset, [noAssert])#

    • value Number
    • offset Number
    • noAssert Boolean, Optional, Default: false

    Writes value to the buffer at the specified offset. Note, value must be a valid unsigned 8 bit integer.

    Set noAssert to true to skip validation of value and offset. This means that value may be too large for the specific function and offset may be beyond the end of the buffer leading to the values being silently dropped. This should not be used unless you are certain of correctness. Defaults to false.

    Example:

    var buf = new Buffer(4);
    buf.writeUInt8(0x3, 0);
    buf.writeUInt8(0x4, 1);
    buf.writeUInt8(0x23, 2);
    buf.writeUInt8(0x42, 3);
    
    console.log(buf);
    
    // <Buffer 03 04 23 42>

    buf.writeUInt16LE(value, offset, [noAssert])#

    buf.writeUInt16BE(value, offset, [noAssert])#

    • value Number
    • offset Number
    • noAssert Boolean, Optional, Default: false

    Writes value to the buffer at the specified offset with specified endian format. Note, value must be a valid unsigned 16 bit integer.

    Set noAssert to true to skip validation of value and offset. This means that value may be too large for the specific function and offset may be beyond the end of the buffer leading to the values being silently dropped. This should not be used unless you are certain of correctness. Defaults to false.

    Example:

    var buf = new Buffer(4);
    buf.writeUInt16BE(0xdead, 0);
    buf.writeUInt16BE(0xbeef, 2);
    
    console.log(buf);
    
    buf.writeUInt16LE(0xdead, 0);
    buf.writeUInt16LE(0xbeef, 2);
    
    console.log(buf);
    
    // <Buffer de ad be ef>
    // <Buffer ad de ef be>

    buf.writeUInt32LE(value, offset, [noAssert])#

    buf.writeUInt32BE(value, offset, [noAssert])#

    • value Number
    • offset Number
    • noAssert Boolean, Optional, Default: false

    Writes value to the buffer at the specified offset with specified endian format. Note, value must be a valid unsigned 32 bit integer.

    Set noAssert to true to skip validation of value and offset. This means that value may be too large for the specific function and offset may be beyond the end of the buffer leading to the values being silently dropped. This should not be used unless you are certain of correctness. Defaults to false.

    Example:

    var buf = new Buffer(4);
    buf.writeUInt32BE(0xfeedface, 0);
    
    console.log(buf);
    
    buf.writeUInt32LE(0xfeedface, 0);
    
    console.log(buf);
    
    // <Buffer fe ed fa ce>
    // <Buffer ce fa ed fe>

    buf.writeInt8(value, offset, [noAssert])#

    • value Number
    • offset Number
    • noAssert Boolean, Optional, Default: false

    Writes value to the buffer at the specified offset. Note, value must be a valid signed 8 bit integer.

    Set noAssert to true to skip validation of value and offset. This means that value may be too large for the specific function and offset may be beyond the end of the buffer leading to the values being silently dropped. This should not be used unless you are certain of correctness. Defaults to false.

    Works as buffer.writeUInt8, except value is written out as a two's complement signed integer into buffer.

    buf.writeInt16LE(value, offset, [noAssert])#

    buf.writeInt16BE(value, offset, [noAssert])#

    • value Number
    • offset Number
    • noAssert Boolean, Optional, Default: false

    Writes value to the buffer at the specified offset with specified endian format. Note, value must be a valid signed 16 bit integer.

    Set noAssert to true to skip validation of value and offset. This means that value may be too large for the specific function and offset may be beyond the end of the buffer leading to the values being silently dropped. This should not be used unless you are certain of correctness. Defaults to false.

    Works as buffer.writeUInt16*, except value is written out as a two's complement signed integer into buffer.

    buf.writeInt32LE(value, offset, [noAssert])#

    buf.writeInt32BE(value, offset, [noAssert])#

    • value Number
    • offset Number
    • noAssert Boolean, Optional, Default: false

    Writes value to the buffer at the specified offset with specified endian format. Note, value must be a valid signed 32 bit integer.

    Set noAssert to true to skip validation of value and offset. This means that value may be too large for the specific function and offset may be beyond the end of the buffer leading to the values being silently dropped. This should not be used unless you are certain of correctness. Defaults to false.

    Works as buffer.writeUInt32*, except value is written out as a two's complement signed integer into buffer.

    buf.writeFloatLE(value, offset, [noAssert])#

    buf.writeFloatBE(value, offset, [noAssert])#

    • value Number
    • offset Number
    • noAssert Boolean, Optional, Default: false

    Writes value to the buffer at the specified offset with specified endian format. Note, behavior is unspecified if value is not a 32 bit float.

    Set noAssert to true to skip validation of value and offset. This means that value may be too large for the specific function and offset may be beyond the end of the buffer leading to the values being silently dropped. This should not be used unless you are certain of correctness. Defaults to false.

    Example:

    var buf = new Buffer(4);
    buf.writeFloatBE(0xcafebabe, 0);
    
    console.log(buf);
    
    buf.writeFloatLE(0xcafebabe, 0);
    
    console.log(buf);
    
    // <Buffer 4f 4a fe bb>
    // <Buffer bb fe 4a 4f>

    buf.writeDoubleLE(value, offset, [noAssert])#

    buf.writeDoubleBE(value, offset, [noAssert])#

    • value Number
    • offset Number
    • noAssert Boolean, Optional, Default: false

    Writes value to the buffer at the specified offset with specified endian format. Note, value must be a valid 64 bit double.

    Set noAssert to true to skip validation of value and offset. This means that value may be too large for the specific function and offset may be beyond the end of the buffer leading to the values being silently dropped. This should not be used unless you are certain of correctness. Defaults to false.

    Example:

    var buf = new Buffer(8);
    buf.writeDoubleBE(0xdeadbeefcafebabe, 0);
    
    console.log(buf);
    
    buf.writeDoubleLE(0xdeadbeefcafebabe, 0);
    
    console.log(buf);
    
    // <Buffer 43 eb d5 b7 dd f9 5f d7>
    // <Buffer d7 5f f9 dd b7 d5 eb 43>

    buf.fill(value, [offset], [end])#

    • value
    • offset Number, Optional
    • end Number, Optional

    Fills the buffer with the specified value. If the offset (defaults to 0) and end (defaults to buffer.length) are not given it will fill the entire buffer.

    var b = new Buffer(50);
    b.fill("h");

    buffer.INSPECT_MAX_BYTES#

    • Number, Default: 50

    How many bytes will be returned when buffer.inspect() is called. This can be overridden by user modules.

    Note that this is a property on the buffer module returned by require('buffer'), not on the Buffer global, or a buffer instance.

    Class: SlowBuffer#

    This class is primarily for internal use. JavaScript programs should use Buffer instead of using SlowBuffer.

    In order to avoid the overhead of allocating many C++ Buffer objects for small blocks of memory in the lifetime of a server, Node allocates memory in 8Kb (8192 byte) chunks. If a buffer is smaller than this size, then it will be backed by a parent SlowBuffer object. If it is larger than this, then Node will allocate a SlowBuffer slab for it directly.

    node-v0.10.25~dfsg2/doc/api/readline.html0000644000000000000000000004112412270264601016605 0ustar rootroot Readline Node.js v0.10.25 Manual & Documentation

    Node.js v0.10.25 Manual & Documentation


    Readline#

    Stability: 2 - Unstable

    To use this module, do require('readline'). Readline allows reading of a stream (such as process.stdin) on a line-by-line basis.

    Note that once you've invoked this module, your node program will not terminate until you've closed the interface. Here's how to allow your program to gracefully exit:

    var readline = require('readline');
    
    var rl = readline.createInterface({
      input: process.stdin,
      output: process.stdout
    });
    
    rl.question("What do you think of node.js? ", function(answer) {
      // TODO: Log the answer in a database
      console.log("Thank you for your valuable feedback:", answer);
    
      rl.close();
    });

    readline.createInterface(options)#

    Creates a readline Interface instance. Accepts an "options" Object that takes the following values:

    • input - the readable stream to listen to (Required).

    • output - the writable stream to write readline data to (Required).

    • completer - an optional function that is used for Tab autocompletion. See below for an example of using this.

    • terminal - pass true if the input and output streams should be treated like a TTY, and have ANSI/VT100 escape codes written to it. Defaults to checking isTTY on the output stream upon instantiation.

    The completer function is given a the current line entered by the user, and is supposed to return an Array with 2 entries:

    1. An Array with matching entries for the completion.

    2. The substring that was used for the matching.

    Which ends up looking something like: [[substr1, substr2, ...], originalsubstring].

    Example:

    function completer(line) {
      var completions = '.help .error .exit .quit .q'.split(' ')
      var hits = completions.filter(function(c) { return c.indexOf(line) == 0 })
      // show all completions if none found
      return [hits.length ? hits : completions, line]
    }

    Also completer can be run in async mode if it accepts two arguments:

    function completer(linePartial, callback) {
      callback(null, [['123'], linePartial]);
    }

    createInterface is commonly used with process.stdin and process.stdout in order to accept user input:

    var readline = require('readline');
    var rl = readline.createInterface({
      input: process.stdin,
      output: process.stdout
    });

    Once you have a readline instance, you most commonly listen for the "line" event.

    If terminal is true for this instance then the output stream will get the best compatibility if it defines an output.columns property, and fires a "resize" event on the output if/when the columns ever change (process.stdout does this automatically when it is a TTY).

    Class: Interface#

    The class that represents a readline interface with an input and output stream.

    rl.setPrompt(prompt, length)#

    Sets the prompt, for example when you run node on the command line, you see > , which is node's prompt.

    rl.prompt([preserveCursor])#

    Readies readline for input from the user, putting the current setPrompt options on a new line, giving the user a new spot to write. Set preserveCursor to true to prevent the cursor placement being reset to 0.

    This will also resume the input stream used with createInterface if it has been paused.

    rl.question(query, callback)#

    Prepends the prompt with query and invokes callback with the user's response. Displays the query to the user, and then invokes callback with the user's response after it has been typed.

    This will also resume the input stream used with createInterface if it has been paused.

    Example usage:

    interface.question('What is your favorite food?', function(answer) {
      console.log('Oh, so your favorite food is ' + answer);
    });

    rl.pause()#

    Pauses the readline input stream, allowing it to be resumed later if needed.

    rl.resume()#

    Resumes the readline input stream.

    rl.close()#

    Closes the Interface instance, relinquishing control on the input and output streams. The "close" event will also be emitted.

    rl.write(data, [key])#

    Writes data to output stream. key is an object literal to represent a key sequence; available if the terminal is a TTY.

    This will also resume the input stream if it has been paused.

    Example:

    rl.write('Delete me!');
    // Simulate ctrl+u to delete the line written previously
    rl.write(null, {ctrl: true, name: 'u'});

    Events#

    Event: 'line'#

    function (line) {}

    Emitted whenever the input stream receives a \n, usually received when the user hits enter, or return. This is a good hook to listen for user input.

    Example of listening for line:

    rl.on('line', function (cmd) {
      console.log('You just typed: '+cmd);
    });

    Event: 'pause'#

    function () {}

    Emitted whenever the input stream is paused.

    Also emitted whenever the input stream is not paused and receives the SIGCONT event. (See events SIGTSTP and SIGCONT)

    Example of listening for pause:

    rl.on('pause', function() {
      console.log('Readline paused.');
    });

    Event: 'resume'#

    function () {}

    Emitted whenever the input stream is resumed.

    Example of listening for resume:

    rl.on('resume', function() {
      console.log('Readline resumed.');
    });

    Event: 'close'#

    function () {}

    Emitted when close() is called.

    Also emitted when the input stream receives its "end" event. The Interface instance should be considered "finished" once this is emitted. For example, when the input stream receives ^D, respectively known as EOT.

    This event is also called if there is no SIGINT event listener present when the input stream receives a ^C, respectively known as SIGINT.

    Event: 'SIGINT'#

    function () {}

    Emitted whenever the input stream receives a ^C, respectively known as SIGINT. If there is no SIGINT event listener present when the input stream receives a SIGINT, pause will be triggered.

    Example of listening for SIGINT:

    rl.on('SIGINT', function() {
      rl.question('Are you sure you want to exit?', function(answer) {
        if (answer.match(/^y(es)?$/i)) rl.pause();
      });
    });

    Event: 'SIGTSTP'#

    function () {}

    This does not work on Windows.

    Emitted whenever the input stream receives a ^Z, respectively known as SIGTSTP. If there is no SIGTSTP event listener present when the input stream receives a SIGTSTP, the program will be sent to the background.

    When the program is resumed with fg, the pause and SIGCONT events will be emitted. You can use either to resume the stream.

    The pause and SIGCONT events will not be triggered if the stream was paused before the program was sent to the background.

    Example of listening for SIGTSTP:

    rl.on('SIGTSTP', function() {
      // This will override SIGTSTP and prevent the program from going to the
      // background.
      console.log('Caught SIGTSTP.');
    });

    Event: 'SIGCONT'#

    function () {}

    This does not work on Windows.

    Emitted whenever the input stream is sent to the background with ^Z, respectively known as SIGTSTP, and then continued with fg(1). This event only emits if the stream was not paused before sending the program to the background.

    Example of listening for SIGCONT:

    rl.on('SIGCONT', function() {
      // `prompt` will automatically resume the stream
      rl.prompt();
    });

    Example: Tiny CLI#

    Here's an example of how to use all these together to craft a tiny command line interface:

    var readline = require('readline'),
        rl = readline.createInterface(process.stdin, process.stdout);
    
    rl.setPrompt('OHAI> ');
    rl.prompt();
    
    rl.on('line', function(line) {
      switch(line.trim()) {
        case 'hello':
          console.log('world!');
          break;
        default:
          console.log('Say what? I might have heard `' + line.trim() + '`');
          break;
      }
      rl.prompt();
    }).on('close', function() {
      console.log('Have a great day!');
      process.exit(0);
    });
    node-v0.10.25~dfsg2/doc/api/timers.html0000644000000000000000000002000512270264601016320 0ustar rootroot Timers Node.js v0.10.25 Manual & Documentation

    Node.js v0.10.25 Manual & Documentation


    Timers#

    Stability: 5 - Locked

    All of the timer functions are globals. You do not need to require() this module in order to use them.

    setTimeout(callback, delay, [arg], [...])#

    To schedule execution of a one-time callback after delay milliseconds. Returns a timeoutId for possible use with clearTimeout(). Optionally you can also pass arguments to the callback.

    It is important to note that your callback will probably not be called in exactly delay milliseconds - Node.js makes no guarantees about the exact timing of when the callback will fire, nor of the ordering things will fire in. The callback will be called as close as possible to the time specified.

    clearTimeout(timeoutId)#

    Prevents a timeout from triggering.

    setInterval(callback, delay, [arg], [...])#

    To schedule the repeated execution of callback every delay milliseconds. Returns a intervalId for possible use with clearInterval(). Optionally you can also pass arguments to the callback.

    clearInterval(intervalId)#

    Stops a interval from triggering.

    unref()#

    The opaque value returned by setTimeout and setInterval also has the method timer.unref() which will allow you to create a timer that is active but if it is the only item left in the event loop won't keep the program running. If the timer is already unrefd calling unref again will have no effect.

    In the case of setTimeout when you unref you create a separate timer that will wakeup the event loop, creating too many of these may adversely effect event loop performance -- use wisely.

    ref()#

    If you had previously unref()d a timer you can call ref() to explicitly request the timer hold the program open. If the timer is already refd calling ref again will have no effect.

    setImmediate(callback, [arg], [...])#

    To schedule the "immediate" execution of callback after I/O events callbacks and before setTimeout and setInterval . Returns an immediateId for possible use with clearImmediate(). Optionally you can also pass arguments to the callback.

    Immediates are queued in the order created, and are popped off the queue once per loop iteration. This is different from process.nextTick which will execute process.maxTickDepth queued callbacks per iteration. setImmediate will yield to the event loop after firing a queued callback to make sure I/O is not being starved. While order is preserved for execution, other I/O events may fire between any two scheduled immediate callbacks.

    clearImmediate(immediateId)#

    Stops an immediate from triggering.

    node-v0.10.25~dfsg2/doc/api/fs.json0000644000000000000000000017235412270264601015451 0ustar rootroot{ "source": "doc/api/fs.markdown", "modules": [ { "textRaw": "File System", "name": "fs", "stability": 3, "stabilityText": "Stable", "desc": "

    File I/O is provided by simple wrappers around standard POSIX functions. To\nuse this module do require('fs'). All the methods have asynchronous and\nsynchronous forms.\n\n

    \n

    The asynchronous form always take a completion callback as its last argument.\nThe arguments passed to the completion callback depend on the method, but the\nfirst argument is always reserved for an exception. If the operation was\ncompleted successfully, then the first argument will be null or undefined.\n\n

    \n

    When using the synchronous form any exceptions are immediately thrown.\nYou can use try/catch to handle exceptions or allow them to bubble up.\n\n

    \n

    Here is an example of the asynchronous version:\n\n

    \n
    var fs = require('fs');\n\nfs.unlink('/tmp/hello', function (err) {\n  if (err) throw err;\n  console.log('successfully deleted /tmp/hello');\n});
    \n

    Here is the synchronous version:\n\n

    \n
    var fs = require('fs');\n\nfs.unlinkSync('/tmp/hello')\nconsole.log('successfully deleted /tmp/hello');
    \n

    With the asynchronous methods there is no guaranteed ordering. So the\nfollowing is prone to error:\n\n

    \n
    fs.rename('/tmp/hello', '/tmp/world', function (err) {\n  if (err) throw err;\n  console.log('renamed complete');\n});\nfs.stat('/tmp/world', function (err, stats) {\n  if (err) throw err;\n  console.log('stats: ' + JSON.stringify(stats));\n});
    \n

    It could be that fs.stat is executed before fs.rename.\nThe correct way to do this is to chain the callbacks.\n\n

    \n
    fs.rename('/tmp/hello', '/tmp/world', function (err) {\n  if (err) throw err;\n  fs.stat('/tmp/world', function (err, stats) {\n    if (err) throw err;\n    console.log('stats: ' + JSON.stringify(stats));\n  });\n});
    \n

    In busy processes, the programmer is strongly encouraged to use the\nasynchronous versions of these calls. The synchronous versions will block\nthe entire process until they complete--halting all connections.\n\n

    \n

    Relative path to filename can be used, remember however that this path will be\nrelative to process.cwd().\n\n

    \n

    Most fs functions let you omit the callback argument. If you do, a default\ncallback is used that ignores errors, but prints a deprecation\nwarning.\n\n

    \n

    IMPORTANT: Omitting the callback is deprecated. v0.12 will throw the\nerrors as exceptions.\n\n\n

    \n", "methods": [ { "textRaw": "fs.rename(oldPath, newPath, callback)", "type": "method", "name": "rename", "desc": "

    Asynchronous rename(2). No arguments other than a possible exception are given\nto the completion callback.\n\n

    \n", "signatures": [ { "params": [ { "name": "oldPath" }, { "name": "newPath" }, { "name": "callback" } ] } ] }, { "textRaw": "fs.renameSync(oldPath, newPath)", "type": "method", "name": "renameSync", "desc": "

    Synchronous rename(2).\n\n

    \n", "signatures": [ { "params": [ { "name": "oldPath" }, { "name": "newPath" } ] } ] }, { "textRaw": "fs.ftruncate(fd, len, callback)", "type": "method", "name": "ftruncate", "desc": "

    Asynchronous ftruncate(2). No arguments other than a possible exception are\ngiven to the completion callback.\n\n

    \n", "signatures": [ { "params": [ { "name": "fd" }, { "name": "len" }, { "name": "callback" } ] } ] }, { "textRaw": "fs.ftruncateSync(fd, len)", "type": "method", "name": "ftruncateSync", "desc": "

    Synchronous ftruncate(2).\n\n

    \n", "signatures": [ { "params": [ { "name": "fd" }, { "name": "len" } ] } ] }, { "textRaw": "fs.truncate(path, len, callback)", "type": "method", "name": "truncate", "desc": "

    Asynchronous truncate(2). No arguments other than a possible exception are\ngiven to the completion callback.\n\n

    \n", "signatures": [ { "params": [ { "name": "path" }, { "name": "len" }, { "name": "callback" } ] } ] }, { "textRaw": "fs.truncateSync(path, len)", "type": "method", "name": "truncateSync", "desc": "

    Synchronous truncate(2).\n\n

    \n", "signatures": [ { "params": [ { "name": "path" }, { "name": "len" } ] } ] }, { "textRaw": "fs.chown(path, uid, gid, callback)", "type": "method", "name": "chown", "desc": "

    Asynchronous chown(2). No arguments other than a possible exception are given\nto the completion callback.\n\n

    \n", "signatures": [ { "params": [ { "name": "path" }, { "name": "uid" }, { "name": "gid" }, { "name": "callback" } ] } ] }, { "textRaw": "fs.chownSync(path, uid, gid)", "type": "method", "name": "chownSync", "desc": "

    Synchronous chown(2).\n\n

    \n", "signatures": [ { "params": [ { "name": "path" }, { "name": "uid" }, { "name": "gid" } ] } ] }, { "textRaw": "fs.fchown(fd, uid, gid, callback)", "type": "method", "name": "fchown", "desc": "

    Asynchronous fchown(2). No arguments other than a possible exception are given\nto the completion callback.\n\n

    \n", "signatures": [ { "params": [ { "name": "fd" }, { "name": "uid" }, { "name": "gid" }, { "name": "callback" } ] } ] }, { "textRaw": "fs.fchownSync(fd, uid, gid)", "type": "method", "name": "fchownSync", "desc": "

    Synchronous fchown(2).\n\n

    \n", "signatures": [ { "params": [ { "name": "fd" }, { "name": "uid" }, { "name": "gid" } ] } ] }, { "textRaw": "fs.lchown(path, uid, gid, callback)", "type": "method", "name": "lchown", "desc": "

    Asynchronous lchown(2). No arguments other than a possible exception are given\nto the completion callback.\n\n

    \n", "signatures": [ { "params": [ { "name": "path" }, { "name": "uid" }, { "name": "gid" }, { "name": "callback" } ] } ] }, { "textRaw": "fs.lchownSync(path, uid, gid)", "type": "method", "name": "lchownSync", "desc": "

    Synchronous lchown(2).\n\n

    \n", "signatures": [ { "params": [ { "name": "path" }, { "name": "uid" }, { "name": "gid" } ] } ] }, { "textRaw": "fs.chmod(path, mode, callback)", "type": "method", "name": "chmod", "desc": "

    Asynchronous chmod(2). No arguments other than a possible exception are given\nto the completion callback.\n\n

    \n", "signatures": [ { "params": [ { "name": "path" }, { "name": "mode" }, { "name": "callback" } ] } ] }, { "textRaw": "fs.chmodSync(path, mode)", "type": "method", "name": "chmodSync", "desc": "

    Synchronous chmod(2).\n\n

    \n", "signatures": [ { "params": [ { "name": "path" }, { "name": "mode" } ] } ] }, { "textRaw": "fs.fchmod(fd, mode, callback)", "type": "method", "name": "fchmod", "desc": "

    Asynchronous fchmod(2). No arguments other than a possible exception\nare given to the completion callback.\n\n

    \n", "signatures": [ { "params": [ { "name": "fd" }, { "name": "mode" }, { "name": "callback" } ] } ] }, { "textRaw": "fs.fchmodSync(fd, mode)", "type": "method", "name": "fchmodSync", "desc": "

    Synchronous fchmod(2).\n\n

    \n", "signatures": [ { "params": [ { "name": "fd" }, { "name": "mode" } ] } ] }, { "textRaw": "fs.lchmod(path, mode, callback)", "type": "method", "name": "lchmod", "desc": "

    Asynchronous lchmod(2). No arguments other than a possible exception\nare given to the completion callback.\n\n

    \n

    Only available on Mac OS X.\n\n

    \n", "signatures": [ { "params": [ { "name": "path" }, { "name": "mode" }, { "name": "callback" } ] } ] }, { "textRaw": "fs.lchmodSync(path, mode)", "type": "method", "name": "lchmodSync", "desc": "

    Synchronous lchmod(2).\n\n

    \n", "signatures": [ { "params": [ { "name": "path" }, { "name": "mode" } ] } ] }, { "textRaw": "fs.stat(path, callback)", "type": "method", "name": "stat", "desc": "

    Asynchronous stat(2). The callback gets two arguments (err, stats) where\nstats is a fs.Stats object. See the fs.Stats\nsection below for more information.\n\n

    \n", "signatures": [ { "params": [ { "name": "path" }, { "name": "callback" } ] } ] }, { "textRaw": "fs.lstat(path, callback)", "type": "method", "name": "lstat", "desc": "

    Asynchronous lstat(2). The callback gets two arguments (err, stats) where\nstats is a fs.Stats object. lstat() is identical to stat(), except that if\npath is a symbolic link, then the link itself is stat-ed, not the file that it\nrefers to.\n\n

    \n", "signatures": [ { "params": [ { "name": "path" }, { "name": "callback" } ] } ] }, { "textRaw": "fs.fstat(fd, callback)", "type": "method", "name": "fstat", "desc": "

    Asynchronous fstat(2). The callback gets two arguments (err, stats) where\nstats is a fs.Stats object. fstat() is identical to stat(), except that\nthe file to be stat-ed is specified by the file descriptor fd.\n\n

    \n", "signatures": [ { "params": [ { "name": "fd" }, { "name": "callback" } ] } ] }, { "textRaw": "fs.statSync(path)", "type": "method", "name": "statSync", "desc": "

    Synchronous stat(2). Returns an instance of fs.Stats.\n\n

    \n", "signatures": [ { "params": [ { "name": "path" } ] } ] }, { "textRaw": "fs.lstatSync(path)", "type": "method", "name": "lstatSync", "desc": "

    Synchronous lstat(2). Returns an instance of fs.Stats.\n\n

    \n", "signatures": [ { "params": [ { "name": "path" } ] } ] }, { "textRaw": "fs.fstatSync(fd)", "type": "method", "name": "fstatSync", "desc": "

    Synchronous fstat(2). Returns an instance of fs.Stats.\n\n

    \n", "signatures": [ { "params": [ { "name": "fd" } ] } ] }, { "textRaw": "fs.link(srcpath, dstpath, callback)", "type": "method", "name": "link", "desc": "

    Asynchronous link(2). No arguments other than a possible exception are given to\nthe completion callback.\n\n

    \n", "signatures": [ { "params": [ { "name": "srcpath" }, { "name": "dstpath" }, { "name": "callback" } ] } ] }, { "textRaw": "fs.linkSync(srcpath, dstpath)", "type": "method", "name": "linkSync", "desc": "

    Synchronous link(2).\n\n

    \n", "signatures": [ { "params": [ { "name": "srcpath" }, { "name": "dstpath" } ] } ] }, { "textRaw": "fs.symlink(srcpath, dstpath, [type], callback)", "type": "method", "name": "symlink", "desc": "

    Asynchronous symlink(2). No arguments other than a possible exception are given\nto the completion callback.\nThe type argument can be set to 'dir', 'file', or 'junction' (default\nis 'file') and is only available on Windows (ignored on other platforms).\nNote that Windows junction points require the destination path to be absolute. When using\n'junction', the destination argument will automatically be normalized to absolute path.\n\n

    \n", "signatures": [ { "params": [ { "name": "srcpath" }, { "name": "dstpath" }, { "name": "type", "optional": true }, { "name": "callback" } ] } ] }, { "textRaw": "fs.symlinkSync(srcpath, dstpath, [type])", "type": "method", "name": "symlinkSync", "desc": "

    Synchronous symlink(2).\n\n

    \n", "signatures": [ { "params": [ { "name": "srcpath" }, { "name": "dstpath" }, { "name": "type", "optional": true } ] } ] }, { "textRaw": "fs.readlink(path, callback)", "type": "method", "name": "readlink", "desc": "

    Asynchronous readlink(2). The callback gets two arguments (err,\nlinkString).\n\n

    \n", "signatures": [ { "params": [ { "name": "path" }, { "name": "callback" } ] } ] }, { "textRaw": "fs.readlinkSync(path)", "type": "method", "name": "readlinkSync", "desc": "

    Synchronous readlink(2). Returns the symbolic link's string value.\n\n

    \n", "signatures": [ { "params": [ { "name": "path" } ] } ] }, { "textRaw": "fs.realpath(path, [cache], callback)", "type": "method", "name": "realpath", "desc": "

    Asynchronous realpath(2). The callback gets two arguments (err,\nresolvedPath). May use process.cwd to resolve relative paths. cache is an\nobject literal of mapped paths that can be used to force a specific path\nresolution or avoid additional fs.stat calls for known real paths.\n\n

    \n

    Example:\n\n

    \n
    var cache = {'/etc':'/private/etc'};\nfs.realpath('/etc/passwd', cache, function (err, resolvedPath) {\n  if (err) throw err;\n  console.log(resolvedPath);\n});
    \n", "signatures": [ { "params": [ { "name": "path" }, { "name": "cache", "optional": true }, { "name": "callback" } ] } ] }, { "textRaw": "fs.realpathSync(path, [cache])", "type": "method", "name": "realpathSync", "desc": "

    Synchronous realpath(2). Returns the resolved path.\n\n

    \n", "signatures": [ { "params": [ { "name": "path" }, { "name": "cache", "optional": true } ] } ] }, { "textRaw": "fs.unlink(path, callback)", "type": "method", "name": "unlink", "desc": "

    Asynchronous unlink(2). No arguments other than a possible exception are given\nto the completion callback.\n\n

    \n", "signatures": [ { "params": [ { "name": "path" }, { "name": "callback" } ] } ] }, { "textRaw": "fs.unlinkSync(path)", "type": "method", "name": "unlinkSync", "desc": "

    Synchronous unlink(2).\n\n

    \n", "signatures": [ { "params": [ { "name": "path" } ] } ] }, { "textRaw": "fs.rmdir(path, callback)", "type": "method", "name": "rmdir", "desc": "

    Asynchronous rmdir(2). No arguments other than a possible exception are given\nto the completion callback.\n\n

    \n", "signatures": [ { "params": [ { "name": "path" }, { "name": "callback" } ] } ] }, { "textRaw": "fs.rmdirSync(path)", "type": "method", "name": "rmdirSync", "desc": "

    Synchronous rmdir(2).\n\n

    \n", "signatures": [ { "params": [ { "name": "path" } ] } ] }, { "textRaw": "fs.mkdir(path, [mode], callback)", "type": "method", "name": "mkdir", "desc": "

    Asynchronous mkdir(2). No arguments other than a possible exception are given\nto the completion callback. mode defaults to 0777.\n\n

    \n", "signatures": [ { "params": [ { "name": "path" }, { "name": "mode", "optional": true }, { "name": "callback" } ] } ] }, { "textRaw": "fs.mkdirSync(path, [mode])", "type": "method", "name": "mkdirSync", "desc": "

    Synchronous mkdir(2).\n\n

    \n", "signatures": [ { "params": [ { "name": "path" }, { "name": "mode", "optional": true } ] } ] }, { "textRaw": "fs.readdir(path, callback)", "type": "method", "name": "readdir", "desc": "

    Asynchronous readdir(3). Reads the contents of a directory.\nThe callback gets two arguments (err, files) where files is an array of\nthe names of the files in the directory excluding '.' and '..'.\n\n

    \n", "signatures": [ { "params": [ { "name": "path" }, { "name": "callback" } ] } ] }, { "textRaw": "fs.readdirSync(path)", "type": "method", "name": "readdirSync", "desc": "

    Synchronous readdir(3). Returns an array of filenames excluding '.' and\n'..'.\n\n

    \n", "signatures": [ { "params": [ { "name": "path" } ] } ] }, { "textRaw": "fs.close(fd, callback)", "type": "method", "name": "close", "desc": "

    Asynchronous close(2). No arguments other than a possible exception are given\nto the completion callback.\n\n

    \n", "signatures": [ { "params": [ { "name": "fd" }, { "name": "callback" } ] } ] }, { "textRaw": "fs.closeSync(fd)", "type": "method", "name": "closeSync", "desc": "

    Synchronous close(2).\n\n

    \n", "signatures": [ { "params": [ { "name": "fd" } ] } ] }, { "textRaw": "fs.open(path, flags, [mode], callback)", "type": "method", "name": "open", "desc": "

    Asynchronous file open. See open(2). flags can be:\n\n

    \n
      \n
    • 'r' - Open file for reading.\nAn exception occurs if the file does not exist.

      \n
    • \n
    • 'r+' - Open file for reading and writing.\nAn exception occurs if the file does not exist.

      \n
    • \n
    • 'rs' - Open file for reading in synchronous mode. Instructs the operating\nsystem to bypass the local file system cache.

      \n

      This is primarily useful for opening files on NFS mounts as it allows you to\nskip the potentially stale local cache. It has a very real impact on I/O\nperformance so don't use this flag unless you need it.

      \n

      Note that this doesn't turn fs.open() into a synchronous blocking call.\nIf that's what you want then you should be using fs.openSync()

      \n
    • \n
    • 'rs+' - Open file for reading and writing, telling the OS to open it\nsynchronously. See notes for 'rs' about using this with caution.

      \n
    • \n
    • 'w' - Open file for writing.\nThe file is created (if it does not exist) or truncated (if it exists).

      \n
    • \n
    • 'wx' - Like 'w' but fails if path exists.

      \n
    • \n
    • 'w+' - Open file for reading and writing.\nThe file is created (if it does not exist) or truncated (if it exists).

      \n
    • \n
    • 'wx+' - Like 'w+' but fails if path exists.

      \n
    • \n
    • 'a' - Open file for appending.\nThe file is created if it does not exist.

      \n
    • \n
    • 'ax' - Like 'a' but fails if path exists.

      \n
    • \n
    • 'a+' - Open file for reading and appending.\nThe file is created if it does not exist.

      \n
    • \n
    • 'ax+' - Like 'a+' but fails if path exists.

      \n
    • \n
    \n

    mode sets the file mode (permission and sticky bits), but only if the file was\ncreated. It defaults to 0666, readable and writeable.\n\n

    \n

    The callback gets two arguments (err, fd).\n\n

    \n

    The exclusive flag 'x' (O_EXCL flag in open(2)) ensures that path is newly\ncreated. On POSIX systems, path is considered to exist even if it is a symlink\nto a non-existent file. The exclusive flag may or may not work with network file\nsystems.\n\n

    \n

    On Linux, positional writes don't work when the file is opened in append mode.\nThe kernel ignores the position argument and always appends the data to\nthe end of the file.\n\n

    \n", "signatures": [ { "params": [ { "name": "path" }, { "name": "flags" }, { "name": "mode", "optional": true }, { "name": "callback" } ] } ] }, { "textRaw": "fs.openSync(path, flags, [mode])", "type": "method", "name": "openSync", "desc": "

    Synchronous version of fs.open().\n\n

    \n", "signatures": [ { "params": [ { "name": "path" }, { "name": "flags" }, { "name": "mode", "optional": true } ] } ] }, { "textRaw": "fs.utimes(path, atime, mtime, callback)", "type": "method", "name": "utimes", "desc": "

    Change file timestamps of the file referenced by the supplied path.\n\n

    \n", "signatures": [ { "params": [ { "name": "path" }, { "name": "atime" }, { "name": "mtime" } ] }, { "params": [ { "name": "path" }, { "name": "atime" }, { "name": "mtime" }, { "name": "callback" } ] } ] }, { "textRaw": "fs.utimesSync(path, atime, mtime)", "type": "method", "name": "utimesSync", "desc": "

    Change file timestamps of the file referenced by the supplied path.\n\n

    \n", "signatures": [ { "params": [ { "name": "path" }, { "name": "atime" }, { "name": "mtime" } ] } ] }, { "textRaw": "fs.futimes(fd, atime, mtime, callback)", "type": "method", "name": "futimes", "desc": "

    Change the file timestamps of a file referenced by the supplied file\ndescriptor.\n\n

    \n", "signatures": [ { "params": [ { "name": "fd" }, { "name": "atime" }, { "name": "mtime" } ] }, { "params": [ { "name": "fd" }, { "name": "atime" }, { "name": "mtime" }, { "name": "callback" } ] } ] }, { "textRaw": "fs.futimesSync(fd, atime, mtime)", "type": "method", "name": "futimesSync", "desc": "

    Change the file timestamps of a file referenced by the supplied file\ndescriptor.\n\n

    \n", "signatures": [ { "params": [ { "name": "fd" }, { "name": "atime" }, { "name": "mtime" } ] } ] }, { "textRaw": "fs.fsync(fd, callback)", "type": "method", "name": "fsync", "desc": "

    Asynchronous fsync(2). No arguments other than a possible exception are given\nto the completion callback.\n\n

    \n", "signatures": [ { "params": [ { "name": "fd" }, { "name": "callback" } ] } ] }, { "textRaw": "fs.fsyncSync(fd)", "type": "method", "name": "fsyncSync", "desc": "

    Synchronous fsync(2).\n\n

    \n", "signatures": [ { "params": [ { "name": "fd" } ] } ] }, { "textRaw": "fs.write(fd, buffer, offset, length, position, callback)", "type": "method", "name": "write", "desc": "

    Write buffer to the file specified by fd.\n\n

    \n

    offset and length determine the part of the buffer to be written.\n\n

    \n

    position refers to the offset from the beginning of the file where this data\nshould be written. If position is null, the data will be written at the\ncurrent position.\nSee pwrite(2).\n\n

    \n

    The callback will be given three arguments (err, written, buffer) where written\nspecifies how many bytes were written from buffer.\n\n

    \n

    Note that it is unsafe to use fs.write multiple times on the same file\nwithout waiting for the callback. For this scenario,\nfs.createWriteStream is strongly recommended.\n\n

    \n

    On Linux, positional writes don't work when the file is opened in append mode.\nThe kernel ignores the position argument and always appends the data to\nthe end of the file.\n\n

    \n", "signatures": [ { "params": [ { "name": "fd" }, { "name": "buffer" }, { "name": "offset" }, { "name": "length" }, { "name": "position" }, { "name": "callback" } ] } ] }, { "textRaw": "fs.writeSync(fd, buffer, offset, length, position)", "type": "method", "name": "writeSync", "desc": "

    Synchronous version of fs.write(). Returns the number of bytes written.\n\n

    \n", "signatures": [ { "params": [ { "name": "fd" }, { "name": "buffer" }, { "name": "offset" }, { "name": "length" }, { "name": "position" } ] } ] }, { "textRaw": "fs.read(fd, buffer, offset, length, position, callback)", "type": "method", "name": "read", "desc": "

    Read data from the file specified by fd.\n\n

    \n

    buffer is the buffer that the data will be written to.\n\n

    \n

    offset is the offset in the buffer to start writing at.\n\n

    \n

    length is an integer specifying the number of bytes to read.\n\n

    \n

    position is an integer specifying where to begin reading from in the file.\nIf position is null, data will be read from the current file position.\n\n

    \n

    The callback is given the three arguments, (err, bytesRead, buffer).\n\n

    \n", "signatures": [ { "params": [ { "name": "fd" }, { "name": "buffer" }, { "name": "offset" }, { "name": "length" }, { "name": "position" }, { "name": "callback" } ] } ] }, { "textRaw": "fs.readSync(fd, buffer, offset, length, position)", "type": "method", "name": "readSync", "desc": "

    Synchronous version of fs.read. Returns the number of bytesRead.\n\n

    \n", "signatures": [ { "params": [ { "name": "fd" }, { "name": "buffer" }, { "name": "offset" }, { "name": "length" }, { "name": "position" } ] } ] }, { "textRaw": "fs.readFile(filename, [options], callback)", "type": "method", "name": "readFile", "signatures": [ { "params": [ { "textRaw": "`filename` {String} ", "name": "filename", "type": "String" }, { "textRaw": "`options` {Object} ", "options": [ { "textRaw": "`encoding` {String | Null} default = `null` ", "name": "encoding", "type": "String | Null", "desc": "default = `null`" }, { "textRaw": "`flag` {String} default = `'r'` ", "name": "flag", "type": "String", "desc": "default = `'r'`" } ], "name": "options", "type": "Object", "optional": true }, { "textRaw": "`callback` {Function} ", "name": "callback", "type": "Function" } ] }, { "params": [ { "name": "filename" }, { "name": "options", "optional": true }, { "name": "callback" } ] } ], "desc": "

    Asynchronously reads the entire contents of a file. Example:\n\n

    \n
    fs.readFile('/etc/passwd', function (err, data) {\n  if (err) throw err;\n  console.log(data);\n});
    \n

    The callback is passed two arguments (err, data), where data is the\ncontents of the file.\n\n

    \n

    If no encoding is specified, then the raw buffer is returned.\n\n\n

    \n" }, { "textRaw": "fs.readFileSync(filename, [options])", "type": "method", "name": "readFileSync", "desc": "

    Synchronous version of fs.readFile. Returns the contents of the filename.\n\n

    \n

    If the encoding option is specified then this function returns a\nstring. Otherwise it returns a buffer.\n\n\n

    \n", "signatures": [ { "params": [ { "name": "filename" }, { "name": "options", "optional": true } ] } ] }, { "textRaw": "fs.writeFile(filename, data, [options], callback)", "type": "method", "name": "writeFile", "signatures": [ { "params": [ { "textRaw": "`filename` {String} ", "name": "filename", "type": "String" }, { "textRaw": "`data` {String | Buffer} ", "name": "data", "type": "String | Buffer" }, { "textRaw": "`options` {Object} ", "options": [ { "textRaw": "`encoding` {String | Null} default = `'utf8'` ", "name": "encoding", "type": "String | Null", "desc": "default = `'utf8'`" }, { "textRaw": "`mode` {Number} default = `438` (aka `0666` in Octal) ", "name": "mode", "type": "Number", "desc": "default = `438` (aka `0666` in Octal)" }, { "textRaw": "`flag` {String} default = `'w'` ", "name": "flag", "type": "String", "desc": "default = `'w'`" } ], "name": "options", "type": "Object", "optional": true }, { "textRaw": "`callback` {Function} ", "name": "callback", "type": "Function" } ] }, { "params": [ { "name": "filename" }, { "name": "data" }, { "name": "options", "optional": true }, { "name": "callback" } ] } ], "desc": "

    Asynchronously writes data to a file, replacing the file if it already exists.\ndata can be a string or a buffer.\n\n

    \n

    The encoding option is ignored if data is a buffer. It defaults\nto 'utf8'.\n\n

    \n

    Example:\n\n

    \n
    fs.writeFile('message.txt', 'Hello Node', function (err) {\n  if (err) throw err;\n  console.log('It\\'s saved!');\n});
    \n" }, { "textRaw": "fs.writeFileSync(filename, data, [options])", "type": "method", "name": "writeFileSync", "desc": "

    The synchronous version of fs.writeFile.\n\n

    \n", "signatures": [ { "params": [ { "name": "filename" }, { "name": "data" }, { "name": "options", "optional": true } ] } ] }, { "textRaw": "fs.appendFile(filename, data, [options], callback)", "type": "method", "name": "appendFile", "signatures": [ { "params": [ { "textRaw": "`filename` {String} ", "name": "filename", "type": "String" }, { "textRaw": "`data` {String | Buffer} ", "name": "data", "type": "String | Buffer" }, { "textRaw": "`options` {Object} ", "options": [ { "textRaw": "`encoding` {String | Null} default = `'utf8'` ", "name": "encoding", "type": "String | Null", "desc": "default = `'utf8'`" }, { "textRaw": "`mode` {Number} default = `438` (aka `0666` in Octal) ", "name": "mode", "type": "Number", "desc": "default = `438` (aka `0666` in Octal)" }, { "textRaw": "`flag` {String} default = `'a'` ", "name": "flag", "type": "String", "desc": "default = `'a'`" } ], "name": "options", "type": "Object", "optional": true }, { "textRaw": "`callback` {Function} ", "name": "callback", "type": "Function" } ] }, { "params": [ { "name": "filename" }, { "name": "data" }, { "name": "options", "optional": true }, { "name": "callback" } ] } ], "desc": "

    Asynchronously append data to a file, creating the file if it not yet exists.\ndata can be a string or a buffer.\n\n

    \n

    Example:\n\n

    \n
    fs.appendFile('message.txt', 'data to append', function (err) {\n  if (err) throw err;\n  console.log('The "data to append" was appended to file!');\n});
    \n" }, { "textRaw": "fs.appendFileSync(filename, data, [options])", "type": "method", "name": "appendFileSync", "desc": "

    The synchronous version of fs.appendFile.\n\n

    \n", "signatures": [ { "params": [ { "name": "filename" }, { "name": "data" }, { "name": "options", "optional": true } ] } ] }, { "textRaw": "fs.watchFile(filename, [options], listener)", "type": "method", "name": "watchFile", "stability": 2, "stabilityText": "Unstable. Use fs.watch instead, if possible.", "desc": "

    Watch for changes on filename. The callback listener will be called each\ntime the file is accessed.\n\n

    \n

    The second argument is optional. The options if provided should be an object\ncontaining two members a boolean, persistent, and interval. persistent\nindicates whether the process should continue to run as long as files are\nbeing watched. interval indicates how often the target should be polled,\nin milliseconds. The default is { persistent: true, interval: 5007 }.\n\n

    \n

    The listener gets two arguments the current stat object and the previous\nstat object:\n\n

    \n
    fs.watchFile('message.text', function (curr, prev) {\n  console.log('the current mtime is: ' + curr.mtime);\n  console.log('the previous mtime was: ' + prev.mtime);\n});
    \n

    These stat objects are instances of fs.Stat.\n\n

    \n

    If you want to be notified when the file was modified, not just accessed\nyou need to compare curr.mtime and prev.mtime.\n\n

    \n", "signatures": [ { "params": [ { "name": "filename" }, { "name": "options", "optional": true }, { "name": "listener" } ] } ] }, { "textRaw": "fs.unwatchFile(filename, [listener])", "type": "method", "name": "unwatchFile", "stability": 2, "stabilityText": "Unstable. Use fs.watch instead, if possible.", "desc": "

    Stop watching for changes on filename. If listener is specified, only that\nparticular listener is removed. Otherwise, all listeners are removed and you\nhave effectively stopped watching filename.\n\n

    \n

    Calling fs.unwatchFile() with a filename that is not being watched is a\nno-op, not an error.\n\n

    \n", "signatures": [ { "params": [ { "name": "filename" }, { "name": "listener", "optional": true } ] } ] }, { "textRaw": "fs.watch(filename, [options], [listener])", "type": "method", "name": "watch", "stability": 2, "stabilityText": "Unstable.", "desc": "

    Watch for changes on filename, where filename is either a file or a\ndirectory. The returned object is a fs.FSWatcher.\n\n

    \n

    The second argument is optional. The options if provided should be an object\ncontaining a boolean member persistent, which indicates whether the process\nshould continue to run as long as files are being watched. The default is\n{ persistent: true }.\n\n

    \n

    The listener callback gets two arguments (event, filename). event is either\n'rename' or 'change', and filename is the name of the file which triggered\nthe event.\n\n

    \n", "miscs": [ { "textRaw": "Caveats", "name": "Caveats", "type": "misc", "desc": "

    The fs.watch API is not 100% consistent across platforms, and is\nunavailable in some situations.\n\n

    \n", "miscs": [ { "textRaw": "Availability", "name": "Availability", "type": "misc", "desc": "

    This feature depends on the underlying operating system providing a way\nto be notified of filesystem changes.\n\n

    \n
      \n
    • On Linux systems, this uses inotify.
    • \n
    • On BSD systems (including OS X), this uses kqueue.
    • \n
    • On SunOS systems (including Solaris and SmartOS), this uses event ports.
    • \n
    • On Windows systems, this feature depends on ReadDirectoryChangesW.
    • \n
    \n

    If the underlying functionality is not available for some reason, then\nfs.watch will not be able to function. For example, watching files or\ndirectories on network file systems (NFS, SMB, etc.) often doesn't work\nreliably or at all.\n\n

    \n

    You can still use fs.watchFile, which uses stat polling, but it is slower and\nless reliable.\n\n

    \n" }, { "textRaw": "Filename Argument", "name": "Filename Argument", "type": "misc", "desc": "

    Providing filename argument in the callback is not supported\non every platform (currently it's only supported on Linux and Windows). Even\non supported platforms filename is not always guaranteed to be provided.\nTherefore, don't assume that filename argument is always provided in the\ncallback, and have some fallback logic if it is null.\n\n

    \n
    fs.watch('somedir', function (event, filename) {\n  console.log('event is: ' + event);\n  if (filename) {\n    console.log('filename provided: ' + filename);\n  } else {\n    console.log('filename not provided');\n  }\n});
    \n" } ] } ], "signatures": [ { "params": [ { "name": "filename" }, { "name": "options", "optional": true }, { "name": "listener", "optional": true } ] } ] }, { "textRaw": "fs.exists(path, callback)", "type": "method", "name": "exists", "desc": "

    Test whether or not the given path exists by checking with the file system.\nThen call the callback argument with either true or false. Example:\n\n

    \n
    fs.exists('/etc/passwd', function (exists) {\n  util.debug(exists ? "it's there" : "no passwd!");\n});
    \n

    fs.exists() is an anachronism and exists only for historical reasons.\nThere should almost never be a reason to use it in your own code.\n\n

    \n

    In particular, checking if a file exists before opening it is an anti-pattern\nthat leaves you vulnerable to race conditions: another process may remove the\nfile between the calls to fs.exists() and fs.open(). Just open the file\nand handle the error when it's not there.\n\n

    \n", "signatures": [ { "params": [ { "name": "path" }, { "name": "callback" } ] } ] }, { "textRaw": "fs.existsSync(path)", "type": "method", "name": "existsSync", "desc": "

    Synchronous version of fs.exists.\n\n

    \n", "signatures": [ { "params": [ { "name": "path" } ] } ] }, { "textRaw": "fs.createReadStream(path, [options])", "type": "method", "name": "createReadStream", "desc": "

    Returns a new ReadStream object (See Readable Stream).\n\n

    \n

    options is an object with the following defaults:\n\n

    \n
    { flags: 'r',\n  encoding: null,\n  fd: null,\n  mode: 0666,\n  autoClose: true\n}
    \n

    options can include start and end values to read a range of bytes from\nthe file instead of the entire file. Both start and end are inclusive and\nstart at 0. The encoding can be 'utf8', 'ascii', or 'base64'.\n\n

    \n

    If autoClose is false, then the file descriptor won't be closed, even if\nthere's an error. It is your responsiblity to close it and make sure\nthere's no file descriptor leak. If autoClose is set to true (default\nbehavior), on error or end the file descriptor will be closed\nautomatically.\n\n

    \n

    An example to read the last 10 bytes of a file which is 100 bytes long:\n\n

    \n
    fs.createReadStream('sample.txt', {start: 90, end: 99});
    \n", "signatures": [ { "params": [ { "name": "path" }, { "name": "options", "optional": true } ] } ] }, { "textRaw": "fs.createWriteStream(path, [options])", "type": "method", "name": "createWriteStream", "desc": "

    Returns a new WriteStream object (See Writable Stream).\n\n

    \n

    options is an object with the following defaults:\n\n

    \n
    { flags: 'w',\n  encoding: null,\n  mode: 0666 }
    \n

    options may also include a start option to allow writing data at\nsome position past the beginning of the file. Modifying a file rather\nthan replacing it may require a flags mode of r+ rather than the\ndefault mode w.\n\n

    \n", "signatures": [ { "params": [ { "name": "path" }, { "name": "options", "optional": true } ] } ] } ], "classes": [ { "textRaw": "Class: fs.Stats", "type": "class", "name": "fs.Stats", "desc": "

    Objects returned from fs.stat(), fs.lstat() and fs.fstat() and their\nsynchronous counterparts are of this type.\n\n

    \n
      \n
    • stats.isFile()
    • \n
    • stats.isDirectory()
    • \n
    • stats.isBlockDevice()
    • \n
    • stats.isCharacterDevice()
    • \n
    • stats.isSymbolicLink() (only valid with fs.lstat())
    • \n
    • stats.isFIFO()
    • \n
    • stats.isSocket()
    • \n
    \n

    For a regular file util.inspect(stats) would return a string very\nsimilar to this:\n\n

    \n
    { dev: 2114,\n  ino: 48064969,\n  mode: 33188,\n  nlink: 1,\n  uid: 85,\n  gid: 100,\n  rdev: 0,\n  size: 527,\n  blksize: 4096,\n  blocks: 8,\n  atime: Mon, 10 Oct 2011 23:24:11 GMT,\n  mtime: Mon, 10 Oct 2011 23:24:11 GMT,\n  ctime: Mon, 10 Oct 2011 23:24:11 GMT }
    \n

    Please note that atime, mtime and ctime are instances\nof [Date][MDN-Date] object and to compare the values of\nthese objects you should use appropriate methods. For most\ngeneral uses [getTime()][MDN-Date-getTime] will return\nthe number of milliseconds elapsed since 1 January 1970\n00:00:00 UTC and this integer should be sufficient for\nany comparison, however there additional methods which can\nbe used for displaying fuzzy information. More details can\nbe found in the [MDN JavaScript Reference][MDN-Date] page.\n\n

    \n" }, { "textRaw": "Class: fs.ReadStream", "type": "class", "name": "fs.ReadStream", "desc": "

    ReadStream is a Readable Stream.\n\n

    \n", "events": [ { "textRaw": "Event: 'open'", "type": "event", "name": "open", "params": [], "desc": "

    Emitted when the ReadStream's file is opened.\n\n\n

    \n" } ] }, { "textRaw": "Class: fs.WriteStream", "type": "class", "name": "fs.WriteStream", "desc": "

    WriteStream is a Writable Stream.\n\n

    \n", "events": [ { "textRaw": "Event: 'open'", "type": "event", "name": "open", "params": [], "desc": "

    Emitted when the WriteStream's file is opened.\n\n

    \n" } ], "properties": [ { "textRaw": "file.bytesWritten", "name": "bytesWritten", "desc": "

    The number of bytes written so far. Does not include data that is still queued\nfor writing.\n\n

    \n" } ] }, { "textRaw": "Class: fs.FSWatcher", "type": "class", "name": "fs.FSWatcher", "desc": "

    Objects returned from fs.watch() are of this type.\n\n

    \n", "methods": [ { "textRaw": "watcher.close()", "type": "method", "name": "close", "desc": "

    Stop watching for changes on the given fs.FSWatcher.\n\n

    \n", "signatures": [ { "params": [] } ] } ], "events": [ { "textRaw": "Event: 'change'", "type": "event", "name": "change", "params": [], "desc": "

    Emitted when something changes in a watched directory or file.\nSee more details in fs.watch.\n\n

    \n" }, { "textRaw": "Event: 'error'", "type": "event", "name": "error", "params": [], "desc": "

    Emitted when an error occurs.\n

    \n" } ] } ], "type": "module", "displayName": "fs" } ] } node-v0.10.25~dfsg2/doc/api/path.markdown0000644000000000000000000001060512270121457016635 0ustar rootroot# Path Stability: 3 - Stable This module contains utilities for handling and transforming file paths. Almost all these methods perform only string transformations. The file system is not consulted to check whether paths are valid. Use `require('path')` to use this module. The following methods are provided: ## path.normalize(p) Normalize a string path, taking care of `'..'` and `'.'` parts. When multiple slashes are found, they're replaced by a single one; when the path contains a trailing slash, it is preserved. On Windows backslashes are used. Example: path.normalize('/foo/bar//baz/asdf/quux/..') // returns '/foo/bar/baz/asdf' ## path.join([path1], [path2], [...]) Join all arguments together and normalize the resulting path. Arguments must be strings. In v0.8, non-string arguments were silently ignored. In v0.10 and up, an exception is thrown. Example: path.join('/foo', 'bar', 'baz/asdf', 'quux', '..') // returns '/foo/bar/baz/asdf' path.join('foo', {}, 'bar') // throws exception TypeError: Arguments to path.join must be strings ## path.resolve([from ...], to) Resolves `to` to an absolute path. If `to` isn't already absolute `from` arguments are prepended in right to left order, until an absolute path is found. If after using all `from` paths still no absolute path is found, the current working directory is used as well. The resulting path is normalized, and trailing slashes are removed unless the path gets resolved to the root directory. Non-string arguments are ignored. Another way to think of it is as a sequence of `cd` commands in a shell. path.resolve('foo/bar', '/tmp/file/', '..', 'a/../subfile') Is similar to: cd foo/bar cd /tmp/file/ cd .. cd a/../subfile pwd The difference is that the different paths don't need to exist and may also be files. Examples: path.resolve('/foo/bar', './baz') // returns '/foo/bar/baz' path.resolve('/foo/bar', '/tmp/file/') // returns '/tmp/file' path.resolve('wwwroot', 'static_files/png/', '../gif/image.gif') // if currently in /home/myself/node, it returns '/home/myself/node/wwwroot/static_files/gif/image.gif' ## path.relative(from, to) Solve the relative path from `from` to `to`. At times we have two absolute paths, and we need to derive the relative path from one to the other. This is actually the reverse transform of `path.resolve`, which means we see that: path.resolve(from, path.relative(from, to)) == path.resolve(to) Examples: path.relative('C:\\orandea\\test\\aaa', 'C:\\orandea\\impl\\bbb') // returns '..\\..\\impl\\bbb' path.relative('/data/orandea/test/aaa', '/data/orandea/impl/bbb') // returns '../../impl/bbb' ## path.dirname(p) Return the directory name of a path. Similar to the Unix `dirname` command. Example: path.dirname('/foo/bar/baz/asdf/quux') // returns '/foo/bar/baz/asdf' ## path.basename(p, [ext]) Return the last portion of a path. Similar to the Unix `basename` command. Example: path.basename('/foo/bar/baz/asdf/quux.html') // returns 'quux.html' path.basename('/foo/bar/baz/asdf/quux.html', '.html') // returns 'quux' ## path.extname(p) Return the extension of the path, from the last '.' to end of string in the last portion of the path. If there is no '.' in the last portion of the path or the first character of it is '.', then it returns an empty string. Examples: path.extname('index.html') // returns '.html' path.extname('index.') // returns '.' path.extname('index') // returns '' ## path.sep The platform-specific file separator. `'\\'` or `'/'`. An example on *nix: 'foo/bar/baz'.split(path.sep) // returns ['foo', 'bar', 'baz'] An example on Windows: 'foo\\bar\\baz'.split(path.sep) // returns ['foo', 'bar', 'baz'] ## path.delimiter The platform-specific path delimiter, `;` or `':'`. An example on *nix: console.log(process.env.PATH) // '/usr/bin:/bin:/usr/sbin:/sbin:/usr/local/bin' process.env.PATH.split(path.delimiter) // returns ['/usr/bin', '/bin', '/usr/sbin', '/sbin', '/usr/local/bin'] An example on Windows: console.log(process.env.PATH) // 'C:\Windows\system32;C:\Windows;C:\Program Files\nodejs\' process.env.PATH.split(path.delimiter) // returns ['C:\Windows\system32', 'C:\Windows', 'C:\Program Files\nodejs\'] node-v0.10.25~dfsg2/doc/api/https.markdown0000644000000000000000000001453612270121457017052 0ustar rootroot# HTTPS Stability: 3 - Stable HTTPS is the HTTP protocol over TLS/SSL. In Node this is implemented as a separate module. ## Class: https.Server This class is a subclass of `tls.Server` and emits events same as `http.Server`. See `http.Server` for more information. ## https.createServer(options, [requestListener]) Returns a new HTTPS web server object. The `options` is similar to [tls.createServer()][]. The `requestListener` is a function which is automatically added to the `'request'` event. Example: // curl -k https://localhost:8000/ var https = require('https'); var fs = require('fs'); var options = { key: fs.readFileSync('test/fixtures/keys/agent2-key.pem'), cert: fs.readFileSync('test/fixtures/keys/agent2-cert.pem') }; https.createServer(options, function (req, res) { res.writeHead(200); res.end("hello world\n"); }).listen(8000); Or var https = require('https'); var fs = require('fs'); var options = { pfx: fs.readFileSync('server.pfx') }; https.createServer(options, function (req, res) { res.writeHead(200); res.end("hello world\n"); }).listen(8000); ### server.listen(port, [host], [backlog], [callback]) ### server.listen(path, [callback]) ### server.listen(handle, [callback]) See [http.listen()][] for details. ### server.close([callback]) See [http.close()][] for details. ## https.request(options, callback) Makes a request to a secure web server. `options` can be an object or a string. If `options` is a string, it is automatically parsed with [url.parse()](url.html#url.parse). All options from [http.request()][] are valid. Example: var https = require('https'); var options = { hostname: 'encrypted.google.com', port: 443, path: '/', method: 'GET' }; var req = https.request(options, function(res) { console.log("statusCode: ", res.statusCode); console.log("headers: ", res.headers); res.on('data', function(d) { process.stdout.write(d); }); }); req.end(); req.on('error', function(e) { console.error(e); }); The options argument has the following options - `host`: A domain name or IP address of the server to issue the request to. Defaults to `'localhost'`. - `hostname`: To support `url.parse()` `hostname` is preferred over `host` - `port`: Port of remote server. Defaults to 443. - `method`: A string specifying the HTTP request method. Defaults to `'GET'`. - `path`: Request path. Defaults to `'/'`. Should include query string if any. E.G. `'/index.html?page=12'` - `headers`: An object containing request headers. - `auth`: Basic authentication i.e. `'user:password'` to compute an Authorization header. - `agent`: Controls [Agent][] behavior. When an Agent is used request will default to `Connection: keep-alive`. Possible values: - `undefined` (default): use [globalAgent][] for this host and port. - `Agent` object: explicitly use the passed in `Agent`. - `false`: opts out of connection pooling with an Agent, defaults request to `Connection: close`. The following options from [tls.connect()][] can also be specified. However, a [globalAgent][] silently ignores these. - `pfx`: Certificate, Private key and CA certificates to use for SSL. Default `null`. - `key`: Private key to use for SSL. Default `null`. - `passphrase`: A string of passphrase for the private key or pfx. Default `null`. - `cert`: Public x509 certificate to use. Default `null`. - `ca`: An authority certificate or array of authority certificates to check the remote host against. - `ciphers`: A string describing the ciphers to use or exclude. Consult for details on the format. - `rejectUnauthorized`: If `true`, the server certificate is verified against the list of supplied CAs. An `'error'` event is emitted if verification fails. Verification happens at the connection level, *before* the HTTP request is sent. Default `true`. - `secureProtocol`: The SSL method to use, e.g. `SSLv3_method` to force SSL version 3. The possible values depend on your installation of OpenSSL and are defined in the constant [SSL_METHODS][]. In order to specify these options, use a custom `Agent`. Example: var options = { hostname: 'encrypted.google.com', port: 443, path: '/', method: 'GET', key: fs.readFileSync('test/fixtures/keys/agent2-key.pem'), cert: fs.readFileSync('test/fixtures/keys/agent2-cert.pem') }; options.agent = new https.Agent(options); var req = https.request(options, function(res) { ... } Or does not use an `Agent`. Example: var options = { hostname: 'encrypted.google.com', port: 443, path: '/', method: 'GET', key: fs.readFileSync('test/fixtures/keys/agent2-key.pem'), cert: fs.readFileSync('test/fixtures/keys/agent2-cert.pem'), agent: false }; var req = https.request(options, function(res) { ... } ## https.get(options, callback) Like `http.get()` but for HTTPS. `options` can be an object or a string. If `options` is a string, it is automatically parsed with [url.parse()](url.html#url.parse). Example: var https = require('https'); https.get('https://encrypted.google.com/', function(res) { console.log("statusCode: ", res.statusCode); console.log("headers: ", res.headers); res.on('data', function(d) { process.stdout.write(d); }); }).on('error', function(e) { console.error(e); }); ## Class: https.Agent An Agent object for HTTPS similar to [http.Agent][]. See [https.request()][] for more information. ## https.globalAgent Global instance of [https.Agent][] for all HTTPS client requests. [Agent]: #https_class_https_agent [globalAgent]: #https_https_globalagent [http.listen()]: http.html#http_server_listen_port_hostname_backlog_callback [http.close()]: http.html#http_server_close_callback [http.Agent]: http.html#http_class_http_agent [http.request()]: http.html#http_http_request_options_callback [https.Agent]: #https_class_https_agent [https.request()]: #https_https_request_options_callback [tls.connect()]: tls.html#tls_tls_connect_options_callback [tls.createServer()]: tls.html#tls_tls_createserver_options_secureconnectionlistener [SSL_METHODS]: http://www.openssl.org/docs/ssl/ssl.html#DEALING_WITH_PROTOCOL_METHODS node-v0.10.25~dfsg2/doc/api/util.markdown0000644000000000000000000001461112270121457016657 0ustar rootroot# util Stability: 4 - API Frozen These functions are in the module `'util'`. Use `require('util')` to access them. ## util.format(format, [...]) Returns a formatted string using the first argument as a `printf`-like format. The first argument is a string that contains zero or more *placeholders*. Each placeholder is replaced with the converted value from its corresponding argument. Supported placeholders are: * `%s` - String. * `%d` - Number (both integer and float). * `%j` - JSON. * `%%` - single percent sign (`'%'`). This does not consume an argument. If the placeholder does not have a corresponding argument, the placeholder is not replaced. util.format('%s:%s', 'foo'); // 'foo:%s' If there are more arguments than placeholders, the extra arguments are converted to strings with `util.inspect()` and these strings are concatenated, delimited by a space. util.format('%s:%s', 'foo', 'bar', 'baz'); // 'foo:bar baz' If the first argument is not a format string then `util.format()` returns a string that is the concatenation of all its arguments separated by spaces. Each argument is converted to a string with `util.inspect()`. util.format(1, 2, 3); // '1 2 3' ## util.debug(string) A synchronous output function. Will block the process and output `string` immediately to `stderr`. require('util').debug('message on stderr'); ## util.error([...]) Same as `util.debug()` except this will output all arguments immediately to `stderr`. ## util.puts([...]) A synchronous output function. Will block the process and output all arguments to `stdout` with newlines after each argument. ## util.print([...]) A synchronous output function. Will block the process, cast each argument to a string then output to `stdout`. Does not place newlines after each argument. ## util.log(string) Output with timestamp on `stdout`. require('util').log('Timestamped message.'); ## util.inspect(object, [options]) Return a string representation of `object`, which is useful for debugging. An optional *options* object may be passed that alters certain aspects of the formatted string: - `showHidden` - if `true` then the object's non-enumerable properties will be shown too. Defaults to `false`. - `depth` - tells `inspect` how many times to recurse while formatting the object. This is useful for inspecting large complicated objects. Defaults to `2`. To make it recurse indefinitely pass `null`. - `colors` - if `true`, then the output will be styled with ANSI color codes. Defaults to `false`. Colors are customizable, see below. - `customInspect` - if `false`, then custom `inspect()` functions defined on the objects being inspected won't be called. Defaults to `true`. Example of inspecting all properties of the `util` object: var util = require('util'); console.log(util.inspect(util, { showHidden: true, depth: null })); ### Customizing `util.inspect` colors Color output (if enabled) of `util.inspect` is customizable globally via `util.inspect.styles` and `util.inspect.colors` objects. `util.inspect.styles` is a map assigning each style a color from `util.inspect.colors`. Highlighted styles and their default values are: * `number` (yellow) * `boolean` (yellow) * `string` (green) * `date` (magenta) * `regexp` (red) * `null` (bold) * `undefined` (grey) * `special` - only function at this time (cyan) * `name` (intentionally no styling) Predefined color codes are: `white`, `grey`, `black`, `blue`, `cyan`, `green`, `magenta`, `red` and `yellow`. There are also `bold`, `italic`, `underline` and `inverse` codes. Objects also may define their own `inspect(depth)` function which `util.inspect()` will invoke and use the result of when inspecting the object: var util = require('util'); var obj = { name: 'nate' }; obj.inspect = function(depth) { return '{' + this.name + '}'; }; util.inspect(obj); // "{nate}" ## util.isArray(object) Returns `true` if the given "object" is an `Array`. `false` otherwise. var util = require('util'); util.isArray([]) // true util.isArray(new Array) // true util.isArray({}) // false ## util.isRegExp(object) Returns `true` if the given "object" is a `RegExp`. `false` otherwise. var util = require('util'); util.isRegExp(/some regexp/) // true util.isRegExp(new RegExp('another regexp')) // true util.isRegExp({}) // false ## util.isDate(object) Returns `true` if the given "object" is a `Date`. `false` otherwise. var util = require('util'); util.isDate(new Date()) // true util.isDate(Date()) // false (without 'new' returns a String) util.isDate({}) // false ## util.isError(object) Returns `true` if the given "object" is an `Error`. `false` otherwise. var util = require('util'); util.isError(new Error()) // true util.isError(new TypeError()) // true util.isError({ name: 'Error', message: 'an error occurred' }) // false ## util.pump(readableStream, writableStream, [callback]) Stability: 0 - Deprecated: Use readableStream.pipe(writableStream) Read the data from `readableStream` and send it to the `writableStream`. When `writableStream.write(data)` returns `false` `readableStream` will be paused until the `drain` event occurs on the `writableStream`. `callback` gets an error as its only argument and is called when `writableStream` is closed or when an error occurs. ## util.inherits(constructor, superConstructor) Inherit the prototype methods from one [constructor](https://developer.mozilla.org/en/JavaScript/Reference/Global_Objects/Object/constructor) into another. The prototype of `constructor` will be set to a new object created from `superConstructor`. As an additional convenience, `superConstructor` will be accessible through the `constructor.super_` property. var util = require("util"); var events = require("events"); function MyStream() { events.EventEmitter.call(this); } util.inherits(MyStream, events.EventEmitter); MyStream.prototype.write = function(data) { this.emit("data", data); } var stream = new MyStream(); console.log(stream instanceof events.EventEmitter); // true console.log(MyStream.super_ === events.EventEmitter); // true stream.on("data", function(data) { console.log('Received data: "' + data + '"'); }) stream.write("It works!"); // Received data: "It works!" node-v0.10.25~dfsg2/doc/api/modules.json0000644000000000000000000005454012270264601016505 0ustar rootroot{ "source": "doc/api/modules.markdown", "modules": [ { "textRaw": "Modules", "name": "module", "stability": 5, "stabilityText": "Locked", "desc": "

    Node has a simple module loading system. In Node, files and modules are in\none-to-one correspondence. As an example, foo.js loads the module\ncircle.js in the same directory.\n\n

    \n

    The contents of foo.js:\n\n

    \n
    var circle = require('./circle.js');\nconsole.log( 'The area of a circle of radius 4 is '\n           + circle.area(4));
    \n

    The contents of circle.js:\n\n

    \n
    var PI = Math.PI;\n\nexports.area = function (r) {\n  return PI * r * r;\n};\n\nexports.circumference = function (r) {\n  return 2 * PI * r;\n};
    \n

    The module circle.js has exported the functions area() and\ncircumference(). To add functions and objects to the root of your module,\nyou can add them to the special exports object.\n\n

    \n

    Variables local to the module will be private, as though the module was wrapped\nin a function. In this example the variable PI is private to circle.js.\n\n

    \n

    If you want the root of your module's export to be a function (such as a\nconstructor) or if you want to export a complete object in one assignment\ninstead of building it one property at a time, assign it to module.exports\ninstead of exports.\n\n

    \n

    Below, bar.js makes use of the square module, which exports a constructor:\n\n

    \n
    var square = require('./square.js');\nvar mySquare = square(2);\nconsole.log('The area of my square is ' + mySquare.area());
    \n

    The square module is defined in square.js:\n\n

    \n
    // assigning to exports will not modify module, must use module.exports\nmodule.exports = function(width) {\n  return {\n    area: function() {\n      return width * width;\n    }\n  };\n}
    \n

    The module system is implemented in the require("module") module.\n\n

    \n", "miscs": [ { "textRaw": "Cycles", "name": "Cycles", "type": "misc", "desc": "

    When there are circular require() calls, a module might not be\ndone being executed when it is returned.\n\n

    \n

    Consider this situation:\n\n

    \n

    a.js:\n\n

    \n
    console.log('a starting');\nexports.done = false;\nvar b = require('./b.js');\nconsole.log('in a, b.done = %j', b.done);\nexports.done = true;\nconsole.log('a done');
    \n

    b.js:\n\n

    \n
    console.log('b starting');\nexports.done = false;\nvar a = require('./a.js');\nconsole.log('in b, a.done = %j', a.done);\nexports.done = true;\nconsole.log('b done');
    \n

    main.js:\n\n

    \n
    console.log('main starting');\nvar a = require('./a.js');\nvar b = require('./b.js');\nconsole.log('in main, a.done=%j, b.done=%j', a.done, b.done);
    \n

    When main.js loads a.js, then a.js in turn loads b.js. At that\npoint, b.js tries to load a.js. In order to prevent an infinite\nloop an unfinished copy of the a.js exports object is returned to the\nb.js module. b.js then finishes loading, and its exports object is\nprovided to the a.js module.\n\n

    \n

    By the time main.js has loaded both modules, they're both finished.\nThe output of this program would thus be:\n\n

    \n
    $ node main.js\nmain starting\na starting\nb starting\nin b, a.done = false\nb done\nin a, b.done = true\na done\nin main, a.done=true, b.done=true
    \n

    If you have cyclic module dependencies in your program, make sure to\nplan accordingly.\n\n

    \n" }, { "textRaw": "Core Modules", "name": "Core Modules", "type": "misc", "desc": "

    Node has several modules compiled into the binary. These modules are\ndescribed in greater detail elsewhere in this documentation.\n\n

    \n

    The core modules are defined in node's source in the lib/ folder.\n\n

    \n

    Core modules are always preferentially loaded if their identifier is\npassed to require(). For instance, require('http') will always\nreturn the built in HTTP module, even if there is a file by that name.\n\n

    \n" }, { "textRaw": "File Modules", "name": "File Modules", "type": "misc", "desc": "

    If the exact filename is not found, then node will attempt to load the\nrequired filename with the added extension of .js, .json, and then .node.\n\n

    \n

    .js files are interpreted as JavaScript text files, and .json files are\nparsed as JSON text files. .node files are interpreted as compiled addon\nmodules loaded with dlopen.\n\n

    \n

    A module prefixed with '/' is an absolute path to the file. For\nexample, require('/home/marco/foo.js') will load the file at\n/home/marco/foo.js.\n\n

    \n

    A module prefixed with './' is relative to the file calling require().\nThat is, circle.js must be in the same directory as foo.js for\nrequire('./circle') to find it.\n\n

    \n

    Without a leading '/' or './' to indicate a file, the module is either a\n"core module" or is loaded from a node_modules folder.\n\n

    \n

    If the given path does not exist, require() will throw an Error with its\ncode property set to 'MODULE_NOT_FOUND'.\n\n

    \n" }, { "textRaw": "Loading from `node_modules` Folders", "name": "Loading from `node_modules` Folders", "type": "misc", "desc": "

    If the module identifier passed to require() is not a native module,\nand does not begin with '/', '../', or './', then node starts at the\nparent directory of the current module, and adds /node_modules, and\nattempts to load the module from that location.\n\n

    \n

    If it is not found there, then it moves to the parent directory, and so\non, until the root of the tree is reached.\n\n

    \n

    For example, if the file at '/home/ry/projects/foo.js' called\nrequire('bar.js'), then node would look in the following locations, in\nthis order:\n\n

    \n
      \n
    • /home/ry/projects/node_modules/bar.js
    • \n
    • /home/ry/node_modules/bar.js
    • \n
    • /home/node_modules/bar.js
    • \n
    • /node_modules/bar.js
    • \n
    \n

    This allows programs to localize their dependencies, so that they do not\nclash.\n\n

    \n" }, { "textRaw": "Folders as Modules", "name": "Folders as Modules", "type": "misc", "desc": "

    It is convenient to organize programs and libraries into self-contained\ndirectories, and then provide a single entry point to that library.\nThere are three ways in which a folder may be passed to require() as\nan argument.\n\n

    \n

    The first is to create a package.json file in the root of the folder,\nwhich specifies a main module. An example package.json file might\nlook like this:\n\n

    \n
    { "name" : "some-library",\n  "main" : "./lib/some-library.js" }
    \n

    If this was in a folder at ./some-library, then\nrequire('./some-library') would attempt to load\n./some-library/lib/some-library.js.\n\n

    \n

    This is the extent of Node's awareness of package.json files.\n\n

    \n

    If there is no package.json file present in the directory, then node\nwill attempt to load an index.js or index.node file out of that\ndirectory. For example, if there was no package.json file in the above\nexample, then require('./some-library') would attempt to load:\n\n

    \n
      \n
    • ./some-library/index.js
    • \n
    • ./some-library/index.node
    • \n
    \n" }, { "textRaw": "Caching", "name": "Caching", "type": "misc", "desc": "

    Modules are cached after the first time they are loaded. This means\n(among other things) that every call to require('foo') will get\nexactly the same object returned, if it would resolve to the same file.\n\n

    \n

    Multiple calls to require('foo') may not cause the module code to be\nexecuted multiple times. This is an important feature. With it,\n"partially done" objects can be returned, thus allowing transitive\ndependencies to be loaded even when they would cause cycles.\n\n

    \n

    If you want to have a module execute code multiple times, then export a\nfunction, and call that function.\n\n

    \n", "miscs": [ { "textRaw": "Module Caching Caveats", "name": "Module Caching Caveats", "type": "misc", "desc": "

    Modules are cached based on their resolved filename. Since modules may\nresolve to a different filename based on the location of the calling\nmodule (loading from node_modules folders), it is not a guarantee\nthat require('foo') will always return the exact same object, if it\nwould resolve to different files.\n\n

    \n" } ] }, { "textRaw": "All Together...", "name": "All Together...", "type": "misc", "desc": "

    To get the exact filename that will be loaded when require() is called, use\nthe require.resolve() function.\n\n

    \n

    Putting together all of the above, here is the high-level algorithm\nin pseudocode of what require.resolve does:\n\n

    \n
    require(X) from module at path Y\n1. If X is a core module,\n   a. return the core module\n   b. STOP\n2. If X begins with './' or '/' or '../'\n   a. LOAD_AS_FILE(Y + X)\n   b. LOAD_AS_DIRECTORY(Y + X)\n3. LOAD_NODE_MODULES(X, dirname(Y))\n4. THROW "not found"\n\nLOAD_AS_FILE(X)\n1. If X is a file, load X as JavaScript text.  STOP\n2. If X.js is a file, load X.js as JavaScript text.  STOP\n3. If X.node is a file, load X.node as binary addon.  STOP\n\nLOAD_AS_DIRECTORY(X)\n1. If X/package.json is a file,\n   a. Parse X/package.json, and look for "main" field.\n   b. let M = X + (json main field)\n   c. LOAD_AS_FILE(M)\n2. If X/index.js is a file, load X/index.js as JavaScript text.  STOP\n3. If X/index.node is a file, load X/index.node as binary addon.  STOP\n\nLOAD_NODE_MODULES(X, START)\n1. let DIRS=NODE_MODULES_PATHS(START)\n2. for each DIR in DIRS:\n   a. LOAD_AS_FILE(DIR/X)\n   b. LOAD_AS_DIRECTORY(DIR/X)\n\nNODE_MODULES_PATHS(START)\n1. let PARTS = path split(START)\n2. let ROOT = index of first instance of "node_modules" in PARTS, or 0\n3. let I = count of PARTS - 1\n4. let DIRS = []\n5. while I > ROOT,\n   a. if PARTS[I] = "node_modules" CONTINUE\n   c. DIR = path join(PARTS[0 .. I] + "node_modules")\n   b. DIRS = DIRS + DIR\n   c. let I = I - 1\n6. return DIRS
    \n" }, { "textRaw": "Loading from the global folders", "name": "Loading from the global folders", "type": "misc", "desc": "

    If the NODE_PATH environment variable is set to a colon-delimited list\nof absolute paths, then node will search those paths for modules if they\nare not found elsewhere. (Note: On Windows, NODE_PATH is delimited by\nsemicolons instead of colons.)\n\n

    \n

    Additionally, node will search in the following locations:\n\n

    \n
      \n
    • 1: $HOME/.node_modules
    • \n
    • 2: $HOME/.node_libraries
    • \n
    • 3: $PREFIX/lib/node
    • \n
    \n

    Where $HOME is the user's home directory, and $PREFIX is node's\nconfigured node_prefix.\n\n

    \n

    These are mostly for historic reasons. You are highly encouraged to\nplace your dependencies locally in node_modules folders. They will be\nloaded faster, and more reliably.\n\n

    \n" }, { "textRaw": "Accessing the main module", "name": "Accessing the main module", "type": "misc", "desc": "

    When a file is run directly from Node, require.main is set to its\nmodule. That means that you can determine whether a file has been run\ndirectly by testing\n\n

    \n
    require.main === module
    \n

    For a file foo.js, this will be true if run via node foo.js, but\nfalse if run by require('./foo').\n\n

    \n

    Because module provides a filename property (normally equivalent to\n__filename), the entry point of the current application can be obtained\nby checking require.main.filename.\n\n

    \n" }, { "textRaw": "Addenda: Package Manager Tips", "name": "Addenda: Package Manager Tips", "type": "misc", "desc": "

    The semantics of Node's require() function were designed to be general\nenough to support a number of sane directory structures. Package manager\nprograms such as dpkg, rpm, and npm will hopefully find it possible to\nbuild native packages from Node modules without modification.\n\n

    \n

    Below we give a suggested directory structure that could work:\n\n

    \n

    Let's say that we wanted to have the folder at\n/usr/lib/node/<some-package>/<some-version> hold the contents of a\nspecific version of a package.\n\n

    \n

    Packages can depend on one another. In order to install package foo, you\nmay have to install a specific version of package bar. The bar package\nmay itself have dependencies, and in some cases, these dependencies may even\ncollide or form cycles.\n\n

    \n

    Since Node looks up the realpath of any modules it loads (that is,\nresolves symlinks), and then looks for their dependencies in the\nnode_modules folders as described above, this situation is very simple to\nresolve with the following architecture:\n\n

    \n
      \n
    • /usr/lib/node/foo/1.2.3/ - Contents of the foo package, version 1.2.3.
    • \n
    • /usr/lib/node/bar/4.3.2/ - Contents of the bar package that foo\ndepends on.
    • \n
    • /usr/lib/node/foo/1.2.3/node_modules/bar - Symbolic link to\n/usr/lib/node/bar/4.3.2/.
    • \n
    • /usr/lib/node/bar/4.3.2/node_modules/* - Symbolic links to the packages\nthat bar depends on.
    • \n
    \n

    Thus, even if a cycle is encountered, or if there are dependency\nconflicts, every module will be able to get a version of its dependency\nthat it can use.\n\n

    \n

    When the code in the foo package does require('bar'), it will get the\nversion that is symlinked into /usr/lib/node/foo/1.2.3/node_modules/bar.\nThen, when the code in the bar package calls require('quux'), it'll get\nthe version that is symlinked into\n/usr/lib/node/bar/4.3.2/node_modules/quux.\n\n

    \n

    Furthermore, to make the module lookup process even more optimal, rather\nthan putting packages directly in /usr/lib/node, we could put them in\n/usr/lib/node_modules/<name>/<version>. Then node will not bother\nlooking for missing dependencies in /usr/node_modules or /node_modules.\n\n

    \n

    In order to make modules available to the node REPL, it might be useful to\nalso add the /usr/lib/node_modules folder to the $NODE_PATH environment\nvariable. Since the module lookups using node_modules folders are all\nrelative, and based on the real path of the files making the calls to\nrequire(), the packages themselves can be anywhere.\n

    \n" } ], "vars": [ { "textRaw": "The `module` Object", "name": "module", "type": "var", "desc": "

    In each module, the module free variable is a reference to the object\nrepresenting the current module. For convenience, module.exports is\nalso accessible via the exports module-global. module isn't actually\na global but rather local to each module.\n\n

    \n", "properties": [ { "textRaw": "`exports` {Object} ", "name": "exports", "desc": "

    The module.exports object is created by the Module system. Sometimes this is not\nacceptable; many want their module to be an instance of some class. To do this\nassign the desired export object to module.exports. Note that assigning the\ndesired object to exports will simply rebind the local exports variable,\nwhich is probably not what you want to do.\n\n

    \n

    For example suppose we were making a module called a.js\n\n

    \n
    var EventEmitter = require('events').EventEmitter;\n\nmodule.exports = new EventEmitter();\n\n// Do some work, and after some time emit\n// the 'ready' event from the module itself.\nsetTimeout(function() {\n  module.exports.emit('ready');\n}, 1000);
    \n

    Then in another file we could do\n\n

    \n
    var a = require('./a');\na.on('ready', function() {\n  console.log('module a is ready');\n});
    \n

    Note that assignment to module.exports must be done immediately. It cannot be\ndone in any callbacks. This does not work:\n\n

    \n

    x.js:\n\n

    \n
    setTimeout(function() {\n  module.exports = { a: "hello" };\n}, 0);
    \n

    y.js:\n\n

    \n
    var x = require('./x');\nconsole.log(x.a);
    \n", "modules": [ { "textRaw": "exports alias", "name": "exports_alias", "desc": "

    The exports variable that is available within a module starts as a reference\nto module.exports. As with any variable, if you assign a new value to it, it\nis no longer bound to the previous value.\n\n

    \n

    To illustrate the behaviour, imagine this hypothetical implementation of\nrequire():\n\n

    \n
    function require(...) {\n  // ...\n  function (module, exports) {\n    // Your module code here\n    exports = some_func;        // re-assigns exports, exports is no longer\n                                // a shortcut, and nothing is exported.\n    module.exports = some_func; // makes your module export 0\n  } (module, module.exports);\n  return module;\n}
    \n

    As a guideline, if the relationship between exports and module.exports\nseems like magic to you, ignore exports and only use module.exports.\n\n

    \n", "type": "module", "displayName": "exports alias" } ] }, { "textRaw": "`id` {String} ", "name": "id", "desc": "

    The identifier for the module. Typically this is the fully resolved\nfilename.\n\n\n

    \n" }, { "textRaw": "`filename` {String} ", "name": "filename", "desc": "

    The fully resolved filename to the module.\n\n\n

    \n" }, { "textRaw": "`loaded` {Boolean} ", "name": "loaded", "desc": "

    Whether or not the module is done loading, or is in the process of\nloading.\n\n\n

    \n" }, { "textRaw": "`parent` {Module Object} ", "name": "parent", "desc": "

    The module that required this one.\n\n\n

    \n" }, { "textRaw": "`children` {Array} ", "name": "children", "desc": "

    The module objects required by this one.\n\n\n\n

    \n" } ], "methods": [ { "textRaw": "module.require(id)", "type": "method", "name": "require", "signatures": [ { "return": { "textRaw": "Return: {Object} `module.exports` from the resolved module ", "name": "return", "type": "Object", "desc": "`module.exports` from the resolved module" }, "params": [ { "textRaw": "`id` {String} ", "name": "id", "type": "String" } ] }, { "params": [ { "name": "id" } ] } ], "desc": "

    The module.require method provides a way to load a module as if\nrequire() was called from the original module.\n\n

    \n

    Note that in order to do this, you must get a reference to the module\nobject. Since require() returns the module.exports, and the module is\ntypically only available within a specific module's code, it must be\nexplicitly exported in order to be used.\n\n\n

    \n" } ] } ], "type": "module", "displayName": "module" } ] } node-v0.10.25~dfsg2/doc/api/path.json0000644000000000000000000002112012270264601015755 0ustar rootroot{ "source": "doc/api/path.markdown", "modules": [ { "textRaw": "Path", "name": "path", "stability": 3, "stabilityText": "Stable", "desc": "

    This module contains utilities for handling and transforming file\npaths. Almost all these methods perform only string transformations.\nThe file system is not consulted to check whether paths are valid.\n\n

    \n

    Use require('path') to use this module. The following methods are provided:\n\n

    \n", "methods": [ { "textRaw": "path.normalize(p)", "type": "method", "name": "normalize", "desc": "

    Normalize a string path, taking care of '..' and '.' parts.\n\n

    \n

    When multiple slashes are found, they're replaced by a single one;\nwhen the path contains a trailing slash, it is preserved.\nOn Windows backslashes are used.\n\n

    \n

    Example:\n\n

    \n
    path.normalize('/foo/bar//baz/asdf/quux/..')\n// returns\n'/foo/bar/baz/asdf'
    \n", "signatures": [ { "params": [ { "name": "p" } ] } ] }, { "textRaw": "path.join([path1], [path2], [...])", "type": "method", "name": "join", "desc": "

    Join all arguments together and normalize the resulting path.\n\n

    \n

    Arguments must be strings. In v0.8, non-string arguments were\nsilently ignored. In v0.10 and up, an exception is thrown.\n\n

    \n

    Example:\n\n

    \n
    path.join('/foo', 'bar', 'baz/asdf', 'quux', '..')\n// returns\n'/foo/bar/baz/asdf'\n\npath.join('foo', {}, 'bar')\n// throws exception\nTypeError: Arguments to path.join must be strings
    \n", "signatures": [ { "params": [ { "name": "path1", "optional": true }, { "name": "path2", "optional": true }, { "name": "...", "optional": true } ] } ] }, { "textRaw": "path.resolve([from ...], to)", "type": "method", "name": "resolve", "desc": "

    Resolves to to an absolute path.\n\n

    \n

    If to isn't already absolute from arguments are prepended in right to left\norder, until an absolute path is found. If after using all from paths still\nno absolute path is found, the current working directory is used as well. The\nresulting path is normalized, and trailing slashes are removed unless the path\ngets resolved to the root directory. Non-string arguments are ignored.\n\n

    \n

    Another way to think of it is as a sequence of cd commands in a shell.\n\n

    \n
    path.resolve('foo/bar', '/tmp/file/', '..', 'a/../subfile')
    \n

    Is similar to:\n\n

    \n
    cd foo/bar\ncd /tmp/file/\ncd ..\ncd a/../subfile\npwd
    \n

    The difference is that the different paths don't need to exist and may also be\nfiles.\n\n

    \n

    Examples:\n\n

    \n
    path.resolve('/foo/bar', './baz')\n// returns\n'/foo/bar/baz'\n\npath.resolve('/foo/bar', '/tmp/file/')\n// returns\n'/tmp/file'\n\npath.resolve('wwwroot', 'static_files/png/', '../gif/image.gif')\n// if currently in /home/myself/node, it returns\n'/home/myself/node/wwwroot/static_files/gif/image.gif'
    \n", "signatures": [ { "params": [ { "name": "from ...", "optional": true }, { "name": "to" } ] } ] }, { "textRaw": "path.relative(from, to)", "type": "method", "name": "relative", "desc": "

    Solve the relative path from from to to.\n\n

    \n

    At times we have two absolute paths, and we need to derive the relative\npath from one to the other. This is actually the reverse transform of\npath.resolve, which means we see that:\n\n

    \n
    path.resolve(from, path.relative(from, to)) == path.resolve(to)
    \n

    Examples:\n\n

    \n
    path.relative('C:\\\\orandea\\\\test\\\\aaa', 'C:\\\\orandea\\\\impl\\\\bbb')\n// returns\n'..\\\\..\\\\impl\\\\bbb'\n\npath.relative('/data/orandea/test/aaa', '/data/orandea/impl/bbb')\n// returns\n'../../impl/bbb'
    \n", "signatures": [ { "params": [ { "name": "from" }, { "name": "to" } ] } ] }, { "textRaw": "path.dirname(p)", "type": "method", "name": "dirname", "desc": "

    Return the directory name of a path. Similar to the Unix dirname command.\n\n

    \n

    Example:\n\n

    \n
    path.dirname('/foo/bar/baz/asdf/quux')\n// returns\n'/foo/bar/baz/asdf'
    \n", "signatures": [ { "params": [ { "name": "p" } ] } ] }, { "textRaw": "path.basename(p, [ext])", "type": "method", "name": "basename", "desc": "

    Return the last portion of a path. Similar to the Unix basename command.\n\n

    \n

    Example:\n\n

    \n
    path.basename('/foo/bar/baz/asdf/quux.html')\n// returns\n'quux.html'\n\npath.basename('/foo/bar/baz/asdf/quux.html', '.html')\n// returns\n'quux'
    \n", "signatures": [ { "params": [ { "name": "p" }, { "name": "ext", "optional": true } ] } ] }, { "textRaw": "path.extname(p)", "type": "method", "name": "extname", "desc": "

    Return the extension of the path, from the last '.' to end of string\nin the last portion of the path. If there is no '.' in the last portion\nof the path or the first character of it is '.', then it returns\nan empty string. Examples:\n\n

    \n
    path.extname('index.html')\n// returns\n'.html'\n\npath.extname('index.')\n// returns\n'.'\n\npath.extname('index')\n// returns\n''
    \n", "signatures": [ { "params": [ { "name": "p" } ] } ] } ], "properties": [ { "textRaw": "path.sep", "name": "sep", "desc": "

    The platform-specific file separator. '\\\\' or '/'.\n\n

    \n

    An example on *nix:\n\n

    \n
    'foo/bar/baz'.split(path.sep)\n// returns\n['foo', 'bar', 'baz']
    \n

    An example on Windows:\n\n

    \n
    'foo\\\\bar\\\\baz'.split(path.sep)\n// returns\n['foo', 'bar', 'baz']
    \n" }, { "textRaw": "path.delimiter", "name": "delimiter", "desc": "

    The platform-specific path delimiter, ; or ':'.\n\n

    \n

    An example on *nix:\n\n

    \n
    console.log(process.env.PATH)\n// '/usr/bin:/bin:/usr/sbin:/sbin:/usr/local/bin'\n\nprocess.env.PATH.split(path.delimiter)\n// returns\n['/usr/bin', '/bin', '/usr/sbin', '/sbin', '/usr/local/bin']
    \n

    An example on Windows:\n\n

    \n
    console.log(process.env.PATH)\n// 'C:\\Windows\\system32;C:\\Windows;C:\\Program Files\\nodejs\\'\n\nprocess.env.PATH.split(path.delimiter)\n// returns\n['C:\\Windows\\system32', 'C:\\Windows', 'C:\\Program Files\\nodejs\\']
    \n" } ], "type": "module", "displayName": "Path" } ] } node-v0.10.25~dfsg2/doc/api/http.html0000644000000000000000000014352312270264601016007 0ustar rootroot HTTP Node.js v0.10.25 Manual & Documentation

    Node.js v0.10.25 Manual & Documentation


    Table of Contents

    HTTP#

    Stability: 3 - Stable

    To use the HTTP server and client one must require('http').

    The HTTP interfaces in Node are designed to support many features of the protocol which have been traditionally difficult to use. In particular, large, possibly chunk-encoded, messages. The interface is careful to never buffer entire requests or responses--the user is able to stream data.

    HTTP message headers are represented by an object like this:

    { 'content-length': '123',
      'content-type': 'text/plain',
      'connection': 'keep-alive',
      'accept': '*/*' }

    Keys are lowercased. Values are not modified.

    In order to support the full spectrum of possible HTTP applications, Node's HTTP API is very low-level. It deals with stream handling and message parsing only. It parses a message into headers and body but it does not parse the actual headers or the body.

    http.STATUS_CODES#

    • Object

    A collection of all the standard HTTP response status codes, and the short description of each. For example, http.STATUS_CODES[404] === 'Not Found'.

    http.createServer([requestListener])#

    Returns a new web server object.

    The requestListener is a function which is automatically added to the 'request' event.

    http.createClient([port], [host])#

    This function is deprecated; please use http.request() instead. Constructs a new HTTP client. port and host refer to the server to be connected to.

    Class: http.Server#

    This is an EventEmitter with the following events:

    Event: 'request'#

    function (request, response) { }

    Emitted each time there is a request. Note that there may be multiple requests per connection (in the case of keep-alive connections). request is an instance of http.IncomingMessage and response is an instance of http.ServerResponse.

    Event: 'connection'#

    function (socket) { }

    When a new TCP stream is established. socket is an object of type net.Socket. Usually users will not want to access this event. In particular, the socket will not emit readable events because of how the protocol parser attaches to the socket. The socket can also be accessed at request.connection.

    Event: 'close'#

    function () { }

    Emitted when the server closes.

    Event: 'checkContinue'#

    function (request, response) { }

    Emitted each time a request with an http Expect: 100-continue is received. If this event isn't listened for, the server will automatically respond with a 100 Continue as appropriate.

    Handling this event involves calling response.writeContinue() if the client should continue to send the request body, or generating an appropriate HTTP response (e.g., 400 Bad Request) if the client should not continue to send the request body.

    Note that when this event is emitted and handled, the request event will not be emitted.

    Event: 'connect'#

    function (request, socket, head) { }

    Emitted each time a client requests a http CONNECT method. If this event isn't listened for, then clients requesting a CONNECT method will have their connections closed.

    • request is the arguments for the http request, as it is in the request event.
    • socket is the network socket between the server and client.
    • head is an instance of Buffer, the first packet of the tunneling stream, this may be empty.

    After this event is emitted, the request's socket will not have a data event listener, meaning you will need to bind to it in order to handle data sent to the server on that socket.

    Event: 'upgrade'#

    function (request, socket, head) { }

    Emitted each time a client requests a http upgrade. If this event isn't listened for, then clients requesting an upgrade will have their connections closed.

    • request is the arguments for the http request, as it is in the request event.
    • socket is the network socket between the server and client.
    • head is an instance of Buffer, the first packet of the upgraded stream, this may be empty.

    After this event is emitted, the request's socket will not have a data event listener, meaning you will need to bind to it in order to handle data sent to the server on that socket.

    Event: 'clientError'#

    function (exception, socket) { }

    If a client connection emits an 'error' event - it will forwarded here.

    socket is the net.Socket object that the error originated from.

    server.listen(port, [hostname], [backlog], [callback])#

    Begin accepting connections on the specified port and hostname. If the hostname is omitted, the server will accept connections directed to any IPv4 address (INADDR_ANY).

    To listen to a unix socket, supply a filename instead of port and hostname.

    Backlog is the maximum length of the queue of pending connections. The actual length will be determined by your OS through sysctl settings such as tcp_max_syn_backlog and somaxconn on linux. The default value of this parameter is 511 (not 512).

    This function is asynchronous. The last parameter callback will be added as a listener for the 'listening' event. See also net.Server.listen(port).

    server.listen(path, [callback])#

    Start a UNIX socket server listening for connections on the given path.

    This function is asynchronous. The last parameter callback will be added as a listener for the 'listening' event. See also net.Server.listen(path).

    server.listen(handle, [callback])#

    • handle Object
    • callback Function

    The handle object can be set to either a server or socket (anything with an underlying _handle member), or a {fd: <n>} object.

    This will cause the server to accept connections on the specified handle, but it is presumed that the file descriptor or handle has already been bound to a port or domain socket.

    Listening on a file descriptor is not supported on Windows.

    This function is asynchronous. The last parameter callback will be added as a listener for the 'listening' event. See also net.Server.listen().

    server.close([callback])#

    Stops the server from accepting new connections. See net.Server.close().

    server.maxHeadersCount#

    Limits maximum incoming headers count, equal to 1000 by default. If set to 0 - no limit will be applied.

    server.setTimeout(msecs, callback)#

    • msecs Number
    • callback Function

    Sets the timeout value for sockets, and emits a 'timeout' event on the Server object, passing the socket as an argument, if a timeout occurs.

    If there is a 'timeout' event listener on the Server object, then it will be called with the timed-out socket as an argument.

    By default, the Server's timeout value is 2 minutes, and sockets are destroyed automatically if they time out. However, if you assign a callback to the Server's 'timeout' event, then you are responsible for handling socket timeouts.

    server.timeout#

    • Number Default = 120000 (2 minutes)

    The number of milliseconds of inactivity before a socket is presumed to have timed out.

    Note that the socket timeout logic is set up on connection, so changing this value only affects new connections to the server, not any existing connections.

    Set to 0 to disable any kind of automatic timeout behavior on incoming connections.

    Class: http.ServerResponse#

    This object is created internally by a HTTP server--not by the user. It is passed as the second parameter to the 'request' event.

    The response implements the Writable Stream interface. This is an EventEmitter with the following events:

    Event: 'close'#

    function () { }

    Indicates that the underlying connection was terminated before response.end() was called or able to flush.

    Event: 'finish'#

    function () { }

    Emitted when the response has been sent. More specifically, this event is emitted when the last segment of the response headers and body have been handed off to the operating system for transmission over the network. It does not imply that the client has received anything yet.

    After this event, no more events will be emitted on the response object.

    response.writeContinue()#

    Sends a HTTP/1.1 100 Continue message to the client, indicating that the request body should be sent. See the 'checkContinue' event on Server.

    response.writeHead(statusCode, [reasonPhrase], [headers])#

    Sends a response header to the request. The status code is a 3-digit HTTP status code, like 404. The last argument, headers, are the response headers. Optionally one can give a human-readable reasonPhrase as the second argument.

    Example:

    var body = 'hello world';
    response.writeHead(200, {
      'Content-Length': body.length,
      'Content-Type': 'text/plain' });

    This method must only be called once on a message and it must be called before response.end() is called.

    If you call response.write() or response.end() before calling this, the implicit/mutable headers will be calculated and call this function for you.

    Note: that Content-Length is given in bytes not characters. The above example works because the string 'hello world' contains only single byte characters. If the body contains higher coded characters then Buffer.byteLength() should be used to determine the number of bytes in a given encoding. And Node does not check whether Content-Length and the length of the body which has been transmitted are equal or not.

    response.setTimeout(msecs, callback)#

    • msecs Number
    • callback Function

    Sets the Socket's timeout value to msecs. If a callback is provided, then it is added as a listener on the 'timeout' event on the response object.

    If no 'timeout' listener is added to the request, the response, or the server, then sockets are destroyed when they time out. If you assign a handler on the request, the response, or the server's 'timeout' events, then it is your responsibility to handle timed out sockets.

    response.statusCode#

    When using implicit headers (not calling response.writeHead() explicitly), this property controls the status code that will be sent to the client when the headers get flushed.

    Example:

    response.statusCode = 404;

    After response header was sent to the client, this property indicates the status code which was sent out.

    response.setHeader(name, value)#

    Sets a single header value for implicit headers. If this header already exists in the to-be-sent headers, its value will be replaced. Use an array of strings here if you need to send multiple headers with the same name.

    Example:

    response.setHeader("Content-Type", "text/html");

    or

    response.setHeader("Set-Cookie", ["type=ninja", "language=javascript"]);

    response.headersSent#

    Boolean (read-only). True if headers were sent, false otherwise.

    response.sendDate#

    When true, the Date header will be automatically generated and sent in the response if it is not already present in the headers. Defaults to true.

    This should only be disabled for testing; HTTP requires the Date header in responses.

    response.getHeader(name)#

    Reads out a header that's already been queued but not sent to the client. Note that the name is case insensitive. This can only be called before headers get implicitly flushed.

    Example:

    var contentType = response.getHeader('content-type');

    response.removeHeader(name)#

    Removes a header that's queued for implicit sending.

    Example:

    response.removeHeader("Content-Encoding");

    response.write(chunk, [encoding])#

    If this method is called and response.writeHead() has not been called, it will switch to implicit header mode and flush the implicit headers.

    This sends a chunk of the response body. This method may be called multiple times to provide successive parts of the body.

    chunk can be a string or a buffer. If chunk is a string, the second parameter specifies how to encode it into a byte stream. By default the encoding is 'utf8'.

    Note: This is the raw HTTP body and has nothing to do with higher-level multi-part body encodings that may be used.

    The first time response.write() is called, it will send the buffered header information and the first body to the client. The second time response.write() is called, Node assumes you're going to be streaming data, and sends that separately. That is, the response is buffered up to the first chunk of body.

    Returns true if the entire data was flushed successfully to the kernel buffer. Returns false if all or part of the data was queued in user memory. 'drain' will be emitted when the buffer is again free.

    response.addTrailers(headers)#

    This method adds HTTP trailing headers (a header but at the end of the message) to the response.

    Trailers will only be emitted if chunked encoding is used for the response; if it is not (e.g., if the request was HTTP/1.0), they will be silently discarded.

    Note that HTTP requires the Trailer header to be sent if you intend to emit trailers, with a list of the header fields in its value. E.g.,

    response.writeHead(200, { 'Content-Type': 'text/plain',
                              'Trailer': 'Content-MD5' });
    response.write(fileData);
    response.addTrailers({'Content-MD5': "7895bf4b8828b55ceaf47747b4bca667"});
    response.end();

    response.end([data], [encoding])#

    This method signals to the server that all of the response headers and body have been sent; that server should consider this message complete. The method, response.end(), MUST be called on each response.

    If data is specified, it is equivalent to calling response.write(data, encoding) followed by response.end().

    http.request(options, [callback])#

    Node maintains several connections per server to make HTTP requests. This function allows one to transparently issue requests.

    options can be an object or a string. If options is a string, it is automatically parsed with url.parse().

    Options:

    • host: A domain name or IP address of the server to issue the request to. Defaults to 'localhost'.
    • hostname: To support url.parse() hostname is preferred over host
    • port: Port of remote server. Defaults to 80.
    • localAddress: Local interface to bind for network connections.
    • socketPath: Unix Domain Socket (use one of host:port or socketPath)
    • method: A string specifying the HTTP request method. Defaults to 'GET'.
    • path: Request path. Defaults to '/'. Should include query string if any. E.G. '/index.html?page=12'
    • headers: An object containing request headers.
    • auth: Basic authentication i.e. 'user:password' to compute an Authorization header.
    • agent: Controls Agent behavior. When an Agent is used request will default to Connection: keep-alive. Possible values:
      • undefined (default): use global Agent for this host and port.
      • Agent object: explicitly use the passed in Agent.
      • false: opts out of connection pooling with an Agent, defaults request to Connection: close.

    The optional callback parameter will be added as a one time listener for the 'response' event.

    http.request() returns an instance of the http.ClientRequest class. The ClientRequest instance is a writable stream. If one needs to upload a file with a POST request, then write to the ClientRequest object.

    Example:

    var options = {
      hostname: 'www.google.com',
      port: 80,
      path: '/upload',
      method: 'POST'
    };
    
    var req = http.request(options, function(res) {
      console.log('STATUS: ' + res.statusCode);
      console.log('HEADERS: ' + JSON.stringify(res.headers));
      res.setEncoding('utf8');
      res.on('data', function (chunk) {
        console.log('BODY: ' + chunk);
      });
    });
    
    req.on('error', function(e) {
      console.log('problem with request: ' + e.message);
    });
    
    // write data to request body
    req.write('data\n');
    req.write('data\n');
    req.end();

    Note that in the example req.end() was called. With http.request() one must always call req.end() to signify that you're done with the request - even if there is no data being written to the request body.

    If any error is encountered during the request (be that with DNS resolution, TCP level errors, or actual HTTP parse errors) an 'error' event is emitted on the returned request object.

    There are a few special headers that should be noted.

    • Sending a 'Connection: keep-alive' will notify Node that the connection to the server should be persisted until the next request.

    • Sending a 'Content-length' header will disable the default chunked encoding.

    • Sending an 'Expect' header will immediately send the request headers. Usually, when sending 'Expect: 100-continue', you should both set a timeout and listen for the continue event. See RFC2616 Section 8.2.3 for more information.

    • Sending an Authorization header will override using the auth option to compute basic authentication.

    http.get(options, [callback])#

    Since most requests are GET requests without bodies, Node provides this convenience method. The only difference between this method and http.request() is that it sets the method to GET and calls req.end() automatically.

    Example:

    http.get("http://www.google.com/index.html", function(res) {
      console.log("Got response: " + res.statusCode);
    }).on('error', function(e) {
      console.log("Got error: " + e.message);
    });

    Class: http.Agent#

    In node 0.5.3+ there is a new implementation of the HTTP Agent which is used for pooling sockets used in HTTP client requests.

    Previously, a single agent instance helped pool for a single host+port. The current implementation now holds sockets for any number of hosts.

    The current HTTP Agent also defaults client requests to using Connection:keep-alive. If no pending HTTP requests are waiting on a socket to become free the socket is closed. This means that node's pool has the benefit of keep-alive when under load but still does not require developers to manually close the HTTP clients using keep-alive.

    Sockets are removed from the agent's pool when the socket emits either a "close" event or a special "agentRemove" event. This means that if you intend to keep one HTTP request open for a long time and don't want it to stay in the pool you can do something along the lines of:

    http.get(options, function(res) {
      // Do stuff
    }).on("socket", function (socket) {
      socket.emit("agentRemove");
    });

    Alternatively, you could just opt out of pooling entirely using agent:false:

    http.get({hostname:'localhost', port:80, path:'/', agent:false}, function (res) {
      // Do stuff
    })

    agent.maxSockets#

    By default set to 5. Determines how many concurrent sockets the agent can have open per host.

    agent.sockets#

    An object which contains arrays of sockets currently in use by the Agent. Do not modify.

    agent.requests#

    An object which contains queues of requests that have not yet been assigned to sockets. Do not modify.

    http.globalAgent#

    Global instance of Agent which is used as the default for all http client requests.

    Class: http.ClientRequest#

    This object is created internally and returned from http.request(). It represents an in-progress request whose header has already been queued. The header is still mutable using the setHeader(name, value), getHeader(name), removeHeader(name) API. The actual header will be sent along with the first data chunk or when closing the connection.

    To get the response, add a listener for 'response' to the request object. 'response' will be emitted from the request object when the response headers have been received. The 'response' event is executed with one argument which is an instance of http.IncomingMessage.

    During the 'response' event, one can add listeners to the response object; particularly to listen for the 'data' event.

    If no 'response' handler is added, then the response will be entirely discarded. However, if you add a 'response' event handler, then you must consume the data from the response object, either by calling response.read() whenever there is a 'readable' event, or by adding a 'data' handler, or by calling the .resume() method. Until the data is consumed, the 'end' event will not fire. Also, until the data is read it will consume memory that can eventually lead to a 'process out of memory' error.

    Note: Node does not check whether Content-Length and the length of the body which has been transmitted are equal or not.

    The request implements the Writable Stream interface. This is an EventEmitter with the following events:

    Event 'response'#

    function (response) { }

    Emitted when a response is received to this request. This event is emitted only once. The response argument will be an instance of http.IncomingMessage.

    Options:

    • host: A domain name or IP address of the server to issue the request to.
    • port: Port of remote server.
    • socketPath: Unix Domain Socket (use one of host:port or socketPath)

    Event: 'socket'#

    function (socket) { }

    Emitted after a socket is assigned to this request.

    Event: 'connect'#

    function (response, socket, head) { }

    Emitted each time a server responds to a request with a CONNECT method. If this event isn't being listened for, clients receiving a CONNECT method will have their connections closed.

    A client server pair that show you how to listen for the connect event.

    var http = require('http');
    var net = require('net');
    var url = require('url');
    
    // Create an HTTP tunneling proxy
    var proxy = http.createServer(function (req, res) {
      res.writeHead(200, {'Content-Type': 'text/plain'});
      res.end('okay');
    });
    proxy.on('connect', function(req, cltSocket, head) {
      // connect to an origin server
      var srvUrl = url.parse('http://' + req.url);
      var srvSocket = net.connect(srvUrl.port, srvUrl.hostname, function() {
        cltSocket.write('HTTP/1.1 200 Connection Established\r\n' +
                        'Proxy-agent: Node-Proxy\r\n' +
                        '\r\n');
        srvSocket.write(head);
        srvSocket.pipe(cltSocket);
        cltSocket.pipe(srvSocket);
      });
    });
    
    // now that proxy is running
    proxy.listen(1337, '127.0.0.1', function() {
    
      // make a request to a tunneling proxy
      var options = {
        port: 1337,
        hostname: '127.0.0.1',
        method: 'CONNECT',
        path: 'www.google.com:80'
      };
    
      var req = http.request(options);
      req.end();
    
      req.on('connect', function(res, socket, head) {
        console.log('got connected!');
    
        // make a request over an HTTP tunnel
        socket.write('GET / HTTP/1.1\r\n' +
                     'Host: www.google.com:80\r\n' +
                     'Connection: close\r\n' +
                     '\r\n');
        socket.on('data', function(chunk) {
          console.log(chunk.toString());
        });
        socket.on('end', function() {
          proxy.close();
        });
      });
    });

    Event: 'upgrade'#

    function (response, socket, head) { }

    Emitted each time a server responds to a request with an upgrade. If this event isn't being listened for, clients receiving an upgrade header will have their connections closed.

    A client server pair that show you how to listen for the upgrade event.

    var http = require('http');
    
    // Create an HTTP server
    var srv = http.createServer(function (req, res) {
      res.writeHead(200, {'Content-Type': 'text/plain'});
      res.end('okay');
    });
    srv.on('upgrade', function(req, socket, head) {
      socket.write('HTTP/1.1 101 Web Socket Protocol Handshake\r\n' +
                   'Upgrade: WebSocket\r\n' +
                   'Connection: Upgrade\r\n' +
                   '\r\n');
    
      socket.pipe(socket); // echo back
    });
    
    // now that server is running
    srv.listen(1337, '127.0.0.1', function() {
    
      // make a request
      var options = {
        port: 1337,
        hostname: '127.0.0.1',
        headers: {
          'Connection': 'Upgrade',
          'Upgrade': 'websocket'
        }
      };
    
      var req = http.request(options);
      req.end();
    
      req.on('upgrade', function(res, socket, upgradeHead) {
        console.log('got upgraded!');
        socket.end();
        process.exit(0);
      });
    });

    Event: 'continue'#

    function () { }

    Emitted when the server sends a '100 Continue' HTTP response, usually because the request contained 'Expect: 100-continue'. This is an instruction that the client should send the request body.

    request.write(chunk, [encoding])#

    Sends a chunk of the body. By calling this method many times, the user can stream a request body to a server--in that case it is suggested to use the ['Transfer-Encoding', 'chunked'] header line when creating the request.

    The chunk argument should be a Buffer or a string.

    The encoding argument is optional and only applies when chunk is a string. Defaults to 'utf8'.

    request.end([data], [encoding])#

    Finishes sending the request. If any parts of the body are unsent, it will flush them to the stream. If the request is chunked, this will send the terminating '0\r\n\r\n'.

    If data is specified, it is equivalent to calling request.write(data, encoding) followed by request.end().

    request.abort()#

    Aborts a request. (New since v0.3.8.)

    request.setTimeout(timeout, [callback])#

    Once a socket is assigned to this request and is connected socket.setTimeout() will be called.

    request.setNoDelay([noDelay])#

    Once a socket is assigned to this request and is connected socket.setNoDelay() will be called.

    request.setSocketKeepAlive([enable], [initialDelay])#

    Once a socket is assigned to this request and is connected socket.setKeepAlive() will be called.

    http.IncomingMessage#

    An IncomingMessage object is created by http.Server or http.ClientRequest and passed as the first argument to the 'request' and 'response' event respectively. It may be used to access response status, headers and data.

    It implements the Readable Stream interface, as well as the following additional events, methods, and properties.

    Event: 'close'#

    function () { }

    Indicates that the underlaying connection was closed. Just like 'end', this event occurs only once per response.

    message.httpVersion#

    In case of server request, the HTTP version sent by the client. In the case of client response, the HTTP version of the connected-to server. Probably either '1.1' or '1.0'.

    Also response.httpVersionMajor is the first integer and response.httpVersionMinor is the second.

    message.headers#

    The request/response headers object.

    Read only map of header names and values. Header names are lower-cased. Example:

    // Prints something like:
    //
    // { 'user-agent': 'curl/7.22.0',
    //   host: '127.0.0.1:8000',
    //   accept: '*/*' }
    console.log(request.headers);

    message.trailers#

    The request/response trailers object. Only populated after the 'end' event.

    message.setTimeout(msecs, callback)#

    • msecs Number
    • callback Function

    Calls message.connection.setTimeout(msecs, callback).

    message.method#

    Only valid for request obtained from http.Server.

    The request method as a string. Read only. Example: 'GET', 'DELETE'.

    message.url#

    Only valid for request obtained from http.Server.

    Request URL string. This contains only the URL that is present in the actual HTTP request. If the request is:

    GET /status?name=ryan HTTP/1.1\r\n
    Accept: text/plain\r\n
    \r\n

    Then request.url will be:

    '/status?name=ryan'

    If you would like to parse the URL into its parts, you can use require('url').parse(request.url). Example:

    node> require('url').parse('/status?name=ryan')
    { href: '/status?name=ryan',
      search: '?name=ryan',
      query: 'name=ryan',
      pathname: '/status' }

    If you would like to extract the params from the query string, you can use the require('querystring').parse function, or pass true as the second argument to require('url').parse. Example:

    node> require('url').parse('/status?name=ryan', true)
    { href: '/status?name=ryan',
      search: '?name=ryan',
      query: { name: 'ryan' },
      pathname: '/status' }

    message.statusCode#

    Only valid for response obtained from http.ClientRequest.

    The 3-digit HTTP response status code. E.G. 404.

    message.socket#

    The net.Socket object associated with the connection.

    With HTTPS support, use request.connection.verifyPeer() and request.connection.getPeerCertificate() to obtain the client's authentication details.

    node-v0.10.25~dfsg2/doc/api/stream.html0000644000000000000000000021077612270264601016330 0ustar rootroot Stream Node.js v0.10.25 Manual & Documentation

    Node.js v0.10.25 Manual & Documentation


    Stream#

    Stability: 2 - Unstable

    A stream is an abstract interface implemented by various objects in Node. For example a request to an HTTP server is a stream, as is stdout. Streams are readable, writable, or both. All streams are instances of EventEmitter

    You can load the Stream base classes by doing require('stream'). There are base classes provided for Readable streams, Writable streams, Duplex streams, and Transform streams.

    This document is split up into 3 sections. The first explains the parts of the API that you need to be aware of to use streams in your programs. If you never implement a streaming API yourself, you can stop there.

    The second section explains the parts of the API that you need to use if you implement your own custom streams yourself. The API is designed to make this easy for you to do.

    The third section goes into more depth about how streams work, including some of the internal mechanisms and functions that you should probably not modify unless you definitely know what you are doing.

    API for Stream Consumers#

    Streams can be either Readable, Writable, or both (Duplex).

    All streams are EventEmitters, but they also have other custom methods and properties depending on whether they are Readable, Writable, or Duplex.

    If a stream is both Readable and Writable, then it implements all of the methods and events below. So, a Duplex or Transform stream is fully described by this API, though their implementation may be somewhat different.

    It is not necessary to implement Stream interfaces in order to consume streams in your programs. If you are implementing streaming interfaces in your own program, please also refer to API for Stream Implementors below.

    Almost all Node programs, no matter how simple, use Streams in some way. Here is an example of using Streams in a Node program:

    var http = require('http');
    
    var server = http.createServer(function (req, res) {
      // req is an http.IncomingMessage, which is a Readable Stream
      // res is an http.ServerResponse, which is a Writable Stream
    
      var body = '';
      // we want to get the data as utf8 strings
      // If you don't set an encoding, then you'll get Buffer objects
      req.setEncoding('utf8');
    
      // Readable streams emit 'data' events once a listener is added
      req.on('data', function (chunk) {
        body += chunk;
      })
    
      // the end event tells you that you have entire body
      req.on('end', function () {
        try {
          var data = JSON.parse(body);
        } catch (er) {
          // uh oh!  bad json!
          res.statusCode = 400;
          return res.end('error: ' + er.message);
        }
    
        // write back something interesting to the user:
        res.write(typeof data);
        res.end();
      })
    })
    
    server.listen(1337);
    
    // $ curl localhost:1337 -d '{}'
    // object
    // $ curl localhost:1337 -d '"foo"'
    // string
    // $ curl localhost:1337 -d 'not json'
    // error: Unexpected token o

    Class: stream.Readable#

    The Readable stream interface is the abstraction for a source of data that you are reading from. In other words, data comes out of a Readable stream.

    A Readable stream will not start emitting data until you indicate that you are ready to receive it.

    Readable streams have two "modes": a flowing mode and a non-flowing mode. When in flowing mode, data is read from the underlying system and provided to your program as fast as possible. In non-flowing mode, you must explicitly call stream.read() to get chunks of data out.

    Examples of readable streams include:

    Event: 'readable'#

    When a chunk of data can be read from the stream, it will emit a 'readable' event.

    In some cases, listening for a 'readable' event will cause some data to be read into the internal buffer from the underlying system, if it hadn't already.

    var readable = getReadableStreamSomehow();
    readable.on('readable', function() {
      // there is some data to read now
    })

    Once the internal buffer is drained, a readable event will fire again when more data is available.

    Event: 'data'#

    • chunk Buffer | String The chunk of data.

    If you attach a data event listener, then it will switch the stream into flowing mode, and data will be passed to your handler as soon as it is available.

    If you just want to get all the data out of the stream as fast as possible, this is the best way to do so.

    var readable = getReadableStreamSomehow();
    readable.on('data', function(chunk) {
      console.log('got %d bytes of data', chunk.length);
    })

    Event: 'end'#

    This event fires when no more data will be provided.

    Note that the end event will not fire unless the data is completely consumed. This can be done by switching into flowing mode, or by calling read() repeatedly until you get to the end.

    var readable = getReadableStreamSomehow();
    readable.on('data', function(chunk) {
      console.log('got %d bytes of data', chunk.length);
    })
    readable.on('end', function() {
      console.log('there will be no more data.');
    });

    Event: 'close'#

    Emitted when the underlying resource (for example, the backing file descriptor) has been closed. Not all streams will emit this.

    Event: 'error'#

    Emitted if there was an error receiving data.

    readable.read([size])#

    • size Number Optional argument to specify how much data to read.
    • Return String | Buffer | null

    The read() method pulls some data out of the internal buffer and returns it. If there is no data available, then it will return null.

    If you pass in a size argument, then it will return that many bytes. If size bytes are not available, then it will return null.

    If you do not specify a size argument, then it will return all the data in the internal buffer.

    This method should only be called in non-flowing mode. In flowing-mode, this method is called automatically until the internal buffer is drained.

    var readable = getReadableStreamSomehow();
    readable.on('readable', function() {
      var chunk;
      while (null !== (chunk = readable.read())) {
        console.log('got %d bytes of data', chunk.length);
      }
    });

    readable.setEncoding(encoding)#

    • encoding String The encoding to use.

    Call this function to cause the stream to return strings of the specified encoding instead of Buffer objects. For example, if you do readable.setEncoding('utf8'), then the output data will be interpreted as UTF-8 data, and returned as strings. If you do readable.setEncoding('hex'), then the data will be encoded in hexadecimal string format.

    This properly handles multi-byte characters that would otherwise be potentially mangled if you simply pulled the Buffers directly and called buf.toString(encoding) on them. If you want to read the data as strings, always use this method.

    var readable = getReadableStreamSomehow();
    readable.setEncoding('utf8');
    readable.on('data', function(chunk) {
      assert.equal(typeof chunk, 'string');
      console.log('got %d characters of string data', chunk.length);
    })

    readable.resume()#

    This method will cause the readable stream to resume emitting data events.

    This method will switch the stream into flowing-mode. If you do not want to consume the data from a stream, but you do want to get to its end event, you can call readable.resume() to open the flow of data.

    var readable = getReadableStreamSomehow();
    readable.resume();
    readable.on('end', function(chunk) {
      console.log('got to the end, but did not read anything');
    })

    readable.pause()#

    This method will cause a stream in flowing-mode to stop emitting data events. Any data that becomes available will remain in the internal buffer.

    This method is only relevant in flowing mode. When called on a non-flowing stream, it will switch into flowing mode, but remain paused.

    var readable = getReadableStreamSomehow();
    readable.on('data', function(chunk) {
      console.log('got %d bytes of data', chunk.length);
      readable.pause();
      console.log('there will be no more data for 1 second');
      setTimeout(function() {
        console.log('now data will start flowing again');
        readable.resume();
      }, 1000);
    })

    readable.pipe(destination, [options])#

    • destination Writable Stream The destination for writing data
    • options Object Pipe options
      • end Boolean End the writer when the reader ends. Default = true

    This method pulls all the data out of a readable stream, and writes it to the supplied destination, automatically managing the flow so that the destination is not overwhelmed by a fast readable stream.

    Multiple destinations can be piped to safely.

    var readable = getReadableStreamSomehow();
    var writable = fs.createWriteStream('file.txt');
    // All the data from readable goes into 'file.txt'
    readable.pipe(writable);

    This function returns the destination stream, so you can set up pipe chains like so:

    var r = fs.createReadStream('file.txt');
    var z = zlib.createGzip();
    var w = fs.createWriteStream('file.txt.gz');
    r.pipe(z).pipe(w);

    For example, emulating the Unix cat command:

    process.stdin.pipe(process.stdout);

    By default end() is called on the destination when the source stream emits end, so that destination is no longer writable. Pass { end: false } as options to keep the destination stream open.

    This keeps writer open so that "Goodbye" can be written at the end.

    reader.pipe(writer, { end: false });
    reader.on('end', function() {
      writer.end('Goodbye\n');
    });

    Note that process.stderr and process.stdout are never closed until the process exits, regardless of the specified options.

    readable.unpipe([destination])#

    • destination Writable Stream Optional specific stream to unpipe

    This method will remove the hooks set up for a previous pipe() call.

    If the destination is not specified, then all pipes are removed.

    If the destination is specified, but no pipe is set up for it, then this is a no-op.

    var readable = getReadableStreamSomehow();
    var writable = fs.createWriteStream('file.txt');
    // All the data from readable goes into 'file.txt',
    // but only for the first second
    readable.pipe(writable);
    setTimeout(function() {
      console.log('stop writing to file.txt');
      readable.unpipe(writable);
      console.log('manually close the file stream');
      writable.end();
    }, 1000);

    readable.unshift(chunk)#

    • chunk Buffer | String Chunk of data to unshift onto the read queue

    This is useful in certain cases where a stream is being consumed by a parser, which needs to "un-consume" some data that it has optimistically pulled out of the source, so that the stream can be passed on to some other party.

    If you find that you must often call stream.unshift(chunk) in your programs, consider implementing a Transform stream instead. (See API for Stream Implementors, below.)

    // Pull off a header delimited by \n\n
    // use unshift() if we get too much
    // Call the callback with (error, header, stream)
    var StringDecoder = require('string_decoder').StringDecoder;
    function parseHeader(stream, callback) {
      stream.on('error', callback);
      stream.on('readable', onReadable);
      var decoder = new StringDecoder('utf8');
      var header = '';
      function onReadable() {
        var chunk;
        while (null !== (chunk = stream.read())) {
          var str = decoder.write(chunk);
          if (str.match(/\n\n/)) {
            // found the header boundary
            var split = str.split(/\n\n/);
            header += split.shift();
            var remaining = split.join('\n\n');
            var buf = new Buffer(remaining, 'utf8');
            if (buf.length)
              stream.unshift(buf);
            stream.removeListener('error', callback);
            stream.removeListener('readable', onReadable);
            // now the body of the message can be read from the stream.
            callback(null, header, stream);
          } else {
            // still reading the header.
            header += str;
          }
        }
      }
    }

    readable.wrap(stream)#

    • stream Stream An "old style" readable stream

    Versions of Node prior to v0.10 had streams that did not implement the entire Streams API as it is today. (See "Compatibility" below for more information.)

    If you are using an older Node library that emits 'data' events and has a pause() method that is advisory only, then you can use the wrap() method to create a Readable stream that uses the old stream as its data source.

    You will very rarely ever need to call this function, but it exists as a convenience for interacting with old Node programs and libraries.

    For example:

    var OldReader = require('./old-api-module.js').OldReader;
    var oreader = new OldReader;
    var Readable = require('stream').Readable;
    var myReader = new Readable().wrap(oreader);
    
    myReader.on('readable', function() {
      myReader.read(); // etc.
    });

    Class: stream.Writable#

    The Writable stream interface is an abstraction for a destination that you are writing data to.

    Examples of writable streams include:

    writable.write(chunk, [encoding], [callback])#

    • chunk String | Buffer The data to write
    • encoding String The encoding, if chunk is a String
    • callback Function Callback for when this chunk of data is flushed
    • Returns: Boolean True if the data was handled completely.

    This method writes some data to the underlying system, and calls the supplied callback once the data has been fully handled.

    The return value indicates if you should continue writing right now. If the data had to be buffered internally, then it will return false. Otherwise, it will return true.

    This return value is strictly advisory. You MAY continue to write, even if it returns false. However, writes will be buffered in memory, so it is best not to do this excessively. Instead, wait for the drain event before writing more data.

    Event: 'drain'#

    If a writable.write(chunk) call returns false, then the drain event will indicate when it is appropriate to begin writing more data to the stream.

    // Write the data to the supplied writable stream 1MM times.
    // Be attentive to back-pressure.
    function writeOneMillionTimes(writer, data, encoding, callback) {
      var i = 1000000;
      write();
      function write() {
        var ok = true;
        do {
          i -= 1;
          if (i === 0) {
            // last time!
            writer.write(data, encoding, callback);
          } else {
            // see if we should continue, or wait
            // don't pass the callback, because we're not done yet.
            ok = writer.write(data, encoding);
          }
        } while (i > 0 && ok);
        if (i > 0) {
          // had to stop early!
          // write some more once it drains
          writer.once('drain', write);
        }
      }
    }

    writable.end([chunk], [encoding], [callback])#

    • chunk String | Buffer Optional data to write
    • encoding String The encoding, if chunk is a String
    • callback Function Optional callback for when the stream is finished

    Call this method when no more data will be written to the stream. If supplied, the callback is attached as a listener on the finish event.

    Calling write() after calling end() will raise an error.

    // write 'hello, ' and then end with 'world!'
    http.createServer(function (req, res) {
      res.write('hello, ');
      res.end('world!');
      // writing more now is not allowed!
    });

    Event: 'finish'#

    When the end() method has been called, and all data has been flushed to the underlying system, this event is emitted.

    var writer = getWritableStreamSomehow();
    for (var i = 0; i < 100; i ++) {
      writer.write('hello, #' + i + '!\n');
    }
    writer.end('this is the end\n');
    writer.on('finish', function() {
      console.error('all writes are now complete.');
    });

    Event: 'pipe'#

    • src Readable Stream source stream that is piping to this writable

    This is emitted whenever the pipe() method is called on a readable stream, adding this writable to its set of destinations.

    var writer = getWritableStreamSomehow();
    var reader = getReadableStreamSomehow();
    writer.on('pipe', function(src) {
      console.error('something is piping into the writer');
      assert.equal(src, reader);
    });
    reader.pipe(writer);

    Event: 'unpipe'#

    This is emitted whenever the unpipe() method is called on a readable stream, removing this writable from its set of destinations.

    var writer = getWritableStreamSomehow();
    var reader = getReadableStreamSomehow();
    writer.on('unpipe', function(src) {
      console.error('something has stopped piping into the writer');
      assert.equal(src, reader);
    });
    reader.pipe(writer);
    reader.unpipe(writer);

    Event: 'error'#

    Emitted if there was an error when writing or piping data.

    Class: stream.Duplex#

    Duplex streams are streams that implement both the Readable and Writable interfaces. See above for usage.

    Examples of Duplex streams include:

    Class: stream.Transform#

    Transform streams are Duplex streams where the output is in some way computed from the input. They implement both the Readable and Writable interfaces. See above for usage.

    Examples of Transform streams include:

    API for Stream Implementors#

    To implement any sort of stream, the pattern is the same:

    1. Extend the appropriate parent class in your own subclass. (The util.inherits method is particularly helpful for this.)
    2. Call the appropriate parent class constructor in your constructor, to be sure that the internal mechanisms are set up properly.
    3. Implement one or more specific methods, as detailed below.

    The class to extend and the method(s) to implement depend on the sort of stream class you are writing:

    Use-case

    Class

    Method(s) to implement

    Reading only

    Readable

    _read

    Writing only

    Writable

    _write

    Reading and writing

    Duplex

    _read, _write

    Operate on written data, then read the result

    Transform

    _transform, _flush

    In your implementation code, it is very important to never call the methods described in API for Stream Consumers above. Otherwise, you can potentially cause adverse side effects in programs that consume your streaming interfaces.

    Class: stream.Readable#

    stream.Readable is an abstract class designed to be extended with an underlying implementation of the _read(size) method.

    Please see above under API for Stream Consumers for how to consume streams in your programs. What follows is an explanation of how to implement Readable streams in your programs.

    Example: A Counting Stream#

    This is a basic example of a Readable stream. It emits the numerals from 1 to 1,000,000 in ascending order, and then ends.

    var Readable = require('stream').Readable;
    var util = require('util');
    util.inherits(Counter, Readable);
    
    function Counter(opt) {
      Readable.call(this, opt);
      this._max = 1000000;
      this._index = 1;
    }
    
    Counter.prototype._read = function() {
      var i = this._index++;
      if (i > this._max)
        this.push(null);
      else {
        var str = '' + i;
        var buf = new Buffer(str, 'ascii');
        this.push(buf);
      }
    };

    Example: SimpleProtocol v1 (Sub-optimal)#

    This is similar to the parseHeader function described above, but implemented as a custom stream. Also, note that this implementation does not convert the incoming data to a string.

    However, this would be better implemented as a Transform stream. See below for a better implementation.

    // A parser for a simple data protocol.
    // The "header" is a JSON object, followed by 2 \n characters, and
    // then a message body.
    //
    // NOTE: This can be done more simply as a Transform stream!
    // Using Readable directly for this is sub-optimal.  See the
    // alternative example below under the Transform section.
    
    var Readable = require('stream').Readable;
    var util = require('util');
    
    util.inherits(SimpleProtocol, Readable);
    
    function SimpleProtocol(source, options) {
      if (!(this instanceof SimpleProtocol))
        return new SimpleProtocol(source, options);
    
      Readable.call(this, options);
      this._inBody = false;
      this._sawFirstCr = false;
    
      // source is a readable stream, such as a socket or file
      this._source = source;
    
      var self = this;
      source.on('end', function() {
        self.push(null);
      });
    
      // give it a kick whenever the source is readable
      // read(0) will not consume any bytes
      source.on('readable', function() {
        self.read(0);
      });
    
      this._rawHeader = [];
      this.header = null;
    }
    
    SimpleProtocol.prototype._read = function(n) {
      if (!this._inBody) {
        var chunk = this._source.read();
    
        // if the source doesn't have data, we don't have data yet.
        if (chunk === null)
          return this.push('');
    
        // check if the chunk has a \n\n
        var split = -1;
        for (var i = 0; i < chunk.length; i++) {
          if (chunk[i] === 10) { // '\n'
            if (this._sawFirstCr) {
              split = i;
              break;
            } else {
              this._sawFirstCr = true;
            }
          } else {
            this._sawFirstCr = false;
          }
        }
    
        if (split === -1) {
          // still waiting for the \n\n
          // stash the chunk, and try again.
          this._rawHeader.push(chunk);
          this.push('');
        } else {
          this._inBody = true;
          var h = chunk.slice(0, split);
          this._rawHeader.push(h);
          var header = Buffer.concat(this._rawHeader).toString();
          try {
            this.header = JSON.parse(header);
          } catch (er) {
            this.emit('error', new Error('invalid simple protocol data'));
            return;
          }
          // now, because we got some extra data, unshift the rest
          // back into the read queue so that our consumer will see it.
          var b = chunk.slice(split);
          this.unshift(b);
    
          // and let them know that we are done parsing the header.
          this.emit('header', this.header);
        }
      } else {
        // from there on, just provide the data to our consumer.
        // careful not to push(null), since that would indicate EOF.
        var chunk = this._source.read();
        if (chunk) this.push(chunk);
      }
    };
    
    // Usage:
    // var parser = new SimpleProtocol(source);
    // Now parser is a readable stream that will emit 'header'
    // with the parsed header data.

    new stream.Readable([options])#

    • options Object
      • highWaterMark Number The maximum number of bytes to store in the internal buffer before ceasing to read from the underlying resource. Default=16kb
      • encoding String If specified, then buffers will be decoded to strings using the specified encoding. Default=null
      • objectMode Boolean Whether this stream should behave as a stream of objects. Meaning that stream.read(n) returns a single value instead of a Buffer of size n. Default=false

    In classes that extend the Readable class, make sure to call the Readable constructor so that the buffering settings can be properly initialized.

    readable._read(size)#

    • size Number Number of bytes to read asynchronously

    Note: Implement this function, but do NOT call it directly.

    This function should NOT be called directly. It should be implemented by child classes, and only called by the internal Readable class methods.

    All Readable stream implementations must provide a _read method to fetch data from the underlying resource.

    This method is prefixed with an underscore because it is internal to the class that defines it, and should not be called directly by user programs. However, you are expected to override this method in your own extension classes.

    When data is available, put it into the read queue by calling readable.push(chunk). If push returns false, then you should stop reading. When _read is called again, you should start pushing more data.

    The size argument is advisory. Implementations where a "read" is a single call that returns data can use this to know how much data to fetch. Implementations where that is not relevant, such as TCP or TLS, may ignore this argument, and simply provide data whenever it becomes available. There is no need, for example to "wait" until size bytes are available before calling stream.push(chunk).

    readable.push(chunk, [encoding])#

    • chunk Buffer | null | String Chunk of data to push into the read queue
    • encoding String Encoding of String chunks. Must be a valid Buffer encoding, such as 'utf8' or 'ascii'
    • return Boolean Whether or not more pushes should be performed

    Note: This function should be called by Readable implementors, NOT by consumers of Readable streams.

    The _read() function will not be called again until at least one push(chunk) call is made.

    The Readable class works by putting data into a read queue to be pulled out later by calling the read() method when the 'readable' event fires.

    The push() method will explicitly insert some data into the read queue. If it is called with null then it will signal the end of the data (EOF).

    This API is designed to be as flexible as possible. For example, you may be wrapping a lower-level source which has some sort of pause/resume mechanism, and a data callback. In those cases, you could wrap the low-level source object by doing something like this:

    // source is an object with readStop() and readStart() methods,
    // and an `ondata` member that gets called when it has data, and
    // an `onend` member that gets called when the data is over.
    
    util.inherits(SourceWrapper, Readable);
    
    function SourceWrapper(options) {
      Readable.call(this, options);
    
      this._source = getLowlevelSourceObject();
      var self = this;
    
      // Every time there's data, we push it into the internal buffer.
      this._source.ondata = function(chunk) {
        // if push() returns false, then we need to stop reading from source
        if (!self.push(chunk))
          self._source.readStop();
      };
    
      // When the source ends, we push the EOF-signalling `null` chunk
      this._source.onend = function() {
        self.push(null);
      };
    }
    
    // _read will be called when the stream wants to pull more data in
    // the advisory size argument is ignored in this case.
    SourceWrapper.prototype._read = function(size) {
      this._source.readStart();
    };

    Class: stream.Writable#

    stream.Writable is an abstract class designed to be extended with an underlying implementation of the _write(chunk, encoding, callback) method.

    Please see above under API for Stream Consumers for how to consume writable streams in your programs. What follows is an explanation of how to implement Writable streams in your programs.

    new stream.Writable([options])#

    • options Object
      • highWaterMark Number Buffer level when write() starts returning false. Default=16kb
      • decodeStrings Boolean Whether or not to decode strings into Buffers before passing them to _write(). Default=true

    In classes that extend the Writable class, make sure to call the constructor so that the buffering settings can be properly initialized.

    writable._write(chunk, encoding, callback)#

    • chunk Buffer | String The chunk to be written. Will always be a buffer unless the decodeStrings option was set to false.
    • encoding String If the chunk is a string, then this is the encoding type. Ignore chunk is a buffer. Note that chunk will always be a buffer unless the decodeStrings option is explicitly set to false.
    • callback Function Call this function (optionally with an error argument) when you are done processing the supplied chunk.

    All Writable stream implementations must provide a _write() method to send data to the underlying resource.

    Note: This function MUST NOT be called directly. It should be implemented by child classes, and called by the internal Writable class methods only.

    Call the callback using the standard callback(error) pattern to signal that the write completed successfully or with an error.

    If the decodeStrings flag is set in the constructor options, then chunk may be a string rather than a Buffer, and encoding will indicate the sort of string that it is. This is to support implementations that have an optimized handling for certain string data encodings. If you do not explicitly set the decodeStrings option to false, then you can safely ignore the encoding argument, and assume that chunk will always be a Buffer.

    This method is prefixed with an underscore because it is internal to the class that defines it, and should not be called directly by user programs. However, you are expected to override this method in your own extension classes.

    Class: stream.Duplex#

    A "duplex" stream is one that is both Readable and Writable, such as a TCP socket connection.

    Note that stream.Duplex is an abstract class designed to be extended with an underlying implementation of the _read(size) and _write(chunk, encoding, callback) methods as you would with a Readable or Writable stream class.

    Since JavaScript doesn't have multiple prototypal inheritance, this class prototypally inherits from Readable, and then parasitically from Writable. It is thus up to the user to implement both the lowlevel _read(n) method as well as the lowlevel _write(chunk, encoding, callback) method on extension duplex classes.

    new stream.Duplex(options)#

    • options Object Passed to both Writable and Readable constructors. Also has the following fields:
      • allowHalfOpen Boolean Default=true. If set to false, then the stream will automatically end the readable side when the writable side ends and vice versa.

    In classes that extend the Duplex class, make sure to call the constructor so that the buffering settings can be properly initialized.

    Class: stream.Transform#

    A "transform" stream is a duplex stream where the output is causally connected in some way to the input, such as a zlib stream or a crypto stream.

    There is no requirement that the output be the same size as the input, the same number of chunks, or arrive at the same time. For example, a Hash stream will only ever have a single chunk of output which is provided when the input is ended. A zlib stream will produce output that is either much smaller or much larger than its input.

    Rather than implement the _read() and _write() methods, Transform classes must implement the _transform() method, and may optionally also implement the _flush() method. (See below.)

    new stream.Transform([options])#

    • options Object Passed to both Writable and Readable constructors.

    In classes that extend the Transform class, make sure to call the constructor so that the buffering settings can be properly initialized.

    transform._transform(chunk, encoding, callback)#

    • chunk Buffer | String The chunk to be transformed. Will always be a buffer unless the decodeStrings option was set to false.
    • encoding String If the chunk is a string, then this is the encoding type. (Ignore if decodeStrings chunk is a buffer.)
    • callback Function Call this function (optionally with an error argument) when you are done processing the supplied chunk.

    Note: This function MUST NOT be called directly. It should be implemented by child classes, and called by the internal Transform class methods only.

    All Transform stream implementations must provide a _transform method to accept input and produce output.

    _transform should do whatever has to be done in this specific Transform class, to handle the bytes being written, and pass them off to the readable portion of the interface. Do asynchronous I/O, process things, and so on.

    Call transform.push(outputChunk) 0 or more times to generate output from this input chunk, depending on how much data you want to output as a result of this chunk.

    Call the callback function only when the current chunk is completely consumed. Note that there may or may not be output as a result of any particular input chunk.

    This method is prefixed with an underscore because it is internal to the class that defines it, and should not be called directly by user programs. However, you are expected to override this method in your own extension classes.

    transform._flush(callback)#

    • callback Function Call this function (optionally with an error argument) when you are done flushing any remaining data.

    Note: This function MUST NOT be called directly. It MAY be implemented by child classes, and if so, will be called by the internal Transform class methods only.

    In some cases, your transform operation may need to emit a bit more data at the end of the stream. For example, a Zlib compression stream will store up some internal state so that it can optimally compress the output. At the end, however, it needs to do the best it can with what is left, so that the data will be complete.

    In those cases, you can implement a _flush method, which will be called at the very end, after all the written data is consumed, but before emitting end to signal the end of the readable side. Just like with _transform, call transform.push(chunk) zero or more times, as appropriate, and call callback when the flush operation is complete.

    This method is prefixed with an underscore because it is internal to the class that defines it, and should not be called directly by user programs. However, you are expected to override this method in your own extension classes.

    Example: SimpleProtocol parser v2#

    The example above of a simple protocol parser can be implemented simply by using the higher level Transform stream class, similar to the parseHeader and SimpleProtocol v1 examples above.

    In this example, rather than providing the input as an argument, it would be piped into the parser, which is a more idiomatic Node stream approach.

    var util = require('util');
    var Transform = require('stream').Transform;
    util.inherits(SimpleProtocol, Transform);
    
    function SimpleProtocol(options) {
      if (!(this instanceof SimpleProtocol))
        return new SimpleProtocol(options);
    
      Transform.call(this, options);
      this._inBody = false;
      this._sawFirstCr = false;
      this._rawHeader = [];
      this.header = null;
    }
    
    SimpleProtocol.prototype._transform = function(chunk, encoding, done) {
      if (!this._inBody) {
        // check if the chunk has a \n\n
        var split = -1;
        for (var i = 0; i < chunk.length; i++) {
          if (chunk[i] === 10) { // '\n'
            if (this._sawFirstCr) {
              split = i;
              break;
            } else {
              this._sawFirstCr = true;
            }
          } else {
            this._sawFirstCr = false;
          }
        }
    
        if (split === -1) {
          // still waiting for the \n\n
          // stash the chunk, and try again.
          this._rawHeader.push(chunk);
        } else {
          this._inBody = true;
          var h = chunk.slice(0, split);
          this._rawHeader.push(h);
          var header = Buffer.concat(this._rawHeader).toString();
          try {
            this.header = JSON.parse(header);
          } catch (er) {
            this.emit('error', new Error('invalid simple protocol data'));
            return;
          }
          // and let them know that we are done parsing the header.
          this.emit('header', this.header);
    
          // now, because we got some extra data, emit this first.
          this.push(chunk.slice(split));
        }
      } else {
        // from there on, just provide the data to our consumer as-is.
        this.push(chunk);
      }
      done();
    };
    
    // Usage:
    // var parser = new SimpleProtocol();
    // source.pipe(parser)
    // Now parser is a readable stream that will emit 'header'
    // with the parsed header data.

    Class: stream.PassThrough#

    This is a trivial implementation of a Transform stream that simply passes the input bytes across to the output. Its purpose is mainly for examples and testing, but there are occasionally use cases where it can come in handy as a building block for novel sorts of streams.

    Streams: Under the Hood#

    Buffering#

    Both Writable and Readable streams will buffer data on an internal object called _writableState.buffer or _readableState.buffer, respectively.

    The amount of data that will potentially be buffered depends on the highWaterMark option which is passed into the constructor.

    Buffering in Readable streams happens when the implementation calls stream.push(chunk). If the consumer of the Stream does not call stream.read(), then the data will sit in the internal queue until it is consumed.

    Buffering in Writable streams happens when the user calls stream.write(chunk) repeatedly, even when write() returns false.

    The purpose of streams, especially with the pipe() method, is to limit the buffering of data to acceptable levels, so that sources and destinations of varying speed will not overwhelm the available memory.

    stream.read(0)#

    There are some cases where you want to trigger a refresh of the underlying readable stream mechanisms, without actually consuming any data. In that case, you can call stream.read(0), which will always return null.

    If the internal read buffer is below the highWaterMark, and the stream is not currently reading, then calling read(0) will trigger a low-level _read call.

    There is almost never a need to do this. However, you will see some cases in Node's internals where this is done, particularly in the Readable stream class internals.

    stream.push('')#

    Pushing a zero-byte string or Buffer (when not in Object mode) has an interesting side effect. Because it is a call to stream.push(), it will end the reading process. However, it does not add any data to the readable buffer, so there's nothing for a user to consume.

    Very rarely, there are cases where you have no data to provide now, but the consumer of your stream (or, perhaps, another bit of your own code) will know when to check again, by calling stream.read(0). In those cases, you may call stream.push('').

    So far, the only use case for this functionality is in the tls.CryptoStream class, which is deprecated in Node v0.12. If you find that you have to use stream.push(''), please consider another approach, because it almost certainly indicates that something is horribly wrong.

    Compatibility with Older Node Versions#

    In versions of Node prior to v0.10, the Readable stream interface was simpler, but also less powerful and less useful.

    • Rather than waiting for you to call the read() method, 'data' events would start emitting immediately. If you needed to do some I/O to decide how to handle data, then you had to store the chunks in some kind of buffer so that they would not be lost.
    • The pause() method was advisory, rather than guaranteed. This meant that you still had to be prepared to receive 'data' events even when the stream was in a paused state.

    In Node v0.10, the Readable class described below was added. For backwards compatibility with older Node programs, Readable streams switch into "flowing mode" when a 'data' event handler is added, or when the pause() or resume() methods are called. The effect is that, even if you are not using the new read() method and 'readable' event, you no longer have to worry about losing 'data' chunks.

    Most programs will continue to function normally. However, this introduces an edge case in the following conditions:

    • No 'data' event handler is added.
    • The pause() and resume() methods are never called.

    For example, consider the following code:

    // WARNING!  BROKEN!
    net.createServer(function(socket) {
    
      // we add an 'end' method, but never consume the data
      socket.on('end', function() {
        // It will never get here.
        socket.end('I got your message (but didnt read it)\n');
      });
    
    }).listen(1337);

    In versions of node prior to v0.10, the incoming message data would be simply discarded. However, in Node v0.10 and beyond, the socket will remain paused forever.

    The workaround in this situation is to call the resume() method to trigger "old mode" behavior:

    // Workaround
    net.createServer(function(socket) {
    
      socket.on('end', function() {
        socket.end('I got your message (but didnt read it)\n');
      });
    
      // start the flow of data, discarding it.
      socket.resume();
    
    }).listen(1337);

    In addition to new Readable streams switching into flowing-mode, pre-v0.10 style streams can be wrapped in a Readable class using the wrap() method.

    Object Mode#

    Normally, Streams operate on Strings and Buffers exclusively.

    Streams that are in object mode can emit generic JavaScript values other than Buffers and Strings.

    A Readable stream in object mode will always return a single item from a call to stream.read(size), regardless of what the size argument is.

    A Writable stream in object mode will always ignore the encoding argument to stream.write(data, encoding).

    The special value null still retains its special value for object mode streams. That is, for object mode readable streams, null as a return value from stream.read() indicates that there is no more data, and stream.push(null) will signal the end of stream data (EOF).

    No streams in Node core are object mode streams. This pattern is only used by userland streaming libraries.

    You should set objectMode in your stream child class constructor on the options object. Setting objectMode mid-stream is not safe.

    State Objects#

    Readable streams have a member object called _readableState. Writable streams have a member object called _writableState. Duplex streams have both.

    These objects should generally not be modified in child classes. However, if you have a Duplex or Transform stream that should be in objectMode on the readable side, and not in objectMode on the writable side, then you may do this in the constructor by setting the flag explicitly on the appropriate state object.

    var util = require('util');
    var StringDecoder = require('string_decoder').StringDecoder;
    var Transform = require('stream').Transform;
    util.inherits(JSONParseStream, Transform);
    
    // Gets \n-delimited JSON string data, and emits the parsed objects
    function JSONParseStream(options) {
      if (!(this instanceof JSONParseStream))
        return new JSONParseStream(options);
    
      Transform.call(this, options);
      this._writableState.objectMode = false;
      this._readableState.objectMode = true;
      this._buffer = '';
      this._decoder = new StringDecoder('utf8');
    }
    
    JSONParseStream.prototype._transform = function(chunk, encoding, cb) {
      this._buffer += this._decoder.write(chunk);
      // split on newlines
      var lines = this._buffer.split(/\r?\n/);
      // keep the last partial line buffered
      this._buffer = lines.pop();
      for (var l = 0; l < lines.length; l++) {
        var line = lines[l];
        try {
          var obj = JSON.parse(line);
        } catch (er) {
          this.emit('error', er);
          return;
        }
        // push the parsed object out to the readable consumer
        this.push(obj);
      }
      cb();
    };
    
    JSONParseStream.prototype._flush = function(cb) {
      // Just handle any leftover
      var rem = this._buffer.trim();
      if (rem) {
        try {
          var obj = JSON.parse(rem);
        } catch (er) {
          this.emit('error', er);
          return;
        }
        // push the parsed object out to the readable consumer
        this.push(obj);
      }
      cb();
    };

    The state objects contain other useful information for debugging the state of streams in your programs. It is safe to look at them, but beyond setting option flags in the constructor, it is not safe to modify them.

    node-v0.10.25~dfsg2/doc/api/string_decoder.html0000644000000000000000000001210312270264601020010 0ustar rootroot StringDecoder Node.js v0.10.25 Manual & Documentation

    Node.js v0.10.25 Manual & Documentation


    StringDecoder#

    Stability: 3 - Stable

    To use this module, do require('string_decoder'). StringDecoder decodes a buffer to a string. It is a simple interface to buffer.toString() but provides additional support for utf8.

    var StringDecoder = require('string_decoder').StringDecoder;
    var decoder = new StringDecoder('utf8');
    
    var cent = new Buffer([0xC2, 0xA2]);
    console.log(decoder.write(cent));
    
    var euro = new Buffer([0xE2, 0x82, 0xAC]);
    console.log(decoder.write(euro));

    Class: StringDecoder#

    Accepts a single argument, encoding which defaults to utf8.

    decoder.write(buffer)#

    Returns a decoded string.

    decoder.end()#

    Returns any trailing bytes that were left in the buffer.

    node-v0.10.25~dfsg2/doc/api/os.json0000644000000000000000000001656312270264601015461 0ustar rootroot{ "source": "doc/api/os.markdown", "modules": [ { "textRaw": "os", "name": "os", "stability": 4, "stabilityText": "API Frozen", "desc": "

    Provides a few basic operating-system related utility functions.\n\n

    \n

    Use require('os') to access this module.\n\n

    \n", "methods": [ { "textRaw": "os.tmpdir()", "type": "method", "name": "tmpdir", "desc": "

    Returns the operating system's default directory for temp files.\n\n

    \n", "signatures": [ { "params": [] } ] }, { "textRaw": "os.endianness()", "type": "method", "name": "endianness", "desc": "

    Returns the endianness of the CPU. Possible values are "BE" or "LE".\n\n

    \n", "signatures": [ { "params": [] } ] }, { "textRaw": "os.hostname()", "type": "method", "name": "hostname", "desc": "

    Returns the hostname of the operating system.\n\n

    \n", "signatures": [ { "params": [] } ] }, { "textRaw": "os.type()", "type": "method", "name": "type", "desc": "

    Returns the operating system name.\n\n

    \n", "signatures": [ { "params": [] } ] }, { "textRaw": "os.platform()", "type": "method", "name": "platform", "desc": "

    Returns the operating system platform.\n\n

    \n", "signatures": [ { "params": [] } ] }, { "textRaw": "os.arch()", "type": "method", "name": "arch", "desc": "

    Returns the operating system CPU architecture.\n\n

    \n", "signatures": [ { "params": [] } ] }, { "textRaw": "os.release()", "type": "method", "name": "release", "desc": "

    Returns the operating system release.\n\n

    \n", "signatures": [ { "params": [] } ] }, { "textRaw": "os.uptime()", "type": "method", "name": "uptime", "desc": "

    Returns the system uptime in seconds.\n\n

    \n", "signatures": [ { "params": [] } ] }, { "textRaw": "os.loadavg()", "type": "method", "name": "loadavg", "desc": "

    Returns an array containing the 1, 5, and 15 minute load averages.\n\n

    \n

    The load average is a measure of system activity, calculated by the operating\nsystem and expressed as a fractional number. As a rule of thumb, the load\naverage should ideally be less than the number of logical CPUs in the system.\n\n

    \n

    The load average is a very UNIX-y concept; there is no real equivalent on\nWindows platforms. That is why this function always returns [0, 0, 0] on\nWindows.\n\n

    \n", "signatures": [ { "params": [] } ] }, { "textRaw": "os.totalmem()", "type": "method", "name": "totalmem", "desc": "

    Returns the total amount of system memory in bytes.\n\n

    \n", "signatures": [ { "params": [] } ] }, { "textRaw": "os.freemem()", "type": "method", "name": "freemem", "desc": "

    Returns the amount of free system memory in bytes.\n\n

    \n", "signatures": [ { "params": [] } ] }, { "textRaw": "os.cpus()", "type": "method", "name": "cpus", "desc": "

    Returns an array of objects containing information about each CPU/core\ninstalled: model, speed (in MHz), and times (an object containing the number of\nmilliseconds the CPU/core spent in: user, nice, sys, idle, and irq).\n\n

    \n

    Example inspection of os.cpus:\n\n

    \n
    [ { model: 'Intel(R) Core(TM) i7 CPU         860  @ 2.80GHz',\n    speed: 2926,\n    times:\n     { user: 252020,\n       nice: 0,\n       sys: 30340,\n       idle: 1070356870,\n       irq: 0 } },\n  { model: 'Intel(R) Core(TM) i7 CPU         860  @ 2.80GHz',\n    speed: 2926,\n    times:\n     { user: 306960,\n       nice: 0,\n       sys: 26980,\n       idle: 1071569080,\n       irq: 0 } },\n  { model: 'Intel(R) Core(TM) i7 CPU         860  @ 2.80GHz',\n    speed: 2926,\n    times:\n     { user: 248450,\n       nice: 0,\n       sys: 21750,\n       idle: 1070919370,\n       irq: 0 } },\n  { model: 'Intel(R) Core(TM) i7 CPU         860  @ 2.80GHz',\n    speed: 2926,\n    times:\n     { user: 256880,\n       nice: 0,\n       sys: 19430,\n       idle: 1070905480,\n       irq: 20 } },\n  { model: 'Intel(R) Core(TM) i7 CPU         860  @ 2.80GHz',\n    speed: 2926,\n    times:\n     { user: 511580,\n       nice: 20,\n       sys: 40900,\n       idle: 1070842510,\n       irq: 0 } },\n  { model: 'Intel(R) Core(TM) i7 CPU         860  @ 2.80GHz',\n    speed: 2926,\n    times:\n     { user: 291660,\n       nice: 0,\n       sys: 34360,\n       idle: 1070888000,\n       irq: 10 } },\n  { model: 'Intel(R) Core(TM) i7 CPU         860  @ 2.80GHz',\n    speed: 2926,\n    times:\n     { user: 308260,\n       nice: 0,\n       sys: 55410,\n       idle: 1071129970,\n       irq: 880 } },\n  { model: 'Intel(R) Core(TM) i7 CPU         860  @ 2.80GHz',\n    speed: 2926,\n    times:\n     { user: 266450,\n       nice: 1480,\n       sys: 34920,\n       idle: 1072572010,\n       irq: 30 } } ]
    \n", "signatures": [ { "params": [] } ] }, { "textRaw": "os.networkInterfaces()", "type": "method", "name": "networkInterfaces", "desc": "

    Get a list of network interfaces:\n\n

    \n
    { lo0: \n   [ { address: '::1', family: 'IPv6', internal: true },\n     { address: 'fe80::1', family: 'IPv6', internal: true },\n     { address: '127.0.0.1', family: 'IPv4', internal: true } ],\n  en1: \n   [ { address: 'fe80::cabc:c8ff:feef:f996', family: 'IPv6',\n       internal: false },\n     { address: '10.0.1.123', family: 'IPv4', internal: false } ],\n  vmnet1: [ { address: '10.99.99.254', family: 'IPv4', internal: false } ],\n  vmnet8: [ { address: '10.88.88.1', family: 'IPv4', internal: false } ],\n  ppp0: [ { address: '10.2.0.231', family: 'IPv4', internal: false } ] }
    \n", "signatures": [ { "params": [] } ] } ], "properties": [ { "textRaw": "os.EOL", "name": "EOL", "desc": "

    A constant defining the appropriate End-of-line marker for the operating system.\n

    \n" } ], "type": "module", "displayName": "os" } ] } node-v0.10.25~dfsg2/doc/api/buffer.json0000644000000000000000000024374612270264601016316 0ustar rootroot{ "source": "doc/api/buffer.markdown", "modules": [ { "textRaw": "Buffer", "name": "buffer", "stability": 3, "stabilityText": "Stable", "desc": "

    Pure JavaScript is Unicode friendly but not nice to binary data. When\ndealing with TCP streams or the file system, it's necessary to handle octet\nstreams. Node has several strategies for manipulating, creating, and\nconsuming octet streams.\n\n

    \n

    Raw data is stored in instances of the Buffer class. A Buffer is similar\nto an array of integers but corresponds to a raw memory allocation outside\nthe V8 heap. A Buffer cannot be resized.\n\n

    \n

    The Buffer class is a global, making it very rare that one would need\nto ever require('buffer').\n\n

    \n

    Converting between Buffers and JavaScript string objects requires an explicit\nencoding method. Here are the different string encodings.\n\n

    \n
      \n
    • 'ascii' - for 7 bit ASCII data only. This encoding method is very fast, and\nwill strip the high bit if set.

      \n

      Note that when converting from string to buffer, this encoding converts a null\ncharacter ('\\0' or '\\u0000') into 0x20 (character code of a space). If\nyou want to convert a null character into 0x00, you should use 'utf8'.

      \n
    • \n
    • 'utf8' - Multibyte encoded Unicode characters. Many web pages and other\ndocument formats use UTF-8.

      \n
    • \n
    • 'utf16le' - 2 or 4 bytes, little endian encoded Unicode characters.\nSurrogate pairs (U+10000 to U+10FFFF) are supported.

      \n
    • \n
    • 'ucs2' - Alias of 'utf16le'.

      \n
    • \n
    • 'base64' - Base64 string encoding.

      \n
    • \n
    • 'binary' - A way of encoding raw binary data into strings by using only\nthe first 8 bits of each character. This encoding method is deprecated and\nshould be avoided in favor of Buffer objects where possible. This encoding\nwill be removed in future versions of Node.

      \n
    • \n
    • 'hex' - Encode each byte as two hexadecimal characters.

      \n
    • \n
    \n

    A Buffer object can also be used with typed arrays. The buffer object is\ncloned to an ArrayBuffer that is used as the backing store for the typed\narray. The memory of the buffer and the ArrayBuffer is not shared.\n\n

    \n

    NOTE: Node.js v0.8 simply retained a reference to the buffer in array.buffer\ninstead of cloning it.\n\n

    \n

    While more efficient, it introduces subtle incompatibilities with the typed\narrays specification. ArrayBuffer#slice() makes a copy of the slice while\nBuffer#slice() creates a view.\n\n

    \n", "classes": [ { "textRaw": "Class: Buffer", "type": "class", "name": "Buffer", "desc": "

    The Buffer class is a global type for dealing with binary data directly.\nIt can be constructed in a variety of ways.\n\n

    \n", "classMethods": [ { "textRaw": "Class Method: Buffer.isEncoding(encoding)", "type": "classMethod", "name": "isEncoding", "signatures": [ { "params": [ { "textRaw": "`encoding` {String} The encoding string to test ", "name": "encoding", "type": "String", "desc": "The encoding string to test" } ] }, { "params": [ { "name": "encoding" } ] } ], "desc": "

    Returns true if the encoding is a valid encoding argument, or false\notherwise.\n\n

    \n" }, { "textRaw": "Class Method: Buffer.isBuffer(obj)", "type": "classMethod", "name": "isBuffer", "signatures": [ { "return": { "textRaw": "Return: Boolean ", "name": "return", "desc": "Boolean" }, "params": [ { "textRaw": "`obj` Object ", "name": "obj", "desc": "Object" } ] }, { "params": [ { "name": "obj" } ] } ], "desc": "

    Tests if obj is a Buffer.\n\n

    \n" }, { "textRaw": "Class Method: Buffer.byteLength(string, [encoding])", "type": "classMethod", "name": "byteLength", "signatures": [ { "return": { "textRaw": "Return: Number ", "name": "return", "desc": "Number" }, "params": [ { "textRaw": "`string` String ", "name": "string", "desc": "String" }, { "textRaw": "`encoding` String, Optional, Default: 'utf8' ", "name": "encoding", "desc": "String, Optional, Default: 'utf8'", "optional": true } ] }, { "params": [ { "name": "string" }, { "name": "encoding", "optional": true } ] } ], "desc": "

    Gives the actual byte length of a string. encoding defaults to 'utf8'.\nThis is not the same as String.prototype.length since that returns the\nnumber of characters in a string.\n\n

    \n

    Example:\n\n

    \n
    str = '\\u00bd + \\u00bc = \\u00be';\n\nconsole.log(str + ": " + str.length + " characters, " +\n  Buffer.byteLength(str, 'utf8') + " bytes");\n\n// ½ + ¼ = ¾: 9 characters, 12 bytes
    \n" }, { "textRaw": "Class Method: Buffer.concat(list, [totalLength])", "type": "classMethod", "name": "concat", "signatures": [ { "params": [ { "textRaw": "`list` {Array} List of Buffer objects to concat ", "name": "list", "type": "Array", "desc": "List of Buffer objects to concat" }, { "textRaw": "`totalLength` {Number} Total length of the buffers when concatenated ", "name": "totalLength", "type": "Number", "desc": "Total length of the buffers when concatenated", "optional": true } ] }, { "params": [ { "name": "list" }, { "name": "totalLength", "optional": true } ] } ], "desc": "

    Returns a buffer which is the result of concatenating all the buffers in\nthe list together.\n\n

    \n

    If the list has no items, or if the totalLength is 0, then it returns a\nzero-length buffer.\n\n

    \n

    If the list has exactly one item, then the first item of the list is\nreturned.\n\n

    \n

    If the list has more than one item, then a new Buffer is created.\n\n

    \n

    If totalLength is not provided, it is read from the buffers in the list.\nHowever, this adds an additional loop to the function, so it is faster\nto provide the length explicitly.\n\n

    \n" } ], "methods": [ { "textRaw": "buf.write(string, [offset], [length], [encoding])", "type": "method", "name": "write", "signatures": [ { "params": [ { "textRaw": "`string` String - data to be written to buffer ", "name": "string", "desc": "String - data to be written to buffer" }, { "textRaw": "`offset` Number, Optional, Default: 0 ", "name": "offset", "desc": "Number, Optional, Default: 0", "optional": true }, { "textRaw": "`length` Number, Optional, Default: `buffer.length - offset` ", "name": "length", "desc": "Number, Optional, Default: `buffer.length - offset`", "optional": true }, { "textRaw": "`encoding` String, Optional, Default: 'utf8' ", "name": "encoding", "desc": "String, Optional, Default: 'utf8'", "optional": true } ] }, { "params": [ { "name": "string" }, { "name": "offset", "optional": true }, { "name": "length", "optional": true }, { "name": "encoding", "optional": true } ] } ], "desc": "

    Writes string to the buffer at offset using the given encoding.\noffset defaults to 0, encoding defaults to 'utf8'. length is\nthe number of bytes to write. Returns number of octets written. If buffer did\nnot contain enough space to fit the entire string, it will write a partial\namount of the string. length defaults to buffer.length - offset.\nThe method will not write partial characters.\n\n

    \n
    buf = new Buffer(256);\nlen = buf.write('\\u00bd + \\u00bc = \\u00be', 0);\nconsole.log(len + " bytes: " + buf.toString('utf8', 0, len));
    \n

    The number of characters written (which may be different than the number of\nbytes written) is set in Buffer._charsWritten and will be overwritten the\nnext time buf.write() is called.\n\n\n

    \n" }, { "textRaw": "buf.toString([encoding], [start], [end])", "type": "method", "name": "toString", "signatures": [ { "params": [ { "textRaw": "`encoding` String, Optional, Default: 'utf8' ", "name": "encoding", "desc": "String, Optional, Default: 'utf8'", "optional": true }, { "textRaw": "`start` Number, Optional, Default: 0 ", "name": "start", "desc": "Number, Optional, Default: 0", "optional": true }, { "textRaw": "`end` Number, Optional, Default: `buffer.length` ", "name": "end", "desc": "Number, Optional, Default: `buffer.length`", "optional": true } ] }, { "params": [ { "name": "encoding", "optional": true }, { "name": "start", "optional": true }, { "name": "end", "optional": true } ] } ], "desc": "

    Decodes and returns a string from buffer data encoded with encoding\n(defaults to 'utf8') beginning at start (defaults to 0) and ending at\nend (defaults to buffer.length).\n\n

    \n

    See buffer.write() example, above.\n\n\n

    \n" }, { "textRaw": "buf.toJSON()", "type": "method", "name": "toJSON", "desc": "

    Returns a JSON-representation of the Buffer instance, which is identical to the\noutput for JSON Arrays. JSON.stringify implicitly calls this function when\nstringifying a Buffer instance.\n\n

    \n

    Example:\n\n

    \n
    var buf = new Buffer('test');\nvar json = JSON.stringify(buf);\n\nconsole.log(json);\n// '[116,101,115,116]'\n\nvar copy = new Buffer(JSON.parse(json));\n\nconsole.log(copy);\n// <Buffer 74 65 73 74>
    \n", "signatures": [ { "params": [] } ] }, { "textRaw": "buf.copy(targetBuffer, [targetStart], [sourceStart], [sourceEnd])", "type": "method", "name": "copy", "signatures": [ { "params": [ { "textRaw": "`targetBuffer` Buffer object - Buffer to copy into ", "name": "targetBuffer", "desc": "Buffer object - Buffer to copy into" }, { "textRaw": "`targetStart` Number, Optional, Default: 0 ", "name": "targetStart", "desc": "Number, Optional, Default: 0", "optional": true }, { "textRaw": "`sourceStart` Number, Optional, Default: 0 ", "name": "sourceStart", "desc": "Number, Optional, Default: 0", "optional": true }, { "textRaw": "`sourceEnd` Number, Optional, Default: `buffer.length` ", "name": "sourceEnd", "desc": "Number, Optional, Default: `buffer.length`", "optional": true } ] }, { "params": [ { "name": "targetBuffer" }, { "name": "targetStart", "optional": true }, { "name": "sourceStart", "optional": true }, { "name": "sourceEnd", "optional": true } ] } ], "desc": "

    Does copy between buffers. The source and target regions can be overlapped.\ntargetStart and sourceStart default to 0.\nsourceEnd defaults to buffer.length.\n\n

    \n

    All values passed that are undefined/NaN or are out of bounds are set equal\nto their respective defaults.\n\n

    \n

    Example: build two Buffers, then copy buf1 from byte 16 through byte 19\ninto buf2, starting at the 8th byte in buf2.\n\n

    \n
    buf1 = new Buffer(26);\nbuf2 = new Buffer(26);\n\nfor (var i = 0 ; i < 26 ; i++) {\n  buf1[i] = i + 97; // 97 is ASCII a\n  buf2[i] = 33; // ASCII !\n}\n\nbuf1.copy(buf2, 8, 16, 20);\nconsole.log(buf2.toString('ascii', 0, 25));\n\n// !!!!!!!!qrst!!!!!!!!!!!!!
    \n" }, { "textRaw": "buf.slice([start], [end])", "type": "method", "name": "slice", "signatures": [ { "params": [ { "textRaw": "`start` Number, Optional, Default: 0 ", "name": "start", "desc": "Number, Optional, Default: 0", "optional": true }, { "textRaw": "`end` Number, Optional, Default: `buffer.length` ", "name": "end", "desc": "Number, Optional, Default: `buffer.length`", "optional": true } ] }, { "params": [ { "name": "start", "optional": true }, { "name": "end", "optional": true } ] } ], "desc": "

    Returns a new buffer which references the same memory as the old, but offset\nand cropped by the start (defaults to 0) and end (defaults to\nbuffer.length) indexes. Negative indexes start from the end of the buffer.\n\n

    \n

    Modifying the new buffer slice will modify memory in the original buffer!\n\n

    \n

    Example: build a Buffer with the ASCII alphabet, take a slice, then modify one\nbyte from the original Buffer.\n\n

    \n
    var buf1 = new Buffer(26);\n\nfor (var i = 0 ; i < 26 ; i++) {\n  buf1[i] = i + 97; // 97 is ASCII a\n}\n\nvar buf2 = buf1.slice(0, 3);\nconsole.log(buf2.toString('ascii', 0, buf2.length));\nbuf1[0] = 33;\nconsole.log(buf2.toString('ascii', 0, buf2.length));\n\n// abc\n// !bc
    \n" }, { "textRaw": "buf.readUInt8(offset, [noAssert])", "type": "method", "name": "readUInt8", "signatures": [ { "return": { "textRaw": "Return: Number ", "name": "return", "desc": "Number" }, "params": [ { "textRaw": "`offset` Number ", "name": "offset", "desc": "Number" }, { "textRaw": "`noAssert` Boolean, Optional, Default: false ", "name": "noAssert", "desc": "Boolean, Optional, Default: false", "optional": true } ] }, { "params": [ { "name": "offset" }, { "name": "noAssert", "optional": true } ] } ], "desc": "

    Reads an unsigned 8 bit integer from the buffer at the specified offset.\n\n

    \n

    Set noAssert to true to skip validation of offset. This means that offset\nmay be beyond the end of the buffer. Defaults to false.\n\n

    \n

    Example:\n\n

    \n
    var buf = new Buffer(4);\n\nbuf[0] = 0x3;\nbuf[1] = 0x4;\nbuf[2] = 0x23;\nbuf[3] = 0x42;\n\nfor (ii = 0; ii < buf.length; ii++) {\n  console.log(buf.readUInt8(ii));\n}\n\n// 0x3\n// 0x4\n// 0x23\n// 0x42
    \n" }, { "textRaw": "buf.readUInt16LE(offset, [noAssert])", "type": "method", "name": "readUInt16LE", "signatures": [ { "return": { "textRaw": "Return: Number ", "name": "return", "desc": "Number" }, "params": [ { "textRaw": "`offset` Number ", "name": "offset", "desc": "Number" }, { "textRaw": "`noAssert` Boolean, Optional, Default: false ", "name": "noAssert", "desc": "Boolean, Optional, Default: false", "optional": true } ] }, { "params": [ { "name": "offset" }, { "name": "noAssert", "optional": true } ] }, { "params": [ { "name": "offset" }, { "name": "noAssert", "optional": true } ] } ], "desc": "

    Reads an unsigned 16 bit integer from the buffer at the specified offset with\nspecified endian format.\n\n

    \n

    Set noAssert to true to skip validation of offset. This means that offset\nmay be beyond the end of the buffer. Defaults to false.\n\n

    \n

    Example:\n\n

    \n
    var buf = new Buffer(4);\n\nbuf[0] = 0x3;\nbuf[1] = 0x4;\nbuf[2] = 0x23;\nbuf[3] = 0x42;\n\nconsole.log(buf.readUInt16BE(0));\nconsole.log(buf.readUInt16LE(0));\nconsole.log(buf.readUInt16BE(1));\nconsole.log(buf.readUInt16LE(1));\nconsole.log(buf.readUInt16BE(2));\nconsole.log(buf.readUInt16LE(2));\n\n// 0x0304\n// 0x0403\n// 0x0423\n// 0x2304\n// 0x2342\n// 0x4223
    \n" }, { "textRaw": "buf.readUInt16BE(offset, [noAssert])", "type": "method", "name": "readUInt16BE", "signatures": [ { "return": { "textRaw": "Return: Number ", "name": "return", "desc": "Number" }, "params": [ { "textRaw": "`offset` Number ", "name": "offset", "desc": "Number" }, { "textRaw": "`noAssert` Boolean, Optional, Default: false ", "name": "noAssert", "desc": "Boolean, Optional, Default: false", "optional": true } ] }, { "params": [ { "name": "offset" }, { "name": "noAssert", "optional": true } ] } ], "desc": "

    Reads an unsigned 16 bit integer from the buffer at the specified offset with\nspecified endian format.\n\n

    \n

    Set noAssert to true to skip validation of offset. This means that offset\nmay be beyond the end of the buffer. Defaults to false.\n\n

    \n

    Example:\n\n

    \n
    var buf = new Buffer(4);\n\nbuf[0] = 0x3;\nbuf[1] = 0x4;\nbuf[2] = 0x23;\nbuf[3] = 0x42;\n\nconsole.log(buf.readUInt16BE(0));\nconsole.log(buf.readUInt16LE(0));\nconsole.log(buf.readUInt16BE(1));\nconsole.log(buf.readUInt16LE(1));\nconsole.log(buf.readUInt16BE(2));\nconsole.log(buf.readUInt16LE(2));\n\n// 0x0304\n// 0x0403\n// 0x0423\n// 0x2304\n// 0x2342\n// 0x4223
    \n" }, { "textRaw": "buf.readUInt32LE(offset, [noAssert])", "type": "method", "name": "readUInt32LE", "signatures": [ { "return": { "textRaw": "Return: Number ", "name": "return", "desc": "Number" }, "params": [ { "textRaw": "`offset` Number ", "name": "offset", "desc": "Number" }, { "textRaw": "`noAssert` Boolean, Optional, Default: false ", "name": "noAssert", "desc": "Boolean, Optional, Default: false", "optional": true } ] }, { "params": [ { "name": "offset" }, { "name": "noAssert", "optional": true } ] }, { "params": [ { "name": "offset" }, { "name": "noAssert", "optional": true } ] } ], "desc": "

    Reads an unsigned 32 bit integer from the buffer at the specified offset with\nspecified endian format.\n\n

    \n

    Set noAssert to true to skip validation of offset. This means that offset\nmay be beyond the end of the buffer. Defaults to false.\n\n

    \n

    Example:\n\n

    \n
    var buf = new Buffer(4);\n\nbuf[0] = 0x3;\nbuf[1] = 0x4;\nbuf[2] = 0x23;\nbuf[3] = 0x42;\n\nconsole.log(buf.readUInt32BE(0));\nconsole.log(buf.readUInt32LE(0));\n\n// 0x03042342\n// 0x42230403
    \n" }, { "textRaw": "buf.readUInt32BE(offset, [noAssert])", "type": "method", "name": "readUInt32BE", "signatures": [ { "return": { "textRaw": "Return: Number ", "name": "return", "desc": "Number" }, "params": [ { "textRaw": "`offset` Number ", "name": "offset", "desc": "Number" }, { "textRaw": "`noAssert` Boolean, Optional, Default: false ", "name": "noAssert", "desc": "Boolean, Optional, Default: false", "optional": true } ] }, { "params": [ { "name": "offset" }, { "name": "noAssert", "optional": true } ] } ], "desc": "

    Reads an unsigned 32 bit integer from the buffer at the specified offset with\nspecified endian format.\n\n

    \n

    Set noAssert to true to skip validation of offset. This means that offset\nmay be beyond the end of the buffer. Defaults to false.\n\n

    \n

    Example:\n\n

    \n
    var buf = new Buffer(4);\n\nbuf[0] = 0x3;\nbuf[1] = 0x4;\nbuf[2] = 0x23;\nbuf[3] = 0x42;\n\nconsole.log(buf.readUInt32BE(0));\nconsole.log(buf.readUInt32LE(0));\n\n// 0x03042342\n// 0x42230403
    \n" }, { "textRaw": "buf.readInt8(offset, [noAssert])", "type": "method", "name": "readInt8", "signatures": [ { "return": { "textRaw": "Return: Number ", "name": "return", "desc": "Number" }, "params": [ { "textRaw": "`offset` Number ", "name": "offset", "desc": "Number" }, { "textRaw": "`noAssert` Boolean, Optional, Default: false ", "name": "noAssert", "desc": "Boolean, Optional, Default: false", "optional": true } ] }, { "params": [ { "name": "offset" }, { "name": "noAssert", "optional": true } ] } ], "desc": "

    Reads a signed 8 bit integer from the buffer at the specified offset.\n\n

    \n

    Set noAssert to true to skip validation of offset. This means that offset\nmay be beyond the end of the buffer. Defaults to false.\n\n

    \n

    Works as buffer.readUInt8, except buffer contents are treated as two's\ncomplement signed values.\n\n

    \n" }, { "textRaw": "buf.readInt16LE(offset, [noAssert])", "type": "method", "name": "readInt16LE", "signatures": [ { "return": { "textRaw": "Return: Number ", "name": "return", "desc": "Number" }, "params": [ { "textRaw": "`offset` Number ", "name": "offset", "desc": "Number" }, { "textRaw": "`noAssert` Boolean, Optional, Default: false ", "name": "noAssert", "desc": "Boolean, Optional, Default: false", "optional": true } ] }, { "params": [ { "name": "offset" }, { "name": "noAssert", "optional": true } ] }, { "params": [ { "name": "offset" }, { "name": "noAssert", "optional": true } ] } ], "desc": "

    Reads a signed 16 bit integer from the buffer at the specified offset with\nspecified endian format.\n\n

    \n

    Set noAssert to true to skip validation of offset. This means that offset\nmay be beyond the end of the buffer. Defaults to false.\n\n

    \n

    Works as buffer.readUInt16*, except buffer contents are treated as two's\ncomplement signed values.\n\n

    \n" }, { "textRaw": "buf.readInt16BE(offset, [noAssert])", "type": "method", "name": "readInt16BE", "signatures": [ { "return": { "textRaw": "Return: Number ", "name": "return", "desc": "Number" }, "params": [ { "textRaw": "`offset` Number ", "name": "offset", "desc": "Number" }, { "textRaw": "`noAssert` Boolean, Optional, Default: false ", "name": "noAssert", "desc": "Boolean, Optional, Default: false", "optional": true } ] }, { "params": [ { "name": "offset" }, { "name": "noAssert", "optional": true } ] } ], "desc": "

    Reads a signed 16 bit integer from the buffer at the specified offset with\nspecified endian format.\n\n

    \n

    Set noAssert to true to skip validation of offset. This means that offset\nmay be beyond the end of the buffer. Defaults to false.\n\n

    \n

    Works as buffer.readUInt16*, except buffer contents are treated as two's\ncomplement signed values.\n\n

    \n" }, { "textRaw": "buf.readInt32LE(offset, [noAssert])", "type": "method", "name": "readInt32LE", "signatures": [ { "return": { "textRaw": "Return: Number ", "name": "return", "desc": "Number" }, "params": [ { "textRaw": "`offset` Number ", "name": "offset", "desc": "Number" }, { "textRaw": "`noAssert` Boolean, Optional, Default: false ", "name": "noAssert", "desc": "Boolean, Optional, Default: false", "optional": true } ] }, { "params": [ { "name": "offset" }, { "name": "noAssert", "optional": true } ] }, { "params": [ { "name": "offset" }, { "name": "noAssert", "optional": true } ] } ], "desc": "

    Reads a signed 32 bit integer from the buffer at the specified offset with\nspecified endian format.\n\n

    \n

    Set noAssert to true to skip validation of offset. This means that offset\nmay be beyond the end of the buffer. Defaults to false.\n\n

    \n

    Works as buffer.readUInt32*, except buffer contents are treated as two's\ncomplement signed values.\n\n

    \n" }, { "textRaw": "buf.readInt32BE(offset, [noAssert])", "type": "method", "name": "readInt32BE", "signatures": [ { "return": { "textRaw": "Return: Number ", "name": "return", "desc": "Number" }, "params": [ { "textRaw": "`offset` Number ", "name": "offset", "desc": "Number" }, { "textRaw": "`noAssert` Boolean, Optional, Default: false ", "name": "noAssert", "desc": "Boolean, Optional, Default: false", "optional": true } ] }, { "params": [ { "name": "offset" }, { "name": "noAssert", "optional": true } ] } ], "desc": "

    Reads a signed 32 bit integer from the buffer at the specified offset with\nspecified endian format.\n\n

    \n

    Set noAssert to true to skip validation of offset. This means that offset\nmay be beyond the end of the buffer. Defaults to false.\n\n

    \n

    Works as buffer.readUInt32*, except buffer contents are treated as two's\ncomplement signed values.\n\n

    \n" }, { "textRaw": "buf.readFloatLE(offset, [noAssert])", "type": "method", "name": "readFloatLE", "signatures": [ { "return": { "textRaw": "Return: Number ", "name": "return", "desc": "Number" }, "params": [ { "textRaw": "`offset` Number ", "name": "offset", "desc": "Number" }, { "textRaw": "`noAssert` Boolean, Optional, Default: false ", "name": "noAssert", "desc": "Boolean, Optional, Default: false", "optional": true } ] }, { "params": [ { "name": "offset" }, { "name": "noAssert", "optional": true } ] }, { "params": [ { "name": "offset" }, { "name": "noAssert", "optional": true } ] } ], "desc": "

    Reads a 32 bit float from the buffer at the specified offset with specified\nendian format.\n\n

    \n

    Set noAssert to true to skip validation of offset. This means that offset\nmay be beyond the end of the buffer. Defaults to false.\n\n

    \n

    Example:\n\n

    \n
    var buf = new Buffer(4);\n\nbuf[0] = 0x00;\nbuf[1] = 0x00;\nbuf[2] = 0x80;\nbuf[3] = 0x3f;\n\nconsole.log(buf.readFloatLE(0));\n\n// 0x01
    \n" }, { "textRaw": "buf.readFloatBE(offset, [noAssert])", "type": "method", "name": "readFloatBE", "signatures": [ { "return": { "textRaw": "Return: Number ", "name": "return", "desc": "Number" }, "params": [ { "textRaw": "`offset` Number ", "name": "offset", "desc": "Number" }, { "textRaw": "`noAssert` Boolean, Optional, Default: false ", "name": "noAssert", "desc": "Boolean, Optional, Default: false", "optional": true } ] }, { "params": [ { "name": "offset" }, { "name": "noAssert", "optional": true } ] } ], "desc": "

    Reads a 32 bit float from the buffer at the specified offset with specified\nendian format.\n\n

    \n

    Set noAssert to true to skip validation of offset. This means that offset\nmay be beyond the end of the buffer. Defaults to false.\n\n

    \n

    Example:\n\n

    \n
    var buf = new Buffer(4);\n\nbuf[0] = 0x00;\nbuf[1] = 0x00;\nbuf[2] = 0x80;\nbuf[3] = 0x3f;\n\nconsole.log(buf.readFloatLE(0));\n\n// 0x01
    \n" }, { "textRaw": "buf.readDoubleLE(offset, [noAssert])", "type": "method", "name": "readDoubleLE", "signatures": [ { "return": { "textRaw": "Return: Number ", "name": "return", "desc": "Number" }, "params": [ { "textRaw": "`offset` Number ", "name": "offset", "desc": "Number" }, { "textRaw": "`noAssert` Boolean, Optional, Default: false ", "name": "noAssert", "desc": "Boolean, Optional, Default: false", "optional": true } ] }, { "params": [ { "name": "offset" }, { "name": "noAssert", "optional": true } ] }, { "params": [ { "name": "offset" }, { "name": "noAssert", "optional": true } ] } ], "desc": "

    Reads a 64 bit double from the buffer at the specified offset with specified\nendian format.\n\n

    \n

    Set noAssert to true to skip validation of offset. This means that offset\nmay be beyond the end of the buffer. Defaults to false.\n\n

    \n

    Example:\n\n

    \n
    var buf = new Buffer(8);\n\nbuf[0] = 0x55;\nbuf[1] = 0x55;\nbuf[2] = 0x55;\nbuf[3] = 0x55;\nbuf[4] = 0x55;\nbuf[5] = 0x55;\nbuf[6] = 0xd5;\nbuf[7] = 0x3f;\n\nconsole.log(buf.readDoubleLE(0));\n\n// 0.3333333333333333
    \n" }, { "textRaw": "buf.readDoubleBE(offset, [noAssert])", "type": "method", "name": "readDoubleBE", "signatures": [ { "return": { "textRaw": "Return: Number ", "name": "return", "desc": "Number" }, "params": [ { "textRaw": "`offset` Number ", "name": "offset", "desc": "Number" }, { "textRaw": "`noAssert` Boolean, Optional, Default: false ", "name": "noAssert", "desc": "Boolean, Optional, Default: false", "optional": true } ] }, { "params": [ { "name": "offset" }, { "name": "noAssert", "optional": true } ] } ], "desc": "

    Reads a 64 bit double from the buffer at the specified offset with specified\nendian format.\n\n

    \n

    Set noAssert to true to skip validation of offset. This means that offset\nmay be beyond the end of the buffer. Defaults to false.\n\n

    \n

    Example:\n\n

    \n
    var buf = new Buffer(8);\n\nbuf[0] = 0x55;\nbuf[1] = 0x55;\nbuf[2] = 0x55;\nbuf[3] = 0x55;\nbuf[4] = 0x55;\nbuf[5] = 0x55;\nbuf[6] = 0xd5;\nbuf[7] = 0x3f;\n\nconsole.log(buf.readDoubleLE(0));\n\n// 0.3333333333333333
    \n" }, { "textRaw": "buf.writeUInt8(value, offset, [noAssert])", "type": "method", "name": "writeUInt8", "signatures": [ { "params": [ { "textRaw": "`value` Number ", "name": "value", "desc": "Number" }, { "textRaw": "`offset` Number ", "name": "offset", "desc": "Number" }, { "textRaw": "`noAssert` Boolean, Optional, Default: false ", "name": "noAssert", "desc": "Boolean, Optional, Default: false", "optional": true } ] }, { "params": [ { "name": "value" }, { "name": "offset" }, { "name": "noAssert", "optional": true } ] } ], "desc": "

    Writes value to the buffer at the specified offset. Note, value must be a\nvalid unsigned 8 bit integer.\n\n

    \n

    Set noAssert to true to skip validation of value and offset. This means\nthat value may be too large for the specific function and offset may be\nbeyond the end of the buffer leading to the values being silently dropped. This\nshould not be used unless you are certain of correctness. Defaults to false.\n\n

    \n

    Example:\n\n

    \n
    var buf = new Buffer(4);\nbuf.writeUInt8(0x3, 0);\nbuf.writeUInt8(0x4, 1);\nbuf.writeUInt8(0x23, 2);\nbuf.writeUInt8(0x42, 3);\n\nconsole.log(buf);\n\n// <Buffer 03 04 23 42>
    \n" }, { "textRaw": "buf.writeUInt16LE(value, offset, [noAssert])", "type": "method", "name": "writeUInt16LE", "signatures": [ { "params": [ { "textRaw": "`value` Number ", "name": "value", "desc": "Number" }, { "textRaw": "`offset` Number ", "name": "offset", "desc": "Number" }, { "textRaw": "`noAssert` Boolean, Optional, Default: false ", "name": "noAssert", "desc": "Boolean, Optional, Default: false", "optional": true } ] }, { "params": [ { "name": "value" }, { "name": "offset" }, { "name": "noAssert", "optional": true } ] }, { "params": [ { "name": "value" }, { "name": "offset" }, { "name": "noAssert", "optional": true } ] } ], "desc": "

    Writes value to the buffer at the specified offset with specified endian\nformat. Note, value must be a valid unsigned 16 bit integer.\n\n

    \n

    Set noAssert to true to skip validation of value and offset. This means\nthat value may be too large for the specific function and offset may be\nbeyond the end of the buffer leading to the values being silently dropped. This\nshould not be used unless you are certain of correctness. Defaults to false.\n\n

    \n

    Example:\n\n

    \n
    var buf = new Buffer(4);\nbuf.writeUInt16BE(0xdead, 0);\nbuf.writeUInt16BE(0xbeef, 2);\n\nconsole.log(buf);\n\nbuf.writeUInt16LE(0xdead, 0);\nbuf.writeUInt16LE(0xbeef, 2);\n\nconsole.log(buf);\n\n// <Buffer de ad be ef>\n// <Buffer ad de ef be>
    \n" }, { "textRaw": "buf.writeUInt16BE(value, offset, [noAssert])", "type": "method", "name": "writeUInt16BE", "signatures": [ { "params": [ { "textRaw": "`value` Number ", "name": "value", "desc": "Number" }, { "textRaw": "`offset` Number ", "name": "offset", "desc": "Number" }, { "textRaw": "`noAssert` Boolean, Optional, Default: false ", "name": "noAssert", "desc": "Boolean, Optional, Default: false", "optional": true } ] }, { "params": [ { "name": "value" }, { "name": "offset" }, { "name": "noAssert", "optional": true } ] } ], "desc": "

    Writes value to the buffer at the specified offset with specified endian\nformat. Note, value must be a valid unsigned 16 bit integer.\n\n

    \n

    Set noAssert to true to skip validation of value and offset. This means\nthat value may be too large for the specific function and offset may be\nbeyond the end of the buffer leading to the values being silently dropped. This\nshould not be used unless you are certain of correctness. Defaults to false.\n\n

    \n

    Example:\n\n

    \n
    var buf = new Buffer(4);\nbuf.writeUInt16BE(0xdead, 0);\nbuf.writeUInt16BE(0xbeef, 2);\n\nconsole.log(buf);\n\nbuf.writeUInt16LE(0xdead, 0);\nbuf.writeUInt16LE(0xbeef, 2);\n\nconsole.log(buf);\n\n// <Buffer de ad be ef>\n// <Buffer ad de ef be>
    \n" }, { "textRaw": "buf.writeUInt32LE(value, offset, [noAssert])", "type": "method", "name": "writeUInt32LE", "signatures": [ { "params": [ { "textRaw": "`value` Number ", "name": "value", "desc": "Number" }, { "textRaw": "`offset` Number ", "name": "offset", "desc": "Number" }, { "textRaw": "`noAssert` Boolean, Optional, Default: false ", "name": "noAssert", "desc": "Boolean, Optional, Default: false", "optional": true } ] }, { "params": [ { "name": "value" }, { "name": "offset" }, { "name": "noAssert", "optional": true } ] }, { "params": [ { "name": "value" }, { "name": "offset" }, { "name": "noAssert", "optional": true } ] } ], "desc": "

    Writes value to the buffer at the specified offset with specified endian\nformat. Note, value must be a valid unsigned 32 bit integer.\n\n

    \n

    Set noAssert to true to skip validation of value and offset. This means\nthat value may be too large for the specific function and offset may be\nbeyond the end of the buffer leading to the values being silently dropped. This\nshould not be used unless you are certain of correctness. Defaults to false.\n\n

    \n

    Example:\n\n

    \n
    var buf = new Buffer(4);\nbuf.writeUInt32BE(0xfeedface, 0);\n\nconsole.log(buf);\n\nbuf.writeUInt32LE(0xfeedface, 0);\n\nconsole.log(buf);\n\n// <Buffer fe ed fa ce>\n// <Buffer ce fa ed fe>
    \n" }, { "textRaw": "buf.writeUInt32BE(value, offset, [noAssert])", "type": "method", "name": "writeUInt32BE", "signatures": [ { "params": [ { "textRaw": "`value` Number ", "name": "value", "desc": "Number" }, { "textRaw": "`offset` Number ", "name": "offset", "desc": "Number" }, { "textRaw": "`noAssert` Boolean, Optional, Default: false ", "name": "noAssert", "desc": "Boolean, Optional, Default: false", "optional": true } ] }, { "params": [ { "name": "value" }, { "name": "offset" }, { "name": "noAssert", "optional": true } ] } ], "desc": "

    Writes value to the buffer at the specified offset with specified endian\nformat. Note, value must be a valid unsigned 32 bit integer.\n\n

    \n

    Set noAssert to true to skip validation of value and offset. This means\nthat value may be too large for the specific function and offset may be\nbeyond the end of the buffer leading to the values being silently dropped. This\nshould not be used unless you are certain of correctness. Defaults to false.\n\n

    \n

    Example:\n\n

    \n
    var buf = new Buffer(4);\nbuf.writeUInt32BE(0xfeedface, 0);\n\nconsole.log(buf);\n\nbuf.writeUInt32LE(0xfeedface, 0);\n\nconsole.log(buf);\n\n// <Buffer fe ed fa ce>\n// <Buffer ce fa ed fe>
    \n" }, { "textRaw": "buf.writeInt8(value, offset, [noAssert])", "type": "method", "name": "writeInt8", "signatures": [ { "params": [ { "textRaw": "`value` Number ", "name": "value", "desc": "Number" }, { "textRaw": "`offset` Number ", "name": "offset", "desc": "Number" }, { "textRaw": "`noAssert` Boolean, Optional, Default: false ", "name": "noAssert", "desc": "Boolean, Optional, Default: false", "optional": true } ] }, { "params": [ { "name": "value" }, { "name": "offset" }, { "name": "noAssert", "optional": true } ] } ], "desc": "

    Writes value to the buffer at the specified offset. Note, value must be a\nvalid signed 8 bit integer.\n\n

    \n

    Set noAssert to true to skip validation of value and offset. This means\nthat value may be too large for the specific function and offset may be\nbeyond the end of the buffer leading to the values being silently dropped. This\nshould not be used unless you are certain of correctness. Defaults to false.\n\n

    \n

    Works as buffer.writeUInt8, except value is written out as a two's complement\nsigned integer into buffer.\n\n

    \n" }, { "textRaw": "buf.writeInt16LE(value, offset, [noAssert])", "type": "method", "name": "writeInt16LE", "signatures": [ { "params": [ { "textRaw": "`value` Number ", "name": "value", "desc": "Number" }, { "textRaw": "`offset` Number ", "name": "offset", "desc": "Number" }, { "textRaw": "`noAssert` Boolean, Optional, Default: false ", "name": "noAssert", "desc": "Boolean, Optional, Default: false", "optional": true } ] }, { "params": [ { "name": "value" }, { "name": "offset" }, { "name": "noAssert", "optional": true } ] }, { "params": [ { "name": "value" }, { "name": "offset" }, { "name": "noAssert", "optional": true } ] } ], "desc": "

    Writes value to the buffer at the specified offset with specified endian\nformat. Note, value must be a valid signed 16 bit integer.\n\n

    \n

    Set noAssert to true to skip validation of value and offset. This means\nthat value may be too large for the specific function and offset may be\nbeyond the end of the buffer leading to the values being silently dropped. This\nshould not be used unless you are certain of correctness. Defaults to false.\n\n

    \n

    Works as buffer.writeUInt16*, except value is written out as a two's\ncomplement signed integer into buffer.\n\n

    \n" }, { "textRaw": "buf.writeInt16BE(value, offset, [noAssert])", "type": "method", "name": "writeInt16BE", "signatures": [ { "params": [ { "textRaw": "`value` Number ", "name": "value", "desc": "Number" }, { "textRaw": "`offset` Number ", "name": "offset", "desc": "Number" }, { "textRaw": "`noAssert` Boolean, Optional, Default: false ", "name": "noAssert", "desc": "Boolean, Optional, Default: false", "optional": true } ] }, { "params": [ { "name": "value" }, { "name": "offset" }, { "name": "noAssert", "optional": true } ] } ], "desc": "

    Writes value to the buffer at the specified offset with specified endian\nformat. Note, value must be a valid signed 16 bit integer.\n\n

    \n

    Set noAssert to true to skip validation of value and offset. This means\nthat value may be too large for the specific function and offset may be\nbeyond the end of the buffer leading to the values being silently dropped. This\nshould not be used unless you are certain of correctness. Defaults to false.\n\n

    \n

    Works as buffer.writeUInt16*, except value is written out as a two's\ncomplement signed integer into buffer.\n\n

    \n" }, { "textRaw": "buf.writeInt32LE(value, offset, [noAssert])", "type": "method", "name": "writeInt32LE", "signatures": [ { "params": [ { "textRaw": "`value` Number ", "name": "value", "desc": "Number" }, { "textRaw": "`offset` Number ", "name": "offset", "desc": "Number" }, { "textRaw": "`noAssert` Boolean, Optional, Default: false ", "name": "noAssert", "desc": "Boolean, Optional, Default: false", "optional": true } ] }, { "params": [ { "name": "value" }, { "name": "offset" }, { "name": "noAssert", "optional": true } ] }, { "params": [ { "name": "value" }, { "name": "offset" }, { "name": "noAssert", "optional": true } ] } ], "desc": "

    Writes value to the buffer at the specified offset with specified endian\nformat. Note, value must be a valid signed 32 bit integer.\n\n

    \n

    Set noAssert to true to skip validation of value and offset. This means\nthat value may be too large for the specific function and offset may be\nbeyond the end of the buffer leading to the values being silently dropped. This\nshould not be used unless you are certain of correctness. Defaults to false.\n\n

    \n

    Works as buffer.writeUInt32*, except value is written out as a two's\ncomplement signed integer into buffer.\n\n

    \n" }, { "textRaw": "buf.writeInt32BE(value, offset, [noAssert])", "type": "method", "name": "writeInt32BE", "signatures": [ { "params": [ { "textRaw": "`value` Number ", "name": "value", "desc": "Number" }, { "textRaw": "`offset` Number ", "name": "offset", "desc": "Number" }, { "textRaw": "`noAssert` Boolean, Optional, Default: false ", "name": "noAssert", "desc": "Boolean, Optional, Default: false", "optional": true } ] }, { "params": [ { "name": "value" }, { "name": "offset" }, { "name": "noAssert", "optional": true } ] } ], "desc": "

    Writes value to the buffer at the specified offset with specified endian\nformat. Note, value must be a valid signed 32 bit integer.\n\n

    \n

    Set noAssert to true to skip validation of value and offset. This means\nthat value may be too large for the specific function and offset may be\nbeyond the end of the buffer leading to the values being silently dropped. This\nshould not be used unless you are certain of correctness. Defaults to false.\n\n

    \n

    Works as buffer.writeUInt32*, except value is written out as a two's\ncomplement signed integer into buffer.\n\n

    \n" }, { "textRaw": "buf.writeFloatLE(value, offset, [noAssert])", "type": "method", "name": "writeFloatLE", "signatures": [ { "params": [ { "textRaw": "`value` Number ", "name": "value", "desc": "Number" }, { "textRaw": "`offset` Number ", "name": "offset", "desc": "Number" }, { "textRaw": "`noAssert` Boolean, Optional, Default: false ", "name": "noAssert", "desc": "Boolean, Optional, Default: false", "optional": true } ] }, { "params": [ { "name": "value" }, { "name": "offset" }, { "name": "noAssert", "optional": true } ] }, { "params": [ { "name": "value" }, { "name": "offset" }, { "name": "noAssert", "optional": true } ] } ], "desc": "

    Writes value to the buffer at the specified offset with specified endian\nformat. Note, behavior is unspecified if value is not a 32 bit float.\n\n

    \n

    Set noAssert to true to skip validation of value and offset. This means\nthat value may be too large for the specific function and offset may be\nbeyond the end of the buffer leading to the values being silently dropped. This\nshould not be used unless you are certain of correctness. Defaults to false.\n\n

    \n

    Example:\n\n

    \n
    var buf = new Buffer(4);\nbuf.writeFloatBE(0xcafebabe, 0);\n\nconsole.log(buf);\n\nbuf.writeFloatLE(0xcafebabe, 0);\n\nconsole.log(buf);\n\n// <Buffer 4f 4a fe bb>\n// <Buffer bb fe 4a 4f>
    \n" }, { "textRaw": "buf.writeFloatBE(value, offset, [noAssert])", "type": "method", "name": "writeFloatBE", "signatures": [ { "params": [ { "textRaw": "`value` Number ", "name": "value", "desc": "Number" }, { "textRaw": "`offset` Number ", "name": "offset", "desc": "Number" }, { "textRaw": "`noAssert` Boolean, Optional, Default: false ", "name": "noAssert", "desc": "Boolean, Optional, Default: false", "optional": true } ] }, { "params": [ { "name": "value" }, { "name": "offset" }, { "name": "noAssert", "optional": true } ] } ], "desc": "

    Writes value to the buffer at the specified offset with specified endian\nformat. Note, behavior is unspecified if value is not a 32 bit float.\n\n

    \n

    Set noAssert to true to skip validation of value and offset. This means\nthat value may be too large for the specific function and offset may be\nbeyond the end of the buffer leading to the values being silently dropped. This\nshould not be used unless you are certain of correctness. Defaults to false.\n\n

    \n

    Example:\n\n

    \n
    var buf = new Buffer(4);\nbuf.writeFloatBE(0xcafebabe, 0);\n\nconsole.log(buf);\n\nbuf.writeFloatLE(0xcafebabe, 0);\n\nconsole.log(buf);\n\n// <Buffer 4f 4a fe bb>\n// <Buffer bb fe 4a 4f>
    \n" }, { "textRaw": "buf.writeDoubleLE(value, offset, [noAssert])", "type": "method", "name": "writeDoubleLE", "signatures": [ { "params": [ { "textRaw": "`value` Number ", "name": "value", "desc": "Number" }, { "textRaw": "`offset` Number ", "name": "offset", "desc": "Number" }, { "textRaw": "`noAssert` Boolean, Optional, Default: false ", "name": "noAssert", "desc": "Boolean, Optional, Default: false", "optional": true } ] }, { "params": [ { "name": "value" }, { "name": "offset" }, { "name": "noAssert", "optional": true } ] }, { "params": [ { "name": "value" }, { "name": "offset" }, { "name": "noAssert", "optional": true } ] } ], "desc": "

    Writes value to the buffer at the specified offset with specified endian\nformat. Note, value must be a valid 64 bit double.\n\n

    \n

    Set noAssert to true to skip validation of value and offset. This means\nthat value may be too large for the specific function and offset may be\nbeyond the end of the buffer leading to the values being silently dropped. This\nshould not be used unless you are certain of correctness. Defaults to false.\n\n

    \n

    Example:\n\n

    \n
    var buf = new Buffer(8);\nbuf.writeDoubleBE(0xdeadbeefcafebabe, 0);\n\nconsole.log(buf);\n\nbuf.writeDoubleLE(0xdeadbeefcafebabe, 0);\n\nconsole.log(buf);\n\n// <Buffer 43 eb d5 b7 dd f9 5f d7>\n// <Buffer d7 5f f9 dd b7 d5 eb 43>
    \n" }, { "textRaw": "buf.writeDoubleBE(value, offset, [noAssert])", "type": "method", "name": "writeDoubleBE", "signatures": [ { "params": [ { "textRaw": "`value` Number ", "name": "value", "desc": "Number" }, { "textRaw": "`offset` Number ", "name": "offset", "desc": "Number" }, { "textRaw": "`noAssert` Boolean, Optional, Default: false ", "name": "noAssert", "desc": "Boolean, Optional, Default: false", "optional": true } ] }, { "params": [ { "name": "value" }, { "name": "offset" }, { "name": "noAssert", "optional": true } ] } ], "desc": "

    Writes value to the buffer at the specified offset with specified endian\nformat. Note, value must be a valid 64 bit double.\n\n

    \n

    Set noAssert to true to skip validation of value and offset. This means\nthat value may be too large for the specific function and offset may be\nbeyond the end of the buffer leading to the values being silently dropped. This\nshould not be used unless you are certain of correctness. Defaults to false.\n\n

    \n

    Example:\n\n

    \n
    var buf = new Buffer(8);\nbuf.writeDoubleBE(0xdeadbeefcafebabe, 0);\n\nconsole.log(buf);\n\nbuf.writeDoubleLE(0xdeadbeefcafebabe, 0);\n\nconsole.log(buf);\n\n// <Buffer 43 eb d5 b7 dd f9 5f d7>\n// <Buffer d7 5f f9 dd b7 d5 eb 43>
    \n" }, { "textRaw": "buf.fill(value, [offset], [end])", "type": "method", "name": "fill", "signatures": [ { "params": [ { "textRaw": "`value` ", "name": "value" }, { "textRaw": "`offset` Number, Optional ", "name": "offset", "optional": true, "desc": "Number" }, { "textRaw": "`end` Number, Optional ", "name": "end", "optional": true, "desc": "Number" } ] }, { "params": [ { "name": "value" }, { "name": "offset", "optional": true }, { "name": "end", "optional": true } ] } ], "desc": "

    Fills the buffer with the specified value. If the offset (defaults to 0)\nand end (defaults to buffer.length) are not given it will fill the entire\nbuffer.\n\n

    \n
    var b = new Buffer(50);\nb.fill("h");
    \n" } ], "properties": [ { "textRaw": "buf[index]", "name": "[index]", "desc": "

    Get and set the octet at index. The values refer to individual bytes,\nso the legal range is between 0x00 and 0xFF hex or 0 and 255.\n\n

    \n

    Example: copy an ASCII string into a buffer, one byte at a time:\n\n

    \n
    str = "node.js";\nbuf = new Buffer(str.length);\n\nfor (var i = 0; i < str.length ; i++) {\n  buf[i] = str.charCodeAt(i);\n}\n\nconsole.log(buf);\n\n// node.js
    \n" }, { "textRaw": "`length` Number ", "name": "length", "desc": "

    The size of the buffer in bytes. Note that this is not necessarily the size\nof the contents. length refers to the amount of memory allocated for the\nbuffer object. It does not change when the contents of the buffer are changed.\n\n

    \n
    buf = new Buffer(1234);\n\nconsole.log(buf.length);\nbuf.write("some string", 0, "ascii");\nconsole.log(buf.length);\n\n// 1234\n// 1234
    \n", "shortDesc": "Number" } ], "signatures": [ { "params": [ { "textRaw": "`size` Number ", "name": "size", "desc": "Number" } ], "desc": "

    Allocates a new buffer of size octets.\n\n

    \n" }, { "params": [ { "name": "size" } ], "desc": "

    Allocates a new buffer of size octets.\n\n

    \n" }, { "params": [ { "textRaw": "`array` Array ", "name": "array", "desc": "Array" } ], "desc": "

    Allocates a new buffer using an array of octets.\n\n

    \n" }, { "params": [ { "name": "array" } ], "desc": "

    Allocates a new buffer using an array of octets.\n\n

    \n" }, { "params": [ { "textRaw": "`str` String - string to encode. ", "name": "str", "desc": "String - string to encode." }, { "textRaw": "`encoding` String - encoding to use, Optional. ", "name": "encoding", "desc": "String - encoding to use, Optional.", "optional": true } ], "desc": "

    Allocates a new buffer containing the given str.\nencoding defaults to 'utf8'.\n\n

    \n" }, { "params": [ { "name": "str" }, { "name": "encoding", "optional": true } ], "desc": "

    Allocates a new buffer containing the given str.\nencoding defaults to 'utf8'.\n\n

    \n" } ] }, { "textRaw": "Class: SlowBuffer", "type": "class", "name": "SlowBuffer", "desc": "

    This class is primarily for internal use. JavaScript programs should\nuse Buffer instead of using SlowBuffer.\n\n

    \n

    In order to avoid the overhead of allocating many C++ Buffer objects for\nsmall blocks of memory in the lifetime of a server, Node allocates memory\nin 8Kb (8192 byte) chunks. If a buffer is smaller than this size, then it\nwill be backed by a parent SlowBuffer object. If it is larger than this,\nthen Node will allocate a SlowBuffer slab for it directly.\n

    \n" } ], "properties": [ { "textRaw": "`INSPECT_MAX_BYTES` Number, Default: 50 ", "name": "INSPECT_MAX_BYTES", "desc": "

    How many bytes will be returned when buffer.inspect() is called. This can\nbe overridden by user modules.\n\n

    \n

    Note that this is a property on the buffer module returned by\nrequire('buffer'), not on the Buffer global, or a buffer instance.\n\n

    \n", "shortDesc": "Number, Default: 50" } ], "type": "module", "displayName": "Buffer" } ] } node-v0.10.25~dfsg2/doc/api/querystring.html0000644000000000000000000001423312270264601017417 0ustar rootroot Query String Node.js v0.10.25 Manual & Documentation

    Node.js v0.10.25 Manual & Documentation


    Query String#

    Stability: 3 - Stable

    This module provides utilities for dealing with query strings. It provides the following methods:

    querystring.stringify(obj, [sep], [eq])#

    Serialize an object to a query string. Optionally override the default separator ('&') and assignment ('=') characters.

    Example:

    querystring.stringify({ foo: 'bar', baz: ['qux', 'quux'], corge: '' })
    // returns
    'foo=bar&baz=qux&baz=quux&corge='
    
    querystring.stringify({foo: 'bar', baz: 'qux'}, ';', ':')
    // returns
    'foo:bar;baz:qux'

    querystring.parse(str, [sep], [eq], [options])#

    Deserialize a query string to an object. Optionally override the default separator ('&') and assignment ('=') characters.

    Options object may contain maxKeys property (equal to 1000 by default), it'll be used to limit processed keys. Set it to 0 to remove key count limitation.

    Example:

    querystring.parse('foo=bar&baz=qux&baz=quux&corge')
    // returns
    { foo: 'bar', baz: ['qux', 'quux'], corge: '' }

    querystring.escape#

    The escape function used by querystring.stringify, provided so that it could be overridden if necessary.

    querystring.unescape#

    The unescape function used by querystring.parse, provided so that it could be overridden if necessary.

    node-v0.10.25~dfsg2/doc/api/index.json0000644000000000000000000001363112270264601016140 0ustar rootroot{ "source": "doc/api/index.markdown", "desc": [ { "type": "list_start", "ordered": false }, { "type": "list_item_start" }, { "type": "text", "text": "[About these Docs](documentation.html)" }, { "type": "list_item_end" }, { "type": "list_item_start" }, { "type": "text", "text": "[Synopsis](synopsis.html)" }, { "type": "list_item_end" }, { "type": "list_item_start" }, { "type": "text", "text": "[Assertion Testing](assert.html)" }, { "type": "list_item_end" }, { "type": "list_item_start" }, { "type": "text", "text": "[Buffer](buffer.html)" }, { "type": "list_item_end" }, { "type": "list_item_start" }, { "type": "text", "text": "[C/C++ Addons](addons.html)" }, { "type": "list_item_end" }, { "type": "list_item_start" }, { "type": "text", "text": "[Child Processes](child_process.html)" }, { "type": "list_item_end" }, { "type": "list_item_start" }, { "type": "text", "text": "[Cluster](cluster.html)" }, { "type": "list_item_end" }, { "type": "list_item_start" }, { "type": "text", "text": "[Console](console.html)" }, { "type": "list_item_end" }, { "type": "list_item_start" }, { "type": "text", "text": "[Crypto](crypto.html)" }, { "type": "list_item_end" }, { "type": "list_item_start" }, { "type": "text", "text": "[Debugger](debugger.html)" }, { "type": "list_item_end" }, { "type": "list_item_start" }, { "type": "text", "text": "[DNS](dns.html)" }, { "type": "list_item_end" }, { "type": "list_item_start" }, { "type": "text", "text": "[Domain](domain.html)" }, { "type": "list_item_end" }, { "type": "list_item_start" }, { "type": "text", "text": "[Events](events.html)" }, { "type": "list_item_end" }, { "type": "list_item_start" }, { "type": "text", "text": "[File System](fs.html)" }, { "type": "list_item_end" }, { "type": "list_item_start" }, { "type": "text", "text": "[Globals](globals.html)" }, { "type": "list_item_end" }, { "type": "list_item_start" }, { "type": "text", "text": "[HTTP](http.html)" }, { "type": "list_item_end" }, { "type": "list_item_start" }, { "type": "text", "text": "[HTTPS](https.html)" }, { "type": "list_item_end" }, { "type": "list_item_start" }, { "type": "text", "text": "[Modules](modules.html)" }, { "type": "list_item_end" }, { "type": "list_item_start" }, { "type": "text", "text": "[Net](net.html)" }, { "type": "list_item_end" }, { "type": "list_item_start" }, { "type": "text", "text": "[OS](os.html)" }, { "type": "list_item_end" }, { "type": "list_item_start" }, { "type": "text", "text": "[Path](path.html)" }, { "type": "list_item_end" }, { "type": "list_item_start" }, { "type": "text", "text": "[Process](process.html)" }, { "type": "list_item_end" }, { "type": "list_item_start" }, { "type": "text", "text": "[Punycode](punycode.html)" }, { "type": "list_item_end" }, { "type": "list_item_start" }, { "type": "text", "text": "[Query Strings](querystring.html)" }, { "type": "list_item_end" }, { "type": "list_item_start" }, { "type": "text", "text": "[Readline](readline.html)" }, { "type": "list_item_end" }, { "type": "list_item_start" }, { "type": "text", "text": "[REPL](repl.html)" }, { "type": "list_item_end" }, { "type": "list_item_start" }, { "type": "text", "text": "[Stream](stream.html)" }, { "type": "list_item_end" }, { "type": "list_item_start" }, { "type": "text", "text": "[String Decoder](string_decoder.html)" }, { "type": "list_item_end" }, { "type": "list_item_start" }, { "type": "text", "text": "[Timers](timers.html)" }, { "type": "list_item_end" }, { "type": "list_item_start" }, { "type": "text", "text": "[TLS/SSL](tls.html)" }, { "type": "list_item_end" }, { "type": "list_item_start" }, { "type": "text", "text": "[TTY](tty.html)" }, { "type": "list_item_end" }, { "type": "list_item_start" }, { "type": "text", "text": "[UDP/Datagram](dgram.html)" }, { "type": "list_item_end" }, { "type": "list_item_start" }, { "type": "text", "text": "[URL](url.html)" }, { "type": "list_item_end" }, { "type": "list_item_start" }, { "type": "text", "text": "[Utilities](util.html)" }, { "type": "list_item_end" }, { "type": "list_item_start" }, { "type": "text", "text": "[VM](vm.html)" }, { "type": "list_item_end" }, { "type": "list_item_start" }, { "type": "text", "text": "[ZLIB](zlib.html)" }, { "type": "space" }, { "type": "list_item_end" }, { "type": "list_end" } ] } node-v0.10.25~dfsg2/doc/api/assert.html0000644000000000000000000002135012270264601016322 0ustar rootroot Assert Node.js v0.10.25 Manual & Documentation

    Node.js v0.10.25 Manual & Documentation


    Assert#

    Stability: 5 - Locked

    This module is used for writing unit tests for your applications, you can access it with require('assert').

    assert.fail(actual, expected, message, operator)#

    Throws an exception that displays the values for actual and expected separated by the provided operator.

    assert(value, message), assert.ok(value, [message])#

    Tests if value is truthy, it is equivalent to assert.equal(true, !!value, message);

    assert.equal(actual, expected, [message])#

    Tests shallow, coercive equality with the equal comparison operator ( == ).

    assert.notEqual(actual, expected, [message])#

    Tests shallow, coercive non-equality with the not equal comparison operator ( != ).

    assert.deepEqual(actual, expected, [message])#

    Tests for deep equality.

    assert.notDeepEqual(actual, expected, [message])#

    Tests for any deep inequality.

    assert.strictEqual(actual, expected, [message])#

    Tests strict equality, as determined by the strict equality operator ( === )

    assert.notStrictEqual(actual, expected, [message])#

    Tests strict non-equality, as determined by the strict not equal operator ( !== )

    assert.throws(block, [error], [message])#

    Expects block to throw an error. error can be constructor, regexp or validation function.

    Validate instanceof using constructor:

    assert.throws(
      function() {
        throw new Error("Wrong value");
      },
      Error
    );

    Validate error message using RegExp:

    assert.throws(
      function() {
        throw new Error("Wrong value");
      },
      /value/
    );

    Custom error validation:

    assert.throws(
      function() {
        throw new Error("Wrong value");
      },
      function(err) {
        if ( (err instanceof Error) && /value/.test(err) ) {
          return true;
        }
      },
      "unexpected error"
    );

    assert.doesNotThrow(block, [message])#

    Expects block not to throw an error, see assert.throws for details.

    assert.ifError(value)#

    Tests if value is not a false value, throws if it is a true value. Useful when testing the first argument, error in callbacks.

    node-v0.10.25~dfsg2/doc/api/console.html0000644000000000000000000001673112270264601016472 0ustar rootroot console Node.js v0.10.25 Manual & Documentation

    Node.js v0.10.25 Manual & Documentation


    console#

    Stability: 4 - API Frozen
    • Object

    For printing to stdout and stderr. Similar to the console object functions provided by most web browsers, here the output is sent to stdout or stderr.

    The console functions are synchronous when the destination is a terminal or a file (to avoid lost messages in case of premature exit) and asynchronous when it's a pipe (to avoid blocking for long periods of time).

    That is, in the following example, stdout is non-blocking while stderr is blocking:

    $ node script.js 2> error.log | tee info.log

    In daily use, the blocking/non-blocking dichotomy is not something you should worry about unless you log huge amounts of data.

    console.log([data], [...])#

    Prints to stdout with newline. This function can take multiple arguments in a printf()-like way. Example:

    console.log('count: %d', count);

    If formatting elements are not found in the first string then util.inspect is used on each argument. See util.format() for more information.

    console.info([data], [...])#

    Same as console.log.

    console.error([data], [...])#

    Same as console.log but prints to stderr.

    console.warn([data], [...])#

    Same as console.error.

    console.dir(obj)#

    Uses util.inspect on obj and prints resulting string to stdout.

    console.time(label)#

    Mark a time.

    console.timeEnd(label)#

    Finish timer, record output. Example:

    console.time('100-elements');
    for (var i = 0; i < 100; i++) {
      ;
    }
    console.timeEnd('100-elements');

    console.trace(label)#

    Print a stack trace to stderr of the current position.

    console.assert(expression, [message])#

    Same as assert.ok() where if the expression evaluates as false throw an AssertionError with message.

    node-v0.10.25~dfsg2/doc/api/tty.markdown0000644000000000000000000000414312270121457016521 0ustar rootroot# TTY Stability: 2 - Unstable The `tty` module houses the `tty.ReadStream` and `tty.WriteStream` classes. In most cases, you will not need to use this module directly. When node detects that it is being run inside a TTY context, then `process.stdin` will be a `tty.ReadStream` instance and `process.stdout` will be a `tty.WriteStream` instance. The preferred way to check if node is being run in a TTY context is to check `process.stdout.isTTY`: $ node -p -e "Boolean(process.stdout.isTTY)" true $ node -p -e "Boolean(process.stdout.isTTY)" | cat false ## tty.isatty(fd) Returns `true` or `false` depending on if the `fd` is associated with a terminal. ## tty.setRawMode(mode) Deprecated. Use `tty.ReadStream#setRawMode()` (i.e. `process.stdin.setRawMode()`) instead. ## Class: ReadStream A `net.Socket` subclass that represents the readable portion of a tty. In normal circumstances, `process.stdin` will be the only `tty.ReadStream` instance in any node program (only when `isatty(0)` is true). ### rs.isRaw A `Boolean` that is initialized to `false`. It represents the current "raw" state of the `tty.ReadStream` instance. ### rs.setRawMode(mode) `mode` should be `true` or `false`. This sets the properties of the `tty.ReadStream` to act either as a raw device or default. `isRaw` will be set to the resulting mode. ## Class: WriteStream A `net.Socket` subclass that represents the writable portion of a tty. In normal circumstances, `process.stdout` will be the only `tty.WriteStream` instance ever created (and only when `isatty(1)` is true). ### ws.columns A `Number` that gives the number of columns the TTY currently has. This property gets updated on "resize" events. ### ws.rows A `Number` that gives the number of rows the TTY currently has. This property gets updated on "resize" events. ### Event: 'resize' `function () {}` Emitted by `refreshSize()` when either of the `columns` or `rows` properties has changed. process.stdout.on('resize', function() { console.log('screen size has changed!'); console.log(process.stdout.columns + 'x' + process.stdout.rows); }); node-v0.10.25~dfsg2/doc/api/punycode.html0000644000000000000000000001750212270264601016653 0ustar rootroot punycode Node.js v0.10.25 Manual & Documentation

    Node.js v0.10.25 Manual & Documentation


    punycode#

    Stability: 2 - Unstable

    Punycode.js is bundled with Node.js v0.6.2+. Use require('punycode') to access it. (To use it with other Node.js versions, use npm to install the punycode module first.)

    punycode.decode(string)#

    Converts a Punycode string of ASCII code points to a string of Unicode code points.

    // decode domain name parts
    punycode.decode('maana-pta'); // 'mañana'
    punycode.decode('--dqo34k'); // '☃-⌘'

    punycode.encode(string)#

    Converts a string of Unicode code points to a Punycode string of ASCII code points.

    // encode domain name parts
    punycode.encode('mañana'); // 'maana-pta'
    punycode.encode('☃-⌘'); // '--dqo34k'

    punycode.toUnicode(domain)#

    Converts a Punycode string representing a domain name to Unicode. Only the Punycoded parts of the domain name will be converted, i.e. it doesn't matter if you call it on a string that has already been converted to Unicode.

    // decode domain names
    punycode.toUnicode('xn--maana-pta.com'); // 'mañana.com'
    punycode.toUnicode('xn----dqo34k.com'); // '☃-⌘.com'

    punycode.toASCII(domain)#

    Converts a Unicode string representing a domain name to Punycode. Only the non-ASCII parts of the domain name will be converted, i.e. it doesn't matter if you call it with a domain that's already in ASCII.

    // encode domain names
    punycode.toASCII('mañana.com'); // 'xn--maana-pta.com'
    punycode.toASCII('☃-⌘.com'); // 'xn----dqo34k.com'

    punycode.ucs2#

    punycode.ucs2.decode(string)#

    Creates an array containing the decimal code points of each Unicode character in the string. While JavaScript uses UCS-2 internally, this function will convert a pair of surrogate halves (each of which UCS-2 exposes as separate characters) into a single code point, matching UTF-16.

    punycode.ucs2.decode('abc'); // [97, 98, 99]
    // surrogate pair for U+1D306 tetragram for centre:
    punycode.ucs2.decode('\uD834\uDF06'); // [0x1D306]

    punycode.ucs2.encode(codePoints)#

    Creates a string based on an array of decimal code points.

    punycode.ucs2.encode([97, 98, 99]); // 'abc'
    punycode.ucs2.encode([0x1D306]); // '\uD834\uDF06'

    punycode.version#

    A string representing the current Punycode.js version number.

    node-v0.10.25~dfsg2/doc/api/cluster.html0000644000000000000000000007434212270264601016513 0ustar rootroot Cluster Node.js v0.10.25 Manual & Documentation

    Node.js v0.10.25 Manual & Documentation


    Cluster#

    Stability: 1 - Experimental

    A single instance of Node runs in a single thread. To take advantage of multi-core systems the user will sometimes want to launch a cluster of Node processes to handle the load.

    The cluster module allows you to easily create child processes that all share server ports.

    var cluster = require('cluster');
    var http = require('http');
    var numCPUs = require('os').cpus().length;
    
    if (cluster.isMaster) {
      // Fork workers.
      for (var i = 0; i < numCPUs; i++) {
        cluster.fork();
      }
    
      cluster.on('exit', function(worker, code, signal) {
        console.log('worker ' + worker.process.pid + ' died');
      });
    } else {
      // Workers can share any TCP connection
      // In this case its a HTTP server
      http.createServer(function(req, res) {
        res.writeHead(200);
        res.end("hello world\n");
      }).listen(8000);
    }

    Running node will now share port 8000 between the workers:

    % NODE_DEBUG=cluster node server.js
    23521,Master Worker 23524 online
    23521,Master Worker 23526 online
    23521,Master Worker 23523 online
    23521,Master Worker 23528 online

    This feature was introduced recently, and may change in future versions. Please try it out and provide feedback.

    Also note that, on Windows, it is not yet possible to set up a named pipe server in a worker.

    How It Works#

    The worker processes are spawned using the child_process.fork method, so that they can communicate with the parent via IPC and pass server handles back and forth.

    When you call server.listen(...) in a worker, it serializes the arguments and passes the request to the master process. If the master process already has a listening server matching the worker's requirements, then it passes the handle to the worker. If it does not already have a listening server matching that requirement, then it will create one, and pass the handle to the worker.

    This causes potentially surprising behavior in three edge cases:

    1. server.listen({fd: 7}) Because the message is passed to the master, file descriptor 7 in the parent will be listened on, and the handle passed to the worker, rather than listening to the worker's idea of what the number 7 file descriptor references.
    2. server.listen(handle) Listening on handles explicitly will cause the worker to use the supplied handle, rather than talk to the master process. If the worker already has the handle, then it's presumed that you know what you are doing.
    3. server.listen(0) Normally, this will cause servers to listen on a random port. However, in a cluster, each worker will receive the same "random" port each time they do listen(0). In essence, the port is random the first time, but predictable thereafter. If you want to listen on a unique port, generate a port number based on the cluster worker ID.

    When multiple processes are all accept()ing on the same underlying resource, the operating system load-balances across them very efficiently. There is no routing logic in Node.js, or in your program, and no shared state between the workers. Therefore, it is important to design your program such that it does not rely too heavily on in-memory data objects for things like sessions and login.

    Because workers are all separate processes, they can be killed or re-spawned depending on your program's needs, without affecting other workers. As long as there are some workers still alive, the server will continue to accept connections. Node does not automatically manage the number of workers for you, however. It is your responsibility to manage the worker pool for your application's needs.

    cluster.settings#

    • Object
      • execArgv Array list of string arguments passed to the node executable. (Default=process.execArgv)
      • exec String file path to worker file. (Default=process.argv[1])
      • args Array string arguments passed to worker. (Default=process.argv.slice(2))
      • silent Boolean whether or not to send output to parent's stdio. (Default=false)

    After calling .setupMaster() (or .fork()) this settings object will contain the settings, including the default values.

    It is effectively frozen after being set, because .setupMaster() can only be called once.

    This object is not supposed to be changed or set manually, by you.

    cluster.isMaster#

    • Boolean

    True if the process is a master. This is determined by the process.env.NODE_UNIQUE_ID. If process.env.NODE_UNIQUE_ID is undefined, then isMaster is true.

    cluster.isWorker#

    • Boolean

    True if the process is not a master (it is the negation of cluster.isMaster).

    Event: 'fork'#

    • worker Worker object

    When a new worker is forked the cluster module will emit a 'fork' event. This can be used to log worker activity, and create your own timeout.

    var timeouts = [];
    function errorMsg() {
      console.error("Something must be wrong with the connection ...");
    }
    
    cluster.on('fork', function(worker) {
      timeouts[worker.id] = setTimeout(errorMsg, 2000);
    });
    cluster.on('listening', function(worker, address) {
      clearTimeout(timeouts[worker.id]);
    });
    cluster.on('exit', function(worker, code, signal) {
      clearTimeout(timeouts[worker.id]);
      errorMsg();
    });

    Event: 'online'#

    • worker Worker object

    After forking a new worker, the worker should respond with an online message. When the master receives an online message it will emit this event. The difference between 'fork' and 'online' is that fork is emitted when the master forks a worker, and 'online' is emitted when the worker is running.

    cluster.on('online', function(worker) {
      console.log("Yay, the worker responded after it was forked");
    });

    Event: 'listening'#

    • worker Worker object
    • address Object

    After calling listen() from a worker, when the 'listening' event is emitted on the server, a listening event will also be emitted on cluster in the master.

    The event handler is executed with two arguments, the worker contains the worker object and the address object contains the following connection properties: address, port and addressType. This is very useful if the worker is listening on more than one address.

    cluster.on('listening', function(worker, address) {
      console.log("A worker is now connected to " + address.address + ":" + address.port);
    });

    The addressType is one of:

    • 4 (TCPv4)
    • 6 (TCPv6)
    • -1 (unix domain socket)
    • "udp4" or "udp6" (UDP v4 or v6)

    Event: 'disconnect'#

    • worker Worker object

    Emitted after the worker IPC channel has disconnected. This can occur when a worker exits gracefully, is killed, or is disconnected manually (such as with worker.disconnect()).

    There may be a delay between the disconnect and exit events. These events can be used to detect if the process is stuck in a cleanup or if there are long-living connections.

    cluster.on('disconnect', function(worker) {
      console.log('The worker #' + worker.id + ' has disconnected');
    });

    Event: 'exit'#

    • worker Worker object
    • code Number the exit code, if it exited normally.
    • signal String the name of the signal (eg. 'SIGHUP') that caused the process to be killed.

    When any of the workers die the cluster module will emit the 'exit' event.

    This can be used to restart the worker by calling .fork() again.

    cluster.on('exit', function(worker, code, signal) {
      console.log('worker %d died (%s). restarting...',
        worker.process.pid, signal || code);
      cluster.fork();
    });

    See child_process event: 'exit'.

    Event: 'setup'#

    Emitted the first time that .setupMaster() is called.

    cluster.setupMaster([settings])#

    • settings Object
      • exec String file path to worker file. (Default=process.argv[1])
      • args Array string arguments passed to worker. (Default=process.argv.slice(2))
      • silent Boolean whether or not to send output to parent's stdio. (Default=false)

    setupMaster is used to change the default 'fork' behavior. Once called, the settings will be present in cluster.settings.

    Note that:

    • Only the first call to .setupMaster() has any effect, subsequent calls are ignored
    • That because of the above, the only attribute of a worker that may be customized per-worker is the env passed to .fork()
    • .fork() calls .setupMaster() internally to establish the defaults, so to have any effect, .setupMaster() must be called before any calls to .fork()

    Example:

    var cluster = require("cluster");
    cluster.setupMaster({
      exec : "worker.js",
      args : ["--use", "https"],
      silent : true
    });
    cluster.fork();

    This can only be called from the master process.

    cluster.fork([env])#

    • env Object Key/value pairs to add to worker process environment.
    • return Worker object

    Spawn a new worker process.

    This can only be called from the master process.

    cluster.disconnect([callback])#

    • callback Function called when all workers are disconnected and handles are closed

    Calls .disconnect() on each worker in cluster.workers.

    When they are disconnected all internal handles will be closed, allowing the master process to die gracefully if no other event is waiting.

    The method takes an optional callback argument which will be called when finished.

    This can only be called from the master process.

    cluster.worker#

    • Object

    A reference to the current worker object. Not available in the master process.

    var cluster = require('cluster');
    
    if (cluster.isMaster) {
      console.log('I am master');
      cluster.fork();
      cluster.fork();
    } else if (cluster.isWorker) {
      console.log('I am worker #' + cluster.worker.id);
    }

    cluster.workers#

    • Object

    A hash that stores the active worker objects, keyed by id field. Makes it easy to loop through all the workers. It is only available in the master process.

    A worker is removed from cluster.workers just before the 'disconnect' or 'exit' event is emitted.

    // Go through all workers
    function eachWorker(callback) {
      for (var id in cluster.workers) {
        callback(cluster.workers[id]);
      }
    }
    eachWorker(function(worker) {
      worker.send('big announcement to all workers');
    });

    Should you wish to reference a worker over a communication channel, using the worker's unique id is the easiest way to find the worker.

    socket.on('data', function(id) {
      var worker = cluster.workers[id];
    });

    Class: Worker#

    A Worker object contains all public information and method about a worker. In the master it can be obtained using cluster.workers. In a worker it can be obtained using cluster.worker.

    worker.id#

    • String

    Each new worker is given its own unique id, this id is stored in the id.

    While a worker is alive, this is the key that indexes it in cluster.workers

    worker.process#

    • ChildProcess object

    All workers are created using child_process.fork(), the returned object from this function is stored as .process. In a worker, the global process is stored.

    See: Child Process module

    Note that workers will call process.exit(0) if the 'disconnect' event occurs on process and .suicide is not true. This protects against accidental disconnection.

    worker.suicide#

    • Boolean

    Set by calling .kill() or .disconnect(), until then it is undefined.

    The boolean worker.suicide lets you distinguish between voluntary and accidental exit, the master may choose not to respawn a worker based on this value.

    cluster.on('exit', function(worker, code, signal) {
      if (worker.suicide === true) {
        console.log('Oh, it was just suicide\' – no need to worry').
      }
    });
    
    // kill worker
    worker.kill();

    worker.send(message, [sendHandle])#

    • message Object
    • sendHandle Handle object

    This function is equal to the send methods provided by child_process.fork(). In the master you should use this function to send a message to a specific worker.

    In a worker you can also use process.send(message), it is the same function.

    This example will echo back all messages from the master:

    if (cluster.isMaster) {
      var worker = cluster.fork();
      worker.send('hi there');
    
    } else if (cluster.isWorker) {
      process.on('message', function(msg) {
        process.send(msg);
      });
    }

    worker.kill([signal='SIGTERM'])#

    • signal String Name of the kill signal to send to the worker process.

    This function will kill the worker. In the master, it does this by disconnecting the worker.process, and once disconnected, killing with signal. In the worker, it does it by disconnecting the channel, and then exiting with code 0.

    Causes .suicide to be set.

    This method is aliased as worker.destroy() for backwards compatibility.

    Note that in a worker, process.kill() exists, but it is not this function, it is kill.

    worker.disconnect()#

    In a worker, this function will close all servers, wait for the 'close' event on those servers, and then disconnect the IPC channel.

    In the master, an internal message is sent to the worker causing it to call .disconnect() on itself.

    Causes .suicide to be set.

    Note that after a server is closed, it will no longer accept new connections, but connections may be accepted by any other listening worker. Existing connections will be allowed to close as usual. When no more connections exist, see server.close(), the IPC channel to the worker will close allowing it to die gracefully.

    The above applies only to server connections, client connections are not automatically closed by workers, and disconnect does not wait for them to close before exiting.

    Note that in a worker, process.disconnect exists, but it is not this function, it is disconnect.

    Because long living server connections may block workers from disconnecting, it may be useful to send a message, so application specific actions may be taken to close them. It also may be useful to implement a timeout, killing a worker if the disconnect event has not been emitted after some time.

    if (cluster.isMaster) {
      var worker = cluster.fork();
      var timeout;
    
      worker.on('listening', function(address) {
        worker.send('shutdown');
        worker.disconnect();
        timeout = setTimeout(function() {
          worker.kill();
        }, 2000);
      });
    
      worker.on('disconnect', function() {
        clearTimeout(timeout);
      });
    
    } else if (cluster.isWorker) {
      var net = require('net');
      var server = net.createServer(function(socket) {
        // connections never end
      });
    
      server.listen(8000);
    
      process.on('message', function(msg) {
        if(msg === 'shutdown') {
          // initiate graceful close of any connections to server
        }
      });
    }

    Event: 'message'#

    • message Object

    This event is the same as the one provided by child_process.fork().

    In a worker you can also use process.on('message').

    As an example, here is a cluster that keeps count of the number of requests in the master process using the message system:

    var cluster = require('cluster');
    var http = require('http');
    
    if (cluster.isMaster) {
    
      // Keep track of http requests
      var numReqs = 0;
      setInterval(function() {
        console.log("numReqs =", numReqs);
      }, 1000);
    
      // Count requestes
      function messageHandler(msg) {
        if (msg.cmd && msg.cmd == 'notifyRequest') {
          numReqs += 1;
        }
      }
    
      // Start workers and listen for messages containing notifyRequest
      var numCPUs = require('os').cpus().length;
      for (var i = 0; i < numCPUs; i++) {
        cluster.fork();
      }
    
      Object.keys(cluster.workers).forEach(function(id) {
        cluster.workers[id].on('message', messageHandler);
      });
    
    } else {
    
      // Worker processes have a http server.
      http.Server(function(req, res) {
        res.writeHead(200);
        res.end("hello world\n");
    
        // notify master about the request
        process.send({ cmd: 'notifyRequest' });
      }).listen(8000);
    }

    Event: 'online'#

    Similar to the cluster.on('online') event, but specific to this worker.

    cluster.fork().on('online', function() {
      // Worker is online
    });

    It is not emitted in the worker.

    Event: 'listening'#

    • address Object

    Similar to the cluster.on('listening') event, but specific to this worker.

    cluster.fork().on('listening', function(address) {
      // Worker is listening
    });

    It is not emitted in the worker.

    Event: 'disconnect'#

    Similar to the cluster.on('disconnect') event, but specfic to this worker.

    cluster.fork().on('disconnect', function() {
      // Worker has disconnected
    });

    Event: 'exit'#

    • code Number the exit code, if it exited normally.
    • signal String the name of the signal (eg. 'SIGHUP') that caused the process to be killed.

    Similar to the cluster.on('exit') event, but specific to this worker.

    var worker = cluster.fork();
    worker.on('exit', function(code, signal) {
      if( signal ) {
        console.log("worker was killed by signal: "+signal);
      } else if( code !== 0 ) {
        console.log("worker exited with error code: "+code);
      } else {
        console.log("worker success!");
      }
    });

    Event: 'error'#

    This event is the same as the one provided by child_process.fork().

    In a worker you can also use process.on('error').

    node-v0.10.25~dfsg2/doc/api/all.json0000644000000000000000000317076312270264601015616 0ustar rootroot{ "source": "doc/api/all.markdown", "miscs": [ { "textRaw": "About this Documentation", "name": "About this Documentation", "type": "misc", "desc": "

    The goal of this documentation is to comprehensively explain the Node.js\nAPI, both from a reference as well as a conceptual point of view. Each\nsection describes a built-in module or high-level concept.\n\n

    \n

    Where appropriate, property types, method arguments, and the arguments\nprovided to event handlers are detailed in a list underneath the topic\nheading.\n\n

    \n

    Every .html document has a corresponding .json document presenting\nthe same information in a structured manner. This feature is\nexperimental, and added for the benefit of IDEs and other utilities that\nwish to do programmatic things with the documentation.\n\n

    \n

    Every .html and .json file is generated based on the corresponding\n.markdown file in the doc/api/ folder in node's source tree. The\ndocumentation is generated using the tools/doc/generate.js program.\nThe HTML template is located at doc/template.html.\n\n

    \n", "miscs": [ { "textRaw": "Stability Index", "name": "Stability Index", "type": "misc", "desc": "

    Throughout the documentation, you will see indications of a section's\nstability. The Node.js API is still somewhat changing, and as it\nmatures, certain parts are more reliable than others. Some are so\nproven, and so relied upon, that they are unlikely to ever change at\nall. Others are brand new and experimental, or known to be hazardous\nand in the process of being redesigned.\n\n

    \n

    The stability indices are as follows:\n\n

    \n
    Stability: 0 - Deprecated\nThis feature is known to be problematic, and changes are\nplanned.  Do not rely on it.  Use of the feature may cause warnings.  Backwards\ncompatibility should not be expected.
    \n
    Stability: 1 - Experimental\nThis feature was introduced recently, and may change\nor be removed in future versions.  Please try it out and provide feedback.\nIf it addresses a use-case that is important to you, tell the node core team.
    \n
    Stability: 2 - Unstable\nThe API is in the process of settling, but has not yet had\nsufficient real-world testing to be considered stable. Backwards-compatibility\nwill be maintained if reasonable.
    \n
    Stability: 3 - Stable\nThe API has proven satisfactory, but cleanup in the underlying\ncode may cause minor changes.  Backwards-compatibility is guaranteed.
    \n
    Stability: 4 - API Frozen\nThis API has been tested extensively in production and is\nunlikely to ever have to change.
    \n
    Stability: 5 - Locked\nUnless serious bugs are found, this code will not ever\nchange.  Please do not suggest changes in this area; they will be refused.
    \n" }, { "textRaw": "JSON Output", "name": "json_output", "stability": 1, "stabilityText": "Experimental", "desc": "

    Every HTML file in the markdown has a corresponding JSON file with the\nsame data.\n\n

    \n

    This feature is new as of node v0.6.12. It is experimental.\n\n

    \n", "type": "misc", "displayName": "JSON Output" } ] }, { "textRaw": "Synopsis", "name": "Synopsis", "type": "misc", "desc": "

    An example of a web server written with Node which responds with 'Hello\nWorld':\n\n

    \n
    var http = require('http');\n\nhttp.createServer(function (request, response) {\n  response.writeHead(200, {'Content-Type': 'text/plain'});\n  response.end('Hello World\\n');\n}).listen(8124);\n\nconsole.log('Server running at http://127.0.0.1:8124/');
    \n

    To run the server, put the code into a file called example.js and execute\nit with the node program\n\n

    \n
    > node example.js\nServer running at http://127.0.0.1:8124/
    \n

    All of the examples in the documentation can be run similarly.\n\n

    \n" }, { "textRaw": "Global Objects", "name": "Global Objects", "type": "misc", "desc": "

    These objects are available in all modules. Some of these objects aren't\nactually in the global scope but in the module scope - this will be noted.\n\n

    \n", "globals": [ { "textRaw": "global", "name": "global", "type": "global", "desc": "

    In browsers, the top-level scope is the global scope. That means that in\nbrowsers if you're in the global scope var something will define a global\nvariable. In Node this is different. The top-level scope is not the global\nscope; var something inside a Node module will be local to that module.\n\n

    \n" }, { "textRaw": "process", "name": "process", "type": "global", "desc": "

    The process object. See the [process object][] section.\n\n

    \n" }, { "textRaw": "console", "name": "console", "type": "global", "desc": "

    Used to print to stdout and stderr. See the [console][] section.\n\n

    \n" }, { "textRaw": "Class: Buffer", "type": "global", "name": "Buffer", "desc": "

    Used to handle binary data. See the [buffer section][]\n\n

    \n" }, { "textRaw": "clearInterval(t)", "type": "global", "name": "clearInterval", "desc": "

    Stop a timer that was previously created with setInterval(). The callback\nwill not execute.\n\n

    \n

    The timer functions are global variables. See the [timers][] section.\n\n

    \n" }, { "textRaw": "console", "name": "console", "stability": 4, "stabilityText": "API Frozen", "type": "global", "desc": "

    For printing to stdout and stderr. Similar to the console object functions\nprovided by most web browsers, here the output is sent to stdout or stderr.\n\n

    \n

    The console functions are synchronous when the destination is a terminal or\na file (to avoid lost messages in case of premature exit) and asynchronous\nwhen it's a pipe (to avoid blocking for long periods of time).\n\n

    \n

    That is, in the following example, stdout is non-blocking while stderr\nis blocking:\n\n

    \n
    $ node script.js 2> error.log | tee info.log
    \n

    In daily use, the blocking/non-blocking dichotomy is not something you\nshould worry about unless you log huge amounts of data.\n\n\n

    \n", "methods": [ { "textRaw": "console.log([data], [...])", "type": "method", "name": "log", "desc": "

    Prints to stdout with newline. This function can take multiple arguments in a\nprintf()-like way. Example:\n\n

    \n
    console.log('count: %d', count);
    \n

    If formatting elements are not found in the first string then util.inspect\nis used on each argument. See [util.format()][] for more information.\n\n

    \n", "signatures": [ { "params": [ { "name": "data", "optional": true }, { "name": "...", "optional": true } ] } ] }, { "textRaw": "console.info([data], [...])", "type": "method", "name": "info", "desc": "

    Same as console.log.\n\n

    \n", "signatures": [ { "params": [ { "name": "data", "optional": true }, { "name": "...", "optional": true } ] } ] }, { "textRaw": "console.error([data], [...])", "type": "method", "name": "error", "desc": "

    Same as console.log but prints to stderr.\n\n

    \n", "signatures": [ { "params": [ { "name": "data", "optional": true }, { "name": "...", "optional": true } ] } ] }, { "textRaw": "console.warn([data], [...])", "type": "method", "name": "warn", "desc": "

    Same as console.error.\n\n

    \n", "signatures": [ { "params": [ { "name": "data", "optional": true }, { "name": "...", "optional": true } ] } ] }, { "textRaw": "console.dir(obj)", "type": "method", "name": "dir", "desc": "

    Uses util.inspect on obj and prints resulting string to stdout.\n\n

    \n", "signatures": [ { "params": [ { "name": "obj" } ] } ] }, { "textRaw": "console.time(label)", "type": "method", "name": "time", "desc": "

    Mark a time.\n\n

    \n", "signatures": [ { "params": [ { "name": "label" } ] } ] }, { "textRaw": "console.timeEnd(label)", "type": "method", "name": "timeEnd", "desc": "

    Finish timer, record output. Example:\n\n

    \n
    console.time('100-elements');\nfor (var i = 0; i < 100; i++) {\n  ;\n}\nconsole.timeEnd('100-elements');
    \n", "signatures": [ { "params": [ { "name": "label" } ] } ] }, { "textRaw": "console.trace(label)", "type": "method", "name": "trace", "desc": "

    Print a stack trace to stderr of the current position.\n\n

    \n", "signatures": [ { "params": [ { "name": "label" } ] } ] }, { "textRaw": "console.assert(expression, [message])", "type": "method", "name": "assert", "desc": "

    Same as [assert.ok()][] where if the expression evaluates as false throw an\nAssertionError with message.\n\n

    \n", "signatures": [ { "params": [ { "name": "expression" }, { "name": "message", "optional": true } ] } ] } ] }, { "textRaw": "process", "name": "process", "type": "global", "desc": "

    The process object is a global object and can be accessed from anywhere.\nIt is an instance of [EventEmitter][].\n\n\n

    \n", "events": [ { "textRaw": "Event: 'exit'", "type": "event", "name": "exit", "desc": "

    Emitted when the process is about to exit. There is no way to prevent the\nexiting of the event loop at this point, and once all exit listeners have\nfinished running the process will exit. Therefore you must only perform\nsynchronous operations in this handler. This is a good hook to perform\nchecks on the module's state (like for unit tests). The callback takes one\nargument, the code the process is exiting with.\n\n

    \n

    Example of listening for exit:\n\n

    \n
    process.on('exit', function(code) {\n  // do *NOT* do this\n  setTimeout(function() {\n    console.log('This will not run');\n  }, 0);\n  console.log('About to exit with code:', code);\n});
    \n", "params": [] }, { "textRaw": "Event: 'uncaughtException'", "type": "event", "name": "uncaughtException", "desc": "

    Emitted when an exception bubbles all the way back to the event loop. If a\nlistener is added for this exception, the default action (which is to print\na stack trace and exit) will not occur.\n\n

    \n

    Example of listening for uncaughtException:\n\n

    \n
    process.on('uncaughtException', function(err) {\n  console.log('Caught exception: ' + err);\n});\n\nsetTimeout(function() {\n  console.log('This will still run.');\n}, 500);\n\n// Intentionally cause an exception, but don't catch it.\nnonexistentFunc();\nconsole.log('This will not run.');
    \n

    Note that uncaughtException is a very crude mechanism for exception\nhandling and may be removed in the future.\n\n

    \n

    Don't use it, use domains instead. If you do use it, restart\nyour application after every unhandled exception!\n\n

    \n

    Do not use it as the node.js equivalent of On Error Resume Next. An\nunhandled exception means your application - and by extension node.js itself -\nis in an undefined state. Blindly resuming means anything could happen.\n\n

    \n

    Think of resuming as pulling the power cord when you are upgrading your system.\nNine out of ten times nothing happens - but the 10th time, your system is bust.\n\n

    \n

    You have been warned.\n\n

    \n", "params": [] }, { "textRaw": "Signal Events", "name": "SIGINT, SIGHUP, etc.", "type": "event", "desc": "

    Emitted when the processes receives a signal. See sigaction(2) for a list of\nstandard POSIX signal names such as SIGINT, SIGHUP, etc.\n\n

    \n

    Example of listening for SIGINT:\n\n

    \n
    // Start reading from stdin so we don't exit.\nprocess.stdin.resume();\n\nprocess.on('SIGINT', function() {\n  console.log('Got SIGINT.  Press Control-D to exit.');\n});
    \n

    An easy way to send the SIGINT signal is with Control-C in most terminal\nprograms.\n\n

    \n

    Note:\n\n

    \n
      \n
    • SIGUSR1 is reserved by node.js to start the debugger. It's possible to\ninstall a listener but that won't stop the debugger from starting.
    • \n
    • SIGTERM and SIGINT have default handlers on non-Windows platforms that resets\nthe terminal mode before exiting with code 128 + signal number. If one of\nthese signals has a listener installed, its default behaviour will be removed\n(node will no longer exit).
    • \n
    • SIGPIPE is ignored by default, it can have a listener installed.
    • \n
    • SIGHUP is generated on Windows when the console window is closed, and on other\nplatforms under various similar conditions, see signal(7). It can have a\nlistener installed, however node will be unconditionally terminated by Windows\nabout 10 seconds later. On non-Windows platforms, the default behaviour of\nSIGHUP is to terminate node, but once a listener has been installed its\ndefault behaviour will be removed.
    • \n
    • SIGTERM is not supported on Windows, it can be listened on.
    • \n
    • SIGINT from the terminal is supported on all platforms, and can usually be\ngenerated with CTRL+C (though this may be configurable). It is not generated\nwhen terminal raw mode is enabled.
    • \n
    • SIGBREAK is delivered on Windows when CTRL+BREAK is pressed, on non-Windows\nplatforms it can be listened on, but there is no way to send or generate it.
    • \n
    • SIGWINCH is delivered when the console has been resized. On Windows, this will\nonly happen on write to the console when the cursor is being moved, or when a\nreadable tty is used in raw mode.
    • \n
    • SIGKILL cannot have a listener installed, it will unconditionally terminate\nnode on all platforms.
    • \n
    • SIGSTOP cannot have a listener installed.
    • \n
    \n

    Note that Windows does not support sending Signals, but node offers some\nemulation with process.kill(), and child_process.kill():\n- Sending signal 0 can be used to search for the existence of a process\n- Sending SIGINT, SIGTERM, and SIGKILL cause the unconditional exit of the\n target process.\n\n

    \n", "params": [] } ], "properties": [ { "textRaw": "process.stdout", "name": "stdout", "desc": "

    A Writable Stream to stdout.\n\n

    \n

    Example: the definition of console.log\n\n

    \n
    console.log = function(d) {\n  process.stdout.write(d + '\\n');\n};
    \n

    process.stderr and process.stdout are unlike other streams in Node in\nthat writes to them are usually blocking. They are blocking in the case\nthat they refer to regular files or TTY file descriptors. In the case they\nrefer to pipes, they are non-blocking like other streams.\n\n

    \n

    To check if Node is being run in a TTY context, read the isTTY property\non process.stderr, process.stdout, or process.stdin:\n\n

    \n
    $ node -p "Boolean(process.stdin.isTTY)"\ntrue\n$ echo "foo" | node -p "Boolean(process.stdin.isTTY)"\nfalse\n\n$ node -p "Boolean(process.stdout.isTTY)"\ntrue\n$ node -p "Boolean(process.stdout.isTTY)" | cat\nfalse
    \n

    See the tty docs for more information.\n\n

    \n" }, { "textRaw": "process.stderr", "name": "stderr", "desc": "

    A writable stream to stderr.\n\n

    \n

    process.stderr and process.stdout are unlike other streams in Node in\nthat writes to them are usually blocking. They are blocking in the case\nthat they refer to regular files or TTY file descriptors. In the case they\nrefer to pipes, they are non-blocking like other streams.\n\n\n

    \n" }, { "textRaw": "process.stdin", "name": "stdin", "desc": "

    A Readable Stream for stdin. The stdin stream is paused by default, so one\nmust call process.stdin.resume() to read from it.\n\n

    \n

    Example of opening standard input and listening for both events:\n\n

    \n
    process.stdin.resume();\nprocess.stdin.setEncoding('utf8');\n\nprocess.stdin.on('data', function(chunk) {\n  process.stdout.write('data: ' + chunk);\n});\n\nprocess.stdin.on('end', function() {\n  process.stdout.write('end');\n});
    \n" }, { "textRaw": "process.argv", "name": "argv", "desc": "

    An array containing the command line arguments. The first element will be\n'node', the second element will be the name of the JavaScript file. The\nnext elements will be any additional command line arguments.\n\n

    \n
    // print process.argv\nprocess.argv.forEach(function(val, index, array) {\n  console.log(index + ': ' + val);\n});
    \n

    This will generate:\n\n

    \n
    $ node process-2.js one two=three four\n0: node\n1: /Users/mjr/work/node/process-2.js\n2: one\n3: two=three\n4: four
    \n" }, { "textRaw": "process.execPath", "name": "execPath", "desc": "

    This is the absolute pathname of the executable that started the process.\n\n

    \n

    Example:\n\n

    \n
    /usr/local/bin/node
    \n" }, { "textRaw": "process.execArgv", "name": "execArgv", "desc": "

    This is the set of node-specific command line options from the\nexecutable that started the process. These options do not show up in\nprocess.argv, and do not include the node executable, the name of\nthe script, or any options following the script name. These options\nare useful in order to spawn child processes with the same execution\nenvironment as the parent.\n\n

    \n

    Example:\n\n

    \n
    $ node --harmony script.js --version
    \n

    results in process.execArgv:\n\n

    \n
    ['--harmony']
    \n

    and process.argv:\n\n

    \n
    ['/usr/local/bin/node', 'script.js', '--version']
    \n" }, { "textRaw": "process.env", "name": "env", "desc": "

    An object containing the user environment. See environ(7).\n\n\n

    \n" }, { "textRaw": "process.version", "name": "version", "desc": "

    A compiled-in property that exposes NODE_VERSION.\n\n

    \n
    console.log('Version: ' + process.version);
    \n" }, { "textRaw": "process.versions", "name": "versions", "desc": "

    A property exposing version strings of node and its dependencies.\n\n

    \n
    console.log(process.versions);
    \n

    Will print something like:\n\n

    \n
    { http_parser: '1.0',\n  node: '0.10.4',\n  v8: '3.14.5.8',\n  ares: '1.9.0-DEV',\n  uv: '0.10.3',\n  zlib: '1.2.3',\n  modules: '11',\n  openssl: '1.0.1e' }
    \n" }, { "textRaw": "process.config", "name": "config", "desc": "

    An Object containing the JavaScript representation of the configure options\nthat were used to compile the current node executable. This is the same as\nthe "config.gypi" file that was produced when running the ./configure script.\n\n

    \n

    An example of the possible output looks like:\n\n

    \n
    { target_defaults:\n   { cflags: [],\n     default_configuration: 'Release',\n     defines: [],\n     include_dirs: [],\n     libraries: [] },\n  variables:\n   { host_arch: 'x64',\n     node_install_npm: 'true',\n     node_prefix: '',\n     node_shared_cares: 'false',\n     node_shared_http_parser: 'false',\n     node_shared_libuv: 'false',\n     node_shared_v8: 'false',\n     node_shared_zlib: 'false',\n     node_use_dtrace: 'false',\n     node_use_openssl: 'true',\n     node_shared_openssl: 'false',\n     strict_aliasing: 'true',\n     target_arch: 'x64',\n     v8_use_snapshot: 'true' } }
    \n" }, { "textRaw": "process.pid", "name": "pid", "desc": "

    The PID of the process.\n\n

    \n
    console.log('This process is pid ' + process.pid);
    \n" }, { "textRaw": "process.title", "name": "title", "desc": "

    Getter/setter to set what is displayed in 'ps'.\n\n

    \n

    When used as a setter, the maximum length is platform-specific and probably\nshort.\n\n

    \n

    On Linux and OS X, it's limited to the size of the binary name plus the\nlength of the command line arguments because it overwrites the argv memory.\n\n

    \n

    v0.8 allowed for longer process title strings by also overwriting the environ\nmemory but that was potentially insecure/confusing in some (rather obscure)\ncases.\n\n\n

    \n" }, { "textRaw": "process.arch", "name": "arch", "desc": "

    What processor architecture you're running on: 'arm', 'ia32', or 'x64'.\n\n

    \n
    console.log('This processor architecture is ' + process.arch);
    \n" }, { "textRaw": "process.platform", "name": "platform", "desc": "

    What platform you're running on:\n'darwin', 'freebsd', 'linux', 'sunos' or 'win32'\n\n

    \n
    console.log('This platform is ' + process.platform);
    \n" }, { "textRaw": "`maxTickDepth` {Number} Default = 1000 ", "name": "maxTickDepth", "desc": "

    Callbacks passed to process.nextTick will usually be called at the\nend of the current flow of execution, and are thus approximately as fast\nas calling a function synchronously. Left unchecked, this would starve\nthe event loop, preventing any I/O from occurring.\n\n

    \n

    Consider this code:\n\n

    \n
    process.nextTick(function foo() {\n  process.nextTick(foo);\n});
    \n

    In order to avoid the situation where Node is blocked by an infinite\nloop of recursive series of nextTick calls, it defers to allow some I/O\nto be done every so often.\n\n

    \n

    The process.maxTickDepth value is the maximum depth of\nnextTick-calling nextTick-callbacks that will be evaluated before\nallowing other forms of I/O to occur.\n\n

    \n", "shortDesc": "Default = 1000" } ], "methods": [ { "textRaw": "process.abort()", "type": "method", "name": "abort", "desc": "

    This causes node to emit an abort. This will cause node to exit and\ngenerate a core file.\n\n

    \n", "signatures": [ { "params": [] } ] }, { "textRaw": "process.chdir(directory)", "type": "method", "name": "chdir", "desc": "

    Changes the current working directory of the process or throws an exception if that fails.\n\n

    \n
    console.log('Starting directory: ' + process.cwd());\ntry {\n  process.chdir('/tmp');\n  console.log('New directory: ' + process.cwd());\n}\ncatch (err) {\n  console.log('chdir: ' + err);\n}
    \n", "signatures": [ { "params": [ { "name": "directory" } ] } ] }, { "textRaw": "process.cwd()", "type": "method", "name": "cwd", "desc": "

    Returns the current working directory of the process.\n\n

    \n
    console.log('Current directory: ' + process.cwd());
    \n", "signatures": [ { "params": [] } ] }, { "textRaw": "process.exit([code])", "type": "method", "name": "exit", "desc": "

    Ends the process with the specified code. If omitted, exit uses the\n'success' code 0.\n\n

    \n

    To exit with a 'failure' code:\n\n

    \n
    process.exit(1);
    \n

    The shell that executed node should see the exit code as 1.\n\n\n

    \n", "signatures": [ { "params": [ { "name": "code", "optional": true } ] } ] }, { "textRaw": "process.getgid()", "type": "method", "name": "getgid", "desc": "

    Note: this function is only available on POSIX platforms (i.e. not Windows)\n\n

    \n

    Gets the group identity of the process. (See getgid(2).)\nThis is the numerical group id, not the group name.\n\n

    \n
    if (process.getgid) {\n  console.log('Current gid: ' + process.getgid());\n}
    \n", "signatures": [ { "params": [] } ] }, { "textRaw": "process.setgid(id)", "type": "method", "name": "setgid", "desc": "

    Note: this function is only available on POSIX platforms (i.e. not Windows)\n\n

    \n

    Sets the group identity of the process. (See setgid(2).) This accepts either\na numerical ID or a groupname string. If a groupname is specified, this method\nblocks while resolving it to a numerical ID.\n\n

    \n
    if (process.getgid && process.setgid) {\n  console.log('Current gid: ' + process.getgid());\n  try {\n    process.setgid(501);\n    console.log('New gid: ' + process.getgid());\n  }\n  catch (err) {\n    console.log('Failed to set gid: ' + err);\n  }\n}
    \n", "signatures": [ { "params": [ { "name": "id" } ] } ] }, { "textRaw": "process.getuid()", "type": "method", "name": "getuid", "desc": "

    Note: this function is only available on POSIX platforms (i.e. not Windows)\n\n

    \n

    Gets the user identity of the process. (See getuid(2).)\nThis is the numerical userid, not the username.\n\n

    \n
    if (process.getuid) {\n  console.log('Current uid: ' + process.getuid());\n}
    \n", "signatures": [ { "params": [] } ] }, { "textRaw": "process.setuid(id)", "type": "method", "name": "setuid", "desc": "

    Note: this function is only available on POSIX platforms (i.e. not Windows)\n\n

    \n

    Sets the user identity of the process. (See setuid(2).) This accepts either\na numerical ID or a username string. If a username is specified, this method\nblocks while resolving it to a numerical ID.\n\n

    \n
    if (process.getuid && process.setuid) {\n  console.log('Current uid: ' + process.getuid());\n  try {\n    process.setuid(501);\n    console.log('New uid: ' + process.getuid());\n  }\n  catch (err) {\n    console.log('Failed to set uid: ' + err);\n  }\n}
    \n", "signatures": [ { "params": [ { "name": "id" } ] } ] }, { "textRaw": "process.getgroups()", "type": "method", "name": "getgroups", "desc": "

    Note: this function is only available on POSIX platforms (i.e. not Windows)\n\n

    \n

    Returns an array with the supplementary group IDs. POSIX leaves it unspecified\nif the effective group ID is included but node.js ensures it always is.\n\n\n

    \n", "signatures": [ { "params": [] } ] }, { "textRaw": "process.setgroups(groups)", "type": "method", "name": "setgroups", "desc": "

    Note: this function is only available on POSIX platforms (i.e. not Windows)\n\n

    \n

    Sets the supplementary group IDs. This is a privileged operation, meaning you\nneed to be root or have the CAP_SETGID capability.\n\n

    \n

    The list can contain group IDs, group names or both.\n\n\n

    \n", "signatures": [ { "params": [ { "name": "groups" } ] } ] }, { "textRaw": "process.initgroups(user, extra_group)", "type": "method", "name": "initgroups", "desc": "

    Note: this function is only available on POSIX platforms (i.e. not Windows)\n\n

    \n

    Reads /etc/group and initializes the group access list, using all groups of\nwhich the user is a member. This is a privileged operation, meaning you need\nto be root or have the CAP_SETGID capability.\n\n

    \n

    user is a user name or user ID. extra_group is a group name or group ID.\n\n

    \n

    Some care needs to be taken when dropping privileges. Example:\n\n

    \n
    console.log(process.getgroups());         // [ 0 ]\nprocess.initgroups('bnoordhuis', 1000);   // switch user\nconsole.log(process.getgroups());         // [ 27, 30, 46, 1000, 0 ]\nprocess.setgid(1000);                     // drop root gid\nconsole.log(process.getgroups());         // [ 27, 30, 46, 1000 ]
    \n", "signatures": [ { "params": [ { "name": "user" }, { "name": "extra_group" } ] } ] }, { "textRaw": "process.kill(pid, [signal])", "type": "method", "name": "kill", "desc": "

    Send a signal to a process. pid is the process id and signal is the\nstring describing the signal to send. Signal names are strings like\n'SIGINT' or 'SIGHUP'. If omitted, the signal will be 'SIGTERM'.\nSee Signal Events and kill(2) for more information.\n\n

    \n

    Will throw an error if target does not exist, and as a special case, a signal of\n0 can be used to test for the existence of a process.\n\n

    \n

    Note that just because the name of this function is process.kill, it is\nreally just a signal sender, like the kill system call. The signal sent\nmay do something other than kill the target process.\n\n

    \n

    Example of sending a signal to yourself:\n\n

    \n
    process.on('SIGHUP', function() {\n  console.log('Got SIGHUP signal.');\n});\n\nsetTimeout(function() {\n  console.log('Exiting.');\n  process.exit(0);\n}, 100);\n\nprocess.kill(process.pid, 'SIGHUP');
    \n

    Note: When SIGUSR1 is received by Node.js it starts the debugger, see\nSignal Events.\n\n

    \n", "signatures": [ { "params": [ { "name": "pid" }, { "name": "signal", "optional": true } ] } ] }, { "textRaw": "process.memoryUsage()", "type": "method", "name": "memoryUsage", "desc": "

    Returns an object describing the memory usage of the Node process\nmeasured in bytes.\n\n

    \n
    var util = require('util');\n\nconsole.log(util.inspect(process.memoryUsage()));
    \n

    This will generate:\n\n

    \n
    { rss: 4935680,\n  heapTotal: 1826816,\n  heapUsed: 650472 }
    \n

    heapTotal and heapUsed refer to V8's memory usage.\n\n\n

    \n", "signatures": [ { "params": [] } ] }, { "textRaw": "process.nextTick(callback)", "type": "method", "name": "nextTick", "desc": "

    On the next loop around the event loop call this callback.\nThis is not a simple alias to setTimeout(fn, 0), it's much more\nefficient. It typically runs before any other I/O events fire, but there\nare some exceptions. See process.maxTickDepth below.\n\n

    \n
    process.nextTick(function() {\n  console.log('nextTick callback');\n});
    \n

    This is important in developing APIs where you want to give the user the\nchance to assign event handlers after an object has been constructed,\nbut before any I/O has occurred.\n\n

    \n
    function MyThing(options) {\n  this.setupOptions(options);\n\n  process.nextTick(function() {\n    this.startDoingStuff();\n  }.bind(this));\n}\n\nvar thing = new MyThing();\nthing.getReadyForStuff();\n\n// thing.startDoingStuff() gets called now, not before.
    \n

    It is very important for APIs to be either 100% synchronous or 100%\nasynchronous. Consider this example:\n\n

    \n
    // WARNING!  DO NOT USE!  BAD UNSAFE HAZARD!\nfunction maybeSync(arg, cb) {\n  if (arg) {\n    cb();\n    return;\n  }\n\n  fs.stat('file', cb);\n}
    \n

    This API is hazardous. If you do this:\n\n

    \n
    maybeSync(true, function() {\n  foo();\n});\nbar();
    \n

    then it's not clear whether foo() or bar() will be called first.\n\n

    \n

    This approach is much better:\n\n

    \n
    function definitelyAsync(arg, cb) {\n  if (arg) {\n    process.nextTick(cb);\n    return;\n  }\n\n  fs.stat('file', cb);\n}
    \n", "signatures": [ { "params": [ { "name": "callback" } ] } ] }, { "textRaw": "process.umask([mask])", "type": "method", "name": "umask", "desc": "

    Sets or reads the process's file mode creation mask. Child processes inherit\nthe mask from the parent process. Returns the old mask if mask argument is\ngiven, otherwise returns the current mask.\n\n

    \n
    var oldmask, newmask = 0644;\n\noldmask = process.umask(newmask);\nconsole.log('Changed umask from: ' + oldmask.toString(8) +\n            ' to ' + newmask.toString(8));
    \n", "signatures": [ { "params": [ { "name": "mask", "optional": true } ] } ] }, { "textRaw": "process.uptime()", "type": "method", "name": "uptime", "desc": "

    Number of seconds Node has been running.\n\n\n

    \n", "signatures": [ { "params": [] } ] }, { "textRaw": "process.hrtime()", "type": "method", "name": "hrtime", "desc": "

    Returns the current high-resolution real time in a [seconds, nanoseconds]\ntuple Array. It is relative to an arbitrary time in the past. It is not\nrelated to the time of day and therefore not subject to clock drift. The\nprimary use is for measuring performance between intervals.\n\n

    \n

    You may pass in the result of a previous call to process.hrtime() to get\na diff reading, useful for benchmarks and measuring intervals:\n\n

    \n
    var time = process.hrtime();\n// [ 1800216, 25 ]\n\nsetTimeout(function() {\n  var diff = process.hrtime(time);\n  // [ 1, 552 ]\n\n  console.log('benchmark took %d nanoseconds', diff[0] * 1e9 + diff[1]);\n  // benchmark took 1000000527 nanoseconds\n}, 1000);
    \n", "signatures": [ { "params": [] } ] } ] } ], "vars": [ { "textRaw": "require()", "type": "var", "name": "require", "desc": "

    To require modules. See the [Modules][] section. require isn't actually a\nglobal but rather local to each module.\n\n

    \n", "methods": [ { "textRaw": "require.resolve()", "type": "method", "name": "resolve", "desc": "

    Use the internal require() machinery to look up the location of a module,\nbut rather than loading the module, just return the resolved filename.\n\n

    \n", "signatures": [ { "params": [] } ] } ], "properties": [ { "textRaw": "`cache` {Object} ", "name": "cache", "desc": "

    Modules are cached in this object when they are required. By deleting a key\nvalue from this object, the next require will reload the module.\n\n

    \n" }, { "textRaw": "`extensions` {Object} ", "name": "extensions", "stability": 0, "stabilityText": "Deprecated", "desc": "

    Instruct require on how to handle certain file extensions.\n\n

    \n

    Process files with the extension .sjs as .js:\n\n

    \n
    require.extensions['.sjs'] = require.extensions['.js'];
    \n

    Deprecated In the past, this list has been used to load\nnon-JavaScript modules into Node by compiling them on-demand.\nHowever, in practice, there are much better ways to do this, such as\nloading modules via some other Node program, or compiling them to\nJavaScript ahead of time.\n\n

    \n

    Since the Module system is locked, this feature will probably never go\naway. However, it may have subtle bugs and complexities that are best\nleft untouched.\n\n

    \n" } ] }, { "textRaw": "__filename", "name": "__filename", "type": "var", "desc": "

    The filename of the code being executed. This is the resolved absolute path\nof this code file. For a main program this is not necessarily the same\nfilename used in the command line. The value inside a module is the path\nto that module file.\n\n

    \n

    Example: running node example.js from /Users/mjr\n\n

    \n
    console.log(__filename);\n// /Users/mjr/example.js
    \n

    __filename isn't actually a global but rather local to each module.\n\n

    \n" }, { "textRaw": "__dirname", "name": "__dirname", "type": "var", "desc": "

    The name of the directory that the currently executing script resides in.\n\n

    \n

    Example: running node example.js from /Users/mjr\n\n

    \n
    console.log(__dirname);\n// /Users/mjr
    \n

    __dirname isn't actually a global but rather local to each module.\n\n\n

    \n" }, { "textRaw": "module", "name": "module", "type": "var", "desc": "

    A reference to the current module. In particular\nmodule.exports is used for defining what a module exports and makes\navailable through require().\n\n

    \n

    module isn't actually a global but rather local to each module.\n\n

    \n

    See the [module system documentation][] for more information.\n\n

    \n" }, { "textRaw": "exports", "name": "exports", "type": "var", "desc": "

    A reference to the module.exports that is shorter to type.\nSee [module system documentation][] for details on when to use exports and\nwhen to use module.exports.\n\n

    \n

    exports isn't actually a global but rather local to each module.\n\n

    \n

    See the [module system documentation][] for more information.\n\n

    \n

    See the [module section][] for more information.\n\n

    \n" } ], "methods": [ { "textRaw": "setTimeout(cb, ms)", "type": "method", "name": "setTimeout", "desc": "

    Run callback cb after at least ms milliseconds. The actual delay depends\non external factors like OS timer granularity and system load.\n\n

    \n

    The timeout must be in the range of 1-2,147,483,647 inclusive. If the value is\noutside that range, it's changed to 1 millisecond. Broadly speaking, a timer\ncannot span more than 24.8 days.\n\n

    \n

    Returns an opaque value that represents the timer.\n\n

    \n", "signatures": [ { "params": [ { "name": "cb" }, { "name": "ms" } ] } ] }, { "textRaw": "clearTimeout(t)", "type": "method", "name": "clearTimeout", "desc": "

    Stop a timer that was previously created with setTimeout(). The callback will\nnot execute.\n\n

    \n", "signatures": [ { "params": [ { "name": "t" } ] } ] }, { "textRaw": "setInterval(cb, ms)", "type": "method", "name": "setInterval", "desc": "

    Run callback cb repeatedly every ms milliseconds. Note that the actual\ninterval may vary, depending on external factors like OS timer granularity and\nsystem load. It's never less than ms but it may be longer.\n\n

    \n

    The interval must be in the range of 1-2,147,483,647 inclusive. If the value is\noutside that range, it's changed to 1 millisecond. Broadly speaking, a timer\ncannot span more than 24.8 days.\n\n

    \n

    Returns an opaque value that represents the timer.\n\n

    \n", "signatures": [ { "params": [ { "name": "cb" }, { "name": "ms" } ] } ] } ] }, { "textRaw": "Debugger", "name": "Debugger", "stability": 3, "stabilityText": "Stable", "type": "misc", "desc": "

    V8 comes with an extensive debugger which is accessible out-of-process via a\nsimple TCP protocol.\nNode has a built-in client for this debugger. To use this, start Node with the\ndebug argument; a prompt will appear:\n\n

    \n
    % node debug myscript.js\n< debugger listening on port 5858\nconnecting... ok\nbreak in /home/indutny/Code/git/indutny/myscript.js:1\n  1 x = 5;\n  2 setTimeout(function () {\n  3   debugger;\ndebug>
    \n

    Node's debugger client doesn't support the full range of commands, but\nsimple step and inspection is possible. By putting the statement debugger;\ninto the source code of your script, you will enable a breakpoint.\n\n

    \n

    For example, suppose myscript.js looked like this:\n\n

    \n
    // myscript.js\nx = 5;\nsetTimeout(function () {\n  debugger;\n  console.log("world");\n}, 1000);\nconsole.log("hello");
    \n

    Then once the debugger is run, it will break on line 4.\n\n

    \n
    % node debug myscript.js\n< debugger listening on port 5858\nconnecting... ok\nbreak in /home/indutny/Code/git/indutny/myscript.js:1\n  1 x = 5;\n  2 setTimeout(function () {\n  3   debugger;\ndebug> cont\n< hello\nbreak in /home/indutny/Code/git/indutny/myscript.js:3\n  1 x = 5;\n  2 setTimeout(function () {\n  3   debugger;\n  4   console.log("world");\n  5 }, 1000);\ndebug> next\nbreak in /home/indutny/Code/git/indutny/myscript.js:4\n  2 setTimeout(function () {\n  3   debugger;\n  4   console.log("world");\n  5 }, 1000);\n  6 console.log("hello");\ndebug> repl\nPress Ctrl + C to leave debug repl\n> x\n5\n> 2+2\n4\ndebug> next\n< world\nbreak in /home/indutny/Code/git/indutny/myscript.js:5\n  3   debugger;\n  4   console.log("world");\n  5 }, 1000);\n  6 console.log("hello");\n  7\ndebug> quit\n%
    \n

    The repl command allows you to evaluate code remotely. The next command\nsteps over to the next line. There are a few other commands available and more\nto come. Type help to see others.\n\n

    \n", "miscs": [ { "textRaw": "Watchers", "name": "watchers", "desc": "

    You can watch expression and variable values while debugging your code.\nOn every breakpoint each expression from the watchers list will be evaluated\nin the current context and displayed just before the breakpoint's source code\nlisting.\n\n

    \n

    To start watching an expression, type watch("my_expression"). watchers\nprints the active watchers. To remove a watcher, type\nunwatch("my_expression").\n\n

    \n", "type": "misc", "displayName": "Watchers" }, { "textRaw": "Commands reference", "name": "commands_reference", "modules": [ { "textRaw": "Stepping", "name": "Stepping", "desc": "

    It is also possible to set a breakpoint in a file (module) that\nisn't loaded yet:\n\n

    \n
    % ./node debug test/fixtures/break-in-module/main.js\n< debugger listening on port 5858\nconnecting to port 5858... ok\nbreak in test/fixtures/break-in-module/main.js:1\n  1 var mod = require('./mod.js');\n  2 mod.hello();\n  3 mod.hello();\ndebug> setBreakpoint('mod.js', 23)\nWarning: script 'mod.js' was not loaded yet.\n  1 var mod = require('./mod.js');\n  2 mod.hello();\n  3 mod.hello();\ndebug> c\nbreak in test/fixtures/break-in-module/mod.js:23\n 21\n 22 exports.hello = function() {\n 23   return 'hello from module';\n 24 };\n 25\ndebug>
    \n", "type": "module", "displayName": "Breakpoints" }, { "textRaw": "Breakpoints", "name": "breakpoints", "desc": "

    It is also possible to set a breakpoint in a file (module) that\nisn't loaded yet:\n\n

    \n
    % ./node debug test/fixtures/break-in-module/main.js\n< debugger listening on port 5858\nconnecting to port 5858... ok\nbreak in test/fixtures/break-in-module/main.js:1\n  1 var mod = require('./mod.js');\n  2 mod.hello();\n  3 mod.hello();\ndebug> setBreakpoint('mod.js', 23)\nWarning: script 'mod.js' was not loaded yet.\n  1 var mod = require('./mod.js');\n  2 mod.hello();\n  3 mod.hello();\ndebug> c\nbreak in test/fixtures/break-in-module/mod.js:23\n 21\n 22 exports.hello = function() {\n 23   return 'hello from module';\n 24 };\n 25\ndebug>
    \n", "type": "module", "displayName": "Breakpoints" }, { "textRaw": "Execution control", "name": "Execution control", "type": "module", "displayName": "Various" }, { "textRaw": "Various", "name": "various", "type": "module", "displayName": "Various" } ], "type": "misc", "displayName": "Commands reference" }, { "textRaw": "Advanced Usage", "name": "advanced_usage", "desc": "

    The V8 debugger can be enabled and accessed either by starting Node with\nthe --debug command-line flag or by signaling an existing Node process\nwith SIGUSR1.\n\n

    \n

    Once a process has been set in debug mode with this it can be connected to\nwith the node debugger. Either connect to the pid or the URI to the debugger.\nThe syntax is:\n\n

    \n
      \n
    • node debug -p <pid> - Connects to the process via the pid
    • \n
    • node debug <URI> - Connects to the process via the URI such as localhost:5858
    • \n
    \n", "type": "misc", "displayName": "Advanced Usage" } ] } ], "globals": [ { "textRaw": "global", "name": "global", "type": "global", "desc": "

    In browsers, the top-level scope is the global scope. That means that in\nbrowsers if you're in the global scope var something will define a global\nvariable. In Node this is different. The top-level scope is not the global\nscope; var something inside a Node module will be local to that module.\n\n

    \n" }, { "textRaw": "process", "name": "process", "type": "global", "desc": "

    The process object. See the [process object][] section.\n\n

    \n" }, { "textRaw": "console", "name": "console", "type": "global", "desc": "

    Used to print to stdout and stderr. See the [console][] section.\n\n

    \n" }, { "textRaw": "Class: Buffer", "type": "global", "name": "Buffer", "desc": "

    Used to handle binary data. See the [buffer section][]\n\n

    \n" }, { "textRaw": "clearInterval(t)", "type": "global", "name": "clearInterval", "desc": "

    Stop a timer that was previously created with setInterval(). The callback\nwill not execute.\n\n

    \n

    The timer functions are global variables. See the [timers][] section.\n\n

    \n" }, { "textRaw": "console", "name": "console", "stability": 4, "stabilityText": "API Frozen", "type": "global", "desc": "

    For printing to stdout and stderr. Similar to the console object functions\nprovided by most web browsers, here the output is sent to stdout or stderr.\n\n

    \n

    The console functions are synchronous when the destination is a terminal or\na file (to avoid lost messages in case of premature exit) and asynchronous\nwhen it's a pipe (to avoid blocking for long periods of time).\n\n

    \n

    That is, in the following example, stdout is non-blocking while stderr\nis blocking:\n\n

    \n
    $ node script.js 2> error.log | tee info.log
    \n

    In daily use, the blocking/non-blocking dichotomy is not something you\nshould worry about unless you log huge amounts of data.\n\n\n

    \n", "methods": [ { "textRaw": "console.log([data], [...])", "type": "method", "name": "log", "desc": "

    Prints to stdout with newline. This function can take multiple arguments in a\nprintf()-like way. Example:\n\n

    \n
    console.log('count: %d', count);
    \n

    If formatting elements are not found in the first string then util.inspect\nis used on each argument. See [util.format()][] for more information.\n\n

    \n", "signatures": [ { "params": [ { "name": "data", "optional": true }, { "name": "...", "optional": true } ] } ] }, { "textRaw": "console.info([data], [...])", "type": "method", "name": "info", "desc": "

    Same as console.log.\n\n

    \n", "signatures": [ { "params": [ { "name": "data", "optional": true }, { "name": "...", "optional": true } ] } ] }, { "textRaw": "console.error([data], [...])", "type": "method", "name": "error", "desc": "

    Same as console.log but prints to stderr.\n\n

    \n", "signatures": [ { "params": [ { "name": "data", "optional": true }, { "name": "...", "optional": true } ] } ] }, { "textRaw": "console.warn([data], [...])", "type": "method", "name": "warn", "desc": "

    Same as console.error.\n\n

    \n", "signatures": [ { "params": [ { "name": "data", "optional": true }, { "name": "...", "optional": true } ] } ] }, { "textRaw": "console.dir(obj)", "type": "method", "name": "dir", "desc": "

    Uses util.inspect on obj and prints resulting string to stdout.\n\n

    \n", "signatures": [ { "params": [ { "name": "obj" } ] } ] }, { "textRaw": "console.time(label)", "type": "method", "name": "time", "desc": "

    Mark a time.\n\n

    \n", "signatures": [ { "params": [ { "name": "label" } ] } ] }, { "textRaw": "console.timeEnd(label)", "type": "method", "name": "timeEnd", "desc": "

    Finish timer, record output. Example:\n\n

    \n
    console.time('100-elements');\nfor (var i = 0; i < 100; i++) {\n  ;\n}\nconsole.timeEnd('100-elements');
    \n", "signatures": [ { "params": [ { "name": "label" } ] } ] }, { "textRaw": "console.trace(label)", "type": "method", "name": "trace", "desc": "

    Print a stack trace to stderr of the current position.\n\n

    \n", "signatures": [ { "params": [ { "name": "label" } ] } ] }, { "textRaw": "console.assert(expression, [message])", "type": "method", "name": "assert", "desc": "

    Same as [assert.ok()][] where if the expression evaluates as false throw an\nAssertionError with message.\n\n

    \n", "signatures": [ { "params": [ { "name": "expression" }, { "name": "message", "optional": true } ] } ] } ] }, { "textRaw": "process", "name": "process", "type": "global", "desc": "

    The process object is a global object and can be accessed from anywhere.\nIt is an instance of [EventEmitter][].\n\n\n

    \n", "events": [ { "textRaw": "Event: 'exit'", "type": "event", "name": "exit", "desc": "

    Emitted when the process is about to exit. There is no way to prevent the\nexiting of the event loop at this point, and once all exit listeners have\nfinished running the process will exit. Therefore you must only perform\nsynchronous operations in this handler. This is a good hook to perform\nchecks on the module's state (like for unit tests). The callback takes one\nargument, the code the process is exiting with.\n\n

    \n

    Example of listening for exit:\n\n

    \n
    process.on('exit', function(code) {\n  // do *NOT* do this\n  setTimeout(function() {\n    console.log('This will not run');\n  }, 0);\n  console.log('About to exit with code:', code);\n});
    \n", "params": [] }, { "textRaw": "Event: 'uncaughtException'", "type": "event", "name": "uncaughtException", "desc": "

    Emitted when an exception bubbles all the way back to the event loop. If a\nlistener is added for this exception, the default action (which is to print\na stack trace and exit) will not occur.\n\n

    \n

    Example of listening for uncaughtException:\n\n

    \n
    process.on('uncaughtException', function(err) {\n  console.log('Caught exception: ' + err);\n});\n\nsetTimeout(function() {\n  console.log('This will still run.');\n}, 500);\n\n// Intentionally cause an exception, but don't catch it.\nnonexistentFunc();\nconsole.log('This will not run.');
    \n

    Note that uncaughtException is a very crude mechanism for exception\nhandling and may be removed in the future.\n\n

    \n

    Don't use it, use domains instead. If you do use it, restart\nyour application after every unhandled exception!\n\n

    \n

    Do not use it as the node.js equivalent of On Error Resume Next. An\nunhandled exception means your application - and by extension node.js itself -\nis in an undefined state. Blindly resuming means anything could happen.\n\n

    \n

    Think of resuming as pulling the power cord when you are upgrading your system.\nNine out of ten times nothing happens - but the 10th time, your system is bust.\n\n

    \n

    You have been warned.\n\n

    \n", "params": [] }, { "textRaw": "Signal Events", "name": "SIGINT, SIGHUP, etc.", "type": "event", "desc": "

    Emitted when the processes receives a signal. See sigaction(2) for a list of\nstandard POSIX signal names such as SIGINT, SIGHUP, etc.\n\n

    \n

    Example of listening for SIGINT:\n\n

    \n
    // Start reading from stdin so we don't exit.\nprocess.stdin.resume();\n\nprocess.on('SIGINT', function() {\n  console.log('Got SIGINT.  Press Control-D to exit.');\n});
    \n

    An easy way to send the SIGINT signal is with Control-C in most terminal\nprograms.\n\n

    \n

    Note:\n\n

    \n
      \n
    • SIGUSR1 is reserved by node.js to start the debugger. It's possible to\ninstall a listener but that won't stop the debugger from starting.
    • \n
    • SIGTERM and SIGINT have default handlers on non-Windows platforms that resets\nthe terminal mode before exiting with code 128 + signal number. If one of\nthese signals has a listener installed, its default behaviour will be removed\n(node will no longer exit).
    • \n
    • SIGPIPE is ignored by default, it can have a listener installed.
    • \n
    • SIGHUP is generated on Windows when the console window is closed, and on other\nplatforms under various similar conditions, see signal(7). It can have a\nlistener installed, however node will be unconditionally terminated by Windows\nabout 10 seconds later. On non-Windows platforms, the default behaviour of\nSIGHUP is to terminate node, but once a listener has been installed its\ndefault behaviour will be removed.
    • \n
    • SIGTERM is not supported on Windows, it can be listened on.
    • \n
    • SIGINT from the terminal is supported on all platforms, and can usually be\ngenerated with CTRL+C (though this may be configurable). It is not generated\nwhen terminal raw mode is enabled.
    • \n
    • SIGBREAK is delivered on Windows when CTRL+BREAK is pressed, on non-Windows\nplatforms it can be listened on, but there is no way to send or generate it.
    • \n
    • SIGWINCH is delivered when the console has been resized. On Windows, this will\nonly happen on write to the console when the cursor is being moved, or when a\nreadable tty is used in raw mode.
    • \n
    • SIGKILL cannot have a listener installed, it will unconditionally terminate\nnode on all platforms.
    • \n
    • SIGSTOP cannot have a listener installed.
    • \n
    \n

    Note that Windows does not support sending Signals, but node offers some\nemulation with process.kill(), and child_process.kill():\n- Sending signal 0 can be used to search for the existence of a process\n- Sending SIGINT, SIGTERM, and SIGKILL cause the unconditional exit of the\n target process.\n\n

    \n", "params": [] } ], "properties": [ { "textRaw": "process.stdout", "name": "stdout", "desc": "

    A Writable Stream to stdout.\n\n

    \n

    Example: the definition of console.log\n\n

    \n
    console.log = function(d) {\n  process.stdout.write(d + '\\n');\n};
    \n

    process.stderr and process.stdout are unlike other streams in Node in\nthat writes to them are usually blocking. They are blocking in the case\nthat they refer to regular files or TTY file descriptors. In the case they\nrefer to pipes, they are non-blocking like other streams.\n\n

    \n

    To check if Node is being run in a TTY context, read the isTTY property\non process.stderr, process.stdout, or process.stdin:\n\n

    \n
    $ node -p "Boolean(process.stdin.isTTY)"\ntrue\n$ echo "foo" | node -p "Boolean(process.stdin.isTTY)"\nfalse\n\n$ node -p "Boolean(process.stdout.isTTY)"\ntrue\n$ node -p "Boolean(process.stdout.isTTY)" | cat\nfalse
    \n

    See the tty docs for more information.\n\n

    \n" }, { "textRaw": "process.stderr", "name": "stderr", "desc": "

    A writable stream to stderr.\n\n

    \n

    process.stderr and process.stdout are unlike other streams in Node in\nthat writes to them are usually blocking. They are blocking in the case\nthat they refer to regular files or TTY file descriptors. In the case they\nrefer to pipes, they are non-blocking like other streams.\n\n\n

    \n" }, { "textRaw": "process.stdin", "name": "stdin", "desc": "

    A Readable Stream for stdin. The stdin stream is paused by default, so one\nmust call process.stdin.resume() to read from it.\n\n

    \n

    Example of opening standard input and listening for both events:\n\n

    \n
    process.stdin.resume();\nprocess.stdin.setEncoding('utf8');\n\nprocess.stdin.on('data', function(chunk) {\n  process.stdout.write('data: ' + chunk);\n});\n\nprocess.stdin.on('end', function() {\n  process.stdout.write('end');\n});
    \n" }, { "textRaw": "process.argv", "name": "argv", "desc": "

    An array containing the command line arguments. The first element will be\n'node', the second element will be the name of the JavaScript file. The\nnext elements will be any additional command line arguments.\n\n

    \n
    // print process.argv\nprocess.argv.forEach(function(val, index, array) {\n  console.log(index + ': ' + val);\n});
    \n

    This will generate:\n\n

    \n
    $ node process-2.js one two=three four\n0: node\n1: /Users/mjr/work/node/process-2.js\n2: one\n3: two=three\n4: four
    \n" }, { "textRaw": "process.execPath", "name": "execPath", "desc": "

    This is the absolute pathname of the executable that started the process.\n\n

    \n

    Example:\n\n

    \n
    /usr/local/bin/node
    \n" }, { "textRaw": "process.execArgv", "name": "execArgv", "desc": "

    This is the set of node-specific command line options from the\nexecutable that started the process. These options do not show up in\nprocess.argv, and do not include the node executable, the name of\nthe script, or any options following the script name. These options\nare useful in order to spawn child processes with the same execution\nenvironment as the parent.\n\n

    \n

    Example:\n\n

    \n
    $ node --harmony script.js --version
    \n

    results in process.execArgv:\n\n

    \n
    ['--harmony']
    \n

    and process.argv:\n\n

    \n
    ['/usr/local/bin/node', 'script.js', '--version']
    \n" }, { "textRaw": "process.env", "name": "env", "desc": "

    An object containing the user environment. See environ(7).\n\n\n

    \n" }, { "textRaw": "process.version", "name": "version", "desc": "

    A compiled-in property that exposes NODE_VERSION.\n\n

    \n
    console.log('Version: ' + process.version);
    \n" }, { "textRaw": "process.versions", "name": "versions", "desc": "

    A property exposing version strings of node and its dependencies.\n\n

    \n
    console.log(process.versions);
    \n

    Will print something like:\n\n

    \n
    { http_parser: '1.0',\n  node: '0.10.4',\n  v8: '3.14.5.8',\n  ares: '1.9.0-DEV',\n  uv: '0.10.3',\n  zlib: '1.2.3',\n  modules: '11',\n  openssl: '1.0.1e' }
    \n" }, { "textRaw": "process.config", "name": "config", "desc": "

    An Object containing the JavaScript representation of the configure options\nthat were used to compile the current node executable. This is the same as\nthe "config.gypi" file that was produced when running the ./configure script.\n\n

    \n

    An example of the possible output looks like:\n\n

    \n
    { target_defaults:\n   { cflags: [],\n     default_configuration: 'Release',\n     defines: [],\n     include_dirs: [],\n     libraries: [] },\n  variables:\n   { host_arch: 'x64',\n     node_install_npm: 'true',\n     node_prefix: '',\n     node_shared_cares: 'false',\n     node_shared_http_parser: 'false',\n     node_shared_libuv: 'false',\n     node_shared_v8: 'false',\n     node_shared_zlib: 'false',\n     node_use_dtrace: 'false',\n     node_use_openssl: 'true',\n     node_shared_openssl: 'false',\n     strict_aliasing: 'true',\n     target_arch: 'x64',\n     v8_use_snapshot: 'true' } }
    \n" }, { "textRaw": "process.pid", "name": "pid", "desc": "

    The PID of the process.\n\n

    \n
    console.log('This process is pid ' + process.pid);
    \n" }, { "textRaw": "process.title", "name": "title", "desc": "

    Getter/setter to set what is displayed in 'ps'.\n\n

    \n

    When used as a setter, the maximum length is platform-specific and probably\nshort.\n\n

    \n

    On Linux and OS X, it's limited to the size of the binary name plus the\nlength of the command line arguments because it overwrites the argv memory.\n\n

    \n

    v0.8 allowed for longer process title strings by also overwriting the environ\nmemory but that was potentially insecure/confusing in some (rather obscure)\ncases.\n\n\n

    \n" }, { "textRaw": "process.arch", "name": "arch", "desc": "

    What processor architecture you're running on: 'arm', 'ia32', or 'x64'.\n\n

    \n
    console.log('This processor architecture is ' + process.arch);
    \n" }, { "textRaw": "process.platform", "name": "platform", "desc": "

    What platform you're running on:\n'darwin', 'freebsd', 'linux', 'sunos' or 'win32'\n\n

    \n
    console.log('This platform is ' + process.platform);
    \n" }, { "textRaw": "`maxTickDepth` {Number} Default = 1000 ", "name": "maxTickDepth", "desc": "

    Callbacks passed to process.nextTick will usually be called at the\nend of the current flow of execution, and are thus approximately as fast\nas calling a function synchronously. Left unchecked, this would starve\nthe event loop, preventing any I/O from occurring.\n\n

    \n

    Consider this code:\n\n

    \n
    process.nextTick(function foo() {\n  process.nextTick(foo);\n});
    \n

    In order to avoid the situation where Node is blocked by an infinite\nloop of recursive series of nextTick calls, it defers to allow some I/O\nto be done every so often.\n\n

    \n

    The process.maxTickDepth value is the maximum depth of\nnextTick-calling nextTick-callbacks that will be evaluated before\nallowing other forms of I/O to occur.\n\n

    \n", "shortDesc": "Default = 1000" } ], "methods": [ { "textRaw": "process.abort()", "type": "method", "name": "abort", "desc": "

    This causes node to emit an abort. This will cause node to exit and\ngenerate a core file.\n\n

    \n", "signatures": [ { "params": [] } ] }, { "textRaw": "process.chdir(directory)", "type": "method", "name": "chdir", "desc": "

    Changes the current working directory of the process or throws an exception if that fails.\n\n

    \n
    console.log('Starting directory: ' + process.cwd());\ntry {\n  process.chdir('/tmp');\n  console.log('New directory: ' + process.cwd());\n}\ncatch (err) {\n  console.log('chdir: ' + err);\n}
    \n", "signatures": [ { "params": [ { "name": "directory" } ] } ] }, { "textRaw": "process.cwd()", "type": "method", "name": "cwd", "desc": "

    Returns the current working directory of the process.\n\n

    \n
    console.log('Current directory: ' + process.cwd());
    \n", "signatures": [ { "params": [] } ] }, { "textRaw": "process.exit([code])", "type": "method", "name": "exit", "desc": "

    Ends the process with the specified code. If omitted, exit uses the\n'success' code 0.\n\n

    \n

    To exit with a 'failure' code:\n\n

    \n
    process.exit(1);
    \n

    The shell that executed node should see the exit code as 1.\n\n\n

    \n", "signatures": [ { "params": [ { "name": "code", "optional": true } ] } ] }, { "textRaw": "process.getgid()", "type": "method", "name": "getgid", "desc": "

    Note: this function is only available on POSIX platforms (i.e. not Windows)\n\n

    \n

    Gets the group identity of the process. (See getgid(2).)\nThis is the numerical group id, not the group name.\n\n

    \n
    if (process.getgid) {\n  console.log('Current gid: ' + process.getgid());\n}
    \n", "signatures": [ { "params": [] } ] }, { "textRaw": "process.setgid(id)", "type": "method", "name": "setgid", "desc": "

    Note: this function is only available on POSIX platforms (i.e. not Windows)\n\n

    \n

    Sets the group identity of the process. (See setgid(2).) This accepts either\na numerical ID or a groupname string. If a groupname is specified, this method\nblocks while resolving it to a numerical ID.\n\n

    \n
    if (process.getgid && process.setgid) {\n  console.log('Current gid: ' + process.getgid());\n  try {\n    process.setgid(501);\n    console.log('New gid: ' + process.getgid());\n  }\n  catch (err) {\n    console.log('Failed to set gid: ' + err);\n  }\n}
    \n", "signatures": [ { "params": [ { "name": "id" } ] } ] }, { "textRaw": "process.getuid()", "type": "method", "name": "getuid", "desc": "

    Note: this function is only available on POSIX platforms (i.e. not Windows)\n\n

    \n

    Gets the user identity of the process. (See getuid(2).)\nThis is the numerical userid, not the username.\n\n

    \n
    if (process.getuid) {\n  console.log('Current uid: ' + process.getuid());\n}
    \n", "signatures": [ { "params": [] } ] }, { "textRaw": "process.setuid(id)", "type": "method", "name": "setuid", "desc": "

    Note: this function is only available on POSIX platforms (i.e. not Windows)\n\n

    \n

    Sets the user identity of the process. (See setuid(2).) This accepts either\na numerical ID or a username string. If a username is specified, this method\nblocks while resolving it to a numerical ID.\n\n

    \n
    if (process.getuid && process.setuid) {\n  console.log('Current uid: ' + process.getuid());\n  try {\n    process.setuid(501);\n    console.log('New uid: ' + process.getuid());\n  }\n  catch (err) {\n    console.log('Failed to set uid: ' + err);\n  }\n}
    \n", "signatures": [ { "params": [ { "name": "id" } ] } ] }, { "textRaw": "process.getgroups()", "type": "method", "name": "getgroups", "desc": "

    Note: this function is only available on POSIX platforms (i.e. not Windows)\n\n

    \n

    Returns an array with the supplementary group IDs. POSIX leaves it unspecified\nif the effective group ID is included but node.js ensures it always is.\n\n\n

    \n", "signatures": [ { "params": [] } ] }, { "textRaw": "process.setgroups(groups)", "type": "method", "name": "setgroups", "desc": "

    Note: this function is only available on POSIX platforms (i.e. not Windows)\n\n

    \n

    Sets the supplementary group IDs. This is a privileged operation, meaning you\nneed to be root or have the CAP_SETGID capability.\n\n

    \n

    The list can contain group IDs, group names or both.\n\n\n

    \n", "signatures": [ { "params": [ { "name": "groups" } ] } ] }, { "textRaw": "process.initgroups(user, extra_group)", "type": "method", "name": "initgroups", "desc": "

    Note: this function is only available on POSIX platforms (i.e. not Windows)\n\n

    \n

    Reads /etc/group and initializes the group access list, using all groups of\nwhich the user is a member. This is a privileged operation, meaning you need\nto be root or have the CAP_SETGID capability.\n\n

    \n

    user is a user name or user ID. extra_group is a group name or group ID.\n\n

    \n

    Some care needs to be taken when dropping privileges. Example:\n\n

    \n
    console.log(process.getgroups());         // [ 0 ]\nprocess.initgroups('bnoordhuis', 1000);   // switch user\nconsole.log(process.getgroups());         // [ 27, 30, 46, 1000, 0 ]\nprocess.setgid(1000);                     // drop root gid\nconsole.log(process.getgroups());         // [ 27, 30, 46, 1000 ]
    \n", "signatures": [ { "params": [ { "name": "user" }, { "name": "extra_group" } ] } ] }, { "textRaw": "process.kill(pid, [signal])", "type": "method", "name": "kill", "desc": "

    Send a signal to a process. pid is the process id and signal is the\nstring describing the signal to send. Signal names are strings like\n'SIGINT' or 'SIGHUP'. If omitted, the signal will be 'SIGTERM'.\nSee Signal Events and kill(2) for more information.\n\n

    \n

    Will throw an error if target does not exist, and as a special case, a signal of\n0 can be used to test for the existence of a process.\n\n

    \n

    Note that just because the name of this function is process.kill, it is\nreally just a signal sender, like the kill system call. The signal sent\nmay do something other than kill the target process.\n\n

    \n

    Example of sending a signal to yourself:\n\n

    \n
    process.on('SIGHUP', function() {\n  console.log('Got SIGHUP signal.');\n});\n\nsetTimeout(function() {\n  console.log('Exiting.');\n  process.exit(0);\n}, 100);\n\nprocess.kill(process.pid, 'SIGHUP');
    \n

    Note: When SIGUSR1 is received by Node.js it starts the debugger, see\nSignal Events.\n\n

    \n", "signatures": [ { "params": [ { "name": "pid" }, { "name": "signal", "optional": true } ] } ] }, { "textRaw": "process.memoryUsage()", "type": "method", "name": "memoryUsage", "desc": "

    Returns an object describing the memory usage of the Node process\nmeasured in bytes.\n\n

    \n
    var util = require('util');\n\nconsole.log(util.inspect(process.memoryUsage()));
    \n

    This will generate:\n\n

    \n
    { rss: 4935680,\n  heapTotal: 1826816,\n  heapUsed: 650472 }
    \n

    heapTotal and heapUsed refer to V8's memory usage.\n\n\n

    \n", "signatures": [ { "params": [] } ] }, { "textRaw": "process.nextTick(callback)", "type": "method", "name": "nextTick", "desc": "

    On the next loop around the event loop call this callback.\nThis is not a simple alias to setTimeout(fn, 0), it's much more\nefficient. It typically runs before any other I/O events fire, but there\nare some exceptions. See process.maxTickDepth below.\n\n

    \n
    process.nextTick(function() {\n  console.log('nextTick callback');\n});
    \n

    This is important in developing APIs where you want to give the user the\nchance to assign event handlers after an object has been constructed,\nbut before any I/O has occurred.\n\n

    \n
    function MyThing(options) {\n  this.setupOptions(options);\n\n  process.nextTick(function() {\n    this.startDoingStuff();\n  }.bind(this));\n}\n\nvar thing = new MyThing();\nthing.getReadyForStuff();\n\n// thing.startDoingStuff() gets called now, not before.
    \n

    It is very important for APIs to be either 100% synchronous or 100%\nasynchronous. Consider this example:\n\n

    \n
    // WARNING!  DO NOT USE!  BAD UNSAFE HAZARD!\nfunction maybeSync(arg, cb) {\n  if (arg) {\n    cb();\n    return;\n  }\n\n  fs.stat('file', cb);\n}
    \n

    This API is hazardous. If you do this:\n\n

    \n
    maybeSync(true, function() {\n  foo();\n});\nbar();
    \n

    then it's not clear whether foo() or bar() will be called first.\n\n

    \n

    This approach is much better:\n\n

    \n
    function definitelyAsync(arg, cb) {\n  if (arg) {\n    process.nextTick(cb);\n    return;\n  }\n\n  fs.stat('file', cb);\n}
    \n", "signatures": [ { "params": [ { "name": "callback" } ] } ] }, { "textRaw": "process.umask([mask])", "type": "method", "name": "umask", "desc": "

    Sets or reads the process's file mode creation mask. Child processes inherit\nthe mask from the parent process. Returns the old mask if mask argument is\ngiven, otherwise returns the current mask.\n\n

    \n
    var oldmask, newmask = 0644;\n\noldmask = process.umask(newmask);\nconsole.log('Changed umask from: ' + oldmask.toString(8) +\n            ' to ' + newmask.toString(8));
    \n", "signatures": [ { "params": [ { "name": "mask", "optional": true } ] } ] }, { "textRaw": "process.uptime()", "type": "method", "name": "uptime", "desc": "

    Number of seconds Node has been running.\n\n\n

    \n", "signatures": [ { "params": [] } ] }, { "textRaw": "process.hrtime()", "type": "method", "name": "hrtime", "desc": "

    Returns the current high-resolution real time in a [seconds, nanoseconds]\ntuple Array. It is relative to an arbitrary time in the past. It is not\nrelated to the time of day and therefore not subject to clock drift. The\nprimary use is for measuring performance between intervals.\n\n

    \n

    You may pass in the result of a previous call to process.hrtime() to get\na diff reading, useful for benchmarks and measuring intervals:\n\n

    \n
    var time = process.hrtime();\n// [ 1800216, 25 ]\n\nsetTimeout(function() {\n  var diff = process.hrtime(time);\n  // [ 1, 552 ]\n\n  console.log('benchmark took %d nanoseconds', diff[0] * 1e9 + diff[1]);\n  // benchmark took 1000000527 nanoseconds\n}, 1000);
    \n", "signatures": [ { "params": [] } ] } ] } ], "vars": [ { "textRaw": "require()", "type": "var", "name": "require", "desc": "

    To require modules. See the [Modules][] section. require isn't actually a\nglobal but rather local to each module.\n\n

    \n", "methods": [ { "textRaw": "require.resolve()", "type": "method", "name": "resolve", "desc": "

    Use the internal require() machinery to look up the location of a module,\nbut rather than loading the module, just return the resolved filename.\n\n

    \n", "signatures": [ { "params": [] } ] } ], "properties": [ { "textRaw": "`cache` {Object} ", "name": "cache", "desc": "

    Modules are cached in this object when they are required. By deleting a key\nvalue from this object, the next require will reload the module.\n\n

    \n" }, { "textRaw": "`extensions` {Object} ", "name": "extensions", "stability": 0, "stabilityText": "Deprecated", "desc": "

    Instruct require on how to handle certain file extensions.\n\n

    \n

    Process files with the extension .sjs as .js:\n\n

    \n
    require.extensions['.sjs'] = require.extensions['.js'];
    \n

    Deprecated In the past, this list has been used to load\nnon-JavaScript modules into Node by compiling them on-demand.\nHowever, in practice, there are much better ways to do this, such as\nloading modules via some other Node program, or compiling them to\nJavaScript ahead of time.\n\n

    \n

    Since the Module system is locked, this feature will probably never go\naway. However, it may have subtle bugs and complexities that are best\nleft untouched.\n\n

    \n" } ] }, { "textRaw": "__filename", "name": "__filename", "type": "var", "desc": "

    The filename of the code being executed. This is the resolved absolute path\nof this code file. For a main program this is not necessarily the same\nfilename used in the command line. The value inside a module is the path\nto that module file.\n\n

    \n

    Example: running node example.js from /Users/mjr\n\n

    \n
    console.log(__filename);\n// /Users/mjr/example.js
    \n

    __filename isn't actually a global but rather local to each module.\n\n

    \n" }, { "textRaw": "__dirname", "name": "__dirname", "type": "var", "desc": "

    The name of the directory that the currently executing script resides in.\n\n

    \n

    Example: running node example.js from /Users/mjr\n\n

    \n
    console.log(__dirname);\n// /Users/mjr
    \n

    __dirname isn't actually a global but rather local to each module.\n\n\n

    \n" }, { "textRaw": "module", "name": "module", "type": "var", "desc": "

    A reference to the current module. In particular\nmodule.exports is used for defining what a module exports and makes\navailable through require().\n\n

    \n

    module isn't actually a global but rather local to each module.\n\n

    \n

    See the [module system documentation][] for more information.\n\n

    \n" }, { "textRaw": "exports", "name": "exports", "type": "var", "desc": "

    A reference to the module.exports that is shorter to type.\nSee [module system documentation][] for details on when to use exports and\nwhen to use module.exports.\n\n

    \n

    exports isn't actually a global but rather local to each module.\n\n

    \n

    See the [module system documentation][] for more information.\n\n

    \n

    See the [module section][] for more information.\n\n

    \n" } ], "methods": [ { "textRaw": "setTimeout(cb, ms)", "type": "method", "name": "setTimeout", "desc": "

    Run callback cb after at least ms milliseconds. The actual delay depends\non external factors like OS timer granularity and system load.\n\n

    \n

    The timeout must be in the range of 1-2,147,483,647 inclusive. If the value is\noutside that range, it's changed to 1 millisecond. Broadly speaking, a timer\ncannot span more than 24.8 days.\n\n

    \n

    Returns an opaque value that represents the timer.\n\n

    \n", "signatures": [ { "params": [ { "name": "cb" }, { "name": "ms" } ] } ] }, { "textRaw": "clearTimeout(t)", "type": "method", "name": "clearTimeout", "desc": "

    Stop a timer that was previously created with setTimeout(). The callback will\nnot execute.\n\n

    \n", "signatures": [ { "params": [ { "name": "t" } ] } ] }, { "textRaw": "setInterval(cb, ms)", "type": "method", "name": "setInterval", "desc": "

    Run callback cb repeatedly every ms milliseconds. Note that the actual\ninterval may vary, depending on external factors like OS timer granularity and\nsystem load. It's never less than ms but it may be longer.\n\n

    \n

    The interval must be in the range of 1-2,147,483,647 inclusive. If the value is\noutside that range, it's changed to 1 millisecond. Broadly speaking, a timer\ncannot span more than 24.8 days.\n\n

    \n

    Returns an opaque value that represents the timer.\n\n

    \n", "signatures": [ { "params": [ { "name": "cb" }, { "name": "ms" } ] } ] } ], "modules": [ { "textRaw": "Timers", "name": "timers", "stability": 5, "stabilityText": "Locked", "desc": "

    All of the timer functions are globals. You do not need to require()\nthis module in order to use them.\n\n

    \n", "methods": [ { "textRaw": "setTimeout(callback, delay, [arg], [...])", "type": "method", "name": "setTimeout", "desc": "

    To schedule execution of a one-time callback after delay milliseconds. Returns a\ntimeoutId for possible use with clearTimeout(). Optionally you can\nalso pass arguments to the callback.\n\n

    \n

    It is important to note that your callback will probably not be called in exactly\ndelay milliseconds - Node.js makes no guarantees about the exact timing of when\nthe callback will fire, nor of the ordering things will fire in. The callback will\nbe called as close as possible to the time specified.\n\n

    \n", "signatures": [ { "params": [ { "name": "callback" }, { "name": "delay" }, { "name": "arg", "optional": true }, { "name": "...", "optional": true } ] } ] }, { "textRaw": "clearTimeout(timeoutId)", "type": "method", "name": "clearTimeout", "desc": "

    Prevents a timeout from triggering.\n\n

    \n", "signatures": [ { "params": [ { "name": "timeoutId" } ] } ] }, { "textRaw": "setInterval(callback, delay, [arg], [...])", "type": "method", "name": "setInterval", "desc": "

    To schedule the repeated execution of callback every delay milliseconds.\nReturns a intervalId for possible use with clearInterval(). Optionally\nyou can also pass arguments to the callback.\n\n

    \n", "signatures": [ { "params": [ { "name": "callback" }, { "name": "delay" }, { "name": "arg", "optional": true }, { "name": "...", "optional": true } ] } ] }, { "textRaw": "clearInterval(intervalId)", "type": "method", "name": "clearInterval", "desc": "

    Stops a interval from triggering.\n\n

    \n", "signatures": [ { "params": [ { "name": "intervalId" } ] } ] }, { "textRaw": "unref()", "type": "method", "name": "unref", "desc": "

    The opaque value returned by setTimeout and setInterval also has the method\ntimer.unref() which will allow you to create a timer that is active but if\nit is the only item left in the event loop won't keep the program running.\nIf the timer is already unrefd calling unref again will have no effect.\n\n

    \n

    In the case of setTimeout when you unref you create a separate timer that\nwill wakeup the event loop, creating too many of these may adversely effect\nevent loop performance -- use wisely.\n\n

    \n", "signatures": [ { "params": [] } ] }, { "textRaw": "ref()", "type": "method", "name": "ref", "desc": "

    If you had previously unref()d a timer you can call ref() to explicitly\nrequest the timer hold the program open. If the timer is already refd calling\nref again will have no effect.\n\n

    \n", "signatures": [ { "params": [] } ] }, { "textRaw": "setImmediate(callback, [arg], [...])", "type": "method", "name": "setImmediate", "desc": "

    To schedule the "immediate" execution of callback after I/O events\ncallbacks and before setTimeout and setInterval . Returns an\nimmediateId for possible use with clearImmediate(). Optionally you\ncan also pass arguments to the callback.\n\n

    \n

    Immediates are queued in the order created, and are popped off the queue once\nper loop iteration. This is different from process.nextTick which will\nexecute process.maxTickDepth queued callbacks per iteration. setImmediate\nwill yield to the event loop after firing a queued callback to make sure I/O is\nnot being starved. While order is preserved for execution, other I/O events may\nfire between any two scheduled immediate callbacks.\n\n

    \n", "signatures": [ { "params": [ { "name": "callback" }, { "name": "arg", "optional": true }, { "name": "...", "optional": true } ] } ] }, { "textRaw": "clearImmediate(immediateId)", "type": "method", "name": "clearImmediate", "desc": "

    Stops an immediate from triggering.\n\n

    \n", "signatures": [ { "params": [ { "name": "immediateId" } ] } ] } ], "type": "module", "displayName": "Timers" }, { "textRaw": "Modules", "name": "module", "stability": 5, "stabilityText": "Locked", "desc": "

    Node has a simple module loading system. In Node, files and modules are in\none-to-one correspondence. As an example, foo.js loads the module\ncircle.js in the same directory.\n\n

    \n

    The contents of foo.js:\n\n

    \n
    var circle = require('./circle.js');\nconsole.log( 'The area of a circle of radius 4 is '\n           + circle.area(4));
    \n

    The contents of circle.js:\n\n

    \n
    var PI = Math.PI;\n\nexports.area = function (r) {\n  return PI * r * r;\n};\n\nexports.circumference = function (r) {\n  return 2 * PI * r;\n};
    \n

    The module circle.js has exported the functions area() and\ncircumference(). To add functions and objects to the root of your module,\nyou can add them to the special exports object.\n\n

    \n

    Variables local to the module will be private, as though the module was wrapped\nin a function. In this example the variable PI is private to circle.js.\n\n

    \n

    If you want the root of your module's export to be a function (such as a\nconstructor) or if you want to export a complete object in one assignment\ninstead of building it one property at a time, assign it to module.exports\ninstead of exports.\n\n

    \n

    Below, bar.js makes use of the square module, which exports a constructor:\n\n

    \n
    var square = require('./square.js');\nvar mySquare = square(2);\nconsole.log('The area of my square is ' + mySquare.area());
    \n

    The square module is defined in square.js:\n\n

    \n
    // assigning to exports will not modify module, must use module.exports\nmodule.exports = function(width) {\n  return {\n    area: function() {\n      return width * width;\n    }\n  };\n}
    \n

    The module system is implemented in the require("module") module.\n\n

    \n", "miscs": [ { "textRaw": "Cycles", "name": "Cycles", "type": "misc", "desc": "

    When there are circular require() calls, a module might not be\ndone being executed when it is returned.\n\n

    \n

    Consider this situation:\n\n

    \n

    a.js:\n\n

    \n
    console.log('a starting');\nexports.done = false;\nvar b = require('./b.js');\nconsole.log('in a, b.done = %j', b.done);\nexports.done = true;\nconsole.log('a done');
    \n

    b.js:\n\n

    \n
    console.log('b starting');\nexports.done = false;\nvar a = require('./a.js');\nconsole.log('in b, a.done = %j', a.done);\nexports.done = true;\nconsole.log('b done');
    \n

    main.js:\n\n

    \n
    console.log('main starting');\nvar a = require('./a.js');\nvar b = require('./b.js');\nconsole.log('in main, a.done=%j, b.done=%j', a.done, b.done);
    \n

    When main.js loads a.js, then a.js in turn loads b.js. At that\npoint, b.js tries to load a.js. In order to prevent an infinite\nloop an unfinished copy of the a.js exports object is returned to the\nb.js module. b.js then finishes loading, and its exports object is\nprovided to the a.js module.\n\n

    \n

    By the time main.js has loaded both modules, they're both finished.\nThe output of this program would thus be:\n\n

    \n
    $ node main.js\nmain starting\na starting\nb starting\nin b, a.done = false\nb done\nin a, b.done = true\na done\nin main, a.done=true, b.done=true
    \n

    If you have cyclic module dependencies in your program, make sure to\nplan accordingly.\n\n

    \n" }, { "textRaw": "Core Modules", "name": "Core Modules", "type": "misc", "desc": "

    Node has several modules compiled into the binary. These modules are\ndescribed in greater detail elsewhere in this documentation.\n\n

    \n

    The core modules are defined in node's source in the lib/ folder.\n\n

    \n

    Core modules are always preferentially loaded if their identifier is\npassed to require(). For instance, require('http') will always\nreturn the built in HTTP module, even if there is a file by that name.\n\n

    \n" }, { "textRaw": "File Modules", "name": "File Modules", "type": "misc", "desc": "

    If the exact filename is not found, then node will attempt to load the\nrequired filename with the added extension of .js, .json, and then .node.\n\n

    \n

    .js files are interpreted as JavaScript text files, and .json files are\nparsed as JSON text files. .node files are interpreted as compiled addon\nmodules loaded with dlopen.\n\n

    \n

    A module prefixed with '/' is an absolute path to the file. For\nexample, require('/home/marco/foo.js') will load the file at\n/home/marco/foo.js.\n\n

    \n

    A module prefixed with './' is relative to the file calling require().\nThat is, circle.js must be in the same directory as foo.js for\nrequire('./circle') to find it.\n\n

    \n

    Without a leading '/' or './' to indicate a file, the module is either a\n"core module" or is loaded from a node_modules folder.\n\n

    \n

    If the given path does not exist, require() will throw an Error with its\ncode property set to 'MODULE_NOT_FOUND'.\n\n

    \n" }, { "textRaw": "Loading from `node_modules` Folders", "name": "Loading from `node_modules` Folders", "type": "misc", "desc": "

    If the module identifier passed to require() is not a native module,\nand does not begin with '/', '../', or './', then node starts at the\nparent directory of the current module, and adds /node_modules, and\nattempts to load the module from that location.\n\n

    \n

    If it is not found there, then it moves to the parent directory, and so\non, until the root of the tree is reached.\n\n

    \n

    For example, if the file at '/home/ry/projects/foo.js' called\nrequire('bar.js'), then node would look in the following locations, in\nthis order:\n\n

    \n
      \n
    • /home/ry/projects/node_modules/bar.js
    • \n
    • /home/ry/node_modules/bar.js
    • \n
    • /home/node_modules/bar.js
    • \n
    • /node_modules/bar.js
    • \n
    \n

    This allows programs to localize their dependencies, so that they do not\nclash.\n\n

    \n" }, { "textRaw": "Folders as Modules", "name": "Folders as Modules", "type": "misc", "desc": "

    It is convenient to organize programs and libraries into self-contained\ndirectories, and then provide a single entry point to that library.\nThere are three ways in which a folder may be passed to require() as\nan argument.\n\n

    \n

    The first is to create a package.json file in the root of the folder,\nwhich specifies a main module. An example package.json file might\nlook like this:\n\n

    \n
    { "name" : "some-library",\n  "main" : "./lib/some-library.js" }
    \n

    If this was in a folder at ./some-library, then\nrequire('./some-library') would attempt to load\n./some-library/lib/some-library.js.\n\n

    \n

    This is the extent of Node's awareness of package.json files.\n\n

    \n

    If there is no package.json file present in the directory, then node\nwill attempt to load an index.js or index.node file out of that\ndirectory. For example, if there was no package.json file in the above\nexample, then require('./some-library') would attempt to load:\n\n

    \n
      \n
    • ./some-library/index.js
    • \n
    • ./some-library/index.node
    • \n
    \n" }, { "textRaw": "Caching", "name": "Caching", "type": "misc", "desc": "

    Modules are cached after the first time they are loaded. This means\n(among other things) that every call to require('foo') will get\nexactly the same object returned, if it would resolve to the same file.\n\n

    \n

    Multiple calls to require('foo') may not cause the module code to be\nexecuted multiple times. This is an important feature. With it,\n"partially done" objects can be returned, thus allowing transitive\ndependencies to be loaded even when they would cause cycles.\n\n

    \n

    If you want to have a module execute code multiple times, then export a\nfunction, and call that function.\n\n

    \n", "miscs": [ { "textRaw": "Module Caching Caveats", "name": "Module Caching Caveats", "type": "misc", "desc": "

    Modules are cached based on their resolved filename. Since modules may\nresolve to a different filename based on the location of the calling\nmodule (loading from node_modules folders), it is not a guarantee\nthat require('foo') will always return the exact same object, if it\nwould resolve to different files.\n\n

    \n" } ] }, { "textRaw": "All Together...", "name": "All Together...", "type": "misc", "desc": "

    To get the exact filename that will be loaded when require() is called, use\nthe require.resolve() function.\n\n

    \n

    Putting together all of the above, here is the high-level algorithm\nin pseudocode of what require.resolve does:\n\n

    \n
    require(X) from module at path Y\n1. If X is a core module,\n   a. return the core module\n   b. STOP\n2. If X begins with './' or '/' or '../'\n   a. LOAD_AS_FILE(Y + X)\n   b. LOAD_AS_DIRECTORY(Y + X)\n3. LOAD_NODE_MODULES(X, dirname(Y))\n4. THROW "not found"\n\nLOAD_AS_FILE(X)\n1. If X is a file, load X as JavaScript text.  STOP\n2. If X.js is a file, load X.js as JavaScript text.  STOP\n3. If X.node is a file, load X.node as binary addon.  STOP\n\nLOAD_AS_DIRECTORY(X)\n1. If X/package.json is a file,\n   a. Parse X/package.json, and look for "main" field.\n   b. let M = X + (json main field)\n   c. LOAD_AS_FILE(M)\n2. If X/index.js is a file, load X/index.js as JavaScript text.  STOP\n3. If X/index.node is a file, load X/index.node as binary addon.  STOP\n\nLOAD_NODE_MODULES(X, START)\n1. let DIRS=NODE_MODULES_PATHS(START)\n2. for each DIR in DIRS:\n   a. LOAD_AS_FILE(DIR/X)\n   b. LOAD_AS_DIRECTORY(DIR/X)\n\nNODE_MODULES_PATHS(START)\n1. let PARTS = path split(START)\n2. let ROOT = index of first instance of "node_modules" in PARTS, or 0\n3. let I = count of PARTS - 1\n4. let DIRS = []\n5. while I > ROOT,\n   a. if PARTS[I] = "node_modules" CONTINUE\n   c. DIR = path join(PARTS[0 .. I] + "node_modules")\n   b. DIRS = DIRS + DIR\n   c. let I = I - 1\n6. return DIRS
    \n" }, { "textRaw": "Loading from the global folders", "name": "Loading from the global folders", "type": "misc", "desc": "

    If the NODE_PATH environment variable is set to a colon-delimited list\nof absolute paths, then node will search those paths for modules if they\nare not found elsewhere. (Note: On Windows, NODE_PATH is delimited by\nsemicolons instead of colons.)\n\n

    \n

    Additionally, node will search in the following locations:\n\n

    \n
      \n
    • 1: $HOME/.node_modules
    • \n
    • 2: $HOME/.node_libraries
    • \n
    • 3: $PREFIX/lib/node
    • \n
    \n

    Where $HOME is the user's home directory, and $PREFIX is node's\nconfigured node_prefix.\n\n

    \n

    These are mostly for historic reasons. You are highly encouraged to\nplace your dependencies locally in node_modules folders. They will be\nloaded faster, and more reliably.\n\n

    \n" }, { "textRaw": "Accessing the main module", "name": "Accessing the main module", "type": "misc", "desc": "

    When a file is run directly from Node, require.main is set to its\nmodule. That means that you can determine whether a file has been run\ndirectly by testing\n\n

    \n
    require.main === module
    \n

    For a file foo.js, this will be true if run via node foo.js, but\nfalse if run by require('./foo').\n\n

    \n

    Because module provides a filename property (normally equivalent to\n__filename), the entry point of the current application can be obtained\nby checking require.main.filename.\n\n

    \n" }, { "textRaw": "Addenda: Package Manager Tips", "name": "Addenda: Package Manager Tips", "type": "misc", "desc": "

    The semantics of Node's require() function were designed to be general\nenough to support a number of sane directory structures. Package manager\nprograms such as dpkg, rpm, and npm will hopefully find it possible to\nbuild native packages from Node modules without modification.\n\n

    \n

    Below we give a suggested directory structure that could work:\n\n

    \n

    Let's say that we wanted to have the folder at\n/usr/lib/node/<some-package>/<some-version> hold the contents of a\nspecific version of a package.\n\n

    \n

    Packages can depend on one another. In order to install package foo, you\nmay have to install a specific version of package bar. The bar package\nmay itself have dependencies, and in some cases, these dependencies may even\ncollide or form cycles.\n\n

    \n

    Since Node looks up the realpath of any modules it loads (that is,\nresolves symlinks), and then looks for their dependencies in the\nnode_modules folders as described above, this situation is very simple to\nresolve with the following architecture:\n\n

    \n
      \n
    • /usr/lib/node/foo/1.2.3/ - Contents of the foo package, version 1.2.3.
    • \n
    • /usr/lib/node/bar/4.3.2/ - Contents of the bar package that foo\ndepends on.
    • \n
    • /usr/lib/node/foo/1.2.3/node_modules/bar - Symbolic link to\n/usr/lib/node/bar/4.3.2/.
    • \n
    • /usr/lib/node/bar/4.3.2/node_modules/* - Symbolic links to the packages\nthat bar depends on.
    • \n
    \n

    Thus, even if a cycle is encountered, or if there are dependency\nconflicts, every module will be able to get a version of its dependency\nthat it can use.\n\n

    \n

    When the code in the foo package does require('bar'), it will get the\nversion that is symlinked into /usr/lib/node/foo/1.2.3/node_modules/bar.\nThen, when the code in the bar package calls require('quux'), it'll get\nthe version that is symlinked into\n/usr/lib/node/bar/4.3.2/node_modules/quux.\n\n

    \n

    Furthermore, to make the module lookup process even more optimal, rather\nthan putting packages directly in /usr/lib/node, we could put them in\n/usr/lib/node_modules/<name>/<version>. Then node will not bother\nlooking for missing dependencies in /usr/node_modules or /node_modules.\n\n

    \n

    In order to make modules available to the node REPL, it might be useful to\nalso add the /usr/lib/node_modules folder to the $NODE_PATH environment\nvariable. Since the module lookups using node_modules folders are all\nrelative, and based on the real path of the files making the calls to\nrequire(), the packages themselves can be anywhere.\n\n

    \n" } ], "vars": [ { "textRaw": "The `module` Object", "name": "module", "type": "var", "desc": "

    In each module, the module free variable is a reference to the object\nrepresenting the current module. For convenience, module.exports is\nalso accessible via the exports module-global. module isn't actually\na global but rather local to each module.\n\n

    \n", "properties": [ { "textRaw": "`exports` {Object} ", "name": "exports", "desc": "

    The module.exports object is created by the Module system. Sometimes this is not\nacceptable; many want their module to be an instance of some class. To do this\nassign the desired export object to module.exports. Note that assigning the\ndesired object to exports will simply rebind the local exports variable,\nwhich is probably not what you want to do.\n\n

    \n

    For example suppose we were making a module called a.js\n\n

    \n
    var EventEmitter = require('events').EventEmitter;\n\nmodule.exports = new EventEmitter();\n\n// Do some work, and after some time emit\n// the 'ready' event from the module itself.\nsetTimeout(function() {\n  module.exports.emit('ready');\n}, 1000);
    \n

    Then in another file we could do\n\n

    \n
    var a = require('./a');\na.on('ready', function() {\n  console.log('module a is ready');\n});
    \n

    Note that assignment to module.exports must be done immediately. It cannot be\ndone in any callbacks. This does not work:\n\n

    \n

    x.js:\n\n

    \n
    setTimeout(function() {\n  module.exports = { a: "hello" };\n}, 0);
    \n

    y.js:\n\n

    \n
    var x = require('./x');\nconsole.log(x.a);
    \n", "modules": [ { "textRaw": "exports alias", "name": "exports_alias", "desc": "

    The exports variable that is available within a module starts as a reference\nto module.exports. As with any variable, if you assign a new value to it, it\nis no longer bound to the previous value.\n\n

    \n

    To illustrate the behaviour, imagine this hypothetical implementation of\nrequire():\n\n

    \n
    function require(...) {\n  // ...\n  function (module, exports) {\n    // Your module code here\n    exports = some_func;        // re-assigns exports, exports is no longer\n                                // a shortcut, and nothing is exported.\n    module.exports = some_func; // makes your module export 0\n  } (module, module.exports);\n  return module;\n}
    \n

    As a guideline, if the relationship between exports and module.exports\nseems like magic to you, ignore exports and only use module.exports.\n\n

    \n", "type": "module", "displayName": "exports alias" } ] }, { "textRaw": "`id` {String} ", "name": "id", "desc": "

    The identifier for the module. Typically this is the fully resolved\nfilename.\n\n\n

    \n" }, { "textRaw": "`filename` {String} ", "name": "filename", "desc": "

    The fully resolved filename to the module.\n\n\n

    \n" }, { "textRaw": "`loaded` {Boolean} ", "name": "loaded", "desc": "

    Whether or not the module is done loading, or is in the process of\nloading.\n\n\n

    \n" }, { "textRaw": "`parent` {Module Object} ", "name": "parent", "desc": "

    The module that required this one.\n\n\n

    \n" }, { "textRaw": "`children` {Array} ", "name": "children", "desc": "

    The module objects required by this one.\n\n\n\n

    \n" } ], "methods": [ { "textRaw": "module.require(id)", "type": "method", "name": "require", "signatures": [ { "return": { "textRaw": "Return: {Object} `module.exports` from the resolved module ", "name": "return", "type": "Object", "desc": "`module.exports` from the resolved module" }, "params": [ { "textRaw": "`id` {String} ", "name": "id", "type": "String" } ] }, { "params": [ { "name": "id" } ] } ], "desc": "

    The module.require method provides a way to load a module as if\nrequire() was called from the original module.\n\n

    \n

    Note that in order to do this, you must get a reference to the module\nobject. Since require() returns the module.exports, and the module is\ntypically only available within a specific module's code, it must be\nexplicitly exported in order to be used.\n\n\n

    \n" } ] } ], "type": "module", "displayName": "module" }, { "textRaw": "Addons", "name": "addons", "desc": "

    Addons are dynamically linked shared objects. They can provide glue to C and\nC++ libraries. The API (at the moment) is rather complex, involving\nknowledge of several libraries:\n\n

    \n
      \n
    • V8 JavaScript, a C++ library. Used for interfacing with JavaScript:\ncreating objects, calling functions, etc. Documented mostly in the\nv8.h header file (deps/v8/include/v8.h in the Node source\ntree), which is also available\nonline.

      \n
    • \n
    • libuv, C event loop library.\nAnytime one needs to wait for a file descriptor to become readable,\nwait for a timer, or wait for a signal to be received one will need\nto interface with libuv. That is, if you perform any I/O, libuv will\nneed to be used.

      \n
    • \n
    • Internal Node libraries. Most importantly is the node::ObjectWrap\nclass which you will likely want to derive from.

      \n
    • \n
    • Others. Look in deps/ for what else is available.

      \n
    • \n
    \n

    Node statically compiles all its dependencies into the executable.\nWhen compiling your module, you don't need to worry about linking to\nany of these libraries.\n\n

    \n

    All of the following examples are available for\ndownload and may be\nused as a starting-point for your own Addon.\n\n

    \n", "modules": [ { "textRaw": "Hello world", "name": "hello_world", "desc": "

    To get started let's make a small Addon which is the C++ equivalent of\nthe following JavaScript code:\n\n

    \n
    module.exports.hello = function() { return 'world'; };
    \n

    First we create a file hello.cc:\n\n

    \n
    #include <node.h>\n#include <v8.h>\n\nusing namespace v8;\n\nHandle<Value> Method(const Arguments& args) {\n  HandleScope scope;\n  return scope.Close(String::New("world"));\n}\n\nvoid init(Handle<Object> exports) {\n  exports->Set(String::NewSymbol("hello"),\n      FunctionTemplate::New(Method)->GetFunction());\n}\n\nNODE_MODULE(hello, init)
    \n

    Note that all Node addons must export an initialization function:\n\n

    \n
    void Initialize (Handle<Object> exports);\nNODE_MODULE(module_name, Initialize)
    \n

    There is no semi-colon after NODE_MODULE as it's not a function (see node.h).\n\n

    \n

    The module_name needs to match the filename of the final binary (minus the\n.node suffix).\n\n

    \n

    The source code needs to be built into hello.node, the binary Addon. To\ndo this we create a file called binding.gyp which describes the configuration\nto build your module in a JSON-like format. This file gets compiled by\nnode-gyp.\n\n

    \n
    {\n  "targets": [\n    {\n      "target_name": "hello",\n      "sources": [ "hello.cc" ]\n    }\n  ]\n}
    \n

    The next step is to generate the appropriate project build files for the\ncurrent platform. Use node-gyp configure for that.\n\n

    \n

    Now you will have either a Makefile (on Unix platforms) or a vcxproj file\n(on Windows) in the build/ directory. Next invoke the node-gyp build\ncommand.\n\n

    \n

    Now you have your compiled .node bindings file! The compiled bindings end up\nin build/Release/.\n\n

    \n

    You can now use the binary addon in a Node project hello.js by pointing require to\nthe recently built hello.node module:\n\n

    \n
    var addon = require('./build/Release/hello');\n\nconsole.log(addon.hello()); // 'world'
    \n

    Please see patterns below for further information or\n

    \n

    https://github.com/arturadib/node-qt for an example in production.\n\n\n

    \n", "type": "module", "displayName": "Hello world" }, { "textRaw": "Addon patterns", "name": "addon_patterns", "desc": "

    Below are some addon patterns to help you get started. Consult the online\nv8 reference for help with the various v8\ncalls, and v8's Embedder's Guide\nfor an explanation of several concepts used such as handles, scopes,\nfunction templates, etc.\n\n

    \n

    In order to use these examples you need to compile them using node-gyp.\nCreate the following binding.gyp file:\n\n

    \n
    {\n  "targets": [\n    {\n      "target_name": "addon",\n      "sources": [ "addon.cc" ]\n    }\n  ]\n}
    \n

    In cases where there is more than one .cc file, simply add the file name to the\nsources array, e.g.:\n\n

    \n
    "sources": ["addon.cc", "myexample.cc"]
    \n

    Now that you have your binding.gyp ready, you can configure and build the\naddon:\n\n

    \n
    $ node-gyp configure build
    \n", "modules": [ { "textRaw": "Function arguments", "name": "function_arguments", "desc": "

    The following pattern illustrates how to read arguments from JavaScript\nfunction calls and return a result. This is the main and only needed source\naddon.cc:\n\n

    \n
    #define BUILDING_NODE_EXTENSION\n#include <node.h>\n\nusing namespace v8;\n\nHandle<Value> Add(const Arguments& args) {\n  HandleScope scope;\n\n  if (args.Length() < 2) {\n    ThrowException(Exception::TypeError(String::New("Wrong number of arguments")));\n    return scope.Close(Undefined());\n  }\n\n  if (!args[0]->IsNumber() || !args[1]->IsNumber()) {\n    ThrowException(Exception::TypeError(String::New("Wrong arguments")));\n    return scope.Close(Undefined());\n  }\n\n  Local<Number> num = Number::New(args[0]->NumberValue() +\n      args[1]->NumberValue());\n  return scope.Close(num);\n}\n\nvoid Init(Handle<Object> exports) {\n  exports->Set(String::NewSymbol("add"),\n      FunctionTemplate::New(Add)->GetFunction());\n}\n\nNODE_MODULE(addon, Init)
    \n

    You can test it with the following JavaScript snippet:\n\n

    \n
    var addon = require('./build/Release/addon');\n\nconsole.log( 'This should be eight:', addon.add(3,5) );
    \n", "type": "module", "displayName": "Function arguments" }, { "textRaw": "Callbacks", "name": "callbacks", "desc": "

    You can pass JavaScript functions to a C++ function and execute them from\nthere. Here's addon.cc:\n\n

    \n
    #define BUILDING_NODE_EXTENSION\n#include <node.h>\n\nusing namespace v8;\n\nHandle<Value> RunCallback(const Arguments& args) {\n  HandleScope scope;\n\n  Local<Function> cb = Local<Function>::Cast(args[0]);\n  const unsigned argc = 1;\n  Local<Value> argv[argc] = { Local<Value>::New(String::New("hello world")) };\n  cb->Call(Context::GetCurrent()->Global(), argc, argv);\n\n  return scope.Close(Undefined());\n}\n\nvoid Init(Handle<Object> exports, Handle<Object> module) {\n  module->Set(String::NewSymbol("exports"),\n      FunctionTemplate::New(RunCallback)->GetFunction());\n}\n\nNODE_MODULE(addon, Init)
    \n

    Note that this example uses a two-argument form of Init() that receives\nthe full module object as the second argument. This allows the addon\nto completely overwrite exports with a single function instead of\nadding the function as a property of exports.\n\n

    \n

    To test it run the following JavaScript snippet:\n\n

    \n
    var addon = require('./build/Release/addon');\n\naddon(function(msg){\n  console.log(msg); // 'hello world'\n});
    \n", "type": "module", "displayName": "Callbacks" }, { "textRaw": "Object factory", "name": "object_factory", "desc": "

    You can create and return new objects from within a C++ function with this\naddon.cc pattern, which returns an object with property msg that echoes\nthe string passed to createObject():\n\n

    \n
    #define BUILDING_NODE_EXTENSION\n#include <node.h>\n\nusing namespace v8;\n\nHandle<Value> CreateObject(const Arguments& args) {\n  HandleScope scope;\n\n  Local<Object> obj = Object::New();\n  obj->Set(String::NewSymbol("msg"), args[0]->ToString());\n\n  return scope.Close(obj);\n}\n\nvoid Init(Handle<Object> exports, Handle<Object> module) {\n  module->Set(String::NewSymbol("exports"),\n      FunctionTemplate::New(CreateObject)->GetFunction());\n}\n\nNODE_MODULE(addon, Init)
    \n

    To test it in JavaScript:\n\n

    \n
    var addon = require('./build/Release/addon');\n\nvar obj1 = addon('hello');\nvar obj2 = addon('world');\nconsole.log(obj1.msg+' '+obj2.msg); // 'hello world'
    \n", "type": "module", "displayName": "Object factory" }, { "textRaw": "Function factory", "name": "function_factory", "desc": "

    This pattern illustrates how to create and return a JavaScript function that\nwraps a C++ function:\n\n

    \n
    #define BUILDING_NODE_EXTENSION\n#include <node.h>\n\nusing namespace v8;\n\nHandle<Value> MyFunction(const Arguments& args) {\n  HandleScope scope;\n  return scope.Close(String::New("hello world"));\n}\n\nHandle<Value> CreateFunction(const Arguments& args) {\n  HandleScope scope;\n\n  Local<FunctionTemplate> tpl = FunctionTemplate::New(MyFunction);\n  Local<Function> fn = tpl->GetFunction();\n  fn->SetName(String::NewSymbol("theFunction")); // omit this to make it anonymous\n\n  return scope.Close(fn);\n}\n\nvoid Init(Handle<Object> exports, Handle<Object> module) {\n  module->Set(String::NewSymbol("exports"),\n      FunctionTemplate::New(CreateFunction)->GetFunction());\n}\n\nNODE_MODULE(addon, Init)
    \n

    To test:\n\n

    \n
    var addon = require('./build/Release/addon');\n\nvar fn = addon();\nconsole.log(fn()); // 'hello world'
    \n", "type": "module", "displayName": "Function factory" }, { "textRaw": "Wrapping C++ objects", "name": "wrapping_c++_objects", "desc": "

    Here we will create a wrapper for a C++ object/class MyObject that can be\ninstantiated in JavaScript through the new operator. First prepare the main\nmodule addon.cc:\n\n

    \n
    #define BUILDING_NODE_EXTENSION\n#include <node.h>\n#include "myobject.h"\n\nusing namespace v8;\n\nvoid InitAll(Handle<Object> exports) {\n  MyObject::Init(exports);\n}\n\nNODE_MODULE(addon, InitAll)
    \n

    Then in myobject.h make your wrapper inherit from node::ObjectWrap:\n\n

    \n
    #ifndef MYOBJECT_H\n#define MYOBJECT_H\n\n#include <node.h>\n\nclass MyObject : public node::ObjectWrap {\n public:\n  static void Init(v8::Handle<v8::Object> exports);\n\n private:\n  explicit MyObject(double value = 0);\n  ~MyObject();\n\n  static v8::Handle<v8::Value> New(const v8::Arguments& args);\n  static v8::Handle<v8::Value> PlusOne(const v8::Arguments& args);\n  static v8::Persistent<v8::Function> constructor;\n  double value_;\n};\n\n#endif
    \n

    And in myobject.cc implement the various methods that you want to expose.\nHere we expose the method plusOne by adding it to the constructor's\nprototype:\n\n

    \n
    #define BUILDING_NODE_EXTENSION\n#include <node.h>\n#include "myobject.h"\n\nusing namespace v8;\n\nPersistent<Function> MyObject::constructor;\n\nMyObject::MyObject(double value) : value_(value) {\n}\n\nMyObject::~MyObject() {\n}\n\nvoid MyObject::Init(Handle<Object> exports) {\n  // Prepare constructor template\n  Local<FunctionTemplate> tpl = FunctionTemplate::New(New);\n  tpl->SetClassName(String::NewSymbol("MyObject"));\n  tpl->InstanceTemplate()->SetInternalFieldCount(1);\n  // Prototype\n  tpl->PrototypeTemplate()->Set(String::NewSymbol("plusOne"),\n      FunctionTemplate::New(PlusOne)->GetFunction());\n  constructor = Persistent<Function>::New(tpl->GetFunction());\n  exports->Set(String::NewSymbol("MyObject"), constructor);\n}\n\nHandle<Value> MyObject::New(const Arguments& args) {\n  HandleScope scope;\n\n  if (args.IsConstructCall()) {\n    // Invoked as constructor: `new MyObject(...)`\n    double value = args[0]->IsUndefined() ? 0 : args[0]->NumberValue();\n    MyObject* obj = new MyObject(value);\n    obj->Wrap(args.This());\n    return args.This();\n  } else {\n    // Invoked as plain function `MyObject(...)`, turn into construct call.\n    const int argc = 1;\n    Local<Value> argv[argc] = { args[0] };\n    return scope.Close(constructor->NewInstance(argc, argv));\n  }\n}\n\nHandle<Value> MyObject::PlusOne(const Arguments& args) {\n  HandleScope scope;\n\n  MyObject* obj = ObjectWrap::Unwrap<MyObject>(args.This());\n  obj->value_ += 1;\n\n  return scope.Close(Number::New(obj->value_));\n}
    \n

    Test it with:\n\n

    \n
    var addon = require('./build/Release/addon');\n\nvar obj = new addon.MyObject(10);\nconsole.log( obj.plusOne() ); // 11\nconsole.log( obj.plusOne() ); // 12\nconsole.log( obj.plusOne() ); // 13
    \n", "type": "module", "displayName": "Wrapping C++ objects" }, { "textRaw": "Factory of wrapped objects", "name": "factory_of_wrapped_objects", "desc": "

    This is useful when you want to be able to create native objects without\nexplicitly instantiating them with the new operator in JavaScript, e.g.\n\n

    \n
    var obj = addon.createObject();\n// instead of:\n// var obj = new addon.Object();
    \n

    Let's register our createObject method in addon.cc:\n\n

    \n
    #define BUILDING_NODE_EXTENSION\n#include <node.h>\n#include "myobject.h"\n\nusing namespace v8;\n\nHandle<Value> CreateObject(const Arguments& args) {\n  HandleScope scope;\n  return scope.Close(MyObject::NewInstance(args));\n}\n\nvoid InitAll(Handle<Object> exports, Handle<Object> module) {\n  MyObject::Init();\n\n  module->Set(String::NewSymbol("exports"),\n      FunctionTemplate::New(CreateObject)->GetFunction());\n}\n\nNODE_MODULE(addon, InitAll)
    \n

    In myobject.h we now introduce the static method NewInstance that takes\ncare of instantiating the object (i.e. it does the job of new in JavaScript):\n\n

    \n
    #define BUILDING_NODE_EXTENSION\n#ifndef MYOBJECT_H\n#define MYOBJECT_H\n\n#include <node.h>\n\nclass MyObject : public node::ObjectWrap {\n public:\n  static void Init();\n  static v8::Handle<v8::Value> NewInstance(const v8::Arguments& args);\n\n private:\n  explicit MyObject(double value = 0);\n  ~MyObject();\n\n  static v8::Handle<v8::Value> New(const v8::Arguments& args);\n  static v8::Handle<v8::Value> PlusOne(const v8::Arguments& args);\n  static v8::Persistent<v8::Function> constructor;\n  double value_;\n};\n\n#endif
    \n

    The implementation is similar to the above in myobject.cc:\n\n

    \n
    #define BUILDING_NODE_EXTENSION\n#include <node.h>\n#include "myobject.h"\n\nusing namespace v8;\n\nPersistent<Function> MyObject::constructor;\n\nMyObject::MyObject(double value) : value_(value) {\n}\n\nMyObject::~MyObject() {\n}\n\nvoid MyObject::Init() {\n  // Prepare constructor template\n  Local<FunctionTemplate> tpl = FunctionTemplate::New(New);\n  tpl->SetClassName(String::NewSymbol("MyObject"));\n  tpl->InstanceTemplate()->SetInternalFieldCount(1);\n  // Prototype\n  tpl->PrototypeTemplate()->Set(String::NewSymbol("plusOne"),\n      FunctionTemplate::New(PlusOne)->GetFunction());\n  constructor = Persistent<Function>::New(tpl->GetFunction());\n}\n\nHandle<Value> MyObject::New(const Arguments& args) {\n  HandleScope scope;\n\n  if (args.IsConstructCall()) {\n    // Invoked as constructor: `new MyObject(...)`\n    double value = args[0]->IsUndefined() ? 0 : args[0]->NumberValue();\n    MyObject* obj = new MyObject(value);\n    obj->Wrap(args.This());\n    return args.This();\n  } else {\n    // Invoked as plain function `MyObject(...)`, turn into construct call.\n    const int argc = 1;\n    Local<Value> argv[argc] = { args[0] };\n    return scope.Close(constructor->NewInstance(argc, argv));\n  }\n}\n\nHandle<Value> MyObject::NewInstance(const Arguments& args) {\n  HandleScope scope;\n\n  const unsigned argc = 1;\n  Handle<Value> argv[argc] = { args[0] };\n  Local<Object> instance = constructor->NewInstance(argc, argv);\n\n  return scope.Close(instance);\n}\n\nHandle<Value> MyObject::PlusOne(const Arguments& args) {\n  HandleScope scope;\n\n  MyObject* obj = ObjectWrap::Unwrap<MyObject>(args.This());\n  obj->value_ += 1;\n\n  return scope.Close(Number::New(obj->value_));\n}
    \n

    Test it with:\n\n

    \n
    var createObject = require('./build/Release/addon');\n\nvar obj = createObject(10);\nconsole.log( obj.plusOne() ); // 11\nconsole.log( obj.plusOne() ); // 12\nconsole.log( obj.plusOne() ); // 13\n\nvar obj2 = createObject(20);\nconsole.log( obj2.plusOne() ); // 21\nconsole.log( obj2.plusOne() ); // 22\nconsole.log( obj2.plusOne() ); // 23
    \n", "type": "module", "displayName": "Factory of wrapped objects" }, { "textRaw": "Passing wrapped objects around", "name": "passing_wrapped_objects_around", "desc": "

    In addition to wrapping and returning C++ objects, you can pass them around\nby unwrapping them with Node's node::ObjectWrap::Unwrap helper function.\nIn the following addon.cc we introduce a function add() that can take on two\nMyObject objects:\n\n

    \n
    #define BUILDING_NODE_EXTENSION\n#include <node.h>\n#include "myobject.h"\n\nusing namespace v8;\n\nHandle<Value> CreateObject(const Arguments& args) {\n  HandleScope scope;\n  return scope.Close(MyObject::NewInstance(args));\n}\n\nHandle<Value> Add(const Arguments& args) {\n  HandleScope scope;\n\n  MyObject* obj1 = node::ObjectWrap::Unwrap<MyObject>(\n      args[0]->ToObject());\n  MyObject* obj2 = node::ObjectWrap::Unwrap<MyObject>(\n      args[1]->ToObject());\n\n  double sum = obj1->Value() + obj2->Value();\n  return scope.Close(Number::New(sum));\n}\n\nvoid InitAll(Handle<Object> exports) {\n  MyObject::Init();\n\n  exports->Set(String::NewSymbol("createObject"),\n      FunctionTemplate::New(CreateObject)->GetFunction());\n\n  exports->Set(String::NewSymbol("add"),\n      FunctionTemplate::New(Add)->GetFunction());\n}\n\nNODE_MODULE(addon, InitAll)
    \n

    To make things interesting we introduce a public method in myobject.h so we\ncan probe private values after unwrapping the object:\n\n

    \n
    #define BUILDING_NODE_EXTENSION\n#ifndef MYOBJECT_H\n#define MYOBJECT_H\n\n#include <node.h>\n\nclass MyObject : public node::ObjectWrap {\n public:\n  static void Init();\n  static v8::Handle<v8::Value> NewInstance(const v8::Arguments& args);\n  double Value() const { return value_; }\n\n private:\n  explicit MyObject(double value = 0);\n  ~MyObject();\n\n  static v8::Handle<v8::Value> New(const v8::Arguments& args);\n  static v8::Persistent<v8::Function> constructor;\n  double value_;\n};\n\n#endif
    \n

    The implementation of myobject.cc is similar as before:\n\n

    \n
    #define BUILDING_NODE_EXTENSION\n#include <node.h>\n#include "myobject.h"\n\nusing namespace v8;\n\nPersistent<Function> MyObject::constructor;\n\nMyObject::MyObject(double value) : value_(value) {\n}\n\nMyObject::~MyObject() {\n}\n\nvoid MyObject::Init() {\n  // Prepare constructor template\n  Local<FunctionTemplate> tpl = FunctionTemplate::New(New);\n  tpl->SetClassName(String::NewSymbol("MyObject"));\n  tpl->InstanceTemplate()->SetInternalFieldCount(1);\n  constructor = Persistent<Function>::New(tpl->GetFunction());\n}\n\nHandle<Value> MyObject::New(const Arguments& args) {\n  HandleScope scope;\n\n  if (args.IsConstructCall()) {\n    // Invoked as constructor: `new MyObject(...)`\n    double value = args[0]->IsUndefined() ? 0 : args[0]->NumberValue();\n    MyObject* obj = new MyObject(value);\n    obj->Wrap(args.This());\n    return args.This();\n  } else {\n    // Invoked as plain function `MyObject(...)`, turn into construct call.\n    const int argc = 1;\n    Local<Value> argv[argc] = { args[0] };\n    return scope.Close(constructor->NewInstance(argc, argv));\n  }\n}\n\nHandle<Value> MyObject::NewInstance(const Arguments& args) {\n  HandleScope scope;\n\n  const unsigned argc = 1;\n  Handle<Value> argv[argc] = { args[0] };\n  Local<Object> instance = constructor->NewInstance(argc, argv);\n\n  return scope.Close(instance);\n}
    \n

    Test it with:\n\n

    \n
    var addon = require('./build/Release/addon');\n\nvar obj1 = addon.createObject(10);\nvar obj2 = addon.createObject(20);\nvar result = addon.add(obj1, obj2);\n\nconsole.log(result); // 30
    \n", "type": "module", "displayName": "Passing wrapped objects around" } ], "type": "module", "displayName": "Addon patterns" } ], "type": "module", "displayName": "Addons" }, { "textRaw": "util", "name": "util", "stability": 4, "stabilityText": "API Frozen", "desc": "

    These functions are in the module 'util'. Use require('util') to access\nthem.\n\n\n

    \n", "methods": [ { "textRaw": "util.format(format, [...])", "type": "method", "name": "format", "desc": "

    Returns a formatted string using the first argument as a printf-like format.\n\n

    \n

    The first argument is a string that contains zero or more placeholders.\nEach placeholder is replaced with the converted value from its corresponding\nargument. Supported placeholders are:\n\n

    \n
      \n
    • %s - String.
    • \n
    • %d - Number (both integer and float).
    • \n
    • %j - JSON.
    • \n
    • % - single percent sign ('%'). This does not consume an argument.
    • \n
    \n

    If the placeholder does not have a corresponding argument, the placeholder is\nnot replaced.\n\n

    \n
    util.format('%s:%s', 'foo'); // 'foo:%s'
    \n

    If there are more arguments than placeholders, the extra arguments are\nconverted to strings with util.inspect() and these strings are concatenated,\ndelimited by a space.\n\n

    \n
    util.format('%s:%s', 'foo', 'bar', 'baz'); // 'foo:bar baz'
    \n

    If the first argument is not a format string then util.format() returns\na string that is the concatenation of all its arguments separated by spaces.\nEach argument is converted to a string with util.inspect().\n\n

    \n
    util.format(1, 2, 3); // '1 2 3'
    \n", "signatures": [ { "params": [ { "name": "format" }, { "name": "...", "optional": true } ] } ] }, { "textRaw": "util.debug(string)", "type": "method", "name": "debug", "desc": "

    A synchronous output function. Will block the process and\noutput string immediately to stderr.\n\n

    \n
    require('util').debug('message on stderr');
    \n", "signatures": [ { "params": [ { "name": "string" } ] } ] }, { "textRaw": "util.error([...])", "type": "method", "name": "error", "desc": "

    Same as util.debug() except this will output all arguments immediately to\nstderr.\n\n

    \n", "signatures": [ { "params": [ { "name": "...", "optional": true } ] } ] }, { "textRaw": "util.puts([...])", "type": "method", "name": "puts", "desc": "

    A synchronous output function. Will block the process and output all arguments\nto stdout with newlines after each argument.\n\n

    \n", "signatures": [ { "params": [ { "name": "...", "optional": true } ] } ] }, { "textRaw": "util.print([...])", "type": "method", "name": "print", "desc": "

    A synchronous output function. Will block the process, cast each argument to a\nstring then output to stdout. Does not place newlines after each argument.\n\n

    \n", "signatures": [ { "params": [ { "name": "...", "optional": true } ] } ] }, { "textRaw": "util.log(string)", "type": "method", "name": "log", "desc": "

    Output with timestamp on stdout.\n\n

    \n
    require('util').log('Timestamped message.');
    \n", "signatures": [ { "params": [ { "name": "string" } ] } ] }, { "textRaw": "util.inspect(object, [options])", "type": "method", "name": "inspect", "desc": "

    Return a string representation of object, which is useful for debugging.\n\n

    \n

    An optional options object may be passed that alters certain aspects of the\nformatted string:\n\n

    \n
      \n
    • showHidden - if true then the object's non-enumerable properties will be\nshown too. Defaults to false.

      \n
    • \n
    • depth - tells inspect how many times to recurse while formatting the\nobject. This is useful for inspecting large complicated objects. Defaults to\n2. To make it recurse indefinitely pass null.

      \n
    • \n
    • colors - if true, then the output will be styled with ANSI color codes.\nDefaults to false. Colors are customizable, see below.

      \n
    • \n
    • customInspect - if false, then custom inspect() functions defined on the\nobjects being inspected won't be called. Defaults to true.

      \n
    • \n
    \n

    Example of inspecting all properties of the util object:\n\n

    \n
    var util = require('util');\n\nconsole.log(util.inspect(util, { showHidden: true, depth: null }));
    \n", "modules": [ { "textRaw": "Customizing `util.inspect` colors", "name": "customizing_`util.inspect`_colors", "desc": "

    Color output (if enabled) of util.inspect is customizable globally\nvia util.inspect.styles and util.inspect.colors objects.\n\n

    \n

    util.inspect.styles is a map assigning each style a color\nfrom util.inspect.colors.\nHighlighted styles and their default values are:\n number (yellow)\n boolean (yellow)\n string (green)\n date (magenta)\n regexp (red)\n null (bold)\n undefined (grey)\n special - only function at this time (cyan)\n * name (intentionally no styling)\n\n

    \n

    Predefined color codes are: white, grey, black, blue, cyan, \ngreen, magenta, red and yellow.\nThere are also bold, italic, underline and inverse codes.\n\n

    \n

    Objects also may define their own inspect(depth) function which util.inspect()\nwill invoke and use the result of when inspecting the object:\n\n

    \n
    var util = require('util');\n\nvar obj = { name: 'nate' };\nobj.inspect = function(depth) {\n  return '{' + this.name + '}';\n};\n\nutil.inspect(obj);\n  // "{nate}"
    \n", "type": "module", "displayName": "Customizing `util.inspect` colors" } ], "signatures": [ { "params": [ { "name": "object" }, { "name": "options", "optional": true } ] } ] }, { "textRaw": "util.isArray(object)", "type": "method", "name": "isArray", "desc": "

    Returns true if the given "object" is an Array. false otherwise.\n\n

    \n
    var util = require('util');\n\nutil.isArray([])\n  // true\nutil.isArray(new Array)\n  // true\nutil.isArray({})\n  // false
    \n", "signatures": [ { "params": [ { "name": "object" } ] } ] }, { "textRaw": "util.isRegExp(object)", "type": "method", "name": "isRegExp", "desc": "

    Returns true if the given "object" is a RegExp. false otherwise.\n\n

    \n
    var util = require('util');\n\nutil.isRegExp(/some regexp/)\n  // true\nutil.isRegExp(new RegExp('another regexp'))\n  // true\nutil.isRegExp({})\n  // false
    \n", "signatures": [ { "params": [ { "name": "object" } ] } ] }, { "textRaw": "util.isDate(object)", "type": "method", "name": "isDate", "desc": "

    Returns true if the given "object" is a Date. false otherwise.\n\n

    \n
    var util = require('util');\n\nutil.isDate(new Date())\n  // true\nutil.isDate(Date())\n  // false (without 'new' returns a String)\nutil.isDate({})\n  // false
    \n", "signatures": [ { "params": [ { "name": "object" } ] } ] }, { "textRaw": "util.isError(object)", "type": "method", "name": "isError", "desc": "

    Returns true if the given "object" is an Error. false otherwise.\n\n

    \n
    var util = require('util');\n\nutil.isError(new Error())\n  // true\nutil.isError(new TypeError())\n  // true\nutil.isError({ name: 'Error', message: 'an error occurred' })\n  // false
    \n", "signatures": [ { "params": [ { "name": "object" } ] } ] }, { "textRaw": "util.pump(readableStream, writableStream, [callback])", "type": "method", "name": "pump", "stability": 0, "stabilityText": "Deprecated: Use readableStream.pipe(writableStream)", "desc": "

    Read the data from readableStream and send it to the writableStream.\nWhen writableStream.write(data) returns false readableStream will be\npaused until the drain event occurs on the writableStream. callback gets\nan error as its only argument and is called when writableStream is closed or\nwhen an error occurs.\n\n\n

    \n", "signatures": [ { "params": [ { "name": "readableStream" }, { "name": "writableStream" }, { "name": "callback", "optional": true } ] } ] }, { "textRaw": "util.inherits(constructor, superConstructor)", "type": "method", "name": "inherits", "desc": "

    Inherit the prototype methods from one\nconstructor\ninto another. The prototype of constructor will be set to a new\nobject created from superConstructor.\n\n

    \n

    As an additional convenience, superConstructor will be accessible\nthrough the constructor.super_ property.\n\n

    \n
    var util = require("util");\nvar events = require("events");\n\nfunction MyStream() {\n    events.EventEmitter.call(this);\n}\n\nutil.inherits(MyStream, events.EventEmitter);\n\nMyStream.prototype.write = function(data) {\n    this.emit("data", data);\n}\n\nvar stream = new MyStream();\n\nconsole.log(stream instanceof events.EventEmitter); // true\nconsole.log(MyStream.super_ === events.EventEmitter); // true\n\nstream.on("data", function(data) {\n    console.log('Received data: "' + data + '"');\n})\nstream.write("It works!"); // Received data: "It works!"
    \n", "signatures": [ { "params": [ { "name": "constructor" }, { "name": "superConstructor" } ] } ] } ], "type": "module", "displayName": "util" }, { "textRaw": "Events", "name": "Events", "stability": 4, "stabilityText": "API Frozen", "type": "module", "desc": "

    Many objects in Node emit events: a net.Server emits an event each time\na peer connects to it, a fs.readStream emits an event when the file is\nopened. All objects which emit events are instances of events.EventEmitter.\nYou can access this module by doing: require("events");\n\n

    \n

    Typically, event names are represented by a camel-cased string, however,\nthere aren't any strict restrictions on that, as any string will be accepted.\n\n

    \n

    Functions can then be attached to objects, to be executed when an event\nis emitted. These functions are called listeners. Inside a listener\nfunction, this refers to the EventEmitter that the listener was\nattached to.\n\n\n

    \n", "classes": [ { "textRaw": "Class: events.EventEmitter", "type": "class", "name": "events.EventEmitter", "desc": "

    To access the EventEmitter class, require('events').EventEmitter.\n\n

    \n

    When an EventEmitter instance experiences an error, the typical action is\nto emit an 'error' event. Error events are treated as a special case in node.\nIf there is no listener for it, then the default action is to print a stack\ntrace and exit the program.\n\n

    \n

    All EventEmitters emit the event 'newListener' when new listeners are\nadded and 'removeListener' when a listener is removed.\n\n

    \n", "methods": [ { "textRaw": "emitter.addListener(event, listener)", "type": "method", "name": "addListener", "desc": "

    Adds a listener to the end of the listeners array for the specified event.\n\n

    \n
    server.on('connection', function (stream) {\n  console.log('someone connected!');\n});
    \n

    Returns emitter, so calls can be chained.\n\n

    \n", "signatures": [ { "params": [ { "name": "event" }, { "name": "listener" } ] }, { "params": [ { "name": "event" }, { "name": "listener" } ] } ] }, { "textRaw": "emitter.on(event, listener)", "type": "method", "name": "on", "desc": "

    Adds a listener to the end of the listeners array for the specified event.\n\n

    \n
    server.on('connection', function (stream) {\n  console.log('someone connected!');\n});
    \n

    Returns emitter, so calls can be chained.\n\n

    \n", "signatures": [ { "params": [ { "name": "event" }, { "name": "listener" } ] } ] }, { "textRaw": "emitter.once(event, listener)", "type": "method", "name": "once", "desc": "

    Adds a one time listener for the event. This listener is\ninvoked only the next time the event is fired, after which\nit is removed.\n\n

    \n
    server.once('connection', function (stream) {\n  console.log('Ah, we have our first user!');\n});
    \n

    Returns emitter, so calls can be chained.\n\n

    \n", "signatures": [ { "params": [ { "name": "event" }, { "name": "listener" } ] } ] }, { "textRaw": "emitter.removeListener(event, listener)", "type": "method", "name": "removeListener", "desc": "

    Remove a listener from the listener array for the specified event.\nCaution: changes array indices in the listener array behind the listener.\n\n

    \n
    var callback = function(stream) {\n  console.log('someone connected!');\n};\nserver.on('connection', callback);\n// ...\nserver.removeListener('connection', callback);
    \n

    Returns emitter, so calls can be chained.\n\n

    \n", "signatures": [ { "params": [ { "name": "event" }, { "name": "listener" } ] } ] }, { "textRaw": "emitter.removeAllListeners([event])", "type": "method", "name": "removeAllListeners", "desc": "

    Removes all listeners, or those of the specified event.\n\n

    \n

    Returns emitter, so calls can be chained.\n\n

    \n", "signatures": [ { "params": [ { "name": "event", "optional": true } ] } ] }, { "textRaw": "emitter.setMaxListeners(n)", "type": "method", "name": "setMaxListeners", "desc": "

    By default EventEmitters will print a warning if more than 10 listeners are\nadded for a particular event. This is a useful default which helps finding memory leaks.\nObviously not all Emitters should be limited to 10. This function allows\nthat to be increased. Set to zero for unlimited.\n\n\n

    \n", "signatures": [ { "params": [ { "name": "n" } ] } ] }, { "textRaw": "emitter.listeners(event)", "type": "method", "name": "listeners", "desc": "

    Returns an array of listeners for the specified event.\n\n

    \n
    server.on('connection', function (stream) {\n  console.log('someone connected!');\n});\nconsole.log(util.inspect(server.listeners('connection'))); // [ [Function] ]
    \n", "signatures": [ { "params": [ { "name": "event" } ] } ] }, { "textRaw": "emitter.emit(event, [arg1], [arg2], [...])", "type": "method", "name": "emit", "desc": "

    Execute each of the listeners in order with the supplied arguments.\n\n

    \n

    Returns true if event had listeners, false otherwise.\n\n\n

    \n", "signatures": [ { "params": [ { "name": "event" }, { "name": "arg1", "optional": true }, { "name": "arg2", "optional": true }, { "name": "...", "optional": true } ] } ] } ], "classMethods": [ { "textRaw": "Class Method: EventEmitter.listenerCount(emitter, event)", "type": "classMethod", "name": "listenerCount", "desc": "

    Return the number of listeners for a given event.\n\n\n

    \n", "signatures": [ { "params": [ { "name": "emitter" }, { "name": "event" } ] } ] } ], "events": [ { "textRaw": "Event: 'newListener'", "type": "event", "name": "newListener", "params": [], "desc": "

    This event is emitted any time someone adds a new listener. It is unspecified\nif listener is in the list returned by emitter.listeners(event).\n\n\n

    \n" }, { "textRaw": "Event: 'removeListener'", "type": "event", "name": "removeListener", "params": [], "desc": "

    This event is emitted any time someone removes a listener. It is unspecified\nif listener is in the list returned by emitter.listeners(event).\n\n

    \n" } ] } ] }, { "textRaw": "Domain", "name": "domain", "stability": 2, "stabilityText": "Unstable", "desc": "

    Domains provide a way to handle multiple different IO operations as a\nsingle group. If any of the event emitters or callbacks registered to a\ndomain emit an error event, or throw an error, then the domain object\nwill be notified, rather than losing the context of the error in the\nprocess.on('uncaughtException') handler, or causing the program to\nexit immediately with an error code.\n\n

    \n", "miscs": [ { "textRaw": "Warning: Don't Ignore Errors!", "name": "Warning: Don't Ignore Errors!", "type": "misc", "desc": "

    Domain error handlers are not a substitute for closing down your\nprocess when an error occurs.\n\n

    \n

    By the very nature of how throw works in JavaScript, there is almost\nnever any way to safely "pick up where you left off", without leaking\nreferences, or creating some other sort of undefined brittle state.\n\n

    \n

    The safest way to respond to a thrown error is to shut down the\nprocess. Of course, in a normal web server, you might have many\nconnections open, and it is not reasonable to abruptly shut those down\nbecause an error was triggered by someone else.\n\n

    \n

    The better approach is send an error response to the request that\ntriggered the error, while letting the others finish in their normal\ntime, and stop listening for new requests in that worker.\n\n

    \n

    In this way, domain usage goes hand-in-hand with the cluster module,\nsince the master process can fork a new worker when a worker\nencounters an error. For node programs that scale to multiple\nmachines, the terminating proxy or service registry can take note of\nthe failure, and react accordingly.\n\n

    \n

    For example, this is not a good idea:\n\n

    \n
    // XXX WARNING!  BAD IDEA!\n\nvar d = require('domain').create();\nd.on('error', function(er) {\n  // The error won't crash the process, but what it does is worse!\n  // Though we've prevented abrupt process restarting, we are leaking\n  // resources like crazy if this ever happens.\n  // This is no better than process.on('uncaughtException')!\n  console.log('error, but oh well', er.message);\n});\nd.run(function() {\n  require('http').createServer(function(req, res) {\n    handleRequest(req, res);\n  }).listen(PORT);\n});
    \n

    By using the context of a domain, and the resilience of separating our\nprogram into multiple worker processes, we can react more\nappropriately, and handle errors with much greater safety.\n\n

    \n
    // Much better!\n\nvar cluster = require('cluster');\nvar PORT = +process.env.PORT || 1337;\n\nif (cluster.isMaster) {\n  // In real life, you'd probably use more than just 2 workers,\n  // and perhaps not put the master and worker in the same file.\n  //\n  // You can also of course get a bit fancier about logging, and\n  // implement whatever custom logic you need to prevent DoS\n  // attacks and other bad behavior.\n  //\n  // See the options in the cluster documentation.\n  //\n  // The important thing is that the master does very little,\n  // increasing our resilience to unexpected errors.\n\n  cluster.fork();\n  cluster.fork();\n\n  cluster.on('disconnect', function(worker) {\n    console.error('disconnect!');\n    cluster.fork();\n  });\n\n} else {\n  // the worker\n  //\n  // This is where we put our bugs!\n\n  var domain = require('domain');\n\n  // See the cluster documentation for more details about using\n  // worker processes to serve requests.  How it works, caveats, etc.\n\n  var server = require('http').createServer(function(req, res) {\n    var d = domain.create();\n    d.on('error', function(er) {\n      console.error('error', er.stack);\n\n      // Note: we're in dangerous territory!\n      // By definition, something unexpected occurred,\n      // which we probably didn't want.\n      // Anything can happen now!  Be very careful!\n\n      try {\n        // make sure we close down within 30 seconds\n        var killtimer = setTimeout(function() {\n          process.exit(1);\n        }, 30000);\n        // But don't keep the process open just for that!\n        killtimer.unref();\n\n        // stop taking new requests.\n        server.close();\n\n        // Let the master know we're dead.  This will trigger a\n        // 'disconnect' in the cluster master, and then it will fork\n        // a new worker.\n        cluster.worker.disconnect();\n\n        // try to send an error to the request that triggered the problem\n        res.statusCode = 500;\n        res.setHeader('content-type', 'text/plain');\n        res.end('Oops, there was a problem!\\n');\n      } catch (er2) {\n        // oh well, not much we can do at this point.\n        console.error('Error sending 500!', er2.stack);\n      }\n    });\n\n    // Because req and res were created before this domain existed,\n    // we need to explicitly add them.\n    // See the explanation of implicit vs explicit binding below.\n    d.add(req);\n    d.add(res);\n\n    // Now run the handler function in the domain.\n    d.run(function() {\n      handleRequest(req, res);\n    });\n  });\n  server.listen(PORT);\n}\n\n// This part isn't important.  Just an example routing thing.\n// You'd put your fancy application logic here.\nfunction handleRequest(req, res) {\n  switch(req.url) {\n    case '/error':\n      // We do some async stuff, and then...\n      setTimeout(function() {\n        // Whoops!\n        flerb.bark();\n      });\n      break;\n    default:\n      res.end('ok');\n  }\n}
    \n" }, { "textRaw": "Additions to Error objects", "name": "Additions to Error objects", "type": "misc", "desc": "

    Any time an Error object is routed through a domain, a few extra fields\nare added to it.\n\n

    \n
      \n
    • error.domain The domain that first handled the error.
    • \n
    • error.domainEmitter The event emitter that emitted an 'error' event\nwith the error object.
    • \n
    • error.domainBound The callback function which was bound to the\ndomain, and passed an error as its first argument.
    • \n
    • error.domainThrown A boolean indicating whether the error was\nthrown, emitted, or passed to a bound callback function.
    • \n
    \n" }, { "textRaw": "Implicit Binding", "name": "Implicit Binding", "type": "misc", "desc": "

    If domains are in use, then all new EventEmitter objects (including\nStream objects, requests, responses, etc.) will be implicitly bound to\nthe active domain at the time of their creation.\n\n

    \n

    Additionally, callbacks passed to lowlevel event loop requests (such as\nto fs.open, or other callback-taking methods) will automatically be\nbound to the active domain. If they throw, then the domain will catch\nthe error.\n\n

    \n

    In order to prevent excessive memory usage, Domain objects themselves\nare not implicitly added as children of the active domain. If they\nwere, then it would be too easy to prevent request and response objects\nfrom being properly garbage collected.\n\n

    \n

    If you want to nest Domain objects as children of a parent Domain,\nthen you must explicitly add them.\n\n

    \n

    Implicit binding routes thrown errors and 'error' events to the\nDomain's error event, but does not register the EventEmitter on the\nDomain, so domain.dispose() will not shut down the EventEmitter.\nImplicit binding only takes care of thrown errors and 'error' events.\n\n

    \n" }, { "textRaw": "Explicit Binding", "name": "Explicit Binding", "type": "misc", "desc": "

    Sometimes, the domain in use is not the one that ought to be used for a\nspecific event emitter. Or, the event emitter could have been created\nin the context of one domain, but ought to instead be bound to some\nother domain.\n\n

    \n

    For example, there could be one domain in use for an HTTP server, but\nperhaps we would like to have a separate domain to use for each request.\n\n

    \n

    That is possible via explicit binding.\n\n

    \n

    For example:\n\n

    \n
    // create a top-level domain for the server\nvar serverDomain = domain.create();\n\nserverDomain.run(function() {\n  // server is created in the scope of serverDomain\n  http.createServer(function(req, res) {\n    // req and res are also created in the scope of serverDomain\n    // however, we'd prefer to have a separate domain for each request.\n    // create it first thing, and add req and res to it.\n    var reqd = domain.create();\n    reqd.add(req);\n    reqd.add(res);\n    reqd.on('error', function(er) {\n      console.error('Error', er, req.url);\n      try {\n        res.writeHead(500);\n        res.end('Error occurred, sorry.');\n      } catch (er) {\n        console.error('Error sending 500', er, req.url);\n      }\n    });\n  }).listen(1337);\n});
    \n" } ], "methods": [ { "textRaw": "domain.create()", "type": "method", "name": "create", "signatures": [ { "return": { "textRaw": "return: {Domain} ", "name": "return", "type": "Domain" }, "params": [] }, { "params": [] } ], "desc": "

    Returns a new Domain object.\n\n

    \n" } ], "classes": [ { "textRaw": "Class: Domain", "type": "class", "name": "Domain", "desc": "

    The Domain class encapsulates the functionality of routing errors and\nuncaught exceptions to the active Domain object.\n\n

    \n

    Domain is a child class of [EventEmitter][]. To handle the errors that it\ncatches, listen to its error event.\n\n

    \n", "methods": [ { "textRaw": "domain.run(fn)", "type": "method", "name": "run", "signatures": [ { "params": [ { "textRaw": "`fn` {Function} ", "name": "fn", "type": "Function" } ] }, { "params": [ { "name": "fn" } ] } ], "desc": "

    Run the supplied function in the context of the domain, implicitly\nbinding all event emitters, timers, and lowlevel requests that are\ncreated in that context.\n\n

    \n

    This is the most basic way to use a domain.\n\n

    \n

    Example:\n\n

    \n
    var d = domain.create();\nd.on('error', function(er) {\n  console.error('Caught error!', er);\n});\nd.run(function() {\n  process.nextTick(function() {\n    setTimeout(function() { // simulating some various async stuff\n      fs.open('non-existent file', 'r', function(er, fd) {\n        if (er) throw er;\n        // proceed...\n      });\n    }, 100);\n  });\n});
    \n

    In this example, the d.on('error') handler will be triggered, rather\nthan crashing the program.\n\n

    \n" }, { "textRaw": "domain.add(emitter)", "type": "method", "name": "add", "signatures": [ { "params": [ { "textRaw": "`emitter` {EventEmitter | Timer} emitter or timer to be added to the domain ", "name": "emitter", "type": "EventEmitter | Timer", "desc": "emitter or timer to be added to the domain" } ] }, { "params": [ { "name": "emitter" } ] } ], "desc": "

    Explicitly adds an emitter to the domain. If any event handlers called by\nthe emitter throw an error, or if the emitter emits an error event, it\nwill be routed to the domain's error event, just like with implicit\nbinding.\n\n

    \n

    This also works with timers that are returned from setInterval and\nsetTimeout. If their callback function throws, it will be caught by\nthe domain 'error' handler.\n\n

    \n

    If the Timer or EventEmitter was already bound to a domain, it is removed\nfrom that one, and bound to this one instead.\n\n

    \n" }, { "textRaw": "domain.remove(emitter)", "type": "method", "name": "remove", "signatures": [ { "params": [ { "textRaw": "`emitter` {EventEmitter | Timer} emitter or timer to be removed from the domain ", "name": "emitter", "type": "EventEmitter | Timer", "desc": "emitter or timer to be removed from the domain" } ] }, { "params": [ { "name": "emitter" } ] } ], "desc": "

    The opposite of domain.add(emitter). Removes domain handling from the\nspecified emitter.\n\n

    \n" }, { "textRaw": "domain.bind(callback)", "type": "method", "name": "bind", "signatures": [ { "return": { "textRaw": "return: {Function} The bound function ", "name": "return", "type": "Function", "desc": "The bound function" }, "params": [ { "textRaw": "`callback` {Function} The callback function ", "name": "callback", "type": "Function", "desc": "The callback function" } ] }, { "params": [ { "name": "callback" } ] } ], "desc": "

    The returned function will be a wrapper around the supplied callback\nfunction. When the returned function is called, any errors that are\nthrown will be routed to the domain's error event.\n\n

    \n

    Example

    \n
    var d = domain.create();\n\nfunction readSomeFile(filename, cb) {\n  fs.readFile(filename, 'utf8', d.bind(function(er, data) {\n    // if this throws, it will also be passed to the domain\n    return cb(er, data ? JSON.parse(data) : null);\n  }));\n}\n\nd.on('error', function(er) {\n  // an error occurred somewhere.\n  // if we throw it now, it will crash the program\n  // with the normal line number and stack message.\n});
    \n" }, { "textRaw": "domain.intercept(callback)", "type": "method", "name": "intercept", "signatures": [ { "return": { "textRaw": "return: {Function} The intercepted function ", "name": "return", "type": "Function", "desc": "The intercepted function" }, "params": [ { "textRaw": "`callback` {Function} The callback function ", "name": "callback", "type": "Function", "desc": "The callback function" } ] }, { "params": [ { "name": "callback" } ] } ], "desc": "

    This method is almost identical to domain.bind(callback). However, in\naddition to catching thrown errors, it will also intercept Error\nobjects sent as the first argument to the function.\n\n

    \n

    In this way, the common if (er) return callback(er); pattern can be replaced\nwith a single error handler in a single place.\n\n

    \n

    Example

    \n
    var d = domain.create();\n\nfunction readSomeFile(filename, cb) {\n  fs.readFile(filename, 'utf8', d.intercept(function(data) {\n    // note, the first argument is never passed to the\n    // callback since it is assumed to be the 'Error' argument\n    // and thus intercepted by the domain.\n\n    // if this throws, it will also be passed to the domain\n    // so the error-handling logic can be moved to the 'error'\n    // event on the domain instead of being repeated throughout\n    // the program.\n    return cb(null, JSON.parse(data));\n  }));\n}\n\nd.on('error', function(er) {\n  // an error occurred somewhere.\n  // if we throw it now, it will crash the program\n  // with the normal line number and stack message.\n});
    \n" }, { "textRaw": "domain.enter()", "type": "method", "name": "enter", "desc": "

    The enter method is plumbing used by the run, bind, and intercept\nmethods to set the active domain. It sets domain.active and process.domain\nto the domain, and implicitly pushes the domain onto the domain stack managed\nby the domain module (see domain.exit() for details on the domain stack). The\ncall to enter delimits the beginning of a chain of asynchronous calls and I/O\noperations bound to a domain.\n\n

    \n

    Calling enter changes only the active domain, and does not alter the domain\nitself. Enter and exit can be called an arbitrary number of times on a\nsingle domain.\n\n

    \n

    If the domain on which enter is called has been disposed, enter will return\nwithout setting the domain.\n\n

    \n", "signatures": [ { "params": [] } ] }, { "textRaw": "domain.exit()", "type": "method", "name": "exit", "desc": "

    The exit method exits the current domain, popping it off the domain stack.\nAny time execution is going to switch to the context of a different chain of\nasynchronous calls, it's important to ensure that the current domain is exited.\nThe call to exit delimits either the end of or an interruption to the chain\nof asynchronous calls and I/O operations bound to a domain.\n\n

    \n

    If there are multiple, nested domains bound to the current execution context,\nexit will exit any domains nested within this domain.\n\n

    \n

    Calling exit changes only the active domain, and does not alter the domain\nitself. Enter and exit can be called an arbitrary number of times on a\nsingle domain.\n\n

    \n

    If the domain on which exit is called has been disposed, exit will return\nwithout exiting the domain.\n\n

    \n", "signatures": [ { "params": [] } ] }, { "textRaw": "domain.dispose()", "type": "method", "name": "dispose", "desc": "

    The dispose method destroys a domain, and makes a best effort attempt to\nclean up any and all IO that is associated with the domain. Streams are\naborted, ended, closed, and/or destroyed. Timers are cleared.\nExplicitly bound callbacks are no longer called. Any error events that\nare raised as a result of this are ignored.\n\n

    \n

    The intention of calling dispose is generally to prevent cascading\nerrors when a critical part of the Domain context is found to be in an\nerror state.\n\n

    \n

    Once the domain is disposed the dispose event will emit.\n\n

    \n

    Note that IO might still be performed. However, to the highest degree\npossible, once a domain is disposed, further errors from the emitters in\nthat set will be ignored. So, even if some remaining actions are still\nin flight, Node.js will not communicate further about them.\n\n

    \n", "signatures": [ { "params": [] } ] } ], "properties": [ { "textRaw": "`members` {Array} ", "name": "members", "desc": "

    An array of timers and event emitters that have been explicitly added\nto the domain.\n\n

    \n" } ] } ], "type": "module", "displayName": "Domain" }, { "textRaw": "Buffer", "name": "buffer", "stability": 3, "stabilityText": "Stable", "desc": "

    Pure JavaScript is Unicode friendly but not nice to binary data. When\ndealing with TCP streams or the file system, it's necessary to handle octet\nstreams. Node has several strategies for manipulating, creating, and\nconsuming octet streams.\n\n

    \n

    Raw data is stored in instances of the Buffer class. A Buffer is similar\nto an array of integers but corresponds to a raw memory allocation outside\nthe V8 heap. A Buffer cannot be resized.\n\n

    \n

    The Buffer class is a global, making it very rare that one would need\nto ever require('buffer').\n\n

    \n

    Converting between Buffers and JavaScript string objects requires an explicit\nencoding method. Here are the different string encodings.\n\n

    \n
      \n
    • 'ascii' - for 7 bit ASCII data only. This encoding method is very fast, and\nwill strip the high bit if set.

      \n

      Note that when converting from string to buffer, this encoding converts a null\ncharacter ('\\0' or '\\u0000') into 0x20 (character code of a space). If\nyou want to convert a null character into 0x00, you should use 'utf8'.

      \n
    • \n
    • 'utf8' - Multibyte encoded Unicode characters. Many web pages and other\ndocument formats use UTF-8.

      \n
    • \n
    • 'utf16le' - 2 or 4 bytes, little endian encoded Unicode characters.\nSurrogate pairs (U+10000 to U+10FFFF) are supported.

      \n
    • \n
    • 'ucs2' - Alias of 'utf16le'.

      \n
    • \n
    • 'base64' - Base64 string encoding.

      \n
    • \n
    • 'binary' - A way of encoding raw binary data into strings by using only\nthe first 8 bits of each character. This encoding method is deprecated and\nshould be avoided in favor of Buffer objects where possible. This encoding\nwill be removed in future versions of Node.

      \n
    • \n
    • 'hex' - Encode each byte as two hexadecimal characters.

      \n
    • \n
    \n

    A Buffer object can also be used with typed arrays. The buffer object is\ncloned to an ArrayBuffer that is used as the backing store for the typed\narray. The memory of the buffer and the ArrayBuffer is not shared.\n\n

    \n

    NOTE: Node.js v0.8 simply retained a reference to the buffer in array.buffer\ninstead of cloning it.\n\n

    \n

    While more efficient, it introduces subtle incompatibilities with the typed\narrays specification. ArrayBuffer#slice() makes a copy of the slice while\nBuffer#slice() creates a view.\n\n

    \n", "classes": [ { "textRaw": "Class: Buffer", "type": "class", "name": "Buffer", "desc": "

    The Buffer class is a global type for dealing with binary data directly.\nIt can be constructed in a variety of ways.\n\n

    \n", "classMethods": [ { "textRaw": "Class Method: Buffer.isEncoding(encoding)", "type": "classMethod", "name": "isEncoding", "signatures": [ { "params": [ { "textRaw": "`encoding` {String} The encoding string to test ", "name": "encoding", "type": "String", "desc": "The encoding string to test" } ] }, { "params": [ { "name": "encoding" } ] } ], "desc": "

    Returns true if the encoding is a valid encoding argument, or false\notherwise.\n\n

    \n" }, { "textRaw": "Class Method: Buffer.isBuffer(obj)", "type": "classMethod", "name": "isBuffer", "signatures": [ { "return": { "textRaw": "Return: Boolean ", "name": "return", "desc": "Boolean" }, "params": [ { "textRaw": "`obj` Object ", "name": "obj", "desc": "Object" } ] }, { "params": [ { "name": "obj" } ] } ], "desc": "

    Tests if obj is a Buffer.\n\n

    \n" }, { "textRaw": "Class Method: Buffer.byteLength(string, [encoding])", "type": "classMethod", "name": "byteLength", "signatures": [ { "return": { "textRaw": "Return: Number ", "name": "return", "desc": "Number" }, "params": [ { "textRaw": "`string` String ", "name": "string", "desc": "String" }, { "textRaw": "`encoding` String, Optional, Default: 'utf8' ", "name": "encoding", "desc": "String, Optional, Default: 'utf8'", "optional": true } ] }, { "params": [ { "name": "string" }, { "name": "encoding", "optional": true } ] } ], "desc": "

    Gives the actual byte length of a string. encoding defaults to 'utf8'.\nThis is not the same as String.prototype.length since that returns the\nnumber of characters in a string.\n\n

    \n

    Example:\n\n

    \n
    str = '\\u00bd + \\u00bc = \\u00be';\n\nconsole.log(str + ": " + str.length + " characters, " +\n  Buffer.byteLength(str, 'utf8') + " bytes");\n\n// ½ + ¼ = ¾: 9 characters, 12 bytes
    \n" }, { "textRaw": "Class Method: Buffer.concat(list, [totalLength])", "type": "classMethod", "name": "concat", "signatures": [ { "params": [ { "textRaw": "`list` {Array} List of Buffer objects to concat ", "name": "list", "type": "Array", "desc": "List of Buffer objects to concat" }, { "textRaw": "`totalLength` {Number} Total length of the buffers when concatenated ", "name": "totalLength", "type": "Number", "desc": "Total length of the buffers when concatenated", "optional": true } ] }, { "params": [ { "name": "list" }, { "name": "totalLength", "optional": true } ] } ], "desc": "

    Returns a buffer which is the result of concatenating all the buffers in\nthe list together.\n\n

    \n

    If the list has no items, or if the totalLength is 0, then it returns a\nzero-length buffer.\n\n

    \n

    If the list has exactly one item, then the first item of the list is\nreturned.\n\n

    \n

    If the list has more than one item, then a new Buffer is created.\n\n

    \n

    If totalLength is not provided, it is read from the buffers in the list.\nHowever, this adds an additional loop to the function, so it is faster\nto provide the length explicitly.\n\n

    \n" } ], "methods": [ { "textRaw": "buf.write(string, [offset], [length], [encoding])", "type": "method", "name": "write", "signatures": [ { "params": [ { "textRaw": "`string` String - data to be written to buffer ", "name": "string", "desc": "String - data to be written to buffer" }, { "textRaw": "`offset` Number, Optional, Default: 0 ", "name": "offset", "desc": "Number, Optional, Default: 0", "optional": true }, { "textRaw": "`length` Number, Optional, Default: `buffer.length - offset` ", "name": "length", "desc": "Number, Optional, Default: `buffer.length - offset`", "optional": true }, { "textRaw": "`encoding` String, Optional, Default: 'utf8' ", "name": "encoding", "desc": "String, Optional, Default: 'utf8'", "optional": true } ] }, { "params": [ { "name": "string" }, { "name": "offset", "optional": true }, { "name": "length", "optional": true }, { "name": "encoding", "optional": true } ] } ], "desc": "

    Writes string to the buffer at offset using the given encoding.\noffset defaults to 0, encoding defaults to 'utf8'. length is\nthe number of bytes to write. Returns number of octets written. If buffer did\nnot contain enough space to fit the entire string, it will write a partial\namount of the string. length defaults to buffer.length - offset.\nThe method will not write partial characters.\n\n

    \n
    buf = new Buffer(256);\nlen = buf.write('\\u00bd + \\u00bc = \\u00be', 0);\nconsole.log(len + " bytes: " + buf.toString('utf8', 0, len));
    \n

    The number of characters written (which may be different than the number of\nbytes written) is set in Buffer._charsWritten and will be overwritten the\nnext time buf.write() is called.\n\n\n

    \n" }, { "textRaw": "buf.toString([encoding], [start], [end])", "type": "method", "name": "toString", "signatures": [ { "params": [ { "textRaw": "`encoding` String, Optional, Default: 'utf8' ", "name": "encoding", "desc": "String, Optional, Default: 'utf8'", "optional": true }, { "textRaw": "`start` Number, Optional, Default: 0 ", "name": "start", "desc": "Number, Optional, Default: 0", "optional": true }, { "textRaw": "`end` Number, Optional, Default: `buffer.length` ", "name": "end", "desc": "Number, Optional, Default: `buffer.length`", "optional": true } ] }, { "params": [ { "name": "encoding", "optional": true }, { "name": "start", "optional": true }, { "name": "end", "optional": true } ] } ], "desc": "

    Decodes and returns a string from buffer data encoded with encoding\n(defaults to 'utf8') beginning at start (defaults to 0) and ending at\nend (defaults to buffer.length).\n\n

    \n

    See buffer.write() example, above.\n\n\n

    \n" }, { "textRaw": "buf.toJSON()", "type": "method", "name": "toJSON", "desc": "

    Returns a JSON-representation of the Buffer instance, which is identical to the\noutput for JSON Arrays. JSON.stringify implicitly calls this function when\nstringifying a Buffer instance.\n\n

    \n

    Example:\n\n

    \n
    var buf = new Buffer('test');\nvar json = JSON.stringify(buf);\n\nconsole.log(json);\n// '[116,101,115,116]'\n\nvar copy = new Buffer(JSON.parse(json));\n\nconsole.log(copy);\n// <Buffer 74 65 73 74>
    \n", "signatures": [ { "params": [] } ] }, { "textRaw": "buf.copy(targetBuffer, [targetStart], [sourceStart], [sourceEnd])", "type": "method", "name": "copy", "signatures": [ { "params": [ { "textRaw": "`targetBuffer` Buffer object - Buffer to copy into ", "name": "targetBuffer", "desc": "Buffer object - Buffer to copy into" }, { "textRaw": "`targetStart` Number, Optional, Default: 0 ", "name": "targetStart", "desc": "Number, Optional, Default: 0", "optional": true }, { "textRaw": "`sourceStart` Number, Optional, Default: 0 ", "name": "sourceStart", "desc": "Number, Optional, Default: 0", "optional": true }, { "textRaw": "`sourceEnd` Number, Optional, Default: `buffer.length` ", "name": "sourceEnd", "desc": "Number, Optional, Default: `buffer.length`", "optional": true } ] }, { "params": [ { "name": "targetBuffer" }, { "name": "targetStart", "optional": true }, { "name": "sourceStart", "optional": true }, { "name": "sourceEnd", "optional": true } ] } ], "desc": "

    Does copy between buffers. The source and target regions can be overlapped.\ntargetStart and sourceStart default to 0.\nsourceEnd defaults to buffer.length.\n\n

    \n

    All values passed that are undefined/NaN or are out of bounds are set equal\nto their respective defaults.\n\n

    \n

    Example: build two Buffers, then copy buf1 from byte 16 through byte 19\ninto buf2, starting at the 8th byte in buf2.\n\n

    \n
    buf1 = new Buffer(26);\nbuf2 = new Buffer(26);\n\nfor (var i = 0 ; i < 26 ; i++) {\n  buf1[i] = i + 97; // 97 is ASCII a\n  buf2[i] = 33; // ASCII !\n}\n\nbuf1.copy(buf2, 8, 16, 20);\nconsole.log(buf2.toString('ascii', 0, 25));\n\n// !!!!!!!!qrst!!!!!!!!!!!!!
    \n" }, { "textRaw": "buf.slice([start], [end])", "type": "method", "name": "slice", "signatures": [ { "params": [ { "textRaw": "`start` Number, Optional, Default: 0 ", "name": "start", "desc": "Number, Optional, Default: 0", "optional": true }, { "textRaw": "`end` Number, Optional, Default: `buffer.length` ", "name": "end", "desc": "Number, Optional, Default: `buffer.length`", "optional": true } ] }, { "params": [ { "name": "start", "optional": true }, { "name": "end", "optional": true } ] } ], "desc": "

    Returns a new buffer which references the same memory as the old, but offset\nand cropped by the start (defaults to 0) and end (defaults to\nbuffer.length) indexes. Negative indexes start from the end of the buffer.\n\n

    \n

    Modifying the new buffer slice will modify memory in the original buffer!\n\n

    \n

    Example: build a Buffer with the ASCII alphabet, take a slice, then modify one\nbyte from the original Buffer.\n\n

    \n
    var buf1 = new Buffer(26);\n\nfor (var i = 0 ; i < 26 ; i++) {\n  buf1[i] = i + 97; // 97 is ASCII a\n}\n\nvar buf2 = buf1.slice(0, 3);\nconsole.log(buf2.toString('ascii', 0, buf2.length));\nbuf1[0] = 33;\nconsole.log(buf2.toString('ascii', 0, buf2.length));\n\n// abc\n// !bc
    \n" }, { "textRaw": "buf.readUInt8(offset, [noAssert])", "type": "method", "name": "readUInt8", "signatures": [ { "return": { "textRaw": "Return: Number ", "name": "return", "desc": "Number" }, "params": [ { "textRaw": "`offset` Number ", "name": "offset", "desc": "Number" }, { "textRaw": "`noAssert` Boolean, Optional, Default: false ", "name": "noAssert", "desc": "Boolean, Optional, Default: false", "optional": true } ] }, { "params": [ { "name": "offset" }, { "name": "noAssert", "optional": true } ] } ], "desc": "

    Reads an unsigned 8 bit integer from the buffer at the specified offset.\n\n

    \n

    Set noAssert to true to skip validation of offset. This means that offset\nmay be beyond the end of the buffer. Defaults to false.\n\n

    \n

    Example:\n\n

    \n
    var buf = new Buffer(4);\n\nbuf[0] = 0x3;\nbuf[1] = 0x4;\nbuf[2] = 0x23;\nbuf[3] = 0x42;\n\nfor (ii = 0; ii < buf.length; ii++) {\n  console.log(buf.readUInt8(ii));\n}\n\n// 0x3\n// 0x4\n// 0x23\n// 0x42
    \n" }, { "textRaw": "buf.readUInt16LE(offset, [noAssert])", "type": "method", "name": "readUInt16LE", "signatures": [ { "return": { "textRaw": "Return: Number ", "name": "return", "desc": "Number" }, "params": [ { "textRaw": "`offset` Number ", "name": "offset", "desc": "Number" }, { "textRaw": "`noAssert` Boolean, Optional, Default: false ", "name": "noAssert", "desc": "Boolean, Optional, Default: false", "optional": true } ] }, { "params": [ { "name": "offset" }, { "name": "noAssert", "optional": true } ] }, { "params": [ { "name": "offset" }, { "name": "noAssert", "optional": true } ] } ], "desc": "

    Reads an unsigned 16 bit integer from the buffer at the specified offset with\nspecified endian format.\n\n

    \n

    Set noAssert to true to skip validation of offset. This means that offset\nmay be beyond the end of the buffer. Defaults to false.\n\n

    \n

    Example:\n\n

    \n
    var buf = new Buffer(4);\n\nbuf[0] = 0x3;\nbuf[1] = 0x4;\nbuf[2] = 0x23;\nbuf[3] = 0x42;\n\nconsole.log(buf.readUInt16BE(0));\nconsole.log(buf.readUInt16LE(0));\nconsole.log(buf.readUInt16BE(1));\nconsole.log(buf.readUInt16LE(1));\nconsole.log(buf.readUInt16BE(2));\nconsole.log(buf.readUInt16LE(2));\n\n// 0x0304\n// 0x0403\n// 0x0423\n// 0x2304\n// 0x2342\n// 0x4223
    \n" }, { "textRaw": "buf.readUInt16BE(offset, [noAssert])", "type": "method", "name": "readUInt16BE", "signatures": [ { "return": { "textRaw": "Return: Number ", "name": "return", "desc": "Number" }, "params": [ { "textRaw": "`offset` Number ", "name": "offset", "desc": "Number" }, { "textRaw": "`noAssert` Boolean, Optional, Default: false ", "name": "noAssert", "desc": "Boolean, Optional, Default: false", "optional": true } ] }, { "params": [ { "name": "offset" }, { "name": "noAssert", "optional": true } ] } ], "desc": "

    Reads an unsigned 16 bit integer from the buffer at the specified offset with\nspecified endian format.\n\n

    \n

    Set noAssert to true to skip validation of offset. This means that offset\nmay be beyond the end of the buffer. Defaults to false.\n\n

    \n

    Example:\n\n

    \n
    var buf = new Buffer(4);\n\nbuf[0] = 0x3;\nbuf[1] = 0x4;\nbuf[2] = 0x23;\nbuf[3] = 0x42;\n\nconsole.log(buf.readUInt16BE(0));\nconsole.log(buf.readUInt16LE(0));\nconsole.log(buf.readUInt16BE(1));\nconsole.log(buf.readUInt16LE(1));\nconsole.log(buf.readUInt16BE(2));\nconsole.log(buf.readUInt16LE(2));\n\n// 0x0304\n// 0x0403\n// 0x0423\n// 0x2304\n// 0x2342\n// 0x4223
    \n" }, { "textRaw": "buf.readUInt32LE(offset, [noAssert])", "type": "method", "name": "readUInt32LE", "signatures": [ { "return": { "textRaw": "Return: Number ", "name": "return", "desc": "Number" }, "params": [ { "textRaw": "`offset` Number ", "name": "offset", "desc": "Number" }, { "textRaw": "`noAssert` Boolean, Optional, Default: false ", "name": "noAssert", "desc": "Boolean, Optional, Default: false", "optional": true } ] }, { "params": [ { "name": "offset" }, { "name": "noAssert", "optional": true } ] }, { "params": [ { "name": "offset" }, { "name": "noAssert", "optional": true } ] } ], "desc": "

    Reads an unsigned 32 bit integer from the buffer at the specified offset with\nspecified endian format.\n\n

    \n

    Set noAssert to true to skip validation of offset. This means that offset\nmay be beyond the end of the buffer. Defaults to false.\n\n

    \n

    Example:\n\n

    \n
    var buf = new Buffer(4);\n\nbuf[0] = 0x3;\nbuf[1] = 0x4;\nbuf[2] = 0x23;\nbuf[3] = 0x42;\n\nconsole.log(buf.readUInt32BE(0));\nconsole.log(buf.readUInt32LE(0));\n\n// 0x03042342\n// 0x42230403
    \n" }, { "textRaw": "buf.readUInt32BE(offset, [noAssert])", "type": "method", "name": "readUInt32BE", "signatures": [ { "return": { "textRaw": "Return: Number ", "name": "return", "desc": "Number" }, "params": [ { "textRaw": "`offset` Number ", "name": "offset", "desc": "Number" }, { "textRaw": "`noAssert` Boolean, Optional, Default: false ", "name": "noAssert", "desc": "Boolean, Optional, Default: false", "optional": true } ] }, { "params": [ { "name": "offset" }, { "name": "noAssert", "optional": true } ] } ], "desc": "

    Reads an unsigned 32 bit integer from the buffer at the specified offset with\nspecified endian format.\n\n

    \n

    Set noAssert to true to skip validation of offset. This means that offset\nmay be beyond the end of the buffer. Defaults to false.\n\n

    \n

    Example:\n\n

    \n
    var buf = new Buffer(4);\n\nbuf[0] = 0x3;\nbuf[1] = 0x4;\nbuf[2] = 0x23;\nbuf[3] = 0x42;\n\nconsole.log(buf.readUInt32BE(0));\nconsole.log(buf.readUInt32LE(0));\n\n// 0x03042342\n// 0x42230403
    \n" }, { "textRaw": "buf.readInt8(offset, [noAssert])", "type": "method", "name": "readInt8", "signatures": [ { "return": { "textRaw": "Return: Number ", "name": "return", "desc": "Number" }, "params": [ { "textRaw": "`offset` Number ", "name": "offset", "desc": "Number" }, { "textRaw": "`noAssert` Boolean, Optional, Default: false ", "name": "noAssert", "desc": "Boolean, Optional, Default: false", "optional": true } ] }, { "params": [ { "name": "offset" }, { "name": "noAssert", "optional": true } ] } ], "desc": "

    Reads a signed 8 bit integer from the buffer at the specified offset.\n\n

    \n

    Set noAssert to true to skip validation of offset. This means that offset\nmay be beyond the end of the buffer. Defaults to false.\n\n

    \n

    Works as buffer.readUInt8, except buffer contents are treated as two's\ncomplement signed values.\n\n

    \n" }, { "textRaw": "buf.readInt16LE(offset, [noAssert])", "type": "method", "name": "readInt16LE", "signatures": [ { "return": { "textRaw": "Return: Number ", "name": "return", "desc": "Number" }, "params": [ { "textRaw": "`offset` Number ", "name": "offset", "desc": "Number" }, { "textRaw": "`noAssert` Boolean, Optional, Default: false ", "name": "noAssert", "desc": "Boolean, Optional, Default: false", "optional": true } ] }, { "params": [ { "name": "offset" }, { "name": "noAssert", "optional": true } ] }, { "params": [ { "name": "offset" }, { "name": "noAssert", "optional": true } ] } ], "desc": "

    Reads a signed 16 bit integer from the buffer at the specified offset with\nspecified endian format.\n\n

    \n

    Set noAssert to true to skip validation of offset. This means that offset\nmay be beyond the end of the buffer. Defaults to false.\n\n

    \n

    Works as buffer.readUInt16*, except buffer contents are treated as two's\ncomplement signed values.\n\n

    \n" }, { "textRaw": "buf.readInt16BE(offset, [noAssert])", "type": "method", "name": "readInt16BE", "signatures": [ { "return": { "textRaw": "Return: Number ", "name": "return", "desc": "Number" }, "params": [ { "textRaw": "`offset` Number ", "name": "offset", "desc": "Number" }, { "textRaw": "`noAssert` Boolean, Optional, Default: false ", "name": "noAssert", "desc": "Boolean, Optional, Default: false", "optional": true } ] }, { "params": [ { "name": "offset" }, { "name": "noAssert", "optional": true } ] } ], "desc": "

    Reads a signed 16 bit integer from the buffer at the specified offset with\nspecified endian format.\n\n

    \n

    Set noAssert to true to skip validation of offset. This means that offset\nmay be beyond the end of the buffer. Defaults to false.\n\n

    \n

    Works as buffer.readUInt16*, except buffer contents are treated as two's\ncomplement signed values.\n\n

    \n" }, { "textRaw": "buf.readInt32LE(offset, [noAssert])", "type": "method", "name": "readInt32LE", "signatures": [ { "return": { "textRaw": "Return: Number ", "name": "return", "desc": "Number" }, "params": [ { "textRaw": "`offset` Number ", "name": "offset", "desc": "Number" }, { "textRaw": "`noAssert` Boolean, Optional, Default: false ", "name": "noAssert", "desc": "Boolean, Optional, Default: false", "optional": true } ] }, { "params": [ { "name": "offset" }, { "name": "noAssert", "optional": true } ] }, { "params": [ { "name": "offset" }, { "name": "noAssert", "optional": true } ] } ], "desc": "

    Reads a signed 32 bit integer from the buffer at the specified offset with\nspecified endian format.\n\n

    \n

    Set noAssert to true to skip validation of offset. This means that offset\nmay be beyond the end of the buffer. Defaults to false.\n\n

    \n

    Works as buffer.readUInt32*, except buffer contents are treated as two's\ncomplement signed values.\n\n

    \n" }, { "textRaw": "buf.readInt32BE(offset, [noAssert])", "type": "method", "name": "readInt32BE", "signatures": [ { "return": { "textRaw": "Return: Number ", "name": "return", "desc": "Number" }, "params": [ { "textRaw": "`offset` Number ", "name": "offset", "desc": "Number" }, { "textRaw": "`noAssert` Boolean, Optional, Default: false ", "name": "noAssert", "desc": "Boolean, Optional, Default: false", "optional": true } ] }, { "params": [ { "name": "offset" }, { "name": "noAssert", "optional": true } ] } ], "desc": "

    Reads a signed 32 bit integer from the buffer at the specified offset with\nspecified endian format.\n\n

    \n

    Set noAssert to true to skip validation of offset. This means that offset\nmay be beyond the end of the buffer. Defaults to false.\n\n

    \n

    Works as buffer.readUInt32*, except buffer contents are treated as two's\ncomplement signed values.\n\n

    \n" }, { "textRaw": "buf.readFloatLE(offset, [noAssert])", "type": "method", "name": "readFloatLE", "signatures": [ { "return": { "textRaw": "Return: Number ", "name": "return", "desc": "Number" }, "params": [ { "textRaw": "`offset` Number ", "name": "offset", "desc": "Number" }, { "textRaw": "`noAssert` Boolean, Optional, Default: false ", "name": "noAssert", "desc": "Boolean, Optional, Default: false", "optional": true } ] }, { "params": [ { "name": "offset" }, { "name": "noAssert", "optional": true } ] }, { "params": [ { "name": "offset" }, { "name": "noAssert", "optional": true } ] } ], "desc": "

    Reads a 32 bit float from the buffer at the specified offset with specified\nendian format.\n\n

    \n

    Set noAssert to true to skip validation of offset. This means that offset\nmay be beyond the end of the buffer. Defaults to false.\n\n

    \n

    Example:\n\n

    \n
    var buf = new Buffer(4);\n\nbuf[0] = 0x00;\nbuf[1] = 0x00;\nbuf[2] = 0x80;\nbuf[3] = 0x3f;\n\nconsole.log(buf.readFloatLE(0));\n\n// 0x01
    \n" }, { "textRaw": "buf.readFloatBE(offset, [noAssert])", "type": "method", "name": "readFloatBE", "signatures": [ { "return": { "textRaw": "Return: Number ", "name": "return", "desc": "Number" }, "params": [ { "textRaw": "`offset` Number ", "name": "offset", "desc": "Number" }, { "textRaw": "`noAssert` Boolean, Optional, Default: false ", "name": "noAssert", "desc": "Boolean, Optional, Default: false", "optional": true } ] }, { "params": [ { "name": "offset" }, { "name": "noAssert", "optional": true } ] } ], "desc": "

    Reads a 32 bit float from the buffer at the specified offset with specified\nendian format.\n\n

    \n

    Set noAssert to true to skip validation of offset. This means that offset\nmay be beyond the end of the buffer. Defaults to false.\n\n

    \n

    Example:\n\n

    \n
    var buf = new Buffer(4);\n\nbuf[0] = 0x00;\nbuf[1] = 0x00;\nbuf[2] = 0x80;\nbuf[3] = 0x3f;\n\nconsole.log(buf.readFloatLE(0));\n\n// 0x01
    \n" }, { "textRaw": "buf.readDoubleLE(offset, [noAssert])", "type": "method", "name": "readDoubleLE", "signatures": [ { "return": { "textRaw": "Return: Number ", "name": "return", "desc": "Number" }, "params": [ { "textRaw": "`offset` Number ", "name": "offset", "desc": "Number" }, { "textRaw": "`noAssert` Boolean, Optional, Default: false ", "name": "noAssert", "desc": "Boolean, Optional, Default: false", "optional": true } ] }, { "params": [ { "name": "offset" }, { "name": "noAssert", "optional": true } ] }, { "params": [ { "name": "offset" }, { "name": "noAssert", "optional": true } ] } ], "desc": "

    Reads a 64 bit double from the buffer at the specified offset with specified\nendian format.\n\n

    \n

    Set noAssert to true to skip validation of offset. This means that offset\nmay be beyond the end of the buffer. Defaults to false.\n\n

    \n

    Example:\n\n

    \n
    var buf = new Buffer(8);\n\nbuf[0] = 0x55;\nbuf[1] = 0x55;\nbuf[2] = 0x55;\nbuf[3] = 0x55;\nbuf[4] = 0x55;\nbuf[5] = 0x55;\nbuf[6] = 0xd5;\nbuf[7] = 0x3f;\n\nconsole.log(buf.readDoubleLE(0));\n\n// 0.3333333333333333
    \n" }, { "textRaw": "buf.readDoubleBE(offset, [noAssert])", "type": "method", "name": "readDoubleBE", "signatures": [ { "return": { "textRaw": "Return: Number ", "name": "return", "desc": "Number" }, "params": [ { "textRaw": "`offset` Number ", "name": "offset", "desc": "Number" }, { "textRaw": "`noAssert` Boolean, Optional, Default: false ", "name": "noAssert", "desc": "Boolean, Optional, Default: false", "optional": true } ] }, { "params": [ { "name": "offset" }, { "name": "noAssert", "optional": true } ] } ], "desc": "

    Reads a 64 bit double from the buffer at the specified offset with specified\nendian format.\n\n

    \n

    Set noAssert to true to skip validation of offset. This means that offset\nmay be beyond the end of the buffer. Defaults to false.\n\n

    \n

    Example:\n\n

    \n
    var buf = new Buffer(8);\n\nbuf[0] = 0x55;\nbuf[1] = 0x55;\nbuf[2] = 0x55;\nbuf[3] = 0x55;\nbuf[4] = 0x55;\nbuf[5] = 0x55;\nbuf[6] = 0xd5;\nbuf[7] = 0x3f;\n\nconsole.log(buf.readDoubleLE(0));\n\n// 0.3333333333333333
    \n" }, { "textRaw": "buf.writeUInt8(value, offset, [noAssert])", "type": "method", "name": "writeUInt8", "signatures": [ { "params": [ { "textRaw": "`value` Number ", "name": "value", "desc": "Number" }, { "textRaw": "`offset` Number ", "name": "offset", "desc": "Number" }, { "textRaw": "`noAssert` Boolean, Optional, Default: false ", "name": "noAssert", "desc": "Boolean, Optional, Default: false", "optional": true } ] }, { "params": [ { "name": "value" }, { "name": "offset" }, { "name": "noAssert", "optional": true } ] } ], "desc": "

    Writes value to the buffer at the specified offset. Note, value must be a\nvalid unsigned 8 bit integer.\n\n

    \n

    Set noAssert to true to skip validation of value and offset. This means\nthat value may be too large for the specific function and offset may be\nbeyond the end of the buffer leading to the values being silently dropped. This\nshould not be used unless you are certain of correctness. Defaults to false.\n\n

    \n

    Example:\n\n

    \n
    var buf = new Buffer(4);\nbuf.writeUInt8(0x3, 0);\nbuf.writeUInt8(0x4, 1);\nbuf.writeUInt8(0x23, 2);\nbuf.writeUInt8(0x42, 3);\n\nconsole.log(buf);\n\n// <Buffer 03 04 23 42>
    \n" }, { "textRaw": "buf.writeUInt16LE(value, offset, [noAssert])", "type": "method", "name": "writeUInt16LE", "signatures": [ { "params": [ { "textRaw": "`value` Number ", "name": "value", "desc": "Number" }, { "textRaw": "`offset` Number ", "name": "offset", "desc": "Number" }, { "textRaw": "`noAssert` Boolean, Optional, Default: false ", "name": "noAssert", "desc": "Boolean, Optional, Default: false", "optional": true } ] }, { "params": [ { "name": "value" }, { "name": "offset" }, { "name": "noAssert", "optional": true } ] }, { "params": [ { "name": "value" }, { "name": "offset" }, { "name": "noAssert", "optional": true } ] } ], "desc": "

    Writes value to the buffer at the specified offset with specified endian\nformat. Note, value must be a valid unsigned 16 bit integer.\n\n

    \n

    Set noAssert to true to skip validation of value and offset. This means\nthat value may be too large for the specific function and offset may be\nbeyond the end of the buffer leading to the values being silently dropped. This\nshould not be used unless you are certain of correctness. Defaults to false.\n\n

    \n

    Example:\n\n

    \n
    var buf = new Buffer(4);\nbuf.writeUInt16BE(0xdead, 0);\nbuf.writeUInt16BE(0xbeef, 2);\n\nconsole.log(buf);\n\nbuf.writeUInt16LE(0xdead, 0);\nbuf.writeUInt16LE(0xbeef, 2);\n\nconsole.log(buf);\n\n// <Buffer de ad be ef>\n// <Buffer ad de ef be>
    \n" }, { "textRaw": "buf.writeUInt16BE(value, offset, [noAssert])", "type": "method", "name": "writeUInt16BE", "signatures": [ { "params": [ { "textRaw": "`value` Number ", "name": "value", "desc": "Number" }, { "textRaw": "`offset` Number ", "name": "offset", "desc": "Number" }, { "textRaw": "`noAssert` Boolean, Optional, Default: false ", "name": "noAssert", "desc": "Boolean, Optional, Default: false", "optional": true } ] }, { "params": [ { "name": "value" }, { "name": "offset" }, { "name": "noAssert", "optional": true } ] } ], "desc": "

    Writes value to the buffer at the specified offset with specified endian\nformat. Note, value must be a valid unsigned 16 bit integer.\n\n

    \n

    Set noAssert to true to skip validation of value and offset. This means\nthat value may be too large for the specific function and offset may be\nbeyond the end of the buffer leading to the values being silently dropped. This\nshould not be used unless you are certain of correctness. Defaults to false.\n\n

    \n

    Example:\n\n

    \n
    var buf = new Buffer(4);\nbuf.writeUInt16BE(0xdead, 0);\nbuf.writeUInt16BE(0xbeef, 2);\n\nconsole.log(buf);\n\nbuf.writeUInt16LE(0xdead, 0);\nbuf.writeUInt16LE(0xbeef, 2);\n\nconsole.log(buf);\n\n// <Buffer de ad be ef>\n// <Buffer ad de ef be>
    \n" }, { "textRaw": "buf.writeUInt32LE(value, offset, [noAssert])", "type": "method", "name": "writeUInt32LE", "signatures": [ { "params": [ { "textRaw": "`value` Number ", "name": "value", "desc": "Number" }, { "textRaw": "`offset` Number ", "name": "offset", "desc": "Number" }, { "textRaw": "`noAssert` Boolean, Optional, Default: false ", "name": "noAssert", "desc": "Boolean, Optional, Default: false", "optional": true } ] }, { "params": [ { "name": "value" }, { "name": "offset" }, { "name": "noAssert", "optional": true } ] }, { "params": [ { "name": "value" }, { "name": "offset" }, { "name": "noAssert", "optional": true } ] } ], "desc": "

    Writes value to the buffer at the specified offset with specified endian\nformat. Note, value must be a valid unsigned 32 bit integer.\n\n

    \n

    Set noAssert to true to skip validation of value and offset. This means\nthat value may be too large for the specific function and offset may be\nbeyond the end of the buffer leading to the values being silently dropped. This\nshould not be used unless you are certain of correctness. Defaults to false.\n\n

    \n

    Example:\n\n

    \n
    var buf = new Buffer(4);\nbuf.writeUInt32BE(0xfeedface, 0);\n\nconsole.log(buf);\n\nbuf.writeUInt32LE(0xfeedface, 0);\n\nconsole.log(buf);\n\n// <Buffer fe ed fa ce>\n// <Buffer ce fa ed fe>
    \n" }, { "textRaw": "buf.writeUInt32BE(value, offset, [noAssert])", "type": "method", "name": "writeUInt32BE", "signatures": [ { "params": [ { "textRaw": "`value` Number ", "name": "value", "desc": "Number" }, { "textRaw": "`offset` Number ", "name": "offset", "desc": "Number" }, { "textRaw": "`noAssert` Boolean, Optional, Default: false ", "name": "noAssert", "desc": "Boolean, Optional, Default: false", "optional": true } ] }, { "params": [ { "name": "value" }, { "name": "offset" }, { "name": "noAssert", "optional": true } ] } ], "desc": "

    Writes value to the buffer at the specified offset with specified endian\nformat. Note, value must be a valid unsigned 32 bit integer.\n\n

    \n

    Set noAssert to true to skip validation of value and offset. This means\nthat value may be too large for the specific function and offset may be\nbeyond the end of the buffer leading to the values being silently dropped. This\nshould not be used unless you are certain of correctness. Defaults to false.\n\n

    \n

    Example:\n\n

    \n
    var buf = new Buffer(4);\nbuf.writeUInt32BE(0xfeedface, 0);\n\nconsole.log(buf);\n\nbuf.writeUInt32LE(0xfeedface, 0);\n\nconsole.log(buf);\n\n// <Buffer fe ed fa ce>\n// <Buffer ce fa ed fe>
    \n" }, { "textRaw": "buf.writeInt8(value, offset, [noAssert])", "type": "method", "name": "writeInt8", "signatures": [ { "params": [ { "textRaw": "`value` Number ", "name": "value", "desc": "Number" }, { "textRaw": "`offset` Number ", "name": "offset", "desc": "Number" }, { "textRaw": "`noAssert` Boolean, Optional, Default: false ", "name": "noAssert", "desc": "Boolean, Optional, Default: false", "optional": true } ] }, { "params": [ { "name": "value" }, { "name": "offset" }, { "name": "noAssert", "optional": true } ] } ], "desc": "

    Writes value to the buffer at the specified offset. Note, value must be a\nvalid signed 8 bit integer.\n\n

    \n

    Set noAssert to true to skip validation of value and offset. This means\nthat value may be too large for the specific function and offset may be\nbeyond the end of the buffer leading to the values being silently dropped. This\nshould not be used unless you are certain of correctness. Defaults to false.\n\n

    \n

    Works as buffer.writeUInt8, except value is written out as a two's complement\nsigned integer into buffer.\n\n

    \n" }, { "textRaw": "buf.writeInt16LE(value, offset, [noAssert])", "type": "method", "name": "writeInt16LE", "signatures": [ { "params": [ { "textRaw": "`value` Number ", "name": "value", "desc": "Number" }, { "textRaw": "`offset` Number ", "name": "offset", "desc": "Number" }, { "textRaw": "`noAssert` Boolean, Optional, Default: false ", "name": "noAssert", "desc": "Boolean, Optional, Default: false", "optional": true } ] }, { "params": [ { "name": "value" }, { "name": "offset" }, { "name": "noAssert", "optional": true } ] }, { "params": [ { "name": "value" }, { "name": "offset" }, { "name": "noAssert", "optional": true } ] } ], "desc": "

    Writes value to the buffer at the specified offset with specified endian\nformat. Note, value must be a valid signed 16 bit integer.\n\n

    \n

    Set noAssert to true to skip validation of value and offset. This means\nthat value may be too large for the specific function and offset may be\nbeyond the end of the buffer leading to the values being silently dropped. This\nshould not be used unless you are certain of correctness. Defaults to false.\n\n

    \n

    Works as buffer.writeUInt16*, except value is written out as a two's\ncomplement signed integer into buffer.\n\n

    \n" }, { "textRaw": "buf.writeInt16BE(value, offset, [noAssert])", "type": "method", "name": "writeInt16BE", "signatures": [ { "params": [ { "textRaw": "`value` Number ", "name": "value", "desc": "Number" }, { "textRaw": "`offset` Number ", "name": "offset", "desc": "Number" }, { "textRaw": "`noAssert` Boolean, Optional, Default: false ", "name": "noAssert", "desc": "Boolean, Optional, Default: false", "optional": true } ] }, { "params": [ { "name": "value" }, { "name": "offset" }, { "name": "noAssert", "optional": true } ] } ], "desc": "

    Writes value to the buffer at the specified offset with specified endian\nformat. Note, value must be a valid signed 16 bit integer.\n\n

    \n

    Set noAssert to true to skip validation of value and offset. This means\nthat value may be too large for the specific function and offset may be\nbeyond the end of the buffer leading to the values being silently dropped. This\nshould not be used unless you are certain of correctness. Defaults to false.\n\n

    \n

    Works as buffer.writeUInt16*, except value is written out as a two's\ncomplement signed integer into buffer.\n\n

    \n" }, { "textRaw": "buf.writeInt32LE(value, offset, [noAssert])", "type": "method", "name": "writeInt32LE", "signatures": [ { "params": [ { "textRaw": "`value` Number ", "name": "value", "desc": "Number" }, { "textRaw": "`offset` Number ", "name": "offset", "desc": "Number" }, { "textRaw": "`noAssert` Boolean, Optional, Default: false ", "name": "noAssert", "desc": "Boolean, Optional, Default: false", "optional": true } ] }, { "params": [ { "name": "value" }, { "name": "offset" }, { "name": "noAssert", "optional": true } ] }, { "params": [ { "name": "value" }, { "name": "offset" }, { "name": "noAssert", "optional": true } ] } ], "desc": "

    Writes value to the buffer at the specified offset with specified endian\nformat. Note, value must be a valid signed 32 bit integer.\n\n

    \n

    Set noAssert to true to skip validation of value and offset. This means\nthat value may be too large for the specific function and offset may be\nbeyond the end of the buffer leading to the values being silently dropped. This\nshould not be used unless you are certain of correctness. Defaults to false.\n\n

    \n

    Works as buffer.writeUInt32*, except value is written out as a two's\ncomplement signed integer into buffer.\n\n

    \n" }, { "textRaw": "buf.writeInt32BE(value, offset, [noAssert])", "type": "method", "name": "writeInt32BE", "signatures": [ { "params": [ { "textRaw": "`value` Number ", "name": "value", "desc": "Number" }, { "textRaw": "`offset` Number ", "name": "offset", "desc": "Number" }, { "textRaw": "`noAssert` Boolean, Optional, Default: false ", "name": "noAssert", "desc": "Boolean, Optional, Default: false", "optional": true } ] }, { "params": [ { "name": "value" }, { "name": "offset" }, { "name": "noAssert", "optional": true } ] } ], "desc": "

    Writes value to the buffer at the specified offset with specified endian\nformat. Note, value must be a valid signed 32 bit integer.\n\n

    \n

    Set noAssert to true to skip validation of value and offset. This means\nthat value may be too large for the specific function and offset may be\nbeyond the end of the buffer leading to the values being silently dropped. This\nshould not be used unless you are certain of correctness. Defaults to false.\n\n

    \n

    Works as buffer.writeUInt32*, except value is written out as a two's\ncomplement signed integer into buffer.\n\n

    \n" }, { "textRaw": "buf.writeFloatLE(value, offset, [noAssert])", "type": "method", "name": "writeFloatLE", "signatures": [ { "params": [ { "textRaw": "`value` Number ", "name": "value", "desc": "Number" }, { "textRaw": "`offset` Number ", "name": "offset", "desc": "Number" }, { "textRaw": "`noAssert` Boolean, Optional, Default: false ", "name": "noAssert", "desc": "Boolean, Optional, Default: false", "optional": true } ] }, { "params": [ { "name": "value" }, { "name": "offset" }, { "name": "noAssert", "optional": true } ] }, { "params": [ { "name": "value" }, { "name": "offset" }, { "name": "noAssert", "optional": true } ] } ], "desc": "

    Writes value to the buffer at the specified offset with specified endian\nformat. Note, behavior is unspecified if value is not a 32 bit float.\n\n

    \n

    Set noAssert to true to skip validation of value and offset. This means\nthat value may be too large for the specific function and offset may be\nbeyond the end of the buffer leading to the values being silently dropped. This\nshould not be used unless you are certain of correctness. Defaults to false.\n\n

    \n

    Example:\n\n

    \n
    var buf = new Buffer(4);\nbuf.writeFloatBE(0xcafebabe, 0);\n\nconsole.log(buf);\n\nbuf.writeFloatLE(0xcafebabe, 0);\n\nconsole.log(buf);\n\n// <Buffer 4f 4a fe bb>\n// <Buffer bb fe 4a 4f>
    \n" }, { "textRaw": "buf.writeFloatBE(value, offset, [noAssert])", "type": "method", "name": "writeFloatBE", "signatures": [ { "params": [ { "textRaw": "`value` Number ", "name": "value", "desc": "Number" }, { "textRaw": "`offset` Number ", "name": "offset", "desc": "Number" }, { "textRaw": "`noAssert` Boolean, Optional, Default: false ", "name": "noAssert", "desc": "Boolean, Optional, Default: false", "optional": true } ] }, { "params": [ { "name": "value" }, { "name": "offset" }, { "name": "noAssert", "optional": true } ] } ], "desc": "

    Writes value to the buffer at the specified offset with specified endian\nformat. Note, behavior is unspecified if value is not a 32 bit float.\n\n

    \n

    Set noAssert to true to skip validation of value and offset. This means\nthat value may be too large for the specific function and offset may be\nbeyond the end of the buffer leading to the values being silently dropped. This\nshould not be used unless you are certain of correctness. Defaults to false.\n\n

    \n

    Example:\n\n

    \n
    var buf = new Buffer(4);\nbuf.writeFloatBE(0xcafebabe, 0);\n\nconsole.log(buf);\n\nbuf.writeFloatLE(0xcafebabe, 0);\n\nconsole.log(buf);\n\n// <Buffer 4f 4a fe bb>\n// <Buffer bb fe 4a 4f>
    \n" }, { "textRaw": "buf.writeDoubleLE(value, offset, [noAssert])", "type": "method", "name": "writeDoubleLE", "signatures": [ { "params": [ { "textRaw": "`value` Number ", "name": "value", "desc": "Number" }, { "textRaw": "`offset` Number ", "name": "offset", "desc": "Number" }, { "textRaw": "`noAssert` Boolean, Optional, Default: false ", "name": "noAssert", "desc": "Boolean, Optional, Default: false", "optional": true } ] }, { "params": [ { "name": "value" }, { "name": "offset" }, { "name": "noAssert", "optional": true } ] }, { "params": [ { "name": "value" }, { "name": "offset" }, { "name": "noAssert", "optional": true } ] } ], "desc": "

    Writes value to the buffer at the specified offset with specified endian\nformat. Note, value must be a valid 64 bit double.\n\n

    \n

    Set noAssert to true to skip validation of value and offset. This means\nthat value may be too large for the specific function and offset may be\nbeyond the end of the buffer leading to the values being silently dropped. This\nshould not be used unless you are certain of correctness. Defaults to false.\n\n

    \n

    Example:\n\n

    \n
    var buf = new Buffer(8);\nbuf.writeDoubleBE(0xdeadbeefcafebabe, 0);\n\nconsole.log(buf);\n\nbuf.writeDoubleLE(0xdeadbeefcafebabe, 0);\n\nconsole.log(buf);\n\n// <Buffer 43 eb d5 b7 dd f9 5f d7>\n// <Buffer d7 5f f9 dd b7 d5 eb 43>
    \n" }, { "textRaw": "buf.writeDoubleBE(value, offset, [noAssert])", "type": "method", "name": "writeDoubleBE", "signatures": [ { "params": [ { "textRaw": "`value` Number ", "name": "value", "desc": "Number" }, { "textRaw": "`offset` Number ", "name": "offset", "desc": "Number" }, { "textRaw": "`noAssert` Boolean, Optional, Default: false ", "name": "noAssert", "desc": "Boolean, Optional, Default: false", "optional": true } ] }, { "params": [ { "name": "value" }, { "name": "offset" }, { "name": "noAssert", "optional": true } ] } ], "desc": "

    Writes value to the buffer at the specified offset with specified endian\nformat. Note, value must be a valid 64 bit double.\n\n

    \n

    Set noAssert to true to skip validation of value and offset. This means\nthat value may be too large for the specific function and offset may be\nbeyond the end of the buffer leading to the values being silently dropped. This\nshould not be used unless you are certain of correctness. Defaults to false.\n\n

    \n

    Example:\n\n

    \n
    var buf = new Buffer(8);\nbuf.writeDoubleBE(0xdeadbeefcafebabe, 0);\n\nconsole.log(buf);\n\nbuf.writeDoubleLE(0xdeadbeefcafebabe, 0);\n\nconsole.log(buf);\n\n// <Buffer 43 eb d5 b7 dd f9 5f d7>\n// <Buffer d7 5f f9 dd b7 d5 eb 43>
    \n" }, { "textRaw": "buf.fill(value, [offset], [end])", "type": "method", "name": "fill", "signatures": [ { "params": [ { "textRaw": "`value` ", "name": "value" }, { "textRaw": "`offset` Number, Optional ", "name": "offset", "optional": true, "desc": "Number" }, { "textRaw": "`end` Number, Optional ", "name": "end", "optional": true, "desc": "Number" } ] }, { "params": [ { "name": "value" }, { "name": "offset", "optional": true }, { "name": "end", "optional": true } ] } ], "desc": "

    Fills the buffer with the specified value. If the offset (defaults to 0)\nand end (defaults to buffer.length) are not given it will fill the entire\nbuffer.\n\n

    \n
    var b = new Buffer(50);\nb.fill("h");
    \n" } ], "properties": [ { "textRaw": "buf[index]", "name": "[index]", "desc": "

    Get and set the octet at index. The values refer to individual bytes,\nso the legal range is between 0x00 and 0xFF hex or 0 and 255.\n\n

    \n

    Example: copy an ASCII string into a buffer, one byte at a time:\n\n

    \n
    str = "node.js";\nbuf = new Buffer(str.length);\n\nfor (var i = 0; i < str.length ; i++) {\n  buf[i] = str.charCodeAt(i);\n}\n\nconsole.log(buf);\n\n// node.js
    \n" }, { "textRaw": "`length` Number ", "name": "length", "desc": "

    The size of the buffer in bytes. Note that this is not necessarily the size\nof the contents. length refers to the amount of memory allocated for the\nbuffer object. It does not change when the contents of the buffer are changed.\n\n

    \n
    buf = new Buffer(1234);\n\nconsole.log(buf.length);\nbuf.write("some string", 0, "ascii");\nconsole.log(buf.length);\n\n// 1234\n// 1234
    \n", "shortDesc": "Number" } ], "signatures": [ { "params": [ { "textRaw": "`size` Number ", "name": "size", "desc": "Number" } ], "desc": "

    Allocates a new buffer of size octets.\n\n

    \n" }, { "params": [ { "name": "size" } ], "desc": "

    Allocates a new buffer of size octets.\n\n

    \n" }, { "params": [ { "textRaw": "`array` Array ", "name": "array", "desc": "Array" } ], "desc": "

    Allocates a new buffer using an array of octets.\n\n

    \n" }, { "params": [ { "name": "array" } ], "desc": "

    Allocates a new buffer using an array of octets.\n\n

    \n" }, { "params": [ { "textRaw": "`str` String - string to encode. ", "name": "str", "desc": "String - string to encode." }, { "textRaw": "`encoding` String - encoding to use, Optional. ", "name": "encoding", "desc": "String - encoding to use, Optional.", "optional": true } ], "desc": "

    Allocates a new buffer containing the given str.\nencoding defaults to 'utf8'.\n\n

    \n" }, { "params": [ { "name": "str" }, { "name": "encoding", "optional": true } ], "desc": "

    Allocates a new buffer containing the given str.\nencoding defaults to 'utf8'.\n\n

    \n" } ] }, { "textRaw": "Class: SlowBuffer", "type": "class", "name": "SlowBuffer", "desc": "

    This class is primarily for internal use. JavaScript programs should\nuse Buffer instead of using SlowBuffer.\n\n

    \n

    In order to avoid the overhead of allocating many C++ Buffer objects for\nsmall blocks of memory in the lifetime of a server, Node allocates memory\nin 8Kb (8192 byte) chunks. If a buffer is smaller than this size, then it\nwill be backed by a parent SlowBuffer object. If it is larger than this,\nthen Node will allocate a SlowBuffer slab for it directly.\n\n

    \n" } ], "properties": [ { "textRaw": "`INSPECT_MAX_BYTES` Number, Default: 50 ", "name": "INSPECT_MAX_BYTES", "desc": "

    How many bytes will be returned when buffer.inspect() is called. This can\nbe overridden by user modules.\n\n

    \n

    Note that this is a property on the buffer module returned by\nrequire('buffer'), not on the Buffer global, or a buffer instance.\n\n

    \n", "shortDesc": "Number, Default: 50" } ], "type": "module", "displayName": "Buffer" }, { "textRaw": "Stream", "name": "stream", "stability": 2, "stabilityText": "Unstable", "desc": "

    A stream is an abstract interface implemented by various objects in\nNode. For example a request to an HTTP\nserver is a stream, as is\n[stdout][]. Streams are readable, writable, or both. All streams are\ninstances of [EventEmitter][]\n\n

    \n

    You can load the Stream base classes by doing require('stream').\nThere are base classes provided for [Readable][] streams, [Writable][]\nstreams, [Duplex][] streams, and [Transform][] streams.\n\n

    \n

    This document is split up into 3 sections. The first explains the\nparts of the API that you need to be aware of to use streams in your\nprograms. If you never implement a streaming API yourself, you can\nstop there.\n\n

    \n

    The second section explains the parts of the API that you need to use\nif you implement your own custom streams yourself. The API is\ndesigned to make this easy for you to do.\n\n

    \n

    The third section goes into more depth about how streams work,\nincluding some of the internal mechanisms and functions that you\nshould probably not modify unless you definitely know what you are\ndoing.\n\n\n

    \n", "classes": [ { "textRaw": "Class: stream.Readable", "type": "class", "name": "stream.Readable", "desc": "

    The Readable stream interface is the abstraction for a source of\ndata that you are reading from. In other words, data comes out of a\nReadable stream.\n\n

    \n

    A Readable stream will not start emitting data until you indicate that\nyou are ready to receive it.\n\n

    \n

    Readable streams have two "modes": a flowing mode and a non-flowing\nmode. When in flowing mode, data is read from the underlying system\nand provided to your program as fast as possible. In non-flowing\nmode, you must explicitly call stream.read() to get chunks of data\nout.\n\n

    \n

    Examples of readable streams include:\n\n

    \n\n", "events": [ { "textRaw": "Event: 'readable'", "type": "event", "name": "readable", "desc": "

    When a chunk of data can be read from the stream, it will emit a\n'readable' event.\n\n

    \n

    In some cases, listening for a 'readable' event will cause some data\nto be read into the internal buffer from the underlying system, if it\nhadn't already.\n\n

    \n
    var readable = getReadableStreamSomehow();\nreadable.on('readable', function() {\n  // there is some data to read now\n})
    \n

    Once the internal buffer is drained, a readable event will fire\nagain when more data is available.\n\n

    \n", "params": [] }, { "textRaw": "Event: 'data'", "type": "event", "name": "data", "params": [], "desc": "

    If you attach a data event listener, then it will switch the stream\ninto flowing mode, and data will be passed to your handler as soon as\nit is available.\n\n

    \n

    If you just want to get all the data out of the stream as fast as\npossible, this is the best way to do so.\n\n

    \n
    var readable = getReadableStreamSomehow();\nreadable.on('data', function(chunk) {\n  console.log('got %d bytes of data', chunk.length);\n})
    \n" }, { "textRaw": "Event: 'end'", "type": "event", "name": "end", "desc": "

    This event fires when no more data will be provided.\n\n

    \n

    Note that the end event will not fire unless the data is\ncompletely consumed. This can be done by switching into flowing mode,\nor by calling read() repeatedly until you get to the end.\n\n

    \n
    var readable = getReadableStreamSomehow();\nreadable.on('data', function(chunk) {\n  console.log('got %d bytes of data', chunk.length);\n})\nreadable.on('end', function() {\n  console.log('there will be no more data.');\n});
    \n", "params": [] }, { "textRaw": "Event: 'close'", "type": "event", "name": "close", "desc": "

    Emitted when the underlying resource (for example, the backing file\ndescriptor) has been closed. Not all streams will emit this.\n\n

    \n", "params": [] }, { "textRaw": "Event: 'error'", "type": "event", "name": "error", "desc": "

    Emitted if there was an error receiving data.\n\n

    \n", "params": [] } ], "methods": [ { "textRaw": "readable.read([size])", "type": "method", "name": "read", "signatures": [ { "return": { "textRaw": "Return {String | Buffer | null} ", "name": "return", "type": "String | Buffer | null" }, "params": [ { "textRaw": "`size` {Number} Optional argument to specify how much data to read. ", "name": "size", "type": "Number", "desc": "Optional argument to specify how much data to read.", "optional": true } ] }, { "params": [ { "name": "size", "optional": true } ] } ], "desc": "

    The read() method pulls some data out of the internal buffer and\nreturns it. If there is no data available, then it will return\nnull.\n\n

    \n

    If you pass in a size argument, then it will return that many\nbytes. If size bytes are not available, then it will return null.\n\n

    \n

    If you do not specify a size argument, then it will return all the\ndata in the internal buffer.\n\n

    \n

    This method should only be called in non-flowing mode. In\nflowing-mode, this method is called automatically until the internal\nbuffer is drained.\n\n

    \n
    var readable = getReadableStreamSomehow();\nreadable.on('readable', function() {\n  var chunk;\n  while (null !== (chunk = readable.read())) {\n    console.log('got %d bytes of data', chunk.length);\n  }\n});
    \n" }, { "textRaw": "readable.setEncoding(encoding)", "type": "method", "name": "setEncoding", "signatures": [ { "params": [ { "textRaw": "`encoding` {String} The encoding to use. ", "name": "encoding", "type": "String", "desc": "The encoding to use." } ] }, { "params": [ { "name": "encoding" } ] } ], "desc": "

    Call this function to cause the stream to return strings of the\nspecified encoding instead of Buffer objects. For example, if you do\nreadable.setEncoding('utf8'), then the output data will be\ninterpreted as UTF-8 data, and returned as strings. If you do\nreadable.setEncoding('hex'), then the data will be encoded in\nhexadecimal string format.\n\n

    \n

    This properly handles multi-byte characters that would otherwise be\npotentially mangled if you simply pulled the Buffers directly and\ncalled buf.toString(encoding) on them. If you want to read the data\nas strings, always use this method.\n\n

    \n
    var readable = getReadableStreamSomehow();\nreadable.setEncoding('utf8');\nreadable.on('data', function(chunk) {\n  assert.equal(typeof chunk, 'string');\n  console.log('got %d characters of string data', chunk.length);\n})
    \n" }, { "textRaw": "readable.resume()", "type": "method", "name": "resume", "desc": "

    This method will cause the readable stream to resume emitting data\nevents.\n\n

    \n

    This method will switch the stream into flowing-mode. If you do not\nwant to consume the data from a stream, but you do want to get to\nits end event, you can call readable.resume() to open the flow of\ndata.\n\n

    \n
    var readable = getReadableStreamSomehow();\nreadable.resume();\nreadable.on('end', function(chunk) {\n  console.log('got to the end, but did not read anything');\n})
    \n", "signatures": [ { "params": [] } ] }, { "textRaw": "readable.pause()", "type": "method", "name": "pause", "desc": "

    This method will cause a stream in flowing-mode to stop emitting\ndata events. Any data that becomes available will remain in the\ninternal buffer.\n\n

    \n

    This method is only relevant in flowing mode. When called on a\nnon-flowing stream, it will switch into flowing mode, but remain\npaused.\n\n

    \n
    var readable = getReadableStreamSomehow();\nreadable.on('data', function(chunk) {\n  console.log('got %d bytes of data', chunk.length);\n  readable.pause();\n  console.log('there will be no more data for 1 second');\n  setTimeout(function() {\n    console.log('now data will start flowing again');\n    readable.resume();\n  }, 1000);\n})
    \n", "signatures": [ { "params": [] } ] }, { "textRaw": "readable.pipe(destination, [options])", "type": "method", "name": "pipe", "signatures": [ { "params": [ { "textRaw": "`destination` {[Writable][] Stream} The destination for writing data ", "name": "destination", "type": "[Writable][] Stream", "desc": "The destination for writing data" }, { "textRaw": "`options` {Object} Pipe options ", "options": [ { "textRaw": "`end` {Boolean} End the writer when the reader ends. Default = `true` ", "name": "end", "type": "Boolean", "desc": "End the writer when the reader ends. Default = `true`" } ], "name": "options", "type": "Object", "desc": "Pipe options", "optional": true } ] }, { "params": [ { "name": "destination" }, { "name": "options", "optional": true } ] } ], "desc": "

    This method pulls all the data out of a readable stream, and writes it\nto the supplied destination, automatically managing the flow so that\nthe destination is not overwhelmed by a fast readable stream.\n\n

    \n

    Multiple destinations can be piped to safely.\n\n

    \n
    var readable = getReadableStreamSomehow();\nvar writable = fs.createWriteStream('file.txt');\n// All the data from readable goes into 'file.txt'\nreadable.pipe(writable);
    \n

    This function returns the destination stream, so you can set up pipe\nchains like so:\n\n

    \n
    var r = fs.createReadStream('file.txt');\nvar z = zlib.createGzip();\nvar w = fs.createWriteStream('file.txt.gz');\nr.pipe(z).pipe(w);
    \n

    For example, emulating the Unix cat command:\n\n

    \n
    process.stdin.pipe(process.stdout);
    \n

    By default [end()][] is called on the destination when the source stream\nemits end, so that destination is no longer writable. Pass { end:\nfalse } as options to keep the destination stream open.\n\n

    \n

    This keeps writer open so that "Goodbye" can be written at the\nend.\n\n

    \n
    reader.pipe(writer, { end: false });\nreader.on('end', function() {\n  writer.end('Goodbye\\n');\n});
    \n

    Note that process.stderr and process.stdout are never closed until\nthe process exits, regardless of the specified options.\n\n

    \n" }, { "textRaw": "readable.unpipe([destination])", "type": "method", "name": "unpipe", "signatures": [ { "params": [ { "textRaw": "`destination` {[Writable][] Stream} Optional specific stream to unpipe ", "name": "destination", "type": "[Writable][] Stream", "desc": "Optional specific stream to unpipe", "optional": true } ] }, { "params": [ { "name": "destination", "optional": true } ] } ], "desc": "

    This method will remove the hooks set up for a previous pipe() call.\n\n

    \n

    If the destination is not specified, then all pipes are removed.\n\n

    \n

    If the destination is specified, but no pipe is set up for it, then\nthis is a no-op.\n\n

    \n
    var readable = getReadableStreamSomehow();\nvar writable = fs.createWriteStream('file.txt');\n// All the data from readable goes into 'file.txt',\n// but only for the first second\nreadable.pipe(writable);\nsetTimeout(function() {\n  console.log('stop writing to file.txt');\n  readable.unpipe(writable);\n  console.log('manually close the file stream');\n  writable.end();\n}, 1000);
    \n" }, { "textRaw": "readable.unshift(chunk)", "type": "method", "name": "unshift", "signatures": [ { "params": [ { "textRaw": "`chunk` {Buffer | String} Chunk of data to unshift onto the read queue ", "name": "chunk", "type": "Buffer | String", "desc": "Chunk of data to unshift onto the read queue" } ] }, { "params": [ { "name": "chunk" } ] } ], "desc": "

    This is useful in certain cases where a stream is being consumed by a\nparser, which needs to "un-consume" some data that it has\noptimistically pulled out of the source, so that the stream can be\npassed on to some other party.\n\n

    \n

    If you find that you must often call stream.unshift(chunk) in your\nprograms, consider implementing a [Transform][] stream instead. (See API\nfor Stream Implementors, below.)\n\n

    \n
    // Pull off a header delimited by \\n\\n\n// use unshift() if we get too much\n// Call the callback with (error, header, stream)\nvar StringDecoder = require('string_decoder').StringDecoder;\nfunction parseHeader(stream, callback) {\n  stream.on('error', callback);\n  stream.on('readable', onReadable);\n  var decoder = new StringDecoder('utf8');\n  var header = '';\n  function onReadable() {\n    var chunk;\n    while (null !== (chunk = stream.read())) {\n      var str = decoder.write(chunk);\n      if (str.match(/\\n\\n/)) {\n        // found the header boundary\n        var split = str.split(/\\n\\n/);\n        header += split.shift();\n        var remaining = split.join('\\n\\n');\n        var buf = new Buffer(remaining, 'utf8');\n        if (buf.length)\n          stream.unshift(buf);\n        stream.removeListener('error', callback);\n        stream.removeListener('readable', onReadable);\n        // now the body of the message can be read from the stream.\n        callback(null, header, stream);\n      } else {\n        // still reading the header.\n        header += str;\n      }\n    }\n  }\n}
    \n" }, { "textRaw": "readable.wrap(stream)", "type": "method", "name": "wrap", "signatures": [ { "params": [ { "textRaw": "`stream` {Stream} An \"old style\" readable stream ", "name": "stream", "type": "Stream", "desc": "An \"old style\" readable stream" } ] }, { "params": [ { "name": "stream" } ] } ], "desc": "

    Versions of Node prior to v0.10 had streams that did not implement the\nentire Streams API as it is today. (See "Compatibility" below for\nmore information.)\n\n

    \n

    If you are using an older Node library that emits 'data' events and\nhas a pause() method that is advisory only, then you can use the\nwrap() method to create a [Readable][] stream that uses the old stream\nas its data source.\n\n

    \n

    You will very rarely ever need to call this function, but it exists\nas a convenience for interacting with old Node programs and libraries.\n\n

    \n

    For example:\n\n

    \n
    var OldReader = require('./old-api-module.js').OldReader;\nvar oreader = new OldReader;\nvar Readable = require('stream').Readable;\nvar myReader = new Readable().wrap(oreader);\n\nmyReader.on('readable', function() {\n  myReader.read(); // etc.\n});
    \n" } ] }, { "textRaw": "Class: stream.Writable", "type": "class", "name": "stream.Writable", "desc": "

    The Writable stream interface is an abstraction for a destination\nthat you are writing data to.\n\n

    \n

    Examples of writable streams include:\n\n

    \n\n", "methods": [ { "textRaw": "writable.write(chunk, [encoding], [callback])", "type": "method", "name": "write", "signatures": [ { "return": { "textRaw": "Returns: {Boolean} True if the data was handled completely. ", "name": "return", "type": "Boolean", "desc": "True if the data was handled completely." }, "params": [ { "textRaw": "`chunk` {String | Buffer} The data to write ", "name": "chunk", "type": "String | Buffer", "desc": "The data to write" }, { "textRaw": "`encoding` {String} The encoding, if `chunk` is a String ", "name": "encoding", "type": "String", "desc": "The encoding, if `chunk` is a String", "optional": true }, { "textRaw": "`callback` {Function} Callback for when this chunk of data is flushed ", "name": "callback", "type": "Function", "desc": "Callback for when this chunk of data is flushed", "optional": true } ] }, { "params": [ { "name": "chunk" }, { "name": "encoding", "optional": true }, { "name": "callback", "optional": true } ] } ], "desc": "

    This method writes some data to the underlying system, and calls the\nsupplied callback once the data has been fully handled.\n\n

    \n

    The return value indicates if you should continue writing right now.\nIf the data had to be buffered internally, then it will return\nfalse. Otherwise, it will return true.\n\n

    \n

    This return value is strictly advisory. You MAY continue to write,\neven if it returns false. However, writes will be buffered in\nmemory, so it is best not to do this excessively. Instead, wait for\nthe drain event before writing more data.\n\n

    \n" }, { "textRaw": "writable.end([chunk], [encoding], [callback])", "type": "method", "name": "end", "signatures": [ { "params": [ { "textRaw": "`chunk` {String | Buffer} Optional data to write ", "name": "chunk", "type": "String | Buffer", "desc": "Optional data to write", "optional": true }, { "textRaw": "`encoding` {String} The encoding, if `chunk` is a String ", "name": "encoding", "type": "String", "desc": "The encoding, if `chunk` is a String", "optional": true }, { "textRaw": "`callback` {Function} Optional callback for when the stream is finished ", "name": "callback", "type": "Function", "desc": "Optional callback for when the stream is finished", "optional": true } ] }, { "params": [ { "name": "chunk", "optional": true }, { "name": "encoding", "optional": true }, { "name": "callback", "optional": true } ] } ], "desc": "

    Call this method when no more data will be written to the stream. If\nsupplied, the callback is attached as a listener on the finish event.\n\n

    \n

    Calling [write()][] after calling [end()][] will raise an error.\n\n

    \n
    // write 'hello, ' and then end with 'world!'\nhttp.createServer(function (req, res) {\n  res.write('hello, ');\n  res.end('world!');\n  // writing more now is not allowed!\n});
    \n" } ], "events": [ { "textRaw": "Event: 'drain'", "type": "event", "name": "drain", "desc": "

    If a [writable.write(chunk)][] call returns false, then the drain\nevent will indicate when it is appropriate to begin writing more data\nto the stream.\n\n

    \n
    // Write the data to the supplied writable stream 1MM times.\n// Be attentive to back-pressure.\nfunction writeOneMillionTimes(writer, data, encoding, callback) {\n  var i = 1000000;\n  write();\n  function write() {\n    var ok = true;\n    do {\n      i -= 1;\n      if (i === 0) {\n        // last time!\n        writer.write(data, encoding, callback);\n      } else {\n        // see if we should continue, or wait\n        // don't pass the callback, because we're not done yet.\n        ok = writer.write(data, encoding);\n      }\n    } while (i > 0 && ok);\n    if (i > 0) {\n      // had to stop early!\n      // write some more once it drains\n      writer.once('drain', write);\n    }\n  }\n}
    \n", "params": [] }, { "textRaw": "Event: 'finish'", "type": "event", "name": "finish", "desc": "

    When the [end()][] method has been called, and all data has been flushed\nto the underlying system, this event is emitted.\n\n

    \n
    var writer = getWritableStreamSomehow();\nfor (var i = 0; i < 100; i ++) {\n  writer.write('hello, #' + i + '!\\n');\n}\nwriter.end('this is the end\\n');\nwriter.on('finish', function() {\n  console.error('all writes are now complete.');\n});
    \n", "params": [] }, { "textRaw": "Event: 'pipe'", "type": "event", "name": "pipe", "params": [], "desc": "

    This is emitted whenever the pipe() method is called on a readable\nstream, adding this writable to its set of destinations.\n\n

    \n
    var writer = getWritableStreamSomehow();\nvar reader = getReadableStreamSomehow();\nwriter.on('pipe', function(src) {\n  console.error('something is piping into the writer');\n  assert.equal(src, reader);\n});\nreader.pipe(writer);
    \n" }, { "textRaw": "Event: 'unpipe'", "type": "event", "name": "unpipe", "params": [], "desc": "

    This is emitted whenever the [unpipe()][] method is called on a\nreadable stream, removing this writable from its set of destinations.\n\n

    \n
    var writer = getWritableStreamSomehow();\nvar reader = getReadableStreamSomehow();\nwriter.on('unpipe', function(src) {\n  console.error('something has stopped piping into the writer');\n  assert.equal(src, reader);\n});\nreader.pipe(writer);\nreader.unpipe(writer);
    \n" }, { "textRaw": "Event: 'error'", "type": "event", "name": "error", "desc": "

    Emitted if there was an error when writing or piping data.\n\n

    \n", "params": [] } ] }, { "textRaw": "Class: stream.Duplex", "type": "class", "name": "stream.Duplex", "desc": "

    Duplex streams are streams that implement both the [Readable][] and\n[Writable][] interfaces. See above for usage.\n\n

    \n

    Examples of Duplex streams include:\n\n

    \n
      \n
    • [tcp sockets][]
    • \n
    • [zlib streams][]
    • \n
    • [crypto streams][]
    • \n
    \n" }, { "textRaw": "Class: stream.Transform", "type": "class", "name": "stream.Transform", "desc": "

    Transform streams are [Duplex][] streams where the output is in some way\ncomputed from the input. They implement both the [Readable][] and\n[Writable][] interfaces. See above for usage.\n\n

    \n

    Examples of Transform streams include:\n\n

    \n
      \n
    • [zlib streams][]
    • \n
    • [crypto streams][]
    • \n
    \n" } ], "miscs": [ { "textRaw": "API for Stream Consumers", "name": "API for Stream Consumers", "type": "misc", "desc": "

    Streams can be either [Readable][], [Writable][], or both ([Duplex][]).\n\n

    \n

    All streams are EventEmitters, but they also have other custom methods\nand properties depending on whether they are Readable, Writable, or\nDuplex.\n\n

    \n

    If a stream is both Readable and Writable, then it implements all of\nthe methods and events below. So, a [Duplex][] or [Transform][] stream is\nfully described by this API, though their implementation may be\nsomewhat different.\n\n

    \n

    It is not necessary to implement Stream interfaces in order to consume\nstreams in your programs. If you are implementing streaming\ninterfaces in your own program, please also refer to\n[API for Stream Implementors][] below.\n\n

    \n

    Almost all Node programs, no matter how simple, use Streams in some\nway. Here is an example of using Streams in a Node program:\n\n

    \n
    var http = require('http');\n\nvar server = http.createServer(function (req, res) {\n  // req is an http.IncomingMessage, which is a Readable Stream\n  // res is an http.ServerResponse, which is a Writable Stream\n\n  var body = '';\n  // we want to get the data as utf8 strings\n  // If you don't set an encoding, then you'll get Buffer objects\n  req.setEncoding('utf8');\n\n  // Readable streams emit 'data' events once a listener is added\n  req.on('data', function (chunk) {\n    body += chunk;\n  })\n\n  // the end event tells you that you have entire body\n  req.on('end', function () {\n    try {\n      var data = JSON.parse(body);\n    } catch (er) {\n      // uh oh!  bad json!\n      res.statusCode = 400;\n      return res.end('error: ' + er.message);\n    }\n\n    // write back something interesting to the user:\n    res.write(typeof data);\n    res.end();\n  })\n})\n\nserver.listen(1337);\n\n// $ curl localhost:1337 -d '{}'\n// object\n// $ curl localhost:1337 -d '"foo"'\n// string\n// $ curl localhost:1337 -d 'not json'\n// error: Unexpected token o
    \n", "classes": [ { "textRaw": "Class: stream.Readable", "type": "class", "name": "stream.Readable", "desc": "

    The Readable stream interface is the abstraction for a source of\ndata that you are reading from. In other words, data comes out of a\nReadable stream.\n\n

    \n

    A Readable stream will not start emitting data until you indicate that\nyou are ready to receive it.\n\n

    \n

    Readable streams have two "modes": a flowing mode and a non-flowing\nmode. When in flowing mode, data is read from the underlying system\nand provided to your program as fast as possible. In non-flowing\nmode, you must explicitly call stream.read() to get chunks of data\nout.\n\n

    \n

    Examples of readable streams include:\n\n

    \n\n", "events": [ { "textRaw": "Event: 'readable'", "type": "event", "name": "readable", "desc": "

    When a chunk of data can be read from the stream, it will emit a\n'readable' event.\n\n

    \n

    In some cases, listening for a 'readable' event will cause some data\nto be read into the internal buffer from the underlying system, if it\nhadn't already.\n\n

    \n
    var readable = getReadableStreamSomehow();\nreadable.on('readable', function() {\n  // there is some data to read now\n})
    \n

    Once the internal buffer is drained, a readable event will fire\nagain when more data is available.\n\n

    \n", "params": [] }, { "textRaw": "Event: 'data'", "type": "event", "name": "data", "params": [], "desc": "

    If you attach a data event listener, then it will switch the stream\ninto flowing mode, and data will be passed to your handler as soon as\nit is available.\n\n

    \n

    If you just want to get all the data out of the stream as fast as\npossible, this is the best way to do so.\n\n

    \n
    var readable = getReadableStreamSomehow();\nreadable.on('data', function(chunk) {\n  console.log('got %d bytes of data', chunk.length);\n})
    \n" }, { "textRaw": "Event: 'end'", "type": "event", "name": "end", "desc": "

    This event fires when no more data will be provided.\n\n

    \n

    Note that the end event will not fire unless the data is\ncompletely consumed. This can be done by switching into flowing mode,\nor by calling read() repeatedly until you get to the end.\n\n

    \n
    var readable = getReadableStreamSomehow();\nreadable.on('data', function(chunk) {\n  console.log('got %d bytes of data', chunk.length);\n})\nreadable.on('end', function() {\n  console.log('there will be no more data.');\n});
    \n", "params": [] }, { "textRaw": "Event: 'close'", "type": "event", "name": "close", "desc": "

    Emitted when the underlying resource (for example, the backing file\ndescriptor) has been closed. Not all streams will emit this.\n\n

    \n", "params": [] }, { "textRaw": "Event: 'error'", "type": "event", "name": "error", "desc": "

    Emitted if there was an error receiving data.\n\n

    \n", "params": [] } ], "methods": [ { "textRaw": "readable.read([size])", "type": "method", "name": "read", "signatures": [ { "return": { "textRaw": "Return {String | Buffer | null} ", "name": "return", "type": "String | Buffer | null" }, "params": [ { "textRaw": "`size` {Number} Optional argument to specify how much data to read. ", "name": "size", "type": "Number", "desc": "Optional argument to specify how much data to read.", "optional": true } ] }, { "params": [ { "name": "size", "optional": true } ] } ], "desc": "

    The read() method pulls some data out of the internal buffer and\nreturns it. If there is no data available, then it will return\nnull.\n\n

    \n

    If you pass in a size argument, then it will return that many\nbytes. If size bytes are not available, then it will return null.\n\n

    \n

    If you do not specify a size argument, then it will return all the\ndata in the internal buffer.\n\n

    \n

    This method should only be called in non-flowing mode. In\nflowing-mode, this method is called automatically until the internal\nbuffer is drained.\n\n

    \n
    var readable = getReadableStreamSomehow();\nreadable.on('readable', function() {\n  var chunk;\n  while (null !== (chunk = readable.read())) {\n    console.log('got %d bytes of data', chunk.length);\n  }\n});
    \n" }, { "textRaw": "readable.setEncoding(encoding)", "type": "method", "name": "setEncoding", "signatures": [ { "params": [ { "textRaw": "`encoding` {String} The encoding to use. ", "name": "encoding", "type": "String", "desc": "The encoding to use." } ] }, { "params": [ { "name": "encoding" } ] } ], "desc": "

    Call this function to cause the stream to return strings of the\nspecified encoding instead of Buffer objects. For example, if you do\nreadable.setEncoding('utf8'), then the output data will be\ninterpreted as UTF-8 data, and returned as strings. If you do\nreadable.setEncoding('hex'), then the data will be encoded in\nhexadecimal string format.\n\n

    \n

    This properly handles multi-byte characters that would otherwise be\npotentially mangled if you simply pulled the Buffers directly and\ncalled buf.toString(encoding) on them. If you want to read the data\nas strings, always use this method.\n\n

    \n
    var readable = getReadableStreamSomehow();\nreadable.setEncoding('utf8');\nreadable.on('data', function(chunk) {\n  assert.equal(typeof chunk, 'string');\n  console.log('got %d characters of string data', chunk.length);\n})
    \n" }, { "textRaw": "readable.resume()", "type": "method", "name": "resume", "desc": "

    This method will cause the readable stream to resume emitting data\nevents.\n\n

    \n

    This method will switch the stream into flowing-mode. If you do not\nwant to consume the data from a stream, but you do want to get to\nits end event, you can call readable.resume() to open the flow of\ndata.\n\n

    \n
    var readable = getReadableStreamSomehow();\nreadable.resume();\nreadable.on('end', function(chunk) {\n  console.log('got to the end, but did not read anything');\n})
    \n", "signatures": [ { "params": [] } ] }, { "textRaw": "readable.pause()", "type": "method", "name": "pause", "desc": "

    This method will cause a stream in flowing-mode to stop emitting\ndata events. Any data that becomes available will remain in the\ninternal buffer.\n\n

    \n

    This method is only relevant in flowing mode. When called on a\nnon-flowing stream, it will switch into flowing mode, but remain\npaused.\n\n

    \n
    var readable = getReadableStreamSomehow();\nreadable.on('data', function(chunk) {\n  console.log('got %d bytes of data', chunk.length);\n  readable.pause();\n  console.log('there will be no more data for 1 second');\n  setTimeout(function() {\n    console.log('now data will start flowing again');\n    readable.resume();\n  }, 1000);\n})
    \n", "signatures": [ { "params": [] } ] }, { "textRaw": "readable.pipe(destination, [options])", "type": "method", "name": "pipe", "signatures": [ { "params": [ { "textRaw": "`destination` {[Writable][] Stream} The destination for writing data ", "name": "destination", "type": "[Writable][] Stream", "desc": "The destination for writing data" }, { "textRaw": "`options` {Object} Pipe options ", "options": [ { "textRaw": "`end` {Boolean} End the writer when the reader ends. Default = `true` ", "name": "end", "type": "Boolean", "desc": "End the writer when the reader ends. Default = `true`" } ], "name": "options", "type": "Object", "desc": "Pipe options", "optional": true } ] }, { "params": [ { "name": "destination" }, { "name": "options", "optional": true } ] } ], "desc": "

    This method pulls all the data out of a readable stream, and writes it\nto the supplied destination, automatically managing the flow so that\nthe destination is not overwhelmed by a fast readable stream.\n\n

    \n

    Multiple destinations can be piped to safely.\n\n

    \n
    var readable = getReadableStreamSomehow();\nvar writable = fs.createWriteStream('file.txt');\n// All the data from readable goes into 'file.txt'\nreadable.pipe(writable);
    \n

    This function returns the destination stream, so you can set up pipe\nchains like so:\n\n

    \n
    var r = fs.createReadStream('file.txt');\nvar z = zlib.createGzip();\nvar w = fs.createWriteStream('file.txt.gz');\nr.pipe(z).pipe(w);
    \n

    For example, emulating the Unix cat command:\n\n

    \n
    process.stdin.pipe(process.stdout);
    \n

    By default [end()][] is called on the destination when the source stream\nemits end, so that destination is no longer writable. Pass { end:\nfalse } as options to keep the destination stream open.\n\n

    \n

    This keeps writer open so that "Goodbye" can be written at the\nend.\n\n

    \n
    reader.pipe(writer, { end: false });\nreader.on('end', function() {\n  writer.end('Goodbye\\n');\n});
    \n

    Note that process.stderr and process.stdout are never closed until\nthe process exits, regardless of the specified options.\n\n

    \n" }, { "textRaw": "readable.unpipe([destination])", "type": "method", "name": "unpipe", "signatures": [ { "params": [ { "textRaw": "`destination` {[Writable][] Stream} Optional specific stream to unpipe ", "name": "destination", "type": "[Writable][] Stream", "desc": "Optional specific stream to unpipe", "optional": true } ] }, { "params": [ { "name": "destination", "optional": true } ] } ], "desc": "

    This method will remove the hooks set up for a previous pipe() call.\n\n

    \n

    If the destination is not specified, then all pipes are removed.\n\n

    \n

    If the destination is specified, but no pipe is set up for it, then\nthis is a no-op.\n\n

    \n
    var readable = getReadableStreamSomehow();\nvar writable = fs.createWriteStream('file.txt');\n// All the data from readable goes into 'file.txt',\n// but only for the first second\nreadable.pipe(writable);\nsetTimeout(function() {\n  console.log('stop writing to file.txt');\n  readable.unpipe(writable);\n  console.log('manually close the file stream');\n  writable.end();\n}, 1000);
    \n" }, { "textRaw": "readable.unshift(chunk)", "type": "method", "name": "unshift", "signatures": [ { "params": [ { "textRaw": "`chunk` {Buffer | String} Chunk of data to unshift onto the read queue ", "name": "chunk", "type": "Buffer | String", "desc": "Chunk of data to unshift onto the read queue" } ] }, { "params": [ { "name": "chunk" } ] } ], "desc": "

    This is useful in certain cases where a stream is being consumed by a\nparser, which needs to "un-consume" some data that it has\noptimistically pulled out of the source, so that the stream can be\npassed on to some other party.\n\n

    \n

    If you find that you must often call stream.unshift(chunk) in your\nprograms, consider implementing a [Transform][] stream instead. (See API\nfor Stream Implementors, below.)\n\n

    \n
    // Pull off a header delimited by \\n\\n\n// use unshift() if we get too much\n// Call the callback with (error, header, stream)\nvar StringDecoder = require('string_decoder').StringDecoder;\nfunction parseHeader(stream, callback) {\n  stream.on('error', callback);\n  stream.on('readable', onReadable);\n  var decoder = new StringDecoder('utf8');\n  var header = '';\n  function onReadable() {\n    var chunk;\n    while (null !== (chunk = stream.read())) {\n      var str = decoder.write(chunk);\n      if (str.match(/\\n\\n/)) {\n        // found the header boundary\n        var split = str.split(/\\n\\n/);\n        header += split.shift();\n        var remaining = split.join('\\n\\n');\n        var buf = new Buffer(remaining, 'utf8');\n        if (buf.length)\n          stream.unshift(buf);\n        stream.removeListener('error', callback);\n        stream.removeListener('readable', onReadable);\n        // now the body of the message can be read from the stream.\n        callback(null, header, stream);\n      } else {\n        // still reading the header.\n        header += str;\n      }\n    }\n  }\n}
    \n" }, { "textRaw": "readable.wrap(stream)", "type": "method", "name": "wrap", "signatures": [ { "params": [ { "textRaw": "`stream` {Stream} An \"old style\" readable stream ", "name": "stream", "type": "Stream", "desc": "An \"old style\" readable stream" } ] }, { "params": [ { "name": "stream" } ] } ], "desc": "

    Versions of Node prior to v0.10 had streams that did not implement the\nentire Streams API as it is today. (See "Compatibility" below for\nmore information.)\n\n

    \n

    If you are using an older Node library that emits 'data' events and\nhas a pause() method that is advisory only, then you can use the\nwrap() method to create a [Readable][] stream that uses the old stream\nas its data source.\n\n

    \n

    You will very rarely ever need to call this function, but it exists\nas a convenience for interacting with old Node programs and libraries.\n\n

    \n

    For example:\n\n

    \n
    var OldReader = require('./old-api-module.js').OldReader;\nvar oreader = new OldReader;\nvar Readable = require('stream').Readable;\nvar myReader = new Readable().wrap(oreader);\n\nmyReader.on('readable', function() {\n  myReader.read(); // etc.\n});
    \n" } ] }, { "textRaw": "Class: stream.Writable", "type": "class", "name": "stream.Writable", "desc": "

    The Writable stream interface is an abstraction for a destination\nthat you are writing data to.\n\n

    \n

    Examples of writable streams include:\n\n

    \n\n", "methods": [ { "textRaw": "writable.write(chunk, [encoding], [callback])", "type": "method", "name": "write", "signatures": [ { "return": { "textRaw": "Returns: {Boolean} True if the data was handled completely. ", "name": "return", "type": "Boolean", "desc": "True if the data was handled completely." }, "params": [ { "textRaw": "`chunk` {String | Buffer} The data to write ", "name": "chunk", "type": "String | Buffer", "desc": "The data to write" }, { "textRaw": "`encoding` {String} The encoding, if `chunk` is a String ", "name": "encoding", "type": "String", "desc": "The encoding, if `chunk` is a String", "optional": true }, { "textRaw": "`callback` {Function} Callback for when this chunk of data is flushed ", "name": "callback", "type": "Function", "desc": "Callback for when this chunk of data is flushed", "optional": true } ] }, { "params": [ { "name": "chunk" }, { "name": "encoding", "optional": true }, { "name": "callback", "optional": true } ] } ], "desc": "

    This method writes some data to the underlying system, and calls the\nsupplied callback once the data has been fully handled.\n\n

    \n

    The return value indicates if you should continue writing right now.\nIf the data had to be buffered internally, then it will return\nfalse. Otherwise, it will return true.\n\n

    \n

    This return value is strictly advisory. You MAY continue to write,\neven if it returns false. However, writes will be buffered in\nmemory, so it is best not to do this excessively. Instead, wait for\nthe drain event before writing more data.\n\n

    \n" }, { "textRaw": "writable.end([chunk], [encoding], [callback])", "type": "method", "name": "end", "signatures": [ { "params": [ { "textRaw": "`chunk` {String | Buffer} Optional data to write ", "name": "chunk", "type": "String | Buffer", "desc": "Optional data to write", "optional": true }, { "textRaw": "`encoding` {String} The encoding, if `chunk` is a String ", "name": "encoding", "type": "String", "desc": "The encoding, if `chunk` is a String", "optional": true }, { "textRaw": "`callback` {Function} Optional callback for when the stream is finished ", "name": "callback", "type": "Function", "desc": "Optional callback for when the stream is finished", "optional": true } ] }, { "params": [ { "name": "chunk", "optional": true }, { "name": "encoding", "optional": true }, { "name": "callback", "optional": true } ] } ], "desc": "

    Call this method when no more data will be written to the stream. If\nsupplied, the callback is attached as a listener on the finish event.\n\n

    \n

    Calling [write()][] after calling [end()][] will raise an error.\n\n

    \n
    // write 'hello, ' and then end with 'world!'\nhttp.createServer(function (req, res) {\n  res.write('hello, ');\n  res.end('world!');\n  // writing more now is not allowed!\n});
    \n" } ], "events": [ { "textRaw": "Event: 'drain'", "type": "event", "name": "drain", "desc": "

    If a [writable.write(chunk)][] call returns false, then the drain\nevent will indicate when it is appropriate to begin writing more data\nto the stream.\n\n

    \n
    // Write the data to the supplied writable stream 1MM times.\n// Be attentive to back-pressure.\nfunction writeOneMillionTimes(writer, data, encoding, callback) {\n  var i = 1000000;\n  write();\n  function write() {\n    var ok = true;\n    do {\n      i -= 1;\n      if (i === 0) {\n        // last time!\n        writer.write(data, encoding, callback);\n      } else {\n        // see if we should continue, or wait\n        // don't pass the callback, because we're not done yet.\n        ok = writer.write(data, encoding);\n      }\n    } while (i > 0 && ok);\n    if (i > 0) {\n      // had to stop early!\n      // write some more once it drains\n      writer.once('drain', write);\n    }\n  }\n}
    \n", "params": [] }, { "textRaw": "Event: 'finish'", "type": "event", "name": "finish", "desc": "

    When the [end()][] method has been called, and all data has been flushed\nto the underlying system, this event is emitted.\n\n

    \n
    var writer = getWritableStreamSomehow();\nfor (var i = 0; i < 100; i ++) {\n  writer.write('hello, #' + i + '!\\n');\n}\nwriter.end('this is the end\\n');\nwriter.on('finish', function() {\n  console.error('all writes are now complete.');\n});
    \n", "params": [] }, { "textRaw": "Event: 'pipe'", "type": "event", "name": "pipe", "params": [], "desc": "

    This is emitted whenever the pipe() method is called on a readable\nstream, adding this writable to its set of destinations.\n\n

    \n
    var writer = getWritableStreamSomehow();\nvar reader = getReadableStreamSomehow();\nwriter.on('pipe', function(src) {\n  console.error('something is piping into the writer');\n  assert.equal(src, reader);\n});\nreader.pipe(writer);
    \n" }, { "textRaw": "Event: 'unpipe'", "type": "event", "name": "unpipe", "params": [], "desc": "

    This is emitted whenever the [unpipe()][] method is called on a\nreadable stream, removing this writable from its set of destinations.\n\n

    \n
    var writer = getWritableStreamSomehow();\nvar reader = getReadableStreamSomehow();\nwriter.on('unpipe', function(src) {\n  console.error('something has stopped piping into the writer');\n  assert.equal(src, reader);\n});\nreader.pipe(writer);\nreader.unpipe(writer);
    \n" }, { "textRaw": "Event: 'error'", "type": "event", "name": "error", "desc": "

    Emitted if there was an error when writing or piping data.\n\n

    \n", "params": [] } ] }, { "textRaw": "Class: stream.Duplex", "type": "class", "name": "stream.Duplex", "desc": "

    Duplex streams are streams that implement both the [Readable][] and\n[Writable][] interfaces. See above for usage.\n\n

    \n

    Examples of Duplex streams include:\n\n

    \n
      \n
    • [tcp sockets][]
    • \n
    • [zlib streams][]
    • \n
    • [crypto streams][]
    • \n
    \n" }, { "textRaw": "Class: stream.Transform", "type": "class", "name": "stream.Transform", "desc": "

    Transform streams are [Duplex][] streams where the output is in some way\ncomputed from the input. They implement both the [Readable][] and\n[Writable][] interfaces. See above for usage.\n\n

    \n

    Examples of Transform streams include:\n\n

    \n
      \n
    • [zlib streams][]
    • \n
    • [crypto streams][]
    • \n
    \n" } ] }, { "textRaw": "API for Stream Implementors", "name": "API for Stream Implementors", "type": "misc", "desc": "

    To implement any sort of stream, the pattern is the same:\n\n

    \n
      \n
    1. Extend the appropriate parent class in your own subclass. (The\n[util.inherits][] method is particularly helpful for this.)
    2. \n
    3. Call the appropriate parent class constructor in your constructor,\nto be sure that the internal mechanisms are set up properly.
    4. \n
    5. Implement one or more specific methods, as detailed below.
    6. \n
    \n

    The class to extend and the method(s) to implement depend on the sort\nof stream class you are writing:\n\n

    \n\n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n
    \n

    Use-case

    \n
    \n

    Class

    \n
    \n

    Method(s) to implement

    \n
    \n

    Reading only

    \n
    \n

    Readable

    \n
    \n

    [_read][]

    \n
    \n

    Writing only

    \n
    \n

    Writable

    \n
    \n

    [_write][]

    \n
    \n

    Reading and writing

    \n
    \n

    Duplex

    \n
    \n

    [_read][], [_write][]

    \n
    \n

    Operate on written data, then read the result

    \n
    \n

    Transform

    \n
    \n

    _transform, _flush

    \n
    \n\n

    In your implementation code, it is very important to never call the\nmethods described in [API for Stream Consumers][] above. Otherwise, you\ncan potentially cause adverse side effects in programs that consume\nyour streaming interfaces.\n\n

    \n", "examples": [ { "textRaw": "Class: stream.Readable", "type": "example", "name": "stream.Readable", "desc": "

    stream.Readable is an abstract class designed to be extended with an\nunderlying implementation of the [_read(size)][] method.\n\n

    \n

    Please see above under [API for Stream Consumers][] for how to consume\nstreams in your programs. What follows is an explanation of how to\nimplement Readable streams in your programs.\n\n

    \n

    Example: A Counting Stream

    \n

    This is a basic example of a Readable stream. It emits the numerals\nfrom 1 to 1,000,000 in ascending order, and then ends.\n\n

    \n
    var Readable = require('stream').Readable;\nvar util = require('util');\nutil.inherits(Counter, Readable);\n\nfunction Counter(opt) {\n  Readable.call(this, opt);\n  this._max = 1000000;\n  this._index = 1;\n}\n\nCounter.prototype._read = function() {\n  var i = this._index++;\n  if (i > this._max)\n    this.push(null);\n  else {\n    var str = '' + i;\n    var buf = new Buffer(str, 'ascii');\n    this.push(buf);\n  }\n};
    \n

    Example: SimpleProtocol v1 (Sub-optimal)

    \n

    This is similar to the parseHeader function described above, but\nimplemented as a custom stream. Also, note that this implementation\ndoes not convert the incoming data to a string.\n\n

    \n

    However, this would be better implemented as a [Transform][] stream. See\nbelow for a better implementation.\n\n

    \n
    // A parser for a simple data protocol.\n// The "header" is a JSON object, followed by 2 \\n characters, and\n// then a message body.\n//\n// NOTE: This can be done more simply as a Transform stream!\n// Using Readable directly for this is sub-optimal.  See the\n// alternative example below under the Transform section.\n\nvar Readable = require('stream').Readable;\nvar util = require('util');\n\nutil.inherits(SimpleProtocol, Readable);\n\nfunction SimpleProtocol(source, options) {\n  if (!(this instanceof SimpleProtocol))\n    return new SimpleProtocol(source, options);\n\n  Readable.call(this, options);\n  this._inBody = false;\n  this._sawFirstCr = false;\n\n  // source is a readable stream, such as a socket or file\n  this._source = source;\n\n  var self = this;\n  source.on('end', function() {\n    self.push(null);\n  });\n\n  // give it a kick whenever the source is readable\n  // read(0) will not consume any bytes\n  source.on('readable', function() {\n    self.read(0);\n  });\n\n  this._rawHeader = [];\n  this.header = null;\n}\n\nSimpleProtocol.prototype._read = function(n) {\n  if (!this._inBody) {\n    var chunk = this._source.read();\n\n    // if the source doesn't have data, we don't have data yet.\n    if (chunk === null)\n      return this.push('');\n\n    // check if the chunk has a \\n\\n\n    var split = -1;\n    for (var i = 0; i < chunk.length; i++) {\n      if (chunk[i] === 10) { // '\\n'\n        if (this._sawFirstCr) {\n          split = i;\n          break;\n        } else {\n          this._sawFirstCr = true;\n        }\n      } else {\n        this._sawFirstCr = false;\n      }\n    }\n\n    if (split === -1) {\n      // still waiting for the \\n\\n\n      // stash the chunk, and try again.\n      this._rawHeader.push(chunk);\n      this.push('');\n    } else {\n      this._inBody = true;\n      var h = chunk.slice(0, split);\n      this._rawHeader.push(h);\n      var header = Buffer.concat(this._rawHeader).toString();\n      try {\n        this.header = JSON.parse(header);\n      } catch (er) {\n        this.emit('error', new Error('invalid simple protocol data'));\n        return;\n      }\n      // now, because we got some extra data, unshift the rest\n      // back into the read queue so that our consumer will see it.\n      var b = chunk.slice(split);\n      this.unshift(b);\n\n      // and let them know that we are done parsing the header.\n      this.emit('header', this.header);\n    }\n  } else {\n    // from there on, just provide the data to our consumer.\n    // careful not to push(null), since that would indicate EOF.\n    var chunk = this._source.read();\n    if (chunk) this.push(chunk);\n  }\n};\n\n// Usage:\n// var parser = new SimpleProtocol(source);\n// Now parser is a readable stream that will emit 'header'\n// with the parsed header data.
    \n", "methods": [ { "textRaw": "new stream.Readable([options])", "type": "method", "name": "Readable", "signatures": [ { "params": [ { "textRaw": "`options` {Object} ", "options": [ { "textRaw": "`highWaterMark` {Number} The maximum number of bytes to store in the internal buffer before ceasing to read from the underlying resource. Default=16kb ", "name": "highWaterMark", "type": "Number", "desc": "The maximum number of bytes to store in the internal buffer before ceasing to read from the underlying resource. Default=16kb" }, { "textRaw": "`encoding` {String} If specified, then buffers will be decoded to strings using the specified encoding. Default=null ", "name": "encoding", "type": "String", "desc": "If specified, then buffers will be decoded to strings using the specified encoding. Default=null" }, { "textRaw": "`objectMode` {Boolean} Whether this stream should behave as a stream of objects. Meaning that stream.read(n) returns a single value instead of a Buffer of size n. Default=false ", "name": "objectMode", "type": "Boolean", "desc": "Whether this stream should behave as a stream of objects. Meaning that stream.read(n) returns a single value instead of a Buffer of size n. Default=false" } ], "name": "options", "type": "Object", "optional": true } ] }, { "params": [ { "name": "options", "optional": true } ] } ], "desc": "

    In classes that extend the Readable class, make sure to call the\nReadable constructor so that the buffering settings can be properly\ninitialized.\n\n

    \n" }, { "textRaw": "readable.\\_read(size)", "type": "method", "name": "\\_read", "signatures": [ { "params": [ { "textRaw": "`size` {Number} Number of bytes to read asynchronously ", "name": "size", "type": "Number", "desc": "Number of bytes to read asynchronously" } ] }, { "params": [ { "name": "size" } ] } ], "desc": "

    Note: Implement this function, but do NOT call it directly.\n\n

    \n

    This function should NOT be called directly. It should be implemented\nby child classes, and only called by the internal Readable class\nmethods.\n\n

    \n

    All Readable stream implementations must provide a _read method to\nfetch data from the underlying resource.\n\n

    \n

    This method is prefixed with an underscore because it is internal to\nthe class that defines it, and should not be called directly by user\nprograms. However, you are expected to override this method in\nyour own extension classes.\n\n

    \n

    When data is available, put it into the read queue by calling\nreadable.push(chunk). If push returns false, then you should stop\nreading. When _read is called again, you should start pushing more\ndata.\n\n

    \n

    The size argument is advisory. Implementations where a "read" is a\nsingle call that returns data can use this to know how much data to\nfetch. Implementations where that is not relevant, such as TCP or\nTLS, may ignore this argument, and simply provide data whenever it\nbecomes available. There is no need, for example to "wait" until\nsize bytes are available before calling [stream.push(chunk)][].\n\n

    \n" }, { "textRaw": "readable.push(chunk, [encoding])", "type": "method", "name": "push", "signatures": [ { "return": { "textRaw": "return {Boolean} Whether or not more pushes should be performed ", "name": "return", "type": "Boolean", "desc": "Whether or not more pushes should be performed" }, "params": [ { "textRaw": "`chunk` {Buffer | null | String} Chunk of data to push into the read queue ", "name": "chunk", "type": "Buffer | null | String", "desc": "Chunk of data to push into the read queue" }, { "textRaw": "`encoding` {String} Encoding of String chunks. Must be a valid Buffer encoding, such as `'utf8'` or `'ascii'` ", "name": "encoding", "type": "String", "desc": "Encoding of String chunks. Must be a valid Buffer encoding, such as `'utf8'` or `'ascii'`", "optional": true } ] }, { "params": [ { "name": "chunk" }, { "name": "encoding", "optional": true } ] } ], "desc": "

    Note: This function should be called by Readable implementors, NOT\nby consumers of Readable streams.\n\n

    \n

    The _read() function will not be called again until at least one\npush(chunk) call is made.\n\n

    \n

    The Readable class works by putting data into a read queue to be\npulled out later by calling the read() method when the 'readable'\nevent fires.\n\n

    \n

    The push() method will explicitly insert some data into the read\nqueue. If it is called with null then it will signal the end of the\ndata (EOF).\n\n

    \n

    This API is designed to be as flexible as possible. For example,\nyou may be wrapping a lower-level source which has some sort of\npause/resume mechanism, and a data callback. In those cases, you\ncould wrap the low-level source object by doing something like this:\n\n

    \n
    // source is an object with readStop() and readStart() methods,\n// and an `ondata` member that gets called when it has data, and\n// an `onend` member that gets called when the data is over.\n\nutil.inherits(SourceWrapper, Readable);\n\nfunction SourceWrapper(options) {\n  Readable.call(this, options);\n\n  this._source = getLowlevelSourceObject();\n  var self = this;\n\n  // Every time there's data, we push it into the internal buffer.\n  this._source.ondata = function(chunk) {\n    // if push() returns false, then we need to stop reading from source\n    if (!self.push(chunk))\n      self._source.readStop();\n  };\n\n  // When the source ends, we push the EOF-signalling `null` chunk\n  this._source.onend = function() {\n    self.push(null);\n  };\n}\n\n// _read will be called when the stream wants to pull more data in\n// the advisory size argument is ignored in this case.\nSourceWrapper.prototype._read = function(size) {\n  this._source.readStart();\n};
    \n" } ] } ], "classes": [ { "textRaw": "Class: stream.Writable", "type": "class", "name": "stream.Writable", "desc": "

    stream.Writable is an abstract class designed to be extended with an\nunderlying implementation of the [_write(chunk, encoding, callback)][] method.\n\n

    \n

    Please see above under [API for Stream Consumers][] for how to consume\nwritable streams in your programs. What follows is an explanation of\nhow to implement Writable streams in your programs.\n\n

    \n", "methods": [ { "textRaw": "new stream.Writable([options])", "type": "method", "name": "Writable", "signatures": [ { "params": [ { "textRaw": "`options` {Object} ", "options": [ { "textRaw": "`highWaterMark` {Number} Buffer level when [`write()`][] starts returning false. Default=16kb ", "name": "highWaterMark", "type": "Number", "desc": "Buffer level when [`write()`][] starts returning false. Default=16kb" }, { "textRaw": "`decodeStrings` {Boolean} Whether or not to decode strings into Buffers before passing them to [`_write()`][]. Default=true ", "name": "decodeStrings", "type": "Boolean", "desc": "Whether or not to decode strings into Buffers before passing them to [`_write()`][]. Default=true" } ], "name": "options", "type": "Object", "optional": true } ] }, { "params": [ { "name": "options", "optional": true } ] } ], "desc": "

    In classes that extend the Writable class, make sure to call the\nconstructor so that the buffering settings can be properly\ninitialized.\n\n

    \n" }, { "textRaw": "writable.\\_write(chunk, encoding, callback)", "type": "method", "name": "\\_write", "signatures": [ { "params": [ { "textRaw": "`chunk` {Buffer | String} The chunk to be written. Will always be a buffer unless the `decodeStrings` option was set to `false`. ", "name": "chunk", "type": "Buffer | String", "desc": "The chunk to be written. Will always be a buffer unless the `decodeStrings` option was set to `false`." }, { "textRaw": "`encoding` {String} If the chunk is a string, then this is the encoding type. Ignore chunk is a buffer. Note that chunk will **always** be a buffer unless the `decodeStrings` option is explicitly set to `false`. ", "name": "encoding", "type": "String", "desc": "If the chunk is a string, then this is the encoding type. Ignore chunk is a buffer. Note that chunk will **always** be a buffer unless the `decodeStrings` option is explicitly set to `false`." }, { "textRaw": "`callback` {Function} Call this function (optionally with an error argument) when you are done processing the supplied chunk. ", "name": "callback", "type": "Function", "desc": "Call this function (optionally with an error argument) when you are done processing the supplied chunk." } ] }, { "params": [ { "name": "chunk" }, { "name": "encoding" }, { "name": "callback" } ] } ], "desc": "

    All Writable stream implementations must provide a [_write()][]\nmethod to send data to the underlying resource.\n\n

    \n

    Note: This function MUST NOT be called directly. It should be\nimplemented by child classes, and called by the internal Writable\nclass methods only.\n\n

    \n

    Call the callback using the standard callback(error) pattern to\nsignal that the write completed successfully or with an error.\n\n

    \n

    If the decodeStrings flag is set in the constructor options, then\nchunk may be a string rather than a Buffer, and encoding will\nindicate the sort of string that it is. This is to support\nimplementations that have an optimized handling for certain string\ndata encodings. If you do not explicitly set the decodeStrings\noption to false, then you can safely ignore the encoding argument,\nand assume that chunk will always be a Buffer.\n\n

    \n

    This method is prefixed with an underscore because it is internal to\nthe class that defines it, and should not be called directly by user\nprograms. However, you are expected to override this method in\nyour own extension classes.\n\n\n

    \n" } ] }, { "textRaw": "Class: stream.Duplex", "type": "class", "name": "stream.Duplex", "desc": "

    A "duplex" stream is one that is both Readable and Writable, such as a\nTCP socket connection.\n\n

    \n

    Note that stream.Duplex is an abstract class designed to be extended\nwith an underlying implementation of the _read(size) and\n[_write(chunk, encoding, callback)][] methods as you would with a\nReadable or Writable stream class.\n\n

    \n

    Since JavaScript doesn't have multiple prototypal inheritance, this\nclass prototypally inherits from Readable, and then parasitically from\nWritable. It is thus up to the user to implement both the lowlevel\n_read(n) method as well as the lowlevel\n[_write(chunk, encoding, callback)][] method on extension duplex classes.\n\n

    \n", "methods": [ { "textRaw": "new stream.Duplex(options)", "type": "method", "name": "Duplex", "signatures": [ { "params": [ { "textRaw": "`options` {Object} Passed to both Writable and Readable constructors. Also has the following fields: ", "options": [ { "textRaw": "`allowHalfOpen` {Boolean} Default=true. If set to `false`, then the stream will automatically end the readable side when the writable side ends and vice versa. ", "name": "allowHalfOpen", "type": "Boolean", "desc": "Default=true. If set to `false`, then the stream will automatically end the readable side when the writable side ends and vice versa." } ], "name": "options", "type": "Object", "desc": "Passed to both Writable and Readable constructors. Also has the following fields:" } ] }, { "params": [ { "name": "options" } ] } ], "desc": "

    In classes that extend the Duplex class, make sure to call the\nconstructor so that the buffering settings can be properly\ninitialized.\n\n\n

    \n" } ] }, { "textRaw": "Class: stream.Transform", "type": "class", "name": "stream.Transform", "desc": "

    A "transform" stream is a duplex stream where the output is causally\nconnected in some way to the input, such as a [zlib][] stream or a\n[crypto][] stream.\n\n

    \n

    There is no requirement that the output be the same size as the input,\nthe same number of chunks, or arrive at the same time. For example, a\nHash stream will only ever have a single chunk of output which is\nprovided when the input is ended. A zlib stream will produce output\nthat is either much smaller or much larger than its input.\n\n

    \n

    Rather than implement the [_read()][] and [_write()][] methods, Transform\nclasses must implement the _transform() method, and may optionally\nalso implement the _flush() method. (See below.)\n\n

    \n", "methods": [ { "textRaw": "new stream.Transform([options])", "type": "method", "name": "Transform", "signatures": [ { "params": [ { "textRaw": "`options` {Object} Passed to both Writable and Readable constructors. ", "name": "options", "type": "Object", "desc": "Passed to both Writable and Readable constructors.", "optional": true } ] }, { "params": [ { "name": "options", "optional": true } ] } ], "desc": "

    In classes that extend the Transform class, make sure to call the\nconstructor so that the buffering settings can be properly\ninitialized.\n\n

    \n" }, { "textRaw": "transform.\\_transform(chunk, encoding, callback)", "type": "method", "name": "\\_transform", "signatures": [ { "params": [ { "textRaw": "`chunk` {Buffer | String} The chunk to be transformed. Will always be a buffer unless the `decodeStrings` option was set to `false`. ", "name": "chunk", "type": "Buffer | String", "desc": "The chunk to be transformed. Will always be a buffer unless the `decodeStrings` option was set to `false`." }, { "textRaw": "`encoding` {String} If the chunk is a string, then this is the encoding type. (Ignore if `decodeStrings` chunk is a buffer.) ", "name": "encoding", "type": "String", "desc": "If the chunk is a string, then this is the encoding type. (Ignore if `decodeStrings` chunk is a buffer.)" }, { "textRaw": "`callback` {Function} Call this function (optionally with an error argument) when you are done processing the supplied chunk. ", "name": "callback", "type": "Function", "desc": "Call this function (optionally with an error argument) when you are done processing the supplied chunk." } ] }, { "params": [ { "name": "chunk" }, { "name": "encoding" }, { "name": "callback" } ] } ], "desc": "

    Note: This function MUST NOT be called directly. It should be\nimplemented by child classes, and called by the internal Transform\nclass methods only.\n\n

    \n

    All Transform stream implementations must provide a _transform\nmethod to accept input and produce output.\n\n

    \n

    _transform should do whatever has to be done in this specific\nTransform class, to handle the bytes being written, and pass them off\nto the readable portion of the interface. Do asynchronous I/O,\nprocess things, and so on.\n\n

    \n

    Call transform.push(outputChunk) 0 or more times to generate output\nfrom this input chunk, depending on how much data you want to output\nas a result of this chunk.\n\n

    \n

    Call the callback function only when the current chunk is completely\nconsumed. Note that there may or may not be output as a result of any\nparticular input chunk.\n\n

    \n

    This method is prefixed with an underscore because it is internal to\nthe class that defines it, and should not be called directly by user\nprograms. However, you are expected to override this method in\nyour own extension classes.\n\n

    \n" }, { "textRaw": "transform.\\_flush(callback)", "type": "method", "name": "\\_flush", "signatures": [ { "params": [ { "textRaw": "`callback` {Function} Call this function (optionally with an error argument) when you are done flushing any remaining data. ", "name": "callback", "type": "Function", "desc": "Call this function (optionally with an error argument) when you are done flushing any remaining data." } ] }, { "params": [ { "name": "callback" } ] } ], "desc": "

    Note: This function MUST NOT be called directly. It MAY be implemented\nby child classes, and if so, will be called by the internal Transform\nclass methods only.\n\n

    \n

    In some cases, your transform operation may need to emit a bit more\ndata at the end of the stream. For example, a Zlib compression\nstream will store up some internal state so that it can optimally\ncompress the output. At the end, however, it needs to do the best it\ncan with what is left, so that the data will be complete.\n\n

    \n

    In those cases, you can implement a _flush method, which will be\ncalled at the very end, after all the written data is consumed, but\nbefore emitting end to signal the end of the readable side. Just\nlike with _transform, call transform.push(chunk) zero or more\ntimes, as appropriate, and call callback when the flush operation is\ncomplete.\n\n

    \n

    This method is prefixed with an underscore because it is internal to\nthe class that defines it, and should not be called directly by user\nprograms. However, you are expected to override this method in\nyour own extension classes.\n\n

    \n

    Example: SimpleProtocol parser v2

    \n

    The example above of a simple protocol parser can be implemented\nsimply by using the higher level [Transform][] stream class, similar to\nthe parseHeader and SimpleProtocol v1 examples above.\n\n

    \n

    In this example, rather than providing the input as an argument, it\nwould be piped into the parser, which is a more idiomatic Node stream\napproach.\n\n

    \n
    var util = require('util');\nvar Transform = require('stream').Transform;\nutil.inherits(SimpleProtocol, Transform);\n\nfunction SimpleProtocol(options) {\n  if (!(this instanceof SimpleProtocol))\n    return new SimpleProtocol(options);\n\n  Transform.call(this, options);\n  this._inBody = false;\n  this._sawFirstCr = false;\n  this._rawHeader = [];\n  this.header = null;\n}\n\nSimpleProtocol.prototype._transform = function(chunk, encoding, done) {\n  if (!this._inBody) {\n    // check if the chunk has a \\n\\n\n    var split = -1;\n    for (var i = 0; i < chunk.length; i++) {\n      if (chunk[i] === 10) { // '\\n'\n        if (this._sawFirstCr) {\n          split = i;\n          break;\n        } else {\n          this._sawFirstCr = true;\n        }\n      } else {\n        this._sawFirstCr = false;\n      }\n    }\n\n    if (split === -1) {\n      // still waiting for the \\n\\n\n      // stash the chunk, and try again.\n      this._rawHeader.push(chunk);\n    } else {\n      this._inBody = true;\n      var h = chunk.slice(0, split);\n      this._rawHeader.push(h);\n      var header = Buffer.concat(this._rawHeader).toString();\n      try {\n        this.header = JSON.parse(header);\n      } catch (er) {\n        this.emit('error', new Error('invalid simple protocol data'));\n        return;\n      }\n      // and let them know that we are done parsing the header.\n      this.emit('header', this.header);\n\n      // now, because we got some extra data, emit this first.\n      this.push(chunk.slice(split));\n    }\n  } else {\n    // from there on, just provide the data to our consumer as-is.\n    this.push(chunk);\n  }\n  done();\n};\n\n// Usage:\n// var parser = new SimpleProtocol();\n// source.pipe(parser)\n// Now parser is a readable stream that will emit 'header'\n// with the parsed header data.
    \n" } ] }, { "textRaw": "Class: stream.PassThrough", "type": "class", "name": "stream.PassThrough", "desc": "

    This is a trivial implementation of a [Transform][] stream that simply\npasses the input bytes across to the output. Its purpose is mainly\nfor examples and testing, but there are occasionally use cases where\nit can come in handy as a building block for novel sorts of streams.\n\n\n

    \n" } ] }, { "textRaw": "Streams: Under the Hood", "name": "Streams: Under the Hood", "type": "misc", "miscs": [ { "textRaw": "Buffering", "name": "Buffering", "type": "misc", "desc": "

    Both Writable and Readable streams will buffer data on an internal\nobject called _writableState.buffer or _readableState.buffer,\nrespectively.\n\n

    \n

    The amount of data that will potentially be buffered depends on the\nhighWaterMark option which is passed into the constructor.\n\n

    \n

    Buffering in Readable streams happens when the implementation calls\n[stream.push(chunk)][]. If the consumer of the Stream does not call\nstream.read(), then the data will sit in the internal queue until it\nis consumed.\n\n

    \n

    Buffering in Writable streams happens when the user calls\n[stream.write(chunk)][] repeatedly, even when write() returns false.\n\n

    \n

    The purpose of streams, especially with the pipe() method, is to\nlimit the buffering of data to acceptable levels, so that sources and\ndestinations of varying speed will not overwhelm the available memory.\n\n

    \n" }, { "textRaw": "`stream.read(0)`", "name": "`stream.read(0)`", "desc": "

    There are some cases where you want to trigger a refresh of the\nunderlying readable stream mechanisms, without actually consuming any\ndata. In that case, you can call stream.read(0), which will always\nreturn null.\n\n

    \n

    If the internal read buffer is below the highWaterMark, and the\nstream is not currently reading, then calling read(0) will trigger\na low-level _read call.\n\n

    \n

    There is almost never a need to do this. However, you will see some\ncases in Node's internals where this is done, particularly in the\nReadable stream class internals.\n\n

    \n", "type": "misc", "displayName": "`stream.read(0)`" }, { "textRaw": "`stream.push('')`", "name": "`stream.push('')`", "desc": "

    Pushing a zero-byte string or Buffer (when not in [Object mode][]) has an\ninteresting side effect. Because it is a call to\n[stream.push()][], it will end the reading process. However, it\ndoes not add any data to the readable buffer, so there's nothing for\na user to consume.\n\n

    \n

    Very rarely, there are cases where you have no data to provide now,\nbut the consumer of your stream (or, perhaps, another bit of your own\ncode) will know when to check again, by calling stream.read(0). In\nthose cases, you may call stream.push('').\n\n

    \n

    So far, the only use case for this functionality is in the\n[tls.CryptoStream][] class, which is deprecated in Node v0.12. If you\nfind that you have to use stream.push(''), please consider another\napproach, because it almost certainly indicates that something is\nhorribly wrong.\n\n

    \n", "type": "misc", "displayName": "`stream.push('')`" }, { "textRaw": "Compatibility with Older Node Versions", "name": "Compatibility with Older Node Versions", "type": "misc", "desc": "

    In versions of Node prior to v0.10, the Readable stream interface was\nsimpler, but also less powerful and less useful.\n\n

    \n
      \n
    • Rather than waiting for you to call the read() method, 'data'\nevents would start emitting immediately. If you needed to do some\nI/O to decide how to handle data, then you had to store the chunks\nin some kind of buffer so that they would not be lost.
    • \n
    • The pause() method was advisory, rather than guaranteed. This\nmeant that you still had to be prepared to receive 'data' events\neven when the stream was in a paused state.
    • \n
    \n

    In Node v0.10, the Readable class described below was added. For\nbackwards compatibility with older Node programs, Readable streams\nswitch into "flowing mode" when a 'data' event handler is added, or\nwhen the pause() or resume() methods are called. The effect is\nthat, even if you are not using the new read() method and\n'readable' event, you no longer have to worry about losing 'data'\nchunks.\n\n

    \n

    Most programs will continue to function normally. However, this\nintroduces an edge case in the following conditions:\n\n

    \n
      \n
    • No 'data' event handler is added.
    • \n
    • The pause() and resume() methods are never called.
    • \n
    \n

    For example, consider the following code:\n\n

    \n
    // WARNING!  BROKEN!\nnet.createServer(function(socket) {\n\n  // we add an 'end' method, but never consume the data\n  socket.on('end', function() {\n    // It will never get here.\n    socket.end('I got your message (but didnt read it)\\n');\n  });\n\n}).listen(1337);
    \n

    In versions of node prior to v0.10, the incoming message data would be\nsimply discarded. However, in Node v0.10 and beyond, the socket will\nremain paused forever.\n\n

    \n

    The workaround in this situation is to call the resume() method to\ntrigger "old mode" behavior:\n\n

    \n
    // Workaround\nnet.createServer(function(socket) {\n\n  socket.on('end', function() {\n    socket.end('I got your message (but didnt read it)\\n');\n  });\n\n  // start the flow of data, discarding it.\n  socket.resume();\n\n}).listen(1337);
    \n

    In addition to new Readable streams switching into flowing-mode, pre-v0.10\nstyle streams can be wrapped in a Readable class using the wrap()\nmethod.\n\n\n

    \n" }, { "textRaw": "Object Mode", "name": "Object Mode", "type": "misc", "desc": "

    Normally, Streams operate on Strings and Buffers exclusively.\n\n

    \n

    Streams that are in object mode can emit generic JavaScript values\nother than Buffers and Strings.\n\n

    \n

    A Readable stream in object mode will always return a single item from\na call to stream.read(size), regardless of what the size argument\nis.\n\n

    \n

    A Writable stream in object mode will always ignore the encoding\nargument to stream.write(data, encoding).\n\n

    \n

    The special value null still retains its special value for object\nmode streams. That is, for object mode readable streams, null as a\nreturn value from stream.read() indicates that there is no more\ndata, and [stream.push(null)][] will signal the end of stream data\n(EOF).\n\n

    \n

    No streams in Node core are object mode streams. This pattern is only\nused by userland streaming libraries.\n\n

    \n

    You should set objectMode in your stream child class constructor on\nthe options object. Setting objectMode mid-stream is not safe.\n\n

    \n" }, { "textRaw": "State Objects", "name": "state_objects", "desc": "

    [Readable][] streams have a member object called _readableState.\n[Writable][] streams have a member object called _writableState.\n[Duplex][] streams have both.\n\n

    \n

    These objects should generally not be modified in child classes.\nHowever, if you have a Duplex or Transform stream that should be in\nobjectMode on the readable side, and not in objectMode on the\nwritable side, then you may do this in the constructor by setting the\nflag explicitly on the appropriate state object.\n\n

    \n
    var util = require('util');\nvar StringDecoder = require('string_decoder').StringDecoder;\nvar Transform = require('stream').Transform;\nutil.inherits(JSONParseStream, Transform);\n\n// Gets \\n-delimited JSON string data, and emits the parsed objects\nfunction JSONParseStream(options) {\n  if (!(this instanceof JSONParseStream))\n    return new JSONParseStream(options);\n\n  Transform.call(this, options);\n  this._writableState.objectMode = false;\n  this._readableState.objectMode = true;\n  this._buffer = '';\n  this._decoder = new StringDecoder('utf8');\n}\n\nJSONParseStream.prototype._transform = function(chunk, encoding, cb) {\n  this._buffer += this._decoder.write(chunk);\n  // split on newlines\n  var lines = this._buffer.split(/\\r?\\n/);\n  // keep the last partial line buffered\n  this._buffer = lines.pop();\n  for (var l = 0; l < lines.length; l++) {\n    var line = lines[l];\n    try {\n      var obj = JSON.parse(line);\n    } catch (er) {\n      this.emit('error', er);\n      return;\n    }\n    // push the parsed object out to the readable consumer\n    this.push(obj);\n  }\n  cb();\n};\n\nJSONParseStream.prototype._flush = function(cb) {\n  // Just handle any leftover\n  var rem = this._buffer.trim();\n  if (rem) {\n    try {\n      var obj = JSON.parse(rem);\n    } catch (er) {\n      this.emit('error', er);\n      return;\n    }\n    // push the parsed object out to the readable consumer\n    this.push(obj);\n  }\n  cb();\n};
    \n

    The state objects contain other useful information for debugging the\nstate of streams in your programs. It is safe to look at them, but\nbeyond setting option flags in the constructor, it is not safe to\nmodify them.\n\n\n

    \n", "type": "misc", "displayName": "State Objects" } ] } ], "examples": [ { "textRaw": "Class: stream.Readable", "type": "example", "name": "stream.Readable", "desc": "

    stream.Readable is an abstract class designed to be extended with an\nunderlying implementation of the [_read(size)][] method.\n\n

    \n

    Please see above under [API for Stream Consumers][] for how to consume\nstreams in your programs. What follows is an explanation of how to\nimplement Readable streams in your programs.\n\n

    \n

    Example: A Counting Stream

    \n

    This is a basic example of a Readable stream. It emits the numerals\nfrom 1 to 1,000,000 in ascending order, and then ends.\n\n

    \n
    var Readable = require('stream').Readable;\nvar util = require('util');\nutil.inherits(Counter, Readable);\n\nfunction Counter(opt) {\n  Readable.call(this, opt);\n  this._max = 1000000;\n  this._index = 1;\n}\n\nCounter.prototype._read = function() {\n  var i = this._index++;\n  if (i > this._max)\n    this.push(null);\n  else {\n    var str = '' + i;\n    var buf = new Buffer(str, 'ascii');\n    this.push(buf);\n  }\n};
    \n

    Example: SimpleProtocol v1 (Sub-optimal)

    \n

    This is similar to the parseHeader function described above, but\nimplemented as a custom stream. Also, note that this implementation\ndoes not convert the incoming data to a string.\n\n

    \n

    However, this would be better implemented as a [Transform][] stream. See\nbelow for a better implementation.\n\n

    \n
    // A parser for a simple data protocol.\n// The "header" is a JSON object, followed by 2 \\n characters, and\n// then a message body.\n//\n// NOTE: This can be done more simply as a Transform stream!\n// Using Readable directly for this is sub-optimal.  See the\n// alternative example below under the Transform section.\n\nvar Readable = require('stream').Readable;\nvar util = require('util');\n\nutil.inherits(SimpleProtocol, Readable);\n\nfunction SimpleProtocol(source, options) {\n  if (!(this instanceof SimpleProtocol))\n    return new SimpleProtocol(source, options);\n\n  Readable.call(this, options);\n  this._inBody = false;\n  this._sawFirstCr = false;\n\n  // source is a readable stream, such as a socket or file\n  this._source = source;\n\n  var self = this;\n  source.on('end', function() {\n    self.push(null);\n  });\n\n  // give it a kick whenever the source is readable\n  // read(0) will not consume any bytes\n  source.on('readable', function() {\n    self.read(0);\n  });\n\n  this._rawHeader = [];\n  this.header = null;\n}\n\nSimpleProtocol.prototype._read = function(n) {\n  if (!this._inBody) {\n    var chunk = this._source.read();\n\n    // if the source doesn't have data, we don't have data yet.\n    if (chunk === null)\n      return this.push('');\n\n    // check if the chunk has a \\n\\n\n    var split = -1;\n    for (var i = 0; i < chunk.length; i++) {\n      if (chunk[i] === 10) { // '\\n'\n        if (this._sawFirstCr) {\n          split = i;\n          break;\n        } else {\n          this._sawFirstCr = true;\n        }\n      } else {\n        this._sawFirstCr = false;\n      }\n    }\n\n    if (split === -1) {\n      // still waiting for the \\n\\n\n      // stash the chunk, and try again.\n      this._rawHeader.push(chunk);\n      this.push('');\n    } else {\n      this._inBody = true;\n      var h = chunk.slice(0, split);\n      this._rawHeader.push(h);\n      var header = Buffer.concat(this._rawHeader).toString();\n      try {\n        this.header = JSON.parse(header);\n      } catch (er) {\n        this.emit('error', new Error('invalid simple protocol data'));\n        return;\n      }\n      // now, because we got some extra data, unshift the rest\n      // back into the read queue so that our consumer will see it.\n      var b = chunk.slice(split);\n      this.unshift(b);\n\n      // and let them know that we are done parsing the header.\n      this.emit('header', this.header);\n    }\n  } else {\n    // from there on, just provide the data to our consumer.\n    // careful not to push(null), since that would indicate EOF.\n    var chunk = this._source.read();\n    if (chunk) this.push(chunk);\n  }\n};\n\n// Usage:\n// var parser = new SimpleProtocol(source);\n// Now parser is a readable stream that will emit 'header'\n// with the parsed header data.
    \n", "methods": [ { "textRaw": "new stream.Readable([options])", "type": "method", "name": "Readable", "signatures": [ { "params": [ { "textRaw": "`options` {Object} ", "options": [ { "textRaw": "`highWaterMark` {Number} The maximum number of bytes to store in the internal buffer before ceasing to read from the underlying resource. Default=16kb ", "name": "highWaterMark", "type": "Number", "desc": "The maximum number of bytes to store in the internal buffer before ceasing to read from the underlying resource. Default=16kb" }, { "textRaw": "`encoding` {String} If specified, then buffers will be decoded to strings using the specified encoding. Default=null ", "name": "encoding", "type": "String", "desc": "If specified, then buffers will be decoded to strings using the specified encoding. Default=null" }, { "textRaw": "`objectMode` {Boolean} Whether this stream should behave as a stream of objects. Meaning that stream.read(n) returns a single value instead of a Buffer of size n. Default=false ", "name": "objectMode", "type": "Boolean", "desc": "Whether this stream should behave as a stream of objects. Meaning that stream.read(n) returns a single value instead of a Buffer of size n. Default=false" } ], "name": "options", "type": "Object", "optional": true } ] }, { "params": [ { "name": "options", "optional": true } ] } ], "desc": "

    In classes that extend the Readable class, make sure to call the\nReadable constructor so that the buffering settings can be properly\ninitialized.\n\n

    \n" }, { "textRaw": "readable.\\_read(size)", "type": "method", "name": "\\_read", "signatures": [ { "params": [ { "textRaw": "`size` {Number} Number of bytes to read asynchronously ", "name": "size", "type": "Number", "desc": "Number of bytes to read asynchronously" } ] }, { "params": [ { "name": "size" } ] } ], "desc": "

    Note: Implement this function, but do NOT call it directly.\n\n

    \n

    This function should NOT be called directly. It should be implemented\nby child classes, and only called by the internal Readable class\nmethods.\n\n

    \n

    All Readable stream implementations must provide a _read method to\nfetch data from the underlying resource.\n\n

    \n

    This method is prefixed with an underscore because it is internal to\nthe class that defines it, and should not be called directly by user\nprograms. However, you are expected to override this method in\nyour own extension classes.\n\n

    \n

    When data is available, put it into the read queue by calling\nreadable.push(chunk). If push returns false, then you should stop\nreading. When _read is called again, you should start pushing more\ndata.\n\n

    \n

    The size argument is advisory. Implementations where a "read" is a\nsingle call that returns data can use this to know how much data to\nfetch. Implementations where that is not relevant, such as TCP or\nTLS, may ignore this argument, and simply provide data whenever it\nbecomes available. There is no need, for example to "wait" until\nsize bytes are available before calling [stream.push(chunk)][].\n\n

    \n" }, { "textRaw": "readable.push(chunk, [encoding])", "type": "method", "name": "push", "signatures": [ { "return": { "textRaw": "return {Boolean} Whether or not more pushes should be performed ", "name": "return", "type": "Boolean", "desc": "Whether or not more pushes should be performed" }, "params": [ { "textRaw": "`chunk` {Buffer | null | String} Chunk of data to push into the read queue ", "name": "chunk", "type": "Buffer | null | String", "desc": "Chunk of data to push into the read queue" }, { "textRaw": "`encoding` {String} Encoding of String chunks. Must be a valid Buffer encoding, such as `'utf8'` or `'ascii'` ", "name": "encoding", "type": "String", "desc": "Encoding of String chunks. Must be a valid Buffer encoding, such as `'utf8'` or `'ascii'`", "optional": true } ] }, { "params": [ { "name": "chunk" }, { "name": "encoding", "optional": true } ] } ], "desc": "

    Note: This function should be called by Readable implementors, NOT\nby consumers of Readable streams.\n\n

    \n

    The _read() function will not be called again until at least one\npush(chunk) call is made.\n\n

    \n

    The Readable class works by putting data into a read queue to be\npulled out later by calling the read() method when the 'readable'\nevent fires.\n\n

    \n

    The push() method will explicitly insert some data into the read\nqueue. If it is called with null then it will signal the end of the\ndata (EOF).\n\n

    \n

    This API is designed to be as flexible as possible. For example,\nyou may be wrapping a lower-level source which has some sort of\npause/resume mechanism, and a data callback. In those cases, you\ncould wrap the low-level source object by doing something like this:\n\n

    \n
    // source is an object with readStop() and readStart() methods,\n// and an `ondata` member that gets called when it has data, and\n// an `onend` member that gets called when the data is over.\n\nutil.inherits(SourceWrapper, Readable);\n\nfunction SourceWrapper(options) {\n  Readable.call(this, options);\n\n  this._source = getLowlevelSourceObject();\n  var self = this;\n\n  // Every time there's data, we push it into the internal buffer.\n  this._source.ondata = function(chunk) {\n    // if push() returns false, then we need to stop reading from source\n    if (!self.push(chunk))\n      self._source.readStop();\n  };\n\n  // When the source ends, we push the EOF-signalling `null` chunk\n  this._source.onend = function() {\n    self.push(null);\n  };\n}\n\n// _read will be called when the stream wants to pull more data in\n// the advisory size argument is ignored in this case.\nSourceWrapper.prototype._read = function(size) {\n  this._source.readStart();\n};
    \n" } ] } ], "type": "module", "displayName": "Stream" }, { "textRaw": "Crypto", "name": "crypto", "desc": "
    Stability: 2 - Unstable; API changes are being discussed for\nfuture versions.  Breaking changes will be minimized.  See below.
    \n

    Use require('crypto') to access this module.\n\n

    \n

    The crypto module offers a way of encapsulating secure credentials to be\nused as part of a secure HTTPS net or http connection.\n\n

    \n

    It also offers a set of wrappers for OpenSSL's hash, hmac, cipher,\ndecipher, sign and verify methods.\n\n\n

    \n", "methods": [ { "textRaw": "crypto.getCiphers()", "type": "method", "name": "getCiphers", "desc": "

    Returns an array with the names of the supported ciphers.\n\n

    \n

    Example:\n\n

    \n
    var ciphers = crypto.getCiphers();\nconsole.log(ciphers); // ['AES-128-CBC', 'AES-128-CBC-HMAC-SHA1', ...]
    \n", "signatures": [ { "params": [] } ] }, { "textRaw": "crypto.getHashes()", "type": "method", "name": "getHashes", "desc": "

    Returns an array with the names of the supported hash algorithms.\n\n

    \n

    Example:\n\n

    \n
    var hashes = crypto.getHashes();\nconsole.log(hashes); // ['sha', 'sha1', 'sha1WithRSAEncryption', ...]
    \n", "signatures": [ { "params": [] } ] }, { "textRaw": "crypto.createCredentials(details)", "type": "method", "name": "createCredentials", "desc": "

    Creates a credentials object, with the optional details being a\ndictionary with keys:\n\n

    \n
      \n
    • pfx : A string or buffer holding the PFX or PKCS12 encoded private\nkey, certificate and CA certificates
    • \n
    • key : A string holding the PEM encoded private key
    • \n
    • passphrase : A string of passphrase for the private key or pfx
    • \n
    • cert : A string holding the PEM encoded certificate
    • \n
    • ca : Either a string or list of strings of PEM encoded CA\ncertificates to trust.
    • \n
    • crl : Either a string or list of strings of PEM encoded CRLs\n(Certificate Revocation List)
    • \n
    • ciphers: A string describing the ciphers to use or exclude.\nConsult\nhttp://www.openssl.org/docs/apps/ciphers.html#CIPHER_LIST_FORMAT\nfor details on the format.
    • \n
    \n

    If no 'ca' details are given, then node.js will use the default\npublicly trusted list of CAs as given in\n

    \n

    http://mxr.mozilla.org/mozilla/source/security/nss/lib/ckfw/builtins/certdata.txt.\n\n\n

    \n", "signatures": [ { "params": [ { "name": "details" } ] } ] }, { "textRaw": "crypto.createHash(algorithm)", "type": "method", "name": "createHash", "desc": "

    Creates and returns a hash object, a cryptographic hash with the given\nalgorithm which can be used to generate hash digests.\n\n

    \n

    algorithm is dependent on the available algorithms supported by the\nversion of OpenSSL on the platform. Examples are 'sha1', 'md5',\n'sha256', 'sha512', etc. On recent releases, openssl\nlist-message-digest-algorithms will display the available digest\nalgorithms.\n\n

    \n

    Example: this program that takes the sha1 sum of a file\n\n

    \n
    var filename = process.argv[2];\nvar crypto = require('crypto');\nvar fs = require('fs');\n\nvar shasum = crypto.createHash('sha1');\n\nvar s = fs.ReadStream(filename);\ns.on('data', function(d) {\n  shasum.update(d);\n});\n\ns.on('end', function() {\n  var d = shasum.digest('hex');\n  console.log(d + '  ' + filename);\n});
    \n", "signatures": [ { "params": [ { "name": "algorithm" } ] } ] }, { "textRaw": "crypto.createHmac(algorithm, key)", "type": "method", "name": "createHmac", "desc": "

    Creates and returns a hmac object, a cryptographic hmac with the given\nalgorithm and key.\n\n

    \n

    It is a stream that is both readable and writable. The\nwritten data is used to compute the hmac. Once the writable side of\nthe stream is ended, use the read() method to get the computed\ndigest. The legacy update and digest methods are also supported.\n\n

    \n

    algorithm is dependent on the available algorithms supported by\nOpenSSL - see createHash above. key is the hmac key to be used.\n\n

    \n", "signatures": [ { "params": [ { "name": "algorithm" }, { "name": "key" } ] } ] }, { "textRaw": "crypto.createCipher(algorithm, password)", "type": "method", "name": "createCipher", "desc": "

    Creates and returns a cipher object, with the given algorithm and\npassword.\n\n

    \n

    algorithm is dependent on OpenSSL, examples are 'aes192', etc. On\nrecent releases, openssl list-cipher-algorithms will display the\navailable cipher algorithms. password is used to derive key and IV,\nwhich must be a 'binary' encoded string or a buffer.\n\n

    \n

    It is a stream that is both readable and writable. The\nwritten data is used to compute the hash. Once the writable side of\nthe stream is ended, use the read() method to get the computed hash\ndigest. The legacy update and digest methods are also supported.\n\n

    \n", "signatures": [ { "params": [ { "name": "algorithm" }, { "name": "password" } ] } ] }, { "textRaw": "crypto.createCipheriv(algorithm, key, iv)", "type": "method", "name": "createCipheriv", "desc": "

    Creates and returns a cipher object, with the given algorithm, key and\niv.\n\n

    \n

    algorithm is the same as the argument to createCipher(). key is\nthe raw key used by the algorithm. iv is an initialization\nvector.\n\n

    \n

    key and iv must be 'binary' encoded strings or\nbuffers.\n\n

    \n", "signatures": [ { "params": [ { "name": "algorithm" }, { "name": "key" }, { "name": "iv" } ] } ] }, { "textRaw": "crypto.createDecipher(algorithm, password)", "type": "method", "name": "createDecipher", "desc": "

    Creates and returns a decipher object, with the given algorithm and\nkey. This is the mirror of the [createCipher()][] above.\n\n

    \n", "signatures": [ { "params": [ { "name": "algorithm" }, { "name": "password" } ] } ] }, { "textRaw": "crypto.createDecipheriv(algorithm, key, iv)", "type": "method", "name": "createDecipheriv", "desc": "

    Creates and returns a decipher object, with the given algorithm, key\nand iv. This is the mirror of the [createCipheriv()][] above.\n\n

    \n", "signatures": [ { "params": [ { "name": "algorithm" }, { "name": "key" }, { "name": "iv" } ] } ] }, { "textRaw": "crypto.createSign(algorithm)", "type": "method", "name": "createSign", "desc": "

    Creates and returns a signing object, with the given algorithm. On\nrecent OpenSSL releases, openssl list-public-key-algorithms will\ndisplay the available signing algorithms. Examples are 'RSA-SHA256'.\n\n

    \n", "signatures": [ { "params": [ { "name": "algorithm" } ] } ] }, { "textRaw": "crypto.createVerify(algorithm)", "type": "method", "name": "createVerify", "desc": "

    Creates and returns a verification object, with the given algorithm.\nThis is the mirror of the signing object above.\n\n

    \n", "signatures": [ { "params": [ { "name": "algorithm" } ] } ] }, { "textRaw": "crypto.createDiffieHellman(prime_length)", "type": "method", "name": "createDiffieHellman", "desc": "

    Creates a Diffie-Hellman key exchange object and generates a prime of\nthe given bit length. The generator used is 2.\n\n

    \n", "signatures": [ { "params": [ { "name": "prime_length" } ] } ] }, { "textRaw": "crypto.createDiffieHellman(prime, [encoding])", "type": "method", "name": "createDiffieHellman", "desc": "

    Creates a Diffie-Hellman key exchange object using the supplied prime.\nThe generator used is 2. Encoding can be 'binary', 'hex', or\n'base64'. If no encoding is specified, then a buffer is expected.\n\n

    \n", "signatures": [ { "params": [ { "name": "prime" }, { "name": "encoding", "optional": true } ] } ] }, { "textRaw": "crypto.getDiffieHellman(group_name)", "type": "method", "name": "getDiffieHellman", "desc": "

    Creates a predefined Diffie-Hellman key exchange object. The\nsupported groups are: 'modp1', 'modp2', 'modp5' (defined in [RFC\n2412][]) and 'modp14', 'modp15', 'modp16', 'modp17',\n'modp18' (defined in [RFC 3526][]). The returned object mimics the\ninterface of objects created by [crypto.createDiffieHellman()][]\nabove, but will not allow to change the keys (with\n[diffieHellman.setPublicKey()][] for example). The advantage of using\nthis routine is that the parties don't have to generate nor exchange\ngroup modulus beforehand, saving both processor and communication\ntime.\n\n

    \n

    Example (obtaining a shared secret):\n\n

    \n
    var crypto = require('crypto');\nvar alice = crypto.getDiffieHellman('modp5');\nvar bob = crypto.getDiffieHellman('modp5');\n\nalice.generateKeys();\nbob.generateKeys();\n\nvar alice_secret = alice.computeSecret(bob.getPublicKey(), null, 'hex');\nvar bob_secret = bob.computeSecret(alice.getPublicKey(), null, 'hex');\n\n/* alice_secret and bob_secret should be the same */\nconsole.log(alice_secret == bob_secret);
    \n", "signatures": [ { "params": [ { "name": "group_name" } ] } ] }, { "textRaw": "crypto.pbkdf2(password, salt, iterations, keylen, callback)", "type": "method", "name": "pbkdf2", "desc": "

    Asynchronous PBKDF2 applies pseudorandom function HMAC-SHA1 to derive\na key of given length from the given password, salt and iterations.\nThe callback gets two arguments (err, derivedKey).\n\n

    \n", "signatures": [ { "params": [ { "name": "password" }, { "name": "salt" }, { "name": "iterations" }, { "name": "keylen" }, { "name": "callback" } ] } ] }, { "textRaw": "crypto.pbkdf2Sync(password, salt, iterations, keylen)", "type": "method", "name": "pbkdf2Sync", "desc": "

    Synchronous PBKDF2 function. Returns derivedKey or throws error.\n\n

    \n", "signatures": [ { "params": [ { "name": "password" }, { "name": "salt" }, { "name": "iterations" }, { "name": "keylen" } ] } ] }, { "textRaw": "crypto.randomBytes(size, [callback])", "type": "method", "name": "randomBytes", "desc": "

    Generates cryptographically strong pseudo-random data. Usage:\n\n

    \n
    // async\ncrypto.randomBytes(256, function(ex, buf) {\n  if (ex) throw ex;\n  console.log('Have %d bytes of random data: %s', buf.length, buf);\n});\n\n// sync\ntry {\n  var buf = crypto.randomBytes(256);\n  console.log('Have %d bytes of random data: %s', buf.length, buf);\n} catch (ex) {\n  // handle error\n  // most likely, entropy sources are drained\n}
    \n

    NOTE: Will throw error or invoke callback with error, if there is not enough\naccumulated entropy to generate cryptographically strong data. In other words,\ncrypto.randomBytes without callback will not block even if all entropy sources\nare drained.\n\n

    \n", "signatures": [ { "params": [ { "name": "size" }, { "name": "callback", "optional": true } ] } ] }, { "textRaw": "crypto.pseudoRandomBytes(size, [callback])", "type": "method", "name": "pseudoRandomBytes", "desc": "

    Generates non-cryptographically strong pseudo-random data. The data\nreturned will be unique if it is sufficiently long, but is not\nnecessarily unpredictable. For this reason, the output of this\nfunction should never be used where unpredictability is important,\nsuch as in the generation of encryption keys.\n\n

    \n

    Usage is otherwise identical to crypto.randomBytes.\n\n

    \n", "signatures": [ { "params": [ { "name": "size" }, { "name": "callback", "optional": true } ] } ] } ], "classes": [ { "textRaw": "Class: Hash", "type": "class", "name": "Hash", "desc": "

    The class for creating hash digests of data.\n\n

    \n

    It is a stream that is both readable and writable. The\nwritten data is used to compute the hash. Once the writable side of\nthe stream is ended, use the read() method to get the computed hash\ndigest. The legacy update and digest methods are also supported.\n\n

    \n

    Returned by crypto.createHash.\n\n

    \n", "methods": [ { "textRaw": "hash.update(data, [input_encoding])", "type": "method", "name": "update", "desc": "

    Updates the hash content with the given data, the encoding of which\nis given in input_encoding and can be 'utf8', 'ascii' or\n'binary'. If no encoding is provided and the input is a string an\nencoding of 'binary' is enforced. If data is a Buffer then\ninput_encoding is ignored.\n\n

    \n

    This can be called many times with new data as it is streamed.\n\n

    \n", "signatures": [ { "params": [ { "name": "data" }, { "name": "input_encoding", "optional": true } ] } ] }, { "textRaw": "hash.digest([encoding])", "type": "method", "name": "digest", "desc": "

    Calculates the digest of all of the passed data to be hashed. The\nencoding can be 'hex', 'binary' or 'base64'. If no encoding\nis provided, then a buffer is returned.\n\n

    \n

    Note: hash object can not be used after digest() method has been\ncalled.\n\n\n

    \n", "signatures": [ { "params": [ { "name": "encoding", "optional": true } ] } ] } ] }, { "textRaw": "Class: Hmac", "type": "class", "name": "Hmac", "desc": "

    Class for creating cryptographic hmac content.\n\n

    \n

    Returned by crypto.createHmac.\n\n

    \n", "methods": [ { "textRaw": "hmac.update(data)", "type": "method", "name": "update", "desc": "

    Update the hmac content with the given data. This can be called\nmany times with new data as it is streamed.\n\n

    \n", "signatures": [ { "params": [ { "name": "data" } ] } ] }, { "textRaw": "hmac.digest([encoding])", "type": "method", "name": "digest", "desc": "

    Calculates the digest of all of the passed data to the hmac. The\nencoding can be 'hex', 'binary' or 'base64'. If no encoding\nis provided, then a buffer is returned.\n\n

    \n

    Note: hmac object can not be used after digest() method has been\ncalled.\n\n\n

    \n", "signatures": [ { "params": [ { "name": "encoding", "optional": true } ] } ] } ] }, { "textRaw": "Class: Cipher", "type": "class", "name": "Cipher", "desc": "

    Class for encrypting data.\n\n

    \n

    Returned by crypto.createCipher and crypto.createCipheriv.\n\n

    \n

    Cipher objects are streams that are both readable and\nwritable. The written plain text data is used to produce the\nencrypted data on the readable side. The legacy update and final\nmethods are also supported.\n\n

    \n", "methods": [ { "textRaw": "cipher.update(data, [input_encoding], [output_encoding])", "type": "method", "name": "update", "desc": "

    Updates the cipher with data, the encoding of which is given in\ninput_encoding and can be 'utf8', 'ascii' or 'binary'. If no\nencoding is provided, then a buffer is expected.\nIf data is a Buffer then input_encoding is ignored.\n\n

    \n

    The output_encoding specifies the output format of the enciphered\ndata, and can be 'binary', 'base64' or 'hex'. If no encoding is\nprovided, then a buffer is returned.\n\n

    \n

    Returns the enciphered contents, and can be called many times with new\ndata as it is streamed.\n\n

    \n", "signatures": [ { "params": [ { "name": "data" }, { "name": "input_encoding", "optional": true }, { "name": "output_encoding", "optional": true } ] } ] }, { "textRaw": "cipher.final([output_encoding])", "type": "method", "name": "final", "desc": "

    Returns any remaining enciphered contents, with output_encoding\nbeing one of: 'binary', 'base64' or 'hex'. If no encoding is\nprovided, then a buffer is returned.\n\n

    \n

    Note: cipher object can not be used after final() method has been\ncalled.\n\n

    \n", "signatures": [ { "params": [ { "name": "output_encoding", "optional": true } ] } ] }, { "textRaw": "cipher.setAutoPadding(auto_padding=true)", "type": "method", "name": "setAutoPadding", "desc": "

    You can disable automatic padding of the input data to block size. If\nauto_padding is false, the length of the entire input data must be a\nmultiple of the cipher's block size or final will fail. Useful for\nnon-standard padding, e.g. using 0x0 instead of PKCS padding. You\nmust call this before cipher.final.\n\n\n

    \n", "signatures": [ { "params": [ { "name": "auto_padding", "default": "true" } ] } ] } ] }, { "textRaw": "Class: Decipher", "type": "class", "name": "Decipher", "desc": "

    Class for decrypting data.\n\n

    \n

    Returned by crypto.createDecipher and crypto.createDecipheriv.\n\n

    \n

    Decipher objects are streams that are both readable and\nwritable. The written enciphered data is used to produce the\nplain-text data on the the readable side. The legacy update and\nfinal methods are also supported.\n\n

    \n", "methods": [ { "textRaw": "decipher.update(data, [input_encoding], [output_encoding])", "type": "method", "name": "update", "desc": "

    Updates the decipher with data, which is encoded in 'binary',\n'base64' or 'hex'. If no encoding is provided, then a buffer is\nexpected.\nIf data is a Buffer then input_encoding is ignored.\n\n

    \n

    The output_decoding specifies in what format to return the\ndeciphered plaintext: 'binary', 'ascii' or 'utf8'. If no\nencoding is provided, then a buffer is returned.\n\n

    \n", "signatures": [ { "params": [ { "name": "data" }, { "name": "input_encoding", "optional": true }, { "name": "output_encoding", "optional": true } ] } ] }, { "textRaw": "decipher.final([output_encoding])", "type": "method", "name": "final", "desc": "

    Returns any remaining plaintext which is deciphered, with\noutput_encoding being one of: 'binary', 'ascii' or 'utf8'. If\nno encoding is provided, then a buffer is returned.\n\n

    \n

    Note: decipher object can not be used after final() method has been\ncalled.\n\n

    \n", "signatures": [ { "params": [ { "name": "output_encoding", "optional": true } ] } ] }, { "textRaw": "decipher.setAutoPadding(auto_padding=true)", "type": "method", "name": "setAutoPadding", "desc": "

    You can disable auto padding if the data has been encrypted without\nstandard block padding to prevent decipher.final from checking and\nremoving it. Can only work if the input data's length is a multiple of\nthe ciphers block size. You must call this before streaming data to\ndecipher.update.\n\n

    \n", "signatures": [ { "params": [ { "name": "auto_padding", "default": "true" } ] } ] } ] }, { "textRaw": "Class: Sign", "type": "class", "name": "Sign", "desc": "

    Class for generating signatures.\n\n

    \n

    Returned by crypto.createSign.\n\n

    \n

    Sign objects are writable streams. The written data is\nused to generate the signature. Once all of the data has been\nwritten, the sign method will return the signature. The legacy\nupdate method is also supported.\n\n

    \n", "methods": [ { "textRaw": "sign.update(data)", "type": "method", "name": "update", "desc": "

    Updates the sign object with data. This can be called many times\nwith new data as it is streamed.\n\n

    \n", "signatures": [ { "params": [ { "name": "data" } ] } ] }, { "textRaw": "sign.sign(private_key, [output_format])", "type": "method", "name": "sign", "desc": "

    Calculates the signature on all the updated data passed through the\nsign. private_key is a string containing the PEM encoded private\nkey for signing.\n\n

    \n

    Returns the signature in output_format which can be 'binary',\n'hex' or 'base64'. If no encoding is provided, then a buffer is\nreturned.\n\n

    \n

    Note: sign object can not be used after sign() method has been\ncalled.\n\n

    \n", "signatures": [ { "params": [ { "name": "private_key" }, { "name": "output_format", "optional": true } ] } ] } ] }, { "textRaw": "Class: Verify", "type": "class", "name": "Verify", "desc": "

    Class for verifying signatures.\n\n

    \n

    Returned by crypto.createVerify.\n\n

    \n

    Verify objects are writable streams. The written data\nis used to validate against the supplied signature. Once all of the\ndata has been written, the verify method will return true if the\nsupplied signature is valid. The legacy update method is also\nsupported.\n\n

    \n", "methods": [ { "textRaw": "verifier.update(data)", "type": "method", "name": "update", "desc": "

    Updates the verifier object with data. This can be called many times\nwith new data as it is streamed.\n\n

    \n", "signatures": [ { "params": [ { "name": "data" } ] } ] }, { "textRaw": "verifier.verify(object, signature, [signature_format])", "type": "method", "name": "verify", "desc": "

    Verifies the signed data by using the object and signature.\nobject is a string containing a PEM encoded object, which can be\none of RSA public key, DSA public key, or X.509 certificate.\nsignature is the previously calculated signature for the data, in\nthe signature_format which can be 'binary', 'hex' or 'base64'.\nIf no encoding is specified, then a buffer is expected.\n\n

    \n

    Returns true or false depending on the validity of the signature for\nthe data and public key.\n\n

    \n

    Note: verifier object can not be used after verify() method has been\ncalled.\n\n

    \n", "signatures": [ { "params": [ { "name": "object" }, { "name": "signature" }, { "name": "signature_format", "optional": true } ] } ] } ] }, { "textRaw": "Class: DiffieHellman", "type": "class", "name": "DiffieHellman", "desc": "

    The class for creating Diffie-Hellman key exchanges.\n\n

    \n

    Returned by crypto.createDiffieHellman.\n\n

    \n", "methods": [ { "textRaw": "diffieHellman.generateKeys([encoding])", "type": "method", "name": "generateKeys", "desc": "

    Generates private and public Diffie-Hellman key values, and returns\nthe public key in the specified encoding. This key should be\ntransferred to the other party. Encoding can be 'binary', 'hex',\nor 'base64'. If no encoding is provided, then a buffer is returned.\n\n

    \n", "signatures": [ { "params": [ { "name": "encoding", "optional": true } ] } ] }, { "textRaw": "diffieHellman.computeSecret(other_public_key, [input_encoding], [output_encoding])", "type": "method", "name": "computeSecret", "desc": "

    Computes the shared secret using other_public_key as the other\nparty's public key and returns the computed shared secret. Supplied\nkey is interpreted using specified input_encoding, and secret is\nencoded using specified output_encoding. Encodings can be\n'binary', 'hex', or 'base64'. If the input encoding is not\nprovided, then a buffer is expected.\n\n

    \n

    If no output encoding is given, then a buffer is returned.\n\n

    \n", "signatures": [ { "params": [ { "name": "other_public_key" }, { "name": "input_encoding", "optional": true }, { "name": "output_encoding", "optional": true } ] } ] }, { "textRaw": "diffieHellman.getPrime([encoding])", "type": "method", "name": "getPrime", "desc": "

    Returns the Diffie-Hellman prime in the specified encoding, which can\nbe 'binary', 'hex', or 'base64'. If no encoding is provided,\nthen a buffer is returned.\n\n

    \n", "signatures": [ { "params": [ { "name": "encoding", "optional": true } ] } ] }, { "textRaw": "diffieHellman.getGenerator([encoding])", "type": "method", "name": "getGenerator", "desc": "

    Returns the Diffie-Hellman prime in the specified encoding, which can\nbe 'binary', 'hex', or 'base64'. If no encoding is provided,\nthen a buffer is returned.\n\n

    \n", "signatures": [ { "params": [ { "name": "encoding", "optional": true } ] } ] }, { "textRaw": "diffieHellman.getPublicKey([encoding])", "type": "method", "name": "getPublicKey", "desc": "

    Returns the Diffie-Hellman public key in the specified encoding, which\ncan be 'binary', 'hex', or 'base64'. If no encoding is provided,\nthen a buffer is returned.\n\n

    \n", "signatures": [ { "params": [ { "name": "encoding", "optional": true } ] } ] }, { "textRaw": "diffieHellman.getPrivateKey([encoding])", "type": "method", "name": "getPrivateKey", "desc": "

    Returns the Diffie-Hellman private key in the specified encoding,\nwhich can be 'binary', 'hex', or 'base64'. If no encoding is\nprovided, then a buffer is returned.\n\n

    \n", "signatures": [ { "params": [ { "name": "encoding", "optional": true } ] } ] }, { "textRaw": "diffieHellman.setPublicKey(public_key, [encoding])", "type": "method", "name": "setPublicKey", "desc": "

    Sets the Diffie-Hellman public key. Key encoding can be 'binary',\n'hex' or 'base64'. If no encoding is provided, then a buffer is\nexpected.\n\n

    \n", "signatures": [ { "params": [ { "name": "public_key" }, { "name": "encoding", "optional": true } ] } ] }, { "textRaw": "diffieHellman.setPrivateKey(private_key, [encoding])", "type": "method", "name": "setPrivateKey", "desc": "

    Sets the Diffie-Hellman private key. Key encoding can be 'binary',\n'hex' or 'base64'. If no encoding is provided, then a buffer is\nexpected.\n\n

    \n", "signatures": [ { "params": [ { "name": "private_key" }, { "name": "encoding", "optional": true } ] } ] } ] } ], "properties": [ { "textRaw": "crypto.DEFAULT_ENCODING", "name": "DEFAULT_ENCODING", "desc": "

    The default encoding to use for functions that can take either strings\nor buffers. The default value is 'buffer', which makes it default\nto using Buffer objects. This is here to make the crypto module more\neasily compatible with legacy programs that expected 'binary' to be\nthe default encoding.\n\n

    \n

    Note that new programs will probably expect buffers, so only use this\nas a temporary measure.\n\n

    \n" } ], "modules": [ { "textRaw": "Recent API Changes", "name": "recent_api_changes", "desc": "

    The Crypto module was added to Node before there was the concept of a\nunified Stream API, and before there were Buffer objects for handling\nbinary data.\n\n

    \n

    As such, the streaming classes don't have the typical methods found on\nother Node classes, and many methods accepted and returned\nBinary-encoded strings by default rather than Buffers. This was\nchanged to use Buffers by default instead.\n\n

    \n

    This is a breaking change for some use cases, but not all.\n\n

    \n

    For example, if you currently use the default arguments to the Sign\nclass, and then pass the results to the Verify class, without ever\ninspecting the data, then it will continue to work as before. Where\nyou once got a binary string and then presented the binary string to\nthe Verify object, you'll now get a Buffer, and present the Buffer to\nthe Verify object.\n\n

    \n

    However, if you were doing things with the string data that will not\nwork properly on Buffers (such as, concatenating them, storing in\ndatabases, etc.), or you are passing binary strings to the crypto\nfunctions without an encoding argument, then you will need to start\nproviding encoding arguments to specify which encoding you'd like to\nuse. To switch to the previous style of using binary strings by\ndefault, set the crypto.DEFAULT_ENCODING field to 'binary'. Note\nthat new programs will probably expect buffers, so only use this as a\ntemporary measure.\n\n\n

    \n", "type": "module", "displayName": "Recent API Changes" } ], "type": "module", "displayName": "Crypto" }, { "textRaw": "TLS (SSL)", "name": "tls_(ssl)", "stability": 3, "stabilityText": "Stable", "desc": "

    Use require('tls') to access this module.\n\n

    \n

    The tls module uses OpenSSL to provide Transport Layer Security and/or\nSecure Socket Layer: encrypted stream communication.\n\n

    \n

    TLS/SSL is a public/private key infrastructure. Each client and each\nserver must have a private key. A private key is created like this\n\n

    \n
    openssl genrsa -out ryans-key.pem 1024
    \n

    All severs and some clients need to have a certificate. Certificates are public\nkeys signed by a Certificate Authority or self-signed. The first step to\ngetting a certificate is to create a "Certificate Signing Request" (CSR)\nfile. This is done with:\n\n

    \n
    openssl req -new -key ryans-key.pem -out ryans-csr.pem
    \n

    To create a self-signed certificate with the CSR, do this:\n\n

    \n
    openssl x509 -req -in ryans-csr.pem -signkey ryans-key.pem -out ryans-cert.pem
    \n

    Alternatively you can send the CSR to a Certificate Authority for signing.\n\n

    \n

    (TODO: docs on creating a CA, for now interested users should just look at\ntest/fixtures/keys/Makefile in the Node source code)\n\n

    \n

    To create .pfx or .p12, do this:\n\n

    \n
    openssl pkcs12 -export -in agent5-cert.pem -inkey agent5-key.pem \\\n    -certfile ca-cert.pem -out agent5.pfx
    \n
      \n
    • in: certificate
    • \n
    • inkey: private key
    • \n
    • certfile: all CA certs concatenated in one file like\ncat ca1-cert.pem ca2-cert.pem > ca-cert.pem
    • \n
    \n", "miscs": [ { "textRaw": "Client-initiated renegotiation attack mitigation", "name": "Client-initiated renegotiation attack mitigation", "type": "misc", "desc": "

    The TLS protocol lets the client renegotiate certain aspects of the TLS session.\nUnfortunately, session renegotiation requires a disproportional amount of\nserver-side resources, which makes it a potential vector for denial-of-service\nattacks.\n\n

    \n

    To mitigate this, renegotiations are limited to three times every 10 minutes. An\nerror is emitted on the [CleartextStream][] instance when the threshold is\nexceeded. The limits are configurable:\n\n

    \n
      \n
    • tls.CLIENT_RENEG_LIMIT: renegotiation limit, default is 3.

      \n
    • \n
    • tls.CLIENT_RENEG_WINDOW: renegotiation window in seconds, default is\n10 minutes.

      \n
    • \n
    \n

    Don't change the defaults unless you know what you are doing.\n\n

    \n

    To test your server, connect to it with openssl s_client -connect address:port\nand tap R<CR> (that's the letter R followed by a carriage return) a few\ntimes.\n\n\n

    \n" }, { "textRaw": "NPN and SNI", "name": "NPN and SNI", "type": "misc", "desc": "

    NPN (Next Protocol Negotiation) and SNI (Server Name Indication) are TLS\nhandshake extensions allowing you:\n\n

    \n
      \n
    • NPN - to use one TLS server for multiple protocols (HTTP, SPDY)
    • \n
    • SNI - to use one TLS server for multiple hostnames with different SSL\ncertificates.
    • \n
    \n" } ], "methods": [ { "textRaw": "tls.getCiphers()", "type": "method", "name": "getCiphers", "desc": "

    Returns an array with the names of the supported SSL ciphers.\n\n

    \n

    Example:\n\n

    \n
    var ciphers = tls.getCiphers();\nconsole.log(ciphers); // ['AES128-SHA', 'AES256-SHA', ...]
    \n", "signatures": [ { "params": [] } ] }, { "textRaw": "tls.createServer(options, [secureConnectionListener])", "type": "method", "name": "createServer", "desc": "

    Creates a new [tls.Server][]. The connectionListener argument is\nautomatically set as a listener for the [secureConnection][] event. The\noptions object has these possibilities:\n\n

    \n
      \n
    • pfx: A string or Buffer containing the private key, certificate and\nCA certs of the server in PFX or PKCS12 format. (Mutually exclusive with\nthe key, cert and ca options.)

      \n
    • \n
    • key: A string or Buffer containing the private key of the server in\nPEM format. (Required)

      \n
    • \n
    • passphrase: A string of passphrase for the private key or pfx.

      \n
    • \n
    • cert: A string or Buffer containing the certificate key of the server in\nPEM format. (Required)

      \n
    • \n
    • ca: An array of strings or Buffers of trusted certificates in PEM\nformat. If this is omitted several well known "root" CAs will be used,\nlike VeriSign. These are used to authorize connections.

      \n
    • \n
    • crl : Either a string or list of strings of PEM encoded CRLs (Certificate\nRevocation List)

      \n
    • \n
    • ciphers: A string describing the ciphers to use or exclude.

      \n

      To mitigate [BEAST attacks] it is recommended that you use this option in\nconjunction with the honorCipherOrder option described below to\nprioritize the non-CBC cipher.

      \n

      Defaults to AES128-GCM-SHA256:RC4:HIGH:!MD5:!aNULL:!EDH.\nConsult the [OpenSSL cipher list format documentation] for details on the\nformat. ECDH (Elliptic Curve Diffie-Hellman) ciphers are not yet supported.

      \n
    • \n
    \n
    `AES128-GCM-SHA256` is used when node.js is linked against OpenSSL 1.0.1\nor newer and the client speaks TLS 1.2, RC4 is used as a secure fallback.\n\n**NOTE**: Previous revisions of this section suggested `AES256-SHA` as an\nacceptable cipher. Unfortunately, `AES256-SHA` is a CBC cipher and therefore\nsusceptible to BEAST attacks. Do *not* use it.
    \n
      \n
    • handshakeTimeout: Abort the connection if the SSL/TLS handshake does not\nfinish in this many milliseconds. The default is 120 seconds.

      \n

      A 'clientError' is emitted on the tls.Server object whenever a handshake\ntimes out.

      \n
    • \n
    • honorCipherOrder : When choosing a cipher, use the server's preferences\ninstead of the client preferences.

      \n

      Note that if SSLv2 is used, the server will send its list of preferences\nto the client, and the client chooses the cipher.

      \n

      Although, this option is disabled by default, it is recommended that you\nuse this option in conjunction with the ciphers option to mitigate\nBEAST attacks.

      \n
    • \n
    • requestCert: If true the server will request a certificate from\nclients that connect and attempt to verify that certificate. Default:\nfalse.

      \n
    • \n
    • rejectUnauthorized: If true the server will reject any connection\nwhich is not authorized with the list of supplied CAs. This option only\nhas an effect if requestCert is true. Default: false.

      \n
    • \n
    • NPNProtocols: An array or Buffer of possible NPN protocols. (Protocols\nshould be ordered by their priority).

      \n
    • \n
    • SNICallback: A function that will be called if client supports SNI TLS\nextension. Only one argument will be passed to it: servername. And\nSNICallback should return SecureContext instance.\n(You can use crypto.createCredentials(...).context to get proper\nSecureContext). If SNICallback wasn't provided - default callback with\nhigh-level API will be used (see below).

      \n
    • \n
    • sessionIdContext: A string containing a opaque identifier for session\nresumption. If requestCert is true, the default is MD5 hash value\ngenerated from command-line. Otherwise, the default is not provided.

      \n
    • \n
    • secureProtocol: The SSL method to use, e.g. SSLv3_method to force\nSSL version 3. The possible values depend on your installation of\nOpenSSL and are defined in the constant [SSL_METHODS][].

      \n
    • \n
    \n

    Here is a simple example echo server:\n\n

    \n
    var tls = require('tls');\nvar fs = require('fs');\n\nvar options = {\n  key: fs.readFileSync('server-key.pem'),\n  cert: fs.readFileSync('server-cert.pem'),\n\n  // This is necessary only if using the client certificate authentication.\n  requestCert: true,\n\n  // This is necessary only if the client uses the self-signed certificate.\n  ca: [ fs.readFileSync('client-cert.pem') ]\n};\n\nvar server = tls.createServer(options, function(cleartextStream) {\n  console.log('server connected',\n              cleartextStream.authorized ? 'authorized' : 'unauthorized');\n  cleartextStream.write("welcome!\\n");\n  cleartextStream.setEncoding('utf8');\n  cleartextStream.pipe(cleartextStream);\n});\nserver.listen(8000, function() {\n  console.log('server bound');\n});
    \n

    Or\n\n

    \n
    var tls = require('tls');\nvar fs = require('fs');\n\nvar options = {\n  pfx: fs.readFileSync('server.pfx'),\n\n  // This is necessary only if using the client certificate authentication.\n  requestCert: true,\n\n};\n\nvar server = tls.createServer(options, function(cleartextStream) {\n  console.log('server connected',\n              cleartextStream.authorized ? 'authorized' : 'unauthorized');\n  cleartextStream.write("welcome!\\n");\n  cleartextStream.setEncoding('utf8');\n  cleartextStream.pipe(cleartextStream);\n});\nserver.listen(8000, function() {\n  console.log('server bound');\n});
    \n

    You can test this server by connecting to it with openssl s_client:\n\n\n

    \n
    openssl s_client -connect 127.0.0.1:8000
    \n", "signatures": [ { "params": [ { "name": "options" }, { "name": "secureConnectionListener", "optional": true } ] } ] }, { "textRaw": "tls.connect(options, [callback])", "type": "method", "name": "connect", "desc": "

    Creates a new client connection to the given port and host (old API) or\noptions.port and options.host. (If host is omitted, it defaults to\nlocalhost.) options should be an object which specifies:\n\n

    \n
      \n
    • host: Host the client should connect to

      \n
    • \n
    • port: Port the client should connect to

      \n
    • \n
    • socket: Establish secure connection on a given socket rather than\ncreating a new socket. If this option is specified, host and port\nare ignored.

      \n
    • \n
    • pfx: A string or Buffer containing the private key, certificate and\nCA certs of the server in PFX or PKCS12 format.

      \n
    • \n
    • key: A string or Buffer containing the private key of the client in\nPEM format.

      \n
    • \n
    • passphrase: A string of passphrase for the private key or pfx.

      \n
    • \n
    • cert: A string or Buffer containing the certificate key of the client in\nPEM format.

      \n
    • \n
    • ca: An array of strings or Buffers of trusted certificates in PEM\nformat. If this is omitted several well known "root" CAs will be used,\nlike VeriSign. These are used to authorize connections.

      \n
    • \n
    • rejectUnauthorized: If true, the server certificate is verified against\nthe list of supplied CAs. An 'error' event is emitted if verification\nfails. Default: true.

      \n
    • \n
    • NPNProtocols: An array of strings or Buffers containing supported NPN\nprotocols. Buffers should have following format: 0x05hello0x05world,\nwhere first byte is next protocol name's length. (Passing array should\nusually be much simpler: ['hello', 'world'].)

      \n
    • \n
    • servername: Servername for SNI (Server Name Indication) TLS extension.

      \n
    • \n
    • secureProtocol: The SSL method to use, e.g. SSLv3_method to force\nSSL version 3. The possible values depend on your installation of\nOpenSSL and are defined in the constant [SSL_METHODS][].

      \n
    • \n
    \n

    The callback parameter will be added as a listener for the\n['secureConnect'][] event.\n\n

    \n

    tls.connect() returns a [CleartextStream][] object.\n\n

    \n

    Here is an example of a client of echo server as described previously:\n\n

    \n
    var tls = require('tls');\nvar fs = require('fs');\n\nvar options = {\n  // These are necessary only if using the client certificate authentication\n  key: fs.readFileSync('client-key.pem'),\n  cert: fs.readFileSync('client-cert.pem'),\n\n  // This is necessary only if the server uses the self-signed certificate\n  ca: [ fs.readFileSync('server-cert.pem') ]\n};\n\nvar cleartextStream = tls.connect(8000, options, function() {\n  console.log('client connected',\n              cleartextStream.authorized ? 'authorized' : 'unauthorized');\n  process.stdin.pipe(cleartextStream);\n  process.stdin.resume();\n});\ncleartextStream.setEncoding('utf8');\ncleartextStream.on('data', function(data) {\n  console.log(data);\n});\ncleartextStream.on('end', function() {\n  server.close();\n});
    \n

    Or\n\n

    \n
    var tls = require('tls');\nvar fs = require('fs');\n\nvar options = {\n  pfx: fs.readFileSync('client.pfx')\n};\n\nvar cleartextStream = tls.connect(8000, options, function() {\n  console.log('client connected',\n              cleartextStream.authorized ? 'authorized' : 'unauthorized');\n  process.stdin.pipe(cleartextStream);\n  process.stdin.resume();\n});\ncleartextStream.setEncoding('utf8');\ncleartextStream.on('data', function(data) {\n  console.log(data);\n});\ncleartextStream.on('end', function() {\n  server.close();\n});
    \n", "signatures": [ { "params": [ { "name": "port" }, { "name": "host", "optional": true }, { "name": "options", "optional": true }, { "name": "callback", "optional": true } ] }, { "params": [ { "name": "options" }, { "name": "callback", "optional": true } ] } ] }, { "textRaw": "tls.connect(port, [host], [options], [callback])", "type": "method", "name": "connect", "desc": "

    Creates a new client connection to the given port and host (old API) or\noptions.port and options.host. (If host is omitted, it defaults to\nlocalhost.) options should be an object which specifies:\n\n

    \n
      \n
    • host: Host the client should connect to

      \n
    • \n
    • port: Port the client should connect to

      \n
    • \n
    • socket: Establish secure connection on a given socket rather than\ncreating a new socket. If this option is specified, host and port\nare ignored.

      \n
    • \n
    • pfx: A string or Buffer containing the private key, certificate and\nCA certs of the server in PFX or PKCS12 format.

      \n
    • \n
    • key: A string or Buffer containing the private key of the client in\nPEM format.

      \n
    • \n
    • passphrase: A string of passphrase for the private key or pfx.

      \n
    • \n
    • cert: A string or Buffer containing the certificate key of the client in\nPEM format.

      \n
    • \n
    • ca: An array of strings or Buffers of trusted certificates in PEM\nformat. If this is omitted several well known "root" CAs will be used,\nlike VeriSign. These are used to authorize connections.

      \n
    • \n
    • rejectUnauthorized: If true, the server certificate is verified against\nthe list of supplied CAs. An 'error' event is emitted if verification\nfails. Default: true.

      \n
    • \n
    • NPNProtocols: An array of strings or Buffers containing supported NPN\nprotocols. Buffers should have following format: 0x05hello0x05world,\nwhere first byte is next protocol name's length. (Passing array should\nusually be much simpler: ['hello', 'world'].)

      \n
    • \n
    • servername: Servername for SNI (Server Name Indication) TLS extension.

      \n
    • \n
    • secureProtocol: The SSL method to use, e.g. SSLv3_method to force\nSSL version 3. The possible values depend on your installation of\nOpenSSL and are defined in the constant [SSL_METHODS][].

      \n
    • \n
    \n

    The callback parameter will be added as a listener for the\n['secureConnect'][] event.\n\n

    \n

    tls.connect() returns a [CleartextStream][] object.\n\n

    \n

    Here is an example of a client of echo server as described previously:\n\n

    \n
    var tls = require('tls');\nvar fs = require('fs');\n\nvar options = {\n  // These are necessary only if using the client certificate authentication\n  key: fs.readFileSync('client-key.pem'),\n  cert: fs.readFileSync('client-cert.pem'),\n\n  // This is necessary only if the server uses the self-signed certificate\n  ca: [ fs.readFileSync('server-cert.pem') ]\n};\n\nvar cleartextStream = tls.connect(8000, options, function() {\n  console.log('client connected',\n              cleartextStream.authorized ? 'authorized' : 'unauthorized');\n  process.stdin.pipe(cleartextStream);\n  process.stdin.resume();\n});\ncleartextStream.setEncoding('utf8');\ncleartextStream.on('data', function(data) {\n  console.log(data);\n});\ncleartextStream.on('end', function() {\n  server.close();\n});
    \n

    Or\n\n

    \n
    var tls = require('tls');\nvar fs = require('fs');\n\nvar options = {\n  pfx: fs.readFileSync('client.pfx')\n};\n\nvar cleartextStream = tls.connect(8000, options, function() {\n  console.log('client connected',\n              cleartextStream.authorized ? 'authorized' : 'unauthorized');\n  process.stdin.pipe(cleartextStream);\n  process.stdin.resume();\n});\ncleartextStream.setEncoding('utf8');\ncleartextStream.on('data', function(data) {\n  console.log(data);\n});\ncleartextStream.on('end', function() {\n  server.close();\n});
    \n", "signatures": [ { "params": [ { "name": "port" }, { "name": "host", "optional": true }, { "name": "options", "optional": true }, { "name": "callback", "optional": true } ] } ] }, { "textRaw": "tls.createSecurePair([credentials], [isServer], [requestCert], [rejectUnauthorized])", "type": "method", "name": "createSecurePair", "desc": "

    Creates a new secure pair object with two streams, one of which reads/writes\nencrypted data, and one reads/writes cleartext data.\nGenerally the encrypted one is piped to/from an incoming encrypted data stream,\nand the cleartext one is used as a replacement for the initial encrypted stream.\n\n

    \n
      \n
    • credentials: A credentials object from crypto.createCredentials( ... )

      \n
    • \n
    • isServer: A boolean indicating whether this tls connection should be\nopened as a server or a client.

      \n
    • \n
    • requestCert: A boolean indicating whether a server should request a\ncertificate from a connecting client. Only applies to server connections.

      \n
    • \n
    • rejectUnauthorized: A boolean indicating whether a server should\nautomatically reject clients with invalid certificates. Only applies to\nservers with requestCert enabled.

      \n
    • \n
    \n

    tls.createSecurePair() returns a SecurePair object with [cleartext][] and\nencrypted stream properties.\n\n

    \n", "signatures": [ { "params": [ { "name": "credentials", "optional": true }, { "name": "isServer", "optional": true }, { "name": "requestCert", "optional": true }, { "name": "rejectUnauthorized", "optional": true } ] } ] } ], "properties": [ { "textRaw": "tls.SLAB_BUFFER_SIZE", "name": "SLAB_BUFFER_SIZE", "desc": "

    Size of slab buffer used by all tls servers and clients.\nDefault: 10 * 1024 * 1024.\n\n\n

    \n

    Don't change the defaults unless you know what you are doing.\n\n\n

    \n" } ], "classes": [ { "textRaw": "Class: SecurePair", "type": "class", "name": "SecurePair", "desc": "

    Returned by tls.createSecurePair.\n\n

    \n", "events": [ { "textRaw": "Event: 'secure'", "type": "event", "name": "secure", "desc": "

    The event is emitted from the SecurePair once the pair has successfully\nestablished a secure connection.\n\n

    \n

    Similarly to the checking for the server 'secureConnection' event,\npair.cleartext.authorized should be checked to confirm whether the certificate\nused properly authorized.\n\n

    \n", "params": [] } ] }, { "textRaw": "Class: tls.Server", "type": "class", "name": "tls.Server", "desc": "

    This class is a subclass of net.Server and has the same methods on it.\nInstead of accepting just raw TCP connections, this accepts encrypted\nconnections using TLS or SSL.\n\n

    \n", "events": [ { "textRaw": "Event: 'secureConnection'", "type": "event", "name": "secureConnection", "desc": "

    function (cleartextStream) {}\n\n

    \n

    This event is emitted after a new connection has been successfully\nhandshaked. The argument is a instance of [CleartextStream][]. It has all the\ncommon stream methods and events.\n\n

    \n

    cleartextStream.authorized is a boolean value which indicates if the\nclient has verified by one of the supplied certificate authorities for the\nserver. If cleartextStream.authorized is false, then\ncleartextStream.authorizationError is set to describe how authorization\nfailed. Implied but worth mentioning: depending on the settings of the TLS\nserver, you unauthorized connections may be accepted.\ncleartextStream.npnProtocol is a string containing selected NPN protocol.\ncleartextStream.servername is a string containing servername requested with\nSNI.\n\n\n

    \n", "params": [] }, { "textRaw": "Event: 'clientError'", "type": "event", "name": "clientError", "desc": "

    function (exception, securePair) { }\n\n

    \n

    When a client connection emits an 'error' event before secure connection is\nestablished - it will be forwarded here.\n\n

    \n

    securePair is the tls.SecurePair that the error originated from.\n\n\n

    \n", "params": [] }, { "textRaw": "Event: 'newSession'", "type": "event", "name": "newSession", "desc": "

    function (sessionId, sessionData) { }\n\n

    \n

    Emitted on creation of TLS session. May be used to store sessions in external\nstorage.\n\n\n

    \n", "params": [] }, { "textRaw": "Event: 'resumeSession'", "type": "event", "name": "resumeSession", "desc": "

    function (sessionId, callback) { }\n\n

    \n

    Emitted when client wants to resume previous TLS session. Event listener may\nperform lookup in external storage using given sessionId, and invoke\ncallback(null, sessionData) once finished. If session can't be resumed\n(i.e. doesn't exist in storage) one may call callback(null, null). Calling\ncallback(err) will terminate incoming connection and destroy socket.\n\n\n

    \n", "params": [] } ], "methods": [ { "textRaw": "server.listen(port, [host], [callback])", "type": "method", "name": "listen", "desc": "

    Begin accepting connections on the specified port and host. If the\nhost is omitted, the server will accept connections directed to any\nIPv4 address (INADDR_ANY).\n\n

    \n

    This function is asynchronous. The last parameter callback will be called\nwhen the server has been bound.\n\n

    \n

    See net.Server for more information.\n\n\n

    \n", "signatures": [ { "params": [ { "name": "port" }, { "name": "host", "optional": true }, { "name": "callback", "optional": true } ] } ] }, { "textRaw": "server.close()", "type": "method", "name": "close", "desc": "

    Stops the server from accepting new connections. This function is\nasynchronous, the server is finally closed when the server emits a 'close'\nevent.\n\n

    \n", "signatures": [ { "params": [] } ] }, { "textRaw": "server.address()", "type": "method", "name": "address", "desc": "

    Returns the bound address, the address family name and port of the\nserver as reported by the operating system. See [net.Server.address()][] for\nmore information.\n\n

    \n", "signatures": [ { "params": [] } ] }, { "textRaw": "server.addContext(hostname, credentials)", "type": "method", "name": "addContext", "desc": "

    Add secure context that will be used if client request's SNI hostname is\nmatching passed hostname (wildcards can be used). credentials can contain\nkey, cert and ca.\n\n

    \n", "signatures": [ { "params": [ { "name": "hostname" }, { "name": "credentials" } ] } ] } ], "properties": [ { "textRaw": "server.maxConnections", "name": "maxConnections", "desc": "

    Set this property to reject connections when the server's connection count\ngets high.\n\n

    \n" }, { "textRaw": "server.connections", "name": "connections", "desc": "

    The number of concurrent connections on the server.\n\n\n

    \n" } ] }, { "textRaw": "Class: CryptoStream", "type": "class", "name": "CryptoStream", "desc": "

    This is an encrypted stream.\n\n

    \n", "properties": [ { "textRaw": "cryptoStream.bytesWritten", "name": "bytesWritten", "desc": "

    A proxy to the underlying socket's bytesWritten accessor, this will return\nthe total bytes written to the socket, including the TLS overhead.\n\n

    \n" } ] }, { "textRaw": "Class: tls.CleartextStream", "type": "class", "name": "tls.CleartextStream", "desc": "

    This is a stream on top of the Encrypted stream that makes it possible to\nread/write an encrypted data as a cleartext data.\n\n

    \n

    This instance implements a duplex [Stream][] interfaces. It has all the\ncommon stream methods and events.\n\n

    \n

    A ClearTextStream is the clear member of a SecurePair object.\n\n

    \n", "events": [ { "textRaw": "Event: 'secureConnect'", "type": "event", "name": "secureConnect", "desc": "

    This event is emitted after a new connection has been successfully handshaked. \nThe listener will be called no matter if the server's certificate was\nauthorized or not. It is up to the user to test cleartextStream.authorized\nto see if the server certificate was signed by one of the specified CAs.\nIf cleartextStream.authorized === false then the error can be found in\ncleartextStream.authorizationError. Also if NPN was used - you can check\ncleartextStream.npnProtocol for negotiated protocol.\n\n

    \n", "params": [] } ], "properties": [ { "textRaw": "cleartextStream.authorized", "name": "authorized", "desc": "

    A boolean that is true if the peer certificate was signed by one of the\nspecified CAs, otherwise false\n\n

    \n" }, { "textRaw": "cleartextStream.authorizationError", "name": "authorizationError", "desc": "

    The reason why the peer's certificate has not been verified. This property\nbecomes available only when cleartextStream.authorized === false.\n\n

    \n" }, { "textRaw": "cleartextStream.remoteAddress", "name": "remoteAddress", "desc": "

    The string representation of the remote IP address. For example,\n'74.125.127.100' or '2001:4860:a005::68'.\n\n

    \n" }, { "textRaw": "cleartextStream.remotePort", "name": "remotePort", "desc": "

    The numeric representation of the remote port. For example, 443.\n\n

    \n" } ], "methods": [ { "textRaw": "cleartextStream.getPeerCertificate()", "type": "method", "name": "getPeerCertificate", "desc": "

    Returns an object representing the peer's certificate. The returned object has\nsome properties corresponding to the field of the certificate.\n\n

    \n

    Example:\n\n

    \n
    { subject: \n   { C: 'UK',\n     ST: 'Acknack Ltd',\n     L: 'Rhys Jones',\n     O: 'node.js',\n     OU: 'Test TLS Certificate',\n     CN: 'localhost' },\n  issuer: \n   { C: 'UK',\n     ST: 'Acknack Ltd',\n     L: 'Rhys Jones',\n     O: 'node.js',\n     OU: 'Test TLS Certificate',\n     CN: 'localhost' },\n  valid_from: 'Nov 11 09:52:22 2009 GMT',\n  valid_to: 'Nov  6 09:52:22 2029 GMT',\n  fingerprint: '2A:7A:C2:DD:E5:F9:CC:53:72:35:99:7A:02:5A:71:38:52:EC:8A:DF' }
    \n

    If the peer does not provide a certificate, it returns null or an empty\nobject.\n\n

    \n", "signatures": [ { "params": [] } ] }, { "textRaw": "cleartextStream.getCipher()", "type": "method", "name": "getCipher", "desc": "

    Returns an object representing the cipher name and the SSL/TLS\nprotocol version of the current connection.\n\n

    \n

    Example:\n{ name: 'AES256-SHA', version: 'TLSv1/SSLv3' }\n\n

    \n

    See SSL_CIPHER_get_name() and SSL_CIPHER_get_version() in\nhttp://www.openssl.org/docs/ssl/ssl.html#DEALING_WITH_CIPHERS for more\ninformation.\n\n

    \n", "signatures": [ { "params": [] } ] }, { "textRaw": "cleartextStream.address()", "type": "method", "name": "address", "desc": "

    Returns the bound address, the address family name and port of the\nunderlying socket as reported by the operating system. Returns an\nobject with three properties, e.g.\n{ port: 12346, family: 'IPv4', address: '127.0.0.1' }\n\n

    \n", "signatures": [ { "params": [] } ] } ] } ], "type": "module", "displayName": "TLS (SSL)" }, { "textRaw": "StringDecoder", "name": "stringdecoder", "stability": 3, "stabilityText": "Stable", "desc": "

    To use this module, do require('string_decoder'). StringDecoder decodes a\nbuffer to a string. It is a simple interface to buffer.toString() but provides\nadditional support for utf8.\n\n

    \n
    var StringDecoder = require('string_decoder').StringDecoder;\nvar decoder = new StringDecoder('utf8');\n\nvar cent = new Buffer([0xC2, 0xA2]);\nconsole.log(decoder.write(cent));\n\nvar euro = new Buffer([0xE2, 0x82, 0xAC]);\nconsole.log(decoder.write(euro));
    \n", "classes": [ { "textRaw": "Class: StringDecoder", "type": "class", "name": "StringDecoder", "desc": "

    Accepts a single argument, encoding which defaults to utf8.\n\n

    \n", "methods": [ { "textRaw": "decoder.write(buffer)", "type": "method", "name": "write", "desc": "

    Returns a decoded string.\n\n

    \n", "signatures": [ { "params": [ { "name": "buffer" } ] } ] }, { "textRaw": "decoder.end()", "type": "method", "name": "end", "desc": "

    Returns any trailing bytes that were left in the buffer.\n\n

    \n", "signatures": [ { "params": [] } ] } ] } ], "type": "module", "displayName": "StringDecoder" }, { "textRaw": "File System", "name": "fs", "stability": 3, "stabilityText": "Stable", "desc": "

    File I/O is provided by simple wrappers around standard POSIX functions. To\nuse this module do require('fs'). All the methods have asynchronous and\nsynchronous forms.\n\n

    \n

    The asynchronous form always take a completion callback as its last argument.\nThe arguments passed to the completion callback depend on the method, but the\nfirst argument is always reserved for an exception. If the operation was\ncompleted successfully, then the first argument will be null or undefined.\n\n

    \n

    When using the synchronous form any exceptions are immediately thrown.\nYou can use try/catch to handle exceptions or allow them to bubble up.\n\n

    \n

    Here is an example of the asynchronous version:\n\n

    \n
    var fs = require('fs');\n\nfs.unlink('/tmp/hello', function (err) {\n  if (err) throw err;\n  console.log('successfully deleted /tmp/hello');\n});
    \n

    Here is the synchronous version:\n\n

    \n
    var fs = require('fs');\n\nfs.unlinkSync('/tmp/hello')\nconsole.log('successfully deleted /tmp/hello');
    \n

    With the asynchronous methods there is no guaranteed ordering. So the\nfollowing is prone to error:\n\n

    \n
    fs.rename('/tmp/hello', '/tmp/world', function (err) {\n  if (err) throw err;\n  console.log('renamed complete');\n});\nfs.stat('/tmp/world', function (err, stats) {\n  if (err) throw err;\n  console.log('stats: ' + JSON.stringify(stats));\n});
    \n

    It could be that fs.stat is executed before fs.rename.\nThe correct way to do this is to chain the callbacks.\n\n

    \n
    fs.rename('/tmp/hello', '/tmp/world', function (err) {\n  if (err) throw err;\n  fs.stat('/tmp/world', function (err, stats) {\n    if (err) throw err;\n    console.log('stats: ' + JSON.stringify(stats));\n  });\n});
    \n

    In busy processes, the programmer is strongly encouraged to use the\nasynchronous versions of these calls. The synchronous versions will block\nthe entire process until they complete--halting all connections.\n\n

    \n

    Relative path to filename can be used, remember however that this path will be\nrelative to process.cwd().\n\n

    \n

    Most fs functions let you omit the callback argument. If you do, a default\ncallback is used that ignores errors, but prints a deprecation\nwarning.\n\n

    \n

    IMPORTANT: Omitting the callback is deprecated. v0.12 will throw the\nerrors as exceptions.\n\n\n

    \n", "methods": [ { "textRaw": "fs.rename(oldPath, newPath, callback)", "type": "method", "name": "rename", "desc": "

    Asynchronous rename(2). No arguments other than a possible exception are given\nto the completion callback.\n\n

    \n", "signatures": [ { "params": [ { "name": "oldPath" }, { "name": "newPath" }, { "name": "callback" } ] } ] }, { "textRaw": "fs.renameSync(oldPath, newPath)", "type": "method", "name": "renameSync", "desc": "

    Synchronous rename(2).\n\n

    \n", "signatures": [ { "params": [ { "name": "oldPath" }, { "name": "newPath" } ] } ] }, { "textRaw": "fs.ftruncate(fd, len, callback)", "type": "method", "name": "ftruncate", "desc": "

    Asynchronous ftruncate(2). No arguments other than a possible exception are\ngiven to the completion callback.\n\n

    \n", "signatures": [ { "params": [ { "name": "fd" }, { "name": "len" }, { "name": "callback" } ] } ] }, { "textRaw": "fs.ftruncateSync(fd, len)", "type": "method", "name": "ftruncateSync", "desc": "

    Synchronous ftruncate(2).\n\n

    \n", "signatures": [ { "params": [ { "name": "fd" }, { "name": "len" } ] } ] }, { "textRaw": "fs.truncate(path, len, callback)", "type": "method", "name": "truncate", "desc": "

    Asynchronous truncate(2). No arguments other than a possible exception are\ngiven to the completion callback.\n\n

    \n", "signatures": [ { "params": [ { "name": "path" }, { "name": "len" }, { "name": "callback" } ] } ] }, { "textRaw": "fs.truncateSync(path, len)", "type": "method", "name": "truncateSync", "desc": "

    Synchronous truncate(2).\n\n

    \n", "signatures": [ { "params": [ { "name": "path" }, { "name": "len" } ] } ] }, { "textRaw": "fs.chown(path, uid, gid, callback)", "type": "method", "name": "chown", "desc": "

    Asynchronous chown(2). No arguments other than a possible exception are given\nto the completion callback.\n\n

    \n", "signatures": [ { "params": [ { "name": "path" }, { "name": "uid" }, { "name": "gid" }, { "name": "callback" } ] } ] }, { "textRaw": "fs.chownSync(path, uid, gid)", "type": "method", "name": "chownSync", "desc": "

    Synchronous chown(2).\n\n

    \n", "signatures": [ { "params": [ { "name": "path" }, { "name": "uid" }, { "name": "gid" } ] } ] }, { "textRaw": "fs.fchown(fd, uid, gid, callback)", "type": "method", "name": "fchown", "desc": "

    Asynchronous fchown(2). No arguments other than a possible exception are given\nto the completion callback.\n\n

    \n", "signatures": [ { "params": [ { "name": "fd" }, { "name": "uid" }, { "name": "gid" }, { "name": "callback" } ] } ] }, { "textRaw": "fs.fchownSync(fd, uid, gid)", "type": "method", "name": "fchownSync", "desc": "

    Synchronous fchown(2).\n\n

    \n", "signatures": [ { "params": [ { "name": "fd" }, { "name": "uid" }, { "name": "gid" } ] } ] }, { "textRaw": "fs.lchown(path, uid, gid, callback)", "type": "method", "name": "lchown", "desc": "

    Asynchronous lchown(2). No arguments other than a possible exception are given\nto the completion callback.\n\n

    \n", "signatures": [ { "params": [ { "name": "path" }, { "name": "uid" }, { "name": "gid" }, { "name": "callback" } ] } ] }, { "textRaw": "fs.lchownSync(path, uid, gid)", "type": "method", "name": "lchownSync", "desc": "

    Synchronous lchown(2).\n\n

    \n", "signatures": [ { "params": [ { "name": "path" }, { "name": "uid" }, { "name": "gid" } ] } ] }, { "textRaw": "fs.chmod(path, mode, callback)", "type": "method", "name": "chmod", "desc": "

    Asynchronous chmod(2). No arguments other than a possible exception are given\nto the completion callback.\n\n

    \n", "signatures": [ { "params": [ { "name": "path" }, { "name": "mode" }, { "name": "callback" } ] } ] }, { "textRaw": "fs.chmodSync(path, mode)", "type": "method", "name": "chmodSync", "desc": "

    Synchronous chmod(2).\n\n

    \n", "signatures": [ { "params": [ { "name": "path" }, { "name": "mode" } ] } ] }, { "textRaw": "fs.fchmod(fd, mode, callback)", "type": "method", "name": "fchmod", "desc": "

    Asynchronous fchmod(2). No arguments other than a possible exception\nare given to the completion callback.\n\n

    \n", "signatures": [ { "params": [ { "name": "fd" }, { "name": "mode" }, { "name": "callback" } ] } ] }, { "textRaw": "fs.fchmodSync(fd, mode)", "type": "method", "name": "fchmodSync", "desc": "

    Synchronous fchmod(2).\n\n

    \n", "signatures": [ { "params": [ { "name": "fd" }, { "name": "mode" } ] } ] }, { "textRaw": "fs.lchmod(path, mode, callback)", "type": "method", "name": "lchmod", "desc": "

    Asynchronous lchmod(2). No arguments other than a possible exception\nare given to the completion callback.\n\n

    \n

    Only available on Mac OS X.\n\n

    \n", "signatures": [ { "params": [ { "name": "path" }, { "name": "mode" }, { "name": "callback" } ] } ] }, { "textRaw": "fs.lchmodSync(path, mode)", "type": "method", "name": "lchmodSync", "desc": "

    Synchronous lchmod(2).\n\n

    \n", "signatures": [ { "params": [ { "name": "path" }, { "name": "mode" } ] } ] }, { "textRaw": "fs.stat(path, callback)", "type": "method", "name": "stat", "desc": "

    Asynchronous stat(2). The callback gets two arguments (err, stats) where\nstats is a fs.Stats object. See the fs.Stats\nsection below for more information.\n\n

    \n", "signatures": [ { "params": [ { "name": "path" }, { "name": "callback" } ] } ] }, { "textRaw": "fs.lstat(path, callback)", "type": "method", "name": "lstat", "desc": "

    Asynchronous lstat(2). The callback gets two arguments (err, stats) where\nstats is a fs.Stats object. lstat() is identical to stat(), except that if\npath is a symbolic link, then the link itself is stat-ed, not the file that it\nrefers to.\n\n

    \n", "signatures": [ { "params": [ { "name": "path" }, { "name": "callback" } ] } ] }, { "textRaw": "fs.fstat(fd, callback)", "type": "method", "name": "fstat", "desc": "

    Asynchronous fstat(2). The callback gets two arguments (err, stats) where\nstats is a fs.Stats object. fstat() is identical to stat(), except that\nthe file to be stat-ed is specified by the file descriptor fd.\n\n

    \n", "signatures": [ { "params": [ { "name": "fd" }, { "name": "callback" } ] } ] }, { "textRaw": "fs.statSync(path)", "type": "method", "name": "statSync", "desc": "

    Synchronous stat(2). Returns an instance of fs.Stats.\n\n

    \n", "signatures": [ { "params": [ { "name": "path" } ] } ] }, { "textRaw": "fs.lstatSync(path)", "type": "method", "name": "lstatSync", "desc": "

    Synchronous lstat(2). Returns an instance of fs.Stats.\n\n

    \n", "signatures": [ { "params": [ { "name": "path" } ] } ] }, { "textRaw": "fs.fstatSync(fd)", "type": "method", "name": "fstatSync", "desc": "

    Synchronous fstat(2). Returns an instance of fs.Stats.\n\n

    \n", "signatures": [ { "params": [ { "name": "fd" } ] } ] }, { "textRaw": "fs.link(srcpath, dstpath, callback)", "type": "method", "name": "link", "desc": "

    Asynchronous link(2). No arguments other than a possible exception are given to\nthe completion callback.\n\n

    \n", "signatures": [ { "params": [ { "name": "srcpath" }, { "name": "dstpath" }, { "name": "callback" } ] } ] }, { "textRaw": "fs.linkSync(srcpath, dstpath)", "type": "method", "name": "linkSync", "desc": "

    Synchronous link(2).\n\n

    \n", "signatures": [ { "params": [ { "name": "srcpath" }, { "name": "dstpath" } ] } ] }, { "textRaw": "fs.symlink(srcpath, dstpath, [type], callback)", "type": "method", "name": "symlink", "desc": "

    Asynchronous symlink(2). No arguments other than a possible exception are given\nto the completion callback.\nThe type argument can be set to 'dir', 'file', or 'junction' (default\nis 'file') and is only available on Windows (ignored on other platforms).\nNote that Windows junction points require the destination path to be absolute. When using\n'junction', the destination argument will automatically be normalized to absolute path.\n\n

    \n", "signatures": [ { "params": [ { "name": "srcpath" }, { "name": "dstpath" }, { "name": "type", "optional": true }, { "name": "callback" } ] } ] }, { "textRaw": "fs.symlinkSync(srcpath, dstpath, [type])", "type": "method", "name": "symlinkSync", "desc": "

    Synchronous symlink(2).\n\n

    \n", "signatures": [ { "params": [ { "name": "srcpath" }, { "name": "dstpath" }, { "name": "type", "optional": true } ] } ] }, { "textRaw": "fs.readlink(path, callback)", "type": "method", "name": "readlink", "desc": "

    Asynchronous readlink(2). The callback gets two arguments (err,\nlinkString).\n\n

    \n", "signatures": [ { "params": [ { "name": "path" }, { "name": "callback" } ] } ] }, { "textRaw": "fs.readlinkSync(path)", "type": "method", "name": "readlinkSync", "desc": "

    Synchronous readlink(2). Returns the symbolic link's string value.\n\n

    \n", "signatures": [ { "params": [ { "name": "path" } ] } ] }, { "textRaw": "fs.realpath(path, [cache], callback)", "type": "method", "name": "realpath", "desc": "

    Asynchronous realpath(2). The callback gets two arguments (err,\nresolvedPath). May use process.cwd to resolve relative paths. cache is an\nobject literal of mapped paths that can be used to force a specific path\nresolution or avoid additional fs.stat calls for known real paths.\n\n

    \n

    Example:\n\n

    \n
    var cache = {'/etc':'/private/etc'};\nfs.realpath('/etc/passwd', cache, function (err, resolvedPath) {\n  if (err) throw err;\n  console.log(resolvedPath);\n});
    \n", "signatures": [ { "params": [ { "name": "path" }, { "name": "cache", "optional": true }, { "name": "callback" } ] } ] }, { "textRaw": "fs.realpathSync(path, [cache])", "type": "method", "name": "realpathSync", "desc": "

    Synchronous realpath(2). Returns the resolved path.\n\n

    \n", "signatures": [ { "params": [ { "name": "path" }, { "name": "cache", "optional": true } ] } ] }, { "textRaw": "fs.unlink(path, callback)", "type": "method", "name": "unlink", "desc": "

    Asynchronous unlink(2). No arguments other than a possible exception are given\nto the completion callback.\n\n

    \n", "signatures": [ { "params": [ { "name": "path" }, { "name": "callback" } ] } ] }, { "textRaw": "fs.unlinkSync(path)", "type": "method", "name": "unlinkSync", "desc": "

    Synchronous unlink(2).\n\n

    \n", "signatures": [ { "params": [ { "name": "path" } ] } ] }, { "textRaw": "fs.rmdir(path, callback)", "type": "method", "name": "rmdir", "desc": "

    Asynchronous rmdir(2). No arguments other than a possible exception are given\nto the completion callback.\n\n

    \n", "signatures": [ { "params": [ { "name": "path" }, { "name": "callback" } ] } ] }, { "textRaw": "fs.rmdirSync(path)", "type": "method", "name": "rmdirSync", "desc": "

    Synchronous rmdir(2).\n\n

    \n", "signatures": [ { "params": [ { "name": "path" } ] } ] }, { "textRaw": "fs.mkdir(path, [mode], callback)", "type": "method", "name": "mkdir", "desc": "

    Asynchronous mkdir(2). No arguments other than a possible exception are given\nto the completion callback. mode defaults to 0777.\n\n

    \n", "signatures": [ { "params": [ { "name": "path" }, { "name": "mode", "optional": true }, { "name": "callback" } ] } ] }, { "textRaw": "fs.mkdirSync(path, [mode])", "type": "method", "name": "mkdirSync", "desc": "

    Synchronous mkdir(2).\n\n

    \n", "signatures": [ { "params": [ { "name": "path" }, { "name": "mode", "optional": true } ] } ] }, { "textRaw": "fs.readdir(path, callback)", "type": "method", "name": "readdir", "desc": "

    Asynchronous readdir(3). Reads the contents of a directory.\nThe callback gets two arguments (err, files) where files is an array of\nthe names of the files in the directory excluding '.' and '..'.\n\n

    \n", "signatures": [ { "params": [ { "name": "path" }, { "name": "callback" } ] } ] }, { "textRaw": "fs.readdirSync(path)", "type": "method", "name": "readdirSync", "desc": "

    Synchronous readdir(3). Returns an array of filenames excluding '.' and\n'..'.\n\n

    \n", "signatures": [ { "params": [ { "name": "path" } ] } ] }, { "textRaw": "fs.close(fd, callback)", "type": "method", "name": "close", "desc": "

    Asynchronous close(2). No arguments other than a possible exception are given\nto the completion callback.\n\n

    \n", "signatures": [ { "params": [ { "name": "fd" }, { "name": "callback" } ] } ] }, { "textRaw": "fs.closeSync(fd)", "type": "method", "name": "closeSync", "desc": "

    Synchronous close(2).\n\n

    \n", "signatures": [ { "params": [ { "name": "fd" } ] } ] }, { "textRaw": "fs.open(path, flags, [mode], callback)", "type": "method", "name": "open", "desc": "

    Asynchronous file open. See open(2). flags can be:\n\n

    \n
      \n
    • 'r' - Open file for reading.\nAn exception occurs if the file does not exist.

      \n
    • \n
    • 'r+' - Open file for reading and writing.\nAn exception occurs if the file does not exist.

      \n
    • \n
    • 'rs' - Open file for reading in synchronous mode. Instructs the operating\nsystem to bypass the local file system cache.

      \n

      This is primarily useful for opening files on NFS mounts as it allows you to\nskip the potentially stale local cache. It has a very real impact on I/O\nperformance so don't use this flag unless you need it.

      \n

      Note that this doesn't turn fs.open() into a synchronous blocking call.\nIf that's what you want then you should be using fs.openSync()

      \n
    • \n
    • 'rs+' - Open file for reading and writing, telling the OS to open it\nsynchronously. See notes for 'rs' about using this with caution.

      \n
    • \n
    • 'w' - Open file for writing.\nThe file is created (if it does not exist) or truncated (if it exists).

      \n
    • \n
    • 'wx' - Like 'w' but fails if path exists.

      \n
    • \n
    • 'w+' - Open file for reading and writing.\nThe file is created (if it does not exist) or truncated (if it exists).

      \n
    • \n
    • 'wx+' - Like 'w+' but fails if path exists.

      \n
    • \n
    • 'a' - Open file for appending.\nThe file is created if it does not exist.

      \n
    • \n
    • 'ax' - Like 'a' but fails if path exists.

      \n
    • \n
    • 'a+' - Open file for reading and appending.\nThe file is created if it does not exist.

      \n
    • \n
    • 'ax+' - Like 'a+' but fails if path exists.

      \n
    • \n
    \n

    mode sets the file mode (permission and sticky bits), but only if the file was\ncreated. It defaults to 0666, readable and writeable.\n\n

    \n

    The callback gets two arguments (err, fd).\n\n

    \n

    The exclusive flag 'x' (O_EXCL flag in open(2)) ensures that path is newly\ncreated. On POSIX systems, path is considered to exist even if it is a symlink\nto a non-existent file. The exclusive flag may or may not work with network file\nsystems.\n\n

    \n

    On Linux, positional writes don't work when the file is opened in append mode.\nThe kernel ignores the position argument and always appends the data to\nthe end of the file.\n\n

    \n", "signatures": [ { "params": [ { "name": "path" }, { "name": "flags" }, { "name": "mode", "optional": true }, { "name": "callback" } ] } ] }, { "textRaw": "fs.openSync(path, flags, [mode])", "type": "method", "name": "openSync", "desc": "

    Synchronous version of fs.open().\n\n

    \n", "signatures": [ { "params": [ { "name": "path" }, { "name": "flags" }, { "name": "mode", "optional": true } ] } ] }, { "textRaw": "fs.utimes(path, atime, mtime, callback)", "type": "method", "name": "utimes", "desc": "

    Change file timestamps of the file referenced by the supplied path.\n\n

    \n", "signatures": [ { "params": [ { "name": "path" }, { "name": "atime" }, { "name": "mtime" } ] }, { "params": [ { "name": "path" }, { "name": "atime" }, { "name": "mtime" }, { "name": "callback" } ] } ] }, { "textRaw": "fs.utimesSync(path, atime, mtime)", "type": "method", "name": "utimesSync", "desc": "

    Change file timestamps of the file referenced by the supplied path.\n\n

    \n", "signatures": [ { "params": [ { "name": "path" }, { "name": "atime" }, { "name": "mtime" } ] } ] }, { "textRaw": "fs.futimes(fd, atime, mtime, callback)", "type": "method", "name": "futimes", "desc": "

    Change the file timestamps of a file referenced by the supplied file\ndescriptor.\n\n

    \n", "signatures": [ { "params": [ { "name": "fd" }, { "name": "atime" }, { "name": "mtime" } ] }, { "params": [ { "name": "fd" }, { "name": "atime" }, { "name": "mtime" }, { "name": "callback" } ] } ] }, { "textRaw": "fs.futimesSync(fd, atime, mtime)", "type": "method", "name": "futimesSync", "desc": "

    Change the file timestamps of a file referenced by the supplied file\ndescriptor.\n\n

    \n", "signatures": [ { "params": [ { "name": "fd" }, { "name": "atime" }, { "name": "mtime" } ] } ] }, { "textRaw": "fs.fsync(fd, callback)", "type": "method", "name": "fsync", "desc": "

    Asynchronous fsync(2). No arguments other than a possible exception are given\nto the completion callback.\n\n

    \n", "signatures": [ { "params": [ { "name": "fd" }, { "name": "callback" } ] } ] }, { "textRaw": "fs.fsyncSync(fd)", "type": "method", "name": "fsyncSync", "desc": "

    Synchronous fsync(2).\n\n

    \n", "signatures": [ { "params": [ { "name": "fd" } ] } ] }, { "textRaw": "fs.write(fd, buffer, offset, length, position, callback)", "type": "method", "name": "write", "desc": "

    Write buffer to the file specified by fd.\n\n

    \n

    offset and length determine the part of the buffer to be written.\n\n

    \n

    position refers to the offset from the beginning of the file where this data\nshould be written. If position is null, the data will be written at the\ncurrent position.\nSee pwrite(2).\n\n

    \n

    The callback will be given three arguments (err, written, buffer) where written\nspecifies how many bytes were written from buffer.\n\n

    \n

    Note that it is unsafe to use fs.write multiple times on the same file\nwithout waiting for the callback. For this scenario,\nfs.createWriteStream is strongly recommended.\n\n

    \n

    On Linux, positional writes don't work when the file is opened in append mode.\nThe kernel ignores the position argument and always appends the data to\nthe end of the file.\n\n

    \n", "signatures": [ { "params": [ { "name": "fd" }, { "name": "buffer" }, { "name": "offset" }, { "name": "length" }, { "name": "position" }, { "name": "callback" } ] } ] }, { "textRaw": "fs.writeSync(fd, buffer, offset, length, position)", "type": "method", "name": "writeSync", "desc": "

    Synchronous version of fs.write(). Returns the number of bytes written.\n\n

    \n", "signatures": [ { "params": [ { "name": "fd" }, { "name": "buffer" }, { "name": "offset" }, { "name": "length" }, { "name": "position" } ] } ] }, { "textRaw": "fs.read(fd, buffer, offset, length, position, callback)", "type": "method", "name": "read", "desc": "

    Read data from the file specified by fd.\n\n

    \n

    buffer is the buffer that the data will be written to.\n\n

    \n

    offset is the offset in the buffer to start writing at.\n\n

    \n

    length is an integer specifying the number of bytes to read.\n\n

    \n

    position is an integer specifying where to begin reading from in the file.\nIf position is null, data will be read from the current file position.\n\n

    \n

    The callback is given the three arguments, (err, bytesRead, buffer).\n\n

    \n", "signatures": [ { "params": [ { "name": "fd" }, { "name": "buffer" }, { "name": "offset" }, { "name": "length" }, { "name": "position" }, { "name": "callback" } ] } ] }, { "textRaw": "fs.readSync(fd, buffer, offset, length, position)", "type": "method", "name": "readSync", "desc": "

    Synchronous version of fs.read. Returns the number of bytesRead.\n\n

    \n", "signatures": [ { "params": [ { "name": "fd" }, { "name": "buffer" }, { "name": "offset" }, { "name": "length" }, { "name": "position" } ] } ] }, { "textRaw": "fs.readFile(filename, [options], callback)", "type": "method", "name": "readFile", "signatures": [ { "params": [ { "textRaw": "`filename` {String} ", "name": "filename", "type": "String" }, { "textRaw": "`options` {Object} ", "options": [ { "textRaw": "`encoding` {String | Null} default = `null` ", "name": "encoding", "type": "String | Null", "desc": "default = `null`" }, { "textRaw": "`flag` {String} default = `'r'` ", "name": "flag", "type": "String", "desc": "default = `'r'`" } ], "name": "options", "type": "Object", "optional": true }, { "textRaw": "`callback` {Function} ", "name": "callback", "type": "Function" } ] }, { "params": [ { "name": "filename" }, { "name": "options", "optional": true }, { "name": "callback" } ] } ], "desc": "

    Asynchronously reads the entire contents of a file. Example:\n\n

    \n
    fs.readFile('/etc/passwd', function (err, data) {\n  if (err) throw err;\n  console.log(data);\n});
    \n

    The callback is passed two arguments (err, data), where data is the\ncontents of the file.\n\n

    \n

    If no encoding is specified, then the raw buffer is returned.\n\n\n

    \n" }, { "textRaw": "fs.readFileSync(filename, [options])", "type": "method", "name": "readFileSync", "desc": "

    Synchronous version of fs.readFile. Returns the contents of the filename.\n\n

    \n

    If the encoding option is specified then this function returns a\nstring. Otherwise it returns a buffer.\n\n\n

    \n", "signatures": [ { "params": [ { "name": "filename" }, { "name": "options", "optional": true } ] } ] }, { "textRaw": "fs.writeFile(filename, data, [options], callback)", "type": "method", "name": "writeFile", "signatures": [ { "params": [ { "textRaw": "`filename` {String} ", "name": "filename", "type": "String" }, { "textRaw": "`data` {String | Buffer} ", "name": "data", "type": "String | Buffer" }, { "textRaw": "`options` {Object} ", "options": [ { "textRaw": "`encoding` {String | Null} default = `'utf8'` ", "name": "encoding", "type": "String | Null", "desc": "default = `'utf8'`" }, { "textRaw": "`mode` {Number} default = `438` (aka `0666` in Octal) ", "name": "mode", "type": "Number", "desc": "default = `438` (aka `0666` in Octal)" }, { "textRaw": "`flag` {String} default = `'w'` ", "name": "flag", "type": "String", "desc": "default = `'w'`" } ], "name": "options", "type": "Object", "optional": true }, { "textRaw": "`callback` {Function} ", "name": "callback", "type": "Function" } ] }, { "params": [ { "name": "filename" }, { "name": "data" }, { "name": "options", "optional": true }, { "name": "callback" } ] } ], "desc": "

    Asynchronously writes data to a file, replacing the file if it already exists.\ndata can be a string or a buffer.\n\n

    \n

    The encoding option is ignored if data is a buffer. It defaults\nto 'utf8'.\n\n

    \n

    Example:\n\n

    \n
    fs.writeFile('message.txt', 'Hello Node', function (err) {\n  if (err) throw err;\n  console.log('It\\'s saved!');\n});
    \n" }, { "textRaw": "fs.writeFileSync(filename, data, [options])", "type": "method", "name": "writeFileSync", "desc": "

    The synchronous version of fs.writeFile.\n\n

    \n", "signatures": [ { "params": [ { "name": "filename" }, { "name": "data" }, { "name": "options", "optional": true } ] } ] }, { "textRaw": "fs.appendFile(filename, data, [options], callback)", "type": "method", "name": "appendFile", "signatures": [ { "params": [ { "textRaw": "`filename` {String} ", "name": "filename", "type": "String" }, { "textRaw": "`data` {String | Buffer} ", "name": "data", "type": "String | Buffer" }, { "textRaw": "`options` {Object} ", "options": [ { "textRaw": "`encoding` {String | Null} default = `'utf8'` ", "name": "encoding", "type": "String | Null", "desc": "default = `'utf8'`" }, { "textRaw": "`mode` {Number} default = `438` (aka `0666` in Octal) ", "name": "mode", "type": "Number", "desc": "default = `438` (aka `0666` in Octal)" }, { "textRaw": "`flag` {String} default = `'a'` ", "name": "flag", "type": "String", "desc": "default = `'a'`" } ], "name": "options", "type": "Object", "optional": true }, { "textRaw": "`callback` {Function} ", "name": "callback", "type": "Function" } ] }, { "params": [ { "name": "filename" }, { "name": "data" }, { "name": "options", "optional": true }, { "name": "callback" } ] } ], "desc": "

    Asynchronously append data to a file, creating the file if it not yet exists.\ndata can be a string or a buffer.\n\n

    \n

    Example:\n\n

    \n
    fs.appendFile('message.txt', 'data to append', function (err) {\n  if (err) throw err;\n  console.log('The "data to append" was appended to file!');\n});
    \n" }, { "textRaw": "fs.appendFileSync(filename, data, [options])", "type": "method", "name": "appendFileSync", "desc": "

    The synchronous version of fs.appendFile.\n\n

    \n", "signatures": [ { "params": [ { "name": "filename" }, { "name": "data" }, { "name": "options", "optional": true } ] } ] }, { "textRaw": "fs.watchFile(filename, [options], listener)", "type": "method", "name": "watchFile", "stability": 2, "stabilityText": "Unstable. Use fs.watch instead, if possible.", "desc": "

    Watch for changes on filename. The callback listener will be called each\ntime the file is accessed.\n\n

    \n

    The second argument is optional. The options if provided should be an object\ncontaining two members a boolean, persistent, and interval. persistent\nindicates whether the process should continue to run as long as files are\nbeing watched. interval indicates how often the target should be polled,\nin milliseconds. The default is { persistent: true, interval: 5007 }.\n\n

    \n

    The listener gets two arguments the current stat object and the previous\nstat object:\n\n

    \n
    fs.watchFile('message.text', function (curr, prev) {\n  console.log('the current mtime is: ' + curr.mtime);\n  console.log('the previous mtime was: ' + prev.mtime);\n});
    \n

    These stat objects are instances of fs.Stat.\n\n

    \n

    If you want to be notified when the file was modified, not just accessed\nyou need to compare curr.mtime and prev.mtime.\n\n

    \n", "signatures": [ { "params": [ { "name": "filename" }, { "name": "options", "optional": true }, { "name": "listener" } ] } ] }, { "textRaw": "fs.unwatchFile(filename, [listener])", "type": "method", "name": "unwatchFile", "stability": 2, "stabilityText": "Unstable. Use fs.watch instead, if possible.", "desc": "

    Stop watching for changes on filename. If listener is specified, only that\nparticular listener is removed. Otherwise, all listeners are removed and you\nhave effectively stopped watching filename.\n\n

    \n

    Calling fs.unwatchFile() with a filename that is not being watched is a\nno-op, not an error.\n\n

    \n", "signatures": [ { "params": [ { "name": "filename" }, { "name": "listener", "optional": true } ] } ] }, { "textRaw": "fs.watch(filename, [options], [listener])", "type": "method", "name": "watch", "stability": 2, "stabilityText": "Unstable.", "desc": "

    Watch for changes on filename, where filename is either a file or a\ndirectory. The returned object is a fs.FSWatcher.\n\n

    \n

    The second argument is optional. The options if provided should be an object\ncontaining a boolean member persistent, which indicates whether the process\nshould continue to run as long as files are being watched. The default is\n{ persistent: true }.\n\n

    \n

    The listener callback gets two arguments (event, filename). event is either\n'rename' or 'change', and filename is the name of the file which triggered\nthe event.\n\n

    \n", "miscs": [ { "textRaw": "Caveats", "name": "Caveats", "type": "misc", "desc": "

    The fs.watch API is not 100% consistent across platforms, and is\nunavailable in some situations.\n\n

    \n", "miscs": [ { "textRaw": "Availability", "name": "Availability", "type": "misc", "desc": "

    This feature depends on the underlying operating system providing a way\nto be notified of filesystem changes.\n\n

    \n
      \n
    • On Linux systems, this uses inotify.
    • \n
    • On BSD systems (including OS X), this uses kqueue.
    • \n
    • On SunOS systems (including Solaris and SmartOS), this uses event ports.
    • \n
    • On Windows systems, this feature depends on ReadDirectoryChangesW.
    • \n
    \n

    If the underlying functionality is not available for some reason, then\nfs.watch will not be able to function. For example, watching files or\ndirectories on network file systems (NFS, SMB, etc.) often doesn't work\nreliably or at all.\n\n

    \n

    You can still use fs.watchFile, which uses stat polling, but it is slower and\nless reliable.\n\n

    \n" }, { "textRaw": "Filename Argument", "name": "Filename Argument", "type": "misc", "desc": "

    Providing filename argument in the callback is not supported\non every platform (currently it's only supported on Linux and Windows). Even\non supported platforms filename is not always guaranteed to be provided.\nTherefore, don't assume that filename argument is always provided in the\ncallback, and have some fallback logic if it is null.\n\n

    \n
    fs.watch('somedir', function (event, filename) {\n  console.log('event is: ' + event);\n  if (filename) {\n    console.log('filename provided: ' + filename);\n  } else {\n    console.log('filename not provided');\n  }\n});
    \n" } ] } ], "signatures": [ { "params": [ { "name": "filename" }, { "name": "options", "optional": true }, { "name": "listener", "optional": true } ] } ] }, { "textRaw": "fs.exists(path, callback)", "type": "method", "name": "exists", "desc": "

    Test whether or not the given path exists by checking with the file system.\nThen call the callback argument with either true or false. Example:\n\n

    \n
    fs.exists('/etc/passwd', function (exists) {\n  util.debug(exists ? "it's there" : "no passwd!");\n});
    \n

    fs.exists() is an anachronism and exists only for historical reasons.\nThere should almost never be a reason to use it in your own code.\n\n

    \n

    In particular, checking if a file exists before opening it is an anti-pattern\nthat leaves you vulnerable to race conditions: another process may remove the\nfile between the calls to fs.exists() and fs.open(). Just open the file\nand handle the error when it's not there.\n\n

    \n", "signatures": [ { "params": [ { "name": "path" }, { "name": "callback" } ] } ] }, { "textRaw": "fs.existsSync(path)", "type": "method", "name": "existsSync", "desc": "

    Synchronous version of fs.exists.\n\n

    \n", "signatures": [ { "params": [ { "name": "path" } ] } ] }, { "textRaw": "fs.createReadStream(path, [options])", "type": "method", "name": "createReadStream", "desc": "

    Returns a new ReadStream object (See Readable Stream).\n\n

    \n

    options is an object with the following defaults:\n\n

    \n
    { flags: 'r',\n  encoding: null,\n  fd: null,\n  mode: 0666,\n  autoClose: true\n}
    \n

    options can include start and end values to read a range of bytes from\nthe file instead of the entire file. Both start and end are inclusive and\nstart at 0. The encoding can be 'utf8', 'ascii', or 'base64'.\n\n

    \n

    If autoClose is false, then the file descriptor won't be closed, even if\nthere's an error. It is your responsiblity to close it and make sure\nthere's no file descriptor leak. If autoClose is set to true (default\nbehavior), on error or end the file descriptor will be closed\nautomatically.\n\n

    \n

    An example to read the last 10 bytes of a file which is 100 bytes long:\n\n

    \n
    fs.createReadStream('sample.txt', {start: 90, end: 99});
    \n", "signatures": [ { "params": [ { "name": "path" }, { "name": "options", "optional": true } ] } ] }, { "textRaw": "fs.createWriteStream(path, [options])", "type": "method", "name": "createWriteStream", "desc": "

    Returns a new WriteStream object (See Writable Stream).\n\n

    \n

    options is an object with the following defaults:\n\n

    \n
    { flags: 'w',\n  encoding: null,\n  mode: 0666 }
    \n

    options may also include a start option to allow writing data at\nsome position past the beginning of the file. Modifying a file rather\nthan replacing it may require a flags mode of r+ rather than the\ndefault mode w.\n\n

    \n", "signatures": [ { "params": [ { "name": "path" }, { "name": "options", "optional": true } ] } ] } ], "classes": [ { "textRaw": "Class: fs.Stats", "type": "class", "name": "fs.Stats", "desc": "

    Objects returned from fs.stat(), fs.lstat() and fs.fstat() and their\nsynchronous counterparts are of this type.\n\n

    \n
      \n
    • stats.isFile()
    • \n
    • stats.isDirectory()
    • \n
    • stats.isBlockDevice()
    • \n
    • stats.isCharacterDevice()
    • \n
    • stats.isSymbolicLink() (only valid with fs.lstat())
    • \n
    • stats.isFIFO()
    • \n
    • stats.isSocket()
    • \n
    \n

    For a regular file util.inspect(stats) would return a string very\nsimilar to this:\n\n

    \n
    { dev: 2114,\n  ino: 48064969,\n  mode: 33188,\n  nlink: 1,\n  uid: 85,\n  gid: 100,\n  rdev: 0,\n  size: 527,\n  blksize: 4096,\n  blocks: 8,\n  atime: Mon, 10 Oct 2011 23:24:11 GMT,\n  mtime: Mon, 10 Oct 2011 23:24:11 GMT,\n  ctime: Mon, 10 Oct 2011 23:24:11 GMT }
    \n

    Please note that atime, mtime and ctime are instances\nof [Date][MDN-Date] object and to compare the values of\nthese objects you should use appropriate methods. For most\ngeneral uses [getTime()][MDN-Date-getTime] will return\nthe number of milliseconds elapsed since 1 January 1970\n00:00:00 UTC and this integer should be sufficient for\nany comparison, however there additional methods which can\nbe used for displaying fuzzy information. More details can\nbe found in the [MDN JavaScript Reference][MDN-Date] page.\n\n

    \n" }, { "textRaw": "Class: fs.ReadStream", "type": "class", "name": "fs.ReadStream", "desc": "

    ReadStream is a Readable Stream.\n\n

    \n", "events": [ { "textRaw": "Event: 'open'", "type": "event", "name": "open", "params": [], "desc": "

    Emitted when the ReadStream's file is opened.\n\n\n

    \n" } ] }, { "textRaw": "Class: fs.WriteStream", "type": "class", "name": "fs.WriteStream", "desc": "

    WriteStream is a Writable Stream.\n\n

    \n", "events": [ { "textRaw": "Event: 'open'", "type": "event", "name": "open", "params": [], "desc": "

    Emitted when the WriteStream's file is opened.\n\n

    \n" } ], "properties": [ { "textRaw": "file.bytesWritten", "name": "bytesWritten", "desc": "

    The number of bytes written so far. Does not include data that is still queued\nfor writing.\n\n

    \n" } ] }, { "textRaw": "Class: fs.FSWatcher", "type": "class", "name": "fs.FSWatcher", "desc": "

    Objects returned from fs.watch() are of this type.\n\n

    \n", "methods": [ { "textRaw": "watcher.close()", "type": "method", "name": "close", "desc": "

    Stop watching for changes on the given fs.FSWatcher.\n\n

    \n", "signatures": [ { "params": [] } ] } ], "events": [ { "textRaw": "Event: 'change'", "type": "event", "name": "change", "params": [], "desc": "

    Emitted when something changes in a watched directory or file.\nSee more details in fs.watch.\n\n

    \n" }, { "textRaw": "Event: 'error'", "type": "event", "name": "error", "params": [], "desc": "

    Emitted when an error occurs.\n\n

    \n" } ] } ], "type": "module", "displayName": "fs" }, { "textRaw": "Path", "name": "path", "stability": 3, "stabilityText": "Stable", "desc": "

    This module contains utilities for handling and transforming file\npaths. Almost all these methods perform only string transformations.\nThe file system is not consulted to check whether paths are valid.\n\n

    \n

    Use require('path') to use this module. The following methods are provided:\n\n

    \n", "methods": [ { "textRaw": "path.normalize(p)", "type": "method", "name": "normalize", "desc": "

    Normalize a string path, taking care of '..' and '.' parts.\n\n

    \n

    When multiple slashes are found, they're replaced by a single one;\nwhen the path contains a trailing slash, it is preserved.\nOn Windows backslashes are used.\n\n

    \n

    Example:\n\n

    \n
    path.normalize('/foo/bar//baz/asdf/quux/..')\n// returns\n'/foo/bar/baz/asdf'
    \n", "signatures": [ { "params": [ { "name": "p" } ] } ] }, { "textRaw": "path.join([path1], [path2], [...])", "type": "method", "name": "join", "desc": "

    Join all arguments together and normalize the resulting path.\n\n

    \n

    Arguments must be strings. In v0.8, non-string arguments were\nsilently ignored. In v0.10 and up, an exception is thrown.\n\n

    \n

    Example:\n\n

    \n
    path.join('/foo', 'bar', 'baz/asdf', 'quux', '..')\n// returns\n'/foo/bar/baz/asdf'\n\npath.join('foo', {}, 'bar')\n// throws exception\nTypeError: Arguments to path.join must be strings
    \n", "signatures": [ { "params": [ { "name": "path1", "optional": true }, { "name": "path2", "optional": true }, { "name": "...", "optional": true } ] } ] }, { "textRaw": "path.resolve([from ...], to)", "type": "method", "name": "resolve", "desc": "

    Resolves to to an absolute path.\n\n

    \n

    If to isn't already absolute from arguments are prepended in right to left\norder, until an absolute path is found. If after using all from paths still\nno absolute path is found, the current working directory is used as well. The\nresulting path is normalized, and trailing slashes are removed unless the path\ngets resolved to the root directory. Non-string arguments are ignored.\n\n

    \n

    Another way to think of it is as a sequence of cd commands in a shell.\n\n

    \n
    path.resolve('foo/bar', '/tmp/file/', '..', 'a/../subfile')
    \n

    Is similar to:\n\n

    \n
    cd foo/bar\ncd /tmp/file/\ncd ..\ncd a/../subfile\npwd
    \n

    The difference is that the different paths don't need to exist and may also be\nfiles.\n\n

    \n

    Examples:\n\n

    \n
    path.resolve('/foo/bar', './baz')\n// returns\n'/foo/bar/baz'\n\npath.resolve('/foo/bar', '/tmp/file/')\n// returns\n'/tmp/file'\n\npath.resolve('wwwroot', 'static_files/png/', '../gif/image.gif')\n// if currently in /home/myself/node, it returns\n'/home/myself/node/wwwroot/static_files/gif/image.gif'
    \n", "signatures": [ { "params": [ { "name": "from ...", "optional": true }, { "name": "to" } ] } ] }, { "textRaw": "path.relative(from, to)", "type": "method", "name": "relative", "desc": "

    Solve the relative path from from to to.\n\n

    \n

    At times we have two absolute paths, and we need to derive the relative\npath from one to the other. This is actually the reverse transform of\npath.resolve, which means we see that:\n\n

    \n
    path.resolve(from, path.relative(from, to)) == path.resolve(to)
    \n

    Examples:\n\n

    \n
    path.relative('C:\\\\orandea\\\\test\\\\aaa', 'C:\\\\orandea\\\\impl\\\\bbb')\n// returns\n'..\\\\..\\\\impl\\\\bbb'\n\npath.relative('/data/orandea/test/aaa', '/data/orandea/impl/bbb')\n// returns\n'../../impl/bbb'
    \n", "signatures": [ { "params": [ { "name": "from" }, { "name": "to" } ] } ] }, { "textRaw": "path.dirname(p)", "type": "method", "name": "dirname", "desc": "

    Return the directory name of a path. Similar to the Unix dirname command.\n\n

    \n

    Example:\n\n

    \n
    path.dirname('/foo/bar/baz/asdf/quux')\n// returns\n'/foo/bar/baz/asdf'
    \n", "signatures": [ { "params": [ { "name": "p" } ] } ] }, { "textRaw": "path.basename(p, [ext])", "type": "method", "name": "basename", "desc": "

    Return the last portion of a path. Similar to the Unix basename command.\n\n

    \n

    Example:\n\n

    \n
    path.basename('/foo/bar/baz/asdf/quux.html')\n// returns\n'quux.html'\n\npath.basename('/foo/bar/baz/asdf/quux.html', '.html')\n// returns\n'quux'
    \n", "signatures": [ { "params": [ { "name": "p" }, { "name": "ext", "optional": true } ] } ] }, { "textRaw": "path.extname(p)", "type": "method", "name": "extname", "desc": "

    Return the extension of the path, from the last '.' to end of string\nin the last portion of the path. If there is no '.' in the last portion\nof the path or the first character of it is '.', then it returns\nan empty string. Examples:\n\n

    \n
    path.extname('index.html')\n// returns\n'.html'\n\npath.extname('index.')\n// returns\n'.'\n\npath.extname('index')\n// returns\n''
    \n", "signatures": [ { "params": [ { "name": "p" } ] } ] } ], "properties": [ { "textRaw": "path.sep", "name": "sep", "desc": "

    The platform-specific file separator. '\\\\' or '/'.\n\n

    \n

    An example on *nix:\n\n

    \n
    'foo/bar/baz'.split(path.sep)\n// returns\n['foo', 'bar', 'baz']
    \n

    An example on Windows:\n\n

    \n
    'foo\\\\bar\\\\baz'.split(path.sep)\n// returns\n['foo', 'bar', 'baz']
    \n" }, { "textRaw": "path.delimiter", "name": "delimiter", "desc": "

    The platform-specific path delimiter, ; or ':'.\n\n

    \n

    An example on *nix:\n\n

    \n
    console.log(process.env.PATH)\n// '/usr/bin:/bin:/usr/sbin:/sbin:/usr/local/bin'\n\nprocess.env.PATH.split(path.delimiter)\n// returns\n['/usr/bin', '/bin', '/usr/sbin', '/sbin', '/usr/local/bin']
    \n

    An example on Windows:\n\n

    \n
    console.log(process.env.PATH)\n// 'C:\\Windows\\system32;C:\\Windows;C:\\Program Files\\nodejs\\'\n\nprocess.env.PATH.split(path.delimiter)\n// returns\n['C:\\Windows\\system32', 'C:\\Windows', 'C:\\Program Files\\nodejs\\']
    \n" } ], "type": "module", "displayName": "Path" }, { "textRaw": "net", "name": "net", "stability": 3, "stabilityText": "Stable", "desc": "

    The net module provides you with an asynchronous network wrapper. It contains\nmethods for creating both servers and clients (called streams). You can include\nthis module with require('net');\n\n

    \n", "methods": [ { "textRaw": "net.createServer([options], [connectionListener])", "type": "method", "name": "createServer", "desc": "

    Creates a new TCP server. The connectionListener argument is\nautomatically set as a listener for the ['connection'][] event.\n\n

    \n

    options is an object with the following defaults:\n\n

    \n
    { allowHalfOpen: false\n}
    \n

    If allowHalfOpen is true, then the socket won't automatically send a FIN\npacket when the other end of the socket sends a FIN packet. The socket becomes\nnon-readable, but still writable. You should call the end() method explicitly.\nSee ['end'][] event for more information.\n\n

    \n

    Here is an example of an echo server which listens for connections\non port 8124:\n\n

    \n
    var net = require('net');\nvar server = net.createServer(function(c) { //'connection' listener\n  console.log('server connected');\n  c.on('end', function() {\n    console.log('server disconnected');\n  });\n  c.write('hello\\r\\n');\n  c.pipe(c);\n});\nserver.listen(8124, function() { //'listening' listener\n  console.log('server bound');\n});
    \n

    Test this by using telnet:\n\n

    \n
    telnet localhost 8124
    \n

    To listen on the socket /tmp/echo.sock the third line from the last would\njust be changed to\n\n

    \n
    server.listen('/tmp/echo.sock', function() { //'listening' listener
    \n

    Use nc to connect to a UNIX domain socket server:\n\n

    \n
    nc -U /tmp/echo.sock
    \n", "signatures": [ { "params": [ { "name": "options", "optional": true }, { "name": "connectionListener", "optional": true } ] } ] }, { "textRaw": "net.connect(options, [connectionListener])", "type": "method", "name": "connect", "desc": "

    Constructs a new socket object and opens the socket to the given location.\nWhen the socket is established, the ['connect'][] event will be emitted.\n\n

    \n

    For TCP sockets, options argument should be an object which specifies:\n\n

    \n
      \n
    • port: Port the client should connect to (Required).

      \n
    • \n
    • host: Host the client should connect to. Defaults to 'localhost'.

      \n
    • \n
    • localAddress: Local interface to bind to for network connections.

      \n
    • \n
    \n

    For UNIX domain sockets, options argument should be an object which specifies:\n\n

    \n
      \n
    • path: Path the client should connect to (Required).
    • \n
    \n

    Common options are:\n\n

    \n
      \n
    • allowHalfOpen: if true, the socket won't automatically send\na FIN packet when the other end of the socket sends a FIN packet.\nDefaults to false. See ['end'][] event for more information.
    • \n
    \n

    The connectListener parameter will be added as an listener for the\n['connect'][] event.\n\n

    \n

    Here is an example of a client of echo server as described previously:\n\n

    \n
    var net = require('net');\nvar client = net.connect({port: 8124},\n    function() { //'connect' listener\n  console.log('client connected');\n  client.write('world!\\r\\n');\n});\nclient.on('data', function(data) {\n  console.log(data.toString());\n  client.end();\n});\nclient.on('end', function() {\n  console.log('client disconnected');\n});
    \n

    To connect on the socket /tmp/echo.sock the second line would just be\nchanged to\n\n

    \n
    var client = net.connect({path: '/tmp/echo.sock'});
    \n", "signatures": [ { "params": [ { "name": "options" }, { "name": "connectionListener", "optional": true } ] }, { "params": [ { "name": "options" }, { "name": "connectionListener", "optional": true } ] } ] }, { "textRaw": "net.createConnection(options, [connectionListener])", "type": "method", "name": "createConnection", "desc": "

    Constructs a new socket object and opens the socket to the given location.\nWhen the socket is established, the ['connect'][] event will be emitted.\n\n

    \n

    For TCP sockets, options argument should be an object which specifies:\n\n

    \n
      \n
    • port: Port the client should connect to (Required).

      \n
    • \n
    • host: Host the client should connect to. Defaults to 'localhost'.

      \n
    • \n
    • localAddress: Local interface to bind to for network connections.

      \n
    • \n
    \n

    For UNIX domain sockets, options argument should be an object which specifies:\n\n

    \n
      \n
    • path: Path the client should connect to (Required).
    • \n
    \n

    Common options are:\n\n

    \n
      \n
    • allowHalfOpen: if true, the socket won't automatically send\na FIN packet when the other end of the socket sends a FIN packet.\nDefaults to false. See ['end'][] event for more information.
    • \n
    \n

    The connectListener parameter will be added as an listener for the\n['connect'][] event.\n\n

    \n

    Here is an example of a client of echo server as described previously:\n\n

    \n
    var net = require('net');\nvar client = net.connect({port: 8124},\n    function() { //'connect' listener\n  console.log('client connected');\n  client.write('world!\\r\\n');\n});\nclient.on('data', function(data) {\n  console.log(data.toString());\n  client.end();\n});\nclient.on('end', function() {\n  console.log('client disconnected');\n});
    \n

    To connect on the socket /tmp/echo.sock the second line would just be\nchanged to\n\n

    \n
    var client = net.connect({path: '/tmp/echo.sock'});
    \n", "signatures": [ { "params": [ { "name": "options" }, { "name": "connectionListener", "optional": true } ] } ] }, { "textRaw": "net.connect(port, [host], [connectListener])", "type": "method", "name": "connect", "desc": "

    Creates a TCP connection to port on host. If host is omitted,\n'localhost' will be assumed.\nThe connectListener parameter will be added as an listener for the\n['connect'][] event.\n\n

    \n", "signatures": [ { "params": [ { "name": "port" }, { "name": "host", "optional": true }, { "name": "connectListener", "optional": true } ] }, { "params": [ { "name": "port" }, { "name": "host", "optional": true }, { "name": "connectListener", "optional": true } ] } ] }, { "textRaw": "net.createConnection(port, [host], [connectListener])", "type": "method", "name": "createConnection", "desc": "

    Creates a TCP connection to port on host. If host is omitted,\n'localhost' will be assumed.\nThe connectListener parameter will be added as an listener for the\n['connect'][] event.\n\n

    \n", "signatures": [ { "params": [ { "name": "port" }, { "name": "host", "optional": true }, { "name": "connectListener", "optional": true } ] } ] }, { "textRaw": "net.connect(path, [connectListener])", "type": "method", "name": "connect", "desc": "

    Creates unix socket connection to path.\nThe connectListener parameter will be added as an listener for the\n['connect'][] event.\n\n

    \n", "signatures": [ { "params": [ { "name": "path" }, { "name": "connectListener", "optional": true } ] }, { "params": [ { "name": "path" }, { "name": "connectListener", "optional": true } ] } ] }, { "textRaw": "net.createConnection(path, [connectListener])", "type": "method", "name": "createConnection", "desc": "

    Creates unix socket connection to path.\nThe connectListener parameter will be added as an listener for the\n['connect'][] event.\n\n

    \n", "signatures": [ { "params": [ { "name": "path" }, { "name": "connectListener", "optional": true } ] } ] }, { "textRaw": "net.isIP(input)", "type": "method", "name": "isIP", "desc": "

    Tests if input is an IP address. Returns 0 for invalid strings,\nreturns 4 for IP version 4 addresses, and returns 6 for IP version 6 addresses.\n\n\n

    \n", "signatures": [ { "params": [ { "name": "input" } ] } ] }, { "textRaw": "net.isIPv4(input)", "type": "method", "name": "isIPv4", "desc": "

    Returns true if input is a version 4 IP address, otherwise returns false.\n\n\n

    \n", "signatures": [ { "params": [ { "name": "input" } ] } ] }, { "textRaw": "net.isIPv6(input)", "type": "method", "name": "isIPv6", "desc": "

    Returns true if input is a version 6 IP address, otherwise returns false.\n\n

    \n", "signatures": [ { "params": [ { "name": "input" } ] } ] } ], "classes": [ { "textRaw": "Class: net.Server", "type": "class", "name": "net.Server", "desc": "

    This class is used to create a TCP or UNIX server.\n\n

    \n", "methods": [ { "textRaw": "server.listen(port, [host], [backlog], [callback])", "type": "method", "name": "listen", "desc": "

    Begin accepting connections on the specified port and host. If the\nhost is omitted, the server will accept connections directed to any\nIPv4 address (INADDR_ANY). A port value of zero will assign a random port.\n\n

    \n

    Backlog is the maximum length of the queue of pending connections.\nThe actual length will be determined by your OS through sysctl settings such as\ntcp_max_syn_backlog and somaxconn on linux. The default value of this\nparameter is 511 (not 512).\n\n

    \n

    This function is asynchronous. When the server has been bound,\n['listening'][] event will be emitted. The last parameter callback\nwill be added as an listener for the ['listening'][] event.\n\n

    \n

    One issue some users run into is getting EADDRINUSE errors. This means that\nanother server is already running on the requested port. One way of handling this\nwould be to wait a second and then try again. This can be done with\n\n

    \n
    server.on('error', function (e) {\n  if (e.code == 'EADDRINUSE') {\n    console.log('Address in use, retrying...');\n    setTimeout(function () {\n      server.close();\n      server.listen(PORT, HOST);\n    }, 1000);\n  }\n});
    \n

    (Note: All sockets in Node set SO_REUSEADDR already)\n\n\n

    \n", "signatures": [ { "params": [ { "name": "port" }, { "name": "host", "optional": true }, { "name": "backlog", "optional": true }, { "name": "callback", "optional": true } ] } ] }, { "textRaw": "server.listen(path, [callback])", "type": "method", "name": "listen", "desc": "

    Start a UNIX socket server listening for connections on the given path.\n\n

    \n

    This function is asynchronous. When the server has been bound,\n['listening'][] event will be emitted. The last parameter callback\nwill be added as an listener for the ['listening'][] event.\n\n

    \n", "signatures": [ { "params": [ { "name": "path" }, { "name": "callback", "optional": true } ] } ] }, { "textRaw": "server.listen(handle, [callback])", "type": "method", "name": "listen", "signatures": [ { "params": [ { "textRaw": "`handle` {Object} ", "name": "handle", "type": "Object" }, { "textRaw": "`callback` {Function} ", "name": "callback", "type": "Function", "optional": true } ] }, { "params": [ { "name": "handle" }, { "name": "callback", "optional": true } ] } ], "desc": "

    The handle object can be set to either a server or socket (anything\nwith an underlying _handle member), or a {fd: <n>} object.\n\n

    \n

    This will cause the server to accept connections on the specified\nhandle, but it is presumed that the file descriptor or handle has\nalready been bound to a port or domain socket.\n\n

    \n

    Listening on a file descriptor is not supported on Windows.\n\n

    \n

    This function is asynchronous. When the server has been bound,\n'listening' event will be emitted.\nthe last parameter callback will be added as an listener for the\n'listening' event.\n\n

    \n" }, { "textRaw": "server.close([callback])", "type": "method", "name": "close", "desc": "

    Stops the server from accepting new connections and keeps existing\nconnections. This function is asynchronous, the server is finally\nclosed when all connections are ended and the server emits a 'close'\nevent. Optionally, you can pass a callback to listen for the 'close'\nevent.\n\n

    \n", "signatures": [ { "params": [ { "name": "callback", "optional": true } ] } ] }, { "textRaw": "server.address()", "type": "method", "name": "address", "desc": "

    Returns the bound address, the address family name and port of the server\nas reported by the operating system.\nUseful to find which port was assigned when giving getting an OS-assigned address.\nReturns an object with three properties, e.g.\n{ port: 12346, family: 'IPv4', address: '127.0.0.1' }\n\n

    \n

    Example:\n\n

    \n
    var server = net.createServer(function (socket) {\n  socket.end("goodbye\\n");\n});\n\n// grab a random port.\nserver.listen(function() {\n  address = server.address();\n  console.log("opened server on %j", address);\n});
    \n

    Don't call server.address() until the 'listening' event has been emitted.\n\n

    \n", "signatures": [ { "params": [] } ] }, { "textRaw": "server.unref()", "type": "method", "name": "unref", "desc": "

    Calling unref on a server will allow the program to exit if this is the only\nactive server in the event system. If the server is already unrefd calling\nunref again will have no effect.\n\n

    \n", "signatures": [ { "params": [] } ] }, { "textRaw": "server.ref()", "type": "method", "name": "ref", "desc": "

    Opposite of unref, calling ref on a previously unrefd server will not\nlet the program exit if it's the only server left (the default behavior). If\nthe server is refd calling ref again will have no effect.\n\n

    \n", "signatures": [ { "params": [] } ] }, { "textRaw": "server.getConnections(callback)", "type": "method", "name": "getConnections", "desc": "

    Asynchronously get the number of concurrent connections on the server. Works\nwhen sockets were sent to forks.\n\n

    \n

    Callback should take two arguments err and count.\n\n

    \n", "signatures": [ { "params": [ { "name": "callback" } ] } ] } ], "properties": [ { "textRaw": "server.maxConnections", "name": "maxConnections", "desc": "

    Set this property to reject connections when the server's connection count gets\nhigh.\n\n

    \n

    It is not recommended to use this option once a socket has been sent to a child\nwith child_process.fork().\n\n

    \n" }, { "textRaw": "server.connections", "name": "connections", "desc": "

    This function is deprecated; please use [server.getConnections()][] instead.\nThe number of concurrent connections on the server.\n\n

    \n

    This becomes null when sending a socket to a child with\nchild_process.fork(). To poll forks and get current number of active\nconnections use asynchronous server.getConnections instead.\n\n

    \n

    net.Server is an [EventEmitter][] with the following events:\n\n

    \n" } ], "events": [ { "textRaw": "Event: 'listening'", "type": "event", "name": "listening", "desc": "

    Emitted when the server has been bound after calling server.listen.\n\n

    \n", "params": [] }, { "textRaw": "Event: 'connection'", "type": "event", "name": "connection", "params": [], "desc": "

    Emitted when a new connection is made. socket is an instance of\nnet.Socket.\n\n

    \n" }, { "textRaw": "Event: 'close'", "type": "event", "name": "close", "desc": "

    Emitted when the server closes. Note that if connections exist, this\nevent is not emitted until all connections are ended.\n\n

    \n", "params": [] }, { "textRaw": "Event: 'error'", "type": "event", "name": "error", "params": [], "desc": "

    Emitted when an error occurs. The 'close' event will be called directly\nfollowing this event. See example in discussion of server.listen.\n\n

    \n" } ] }, { "textRaw": "Class: net.Socket", "type": "class", "name": "net.Socket", "desc": "

    This object is an abstraction of a TCP or UNIX socket. net.Socket\ninstances implement a duplex Stream interface. They can be created by the\nuser and used as a client (with connect()) or they can be created by Node\nand passed to the user through the 'connection' event of a server.\n\n

    \n", "methods": [ { "textRaw": "new net.Socket([options])", "type": "method", "name": "Socket", "desc": "

    Construct a new socket object.\n\n

    \n

    options is an object with the following defaults:\n\n

    \n
    { fd: null\n  allowHalfOpen: false,\n  readable: false,\n  writable: false\n}
    \n

    fd allows you to specify the existing file descriptor of socket.\nSet readable and/or writable to true to allow reads and/or writes on this\nsocket (NOTE: Works only when fd is passed).\nAbout allowHalfOpen, refer to createServer() and 'end' event.\n\n

    \n", "signatures": [ { "params": [ { "name": "options", "optional": true } ] } ] }, { "textRaw": "socket.connect(port, [host], [connectListener])", "type": "method", "name": "connect", "desc": "

    Opens the connection for a given socket. If port and host are given,\nthen the socket will be opened as a TCP socket, if host is omitted,\nlocalhost will be assumed. If a path is given, the socket will be\nopened as a unix socket to that path.\n\n

    \n

    Normally this method is not needed, as net.createConnection opens the\nsocket. Use this only if you are implementing a custom Socket.\n\n

    \n

    This function is asynchronous. When the ['connect'][] event is emitted the\nsocket is established. If there is a problem connecting, the 'connect' event\nwill not be emitted, the 'error' event will be emitted with the exception.\n\n

    \n

    The connectListener parameter will be added as an listener for the\n['connect'][] event.\n\n\n

    \n", "signatures": [ { "params": [ { "name": "path" }, { "name": "connectListener", "optional": true } ] }, { "params": [ { "name": "port" }, { "name": "host", "optional": true }, { "name": "connectListener", "optional": true } ] } ] }, { "textRaw": "socket.connect(path, [connectListener])", "type": "method", "name": "connect", "desc": "

    Opens the connection for a given socket. If port and host are given,\nthen the socket will be opened as a TCP socket, if host is omitted,\nlocalhost will be assumed. If a path is given, the socket will be\nopened as a unix socket to that path.\n\n

    \n

    Normally this method is not needed, as net.createConnection opens the\nsocket. Use this only if you are implementing a custom Socket.\n\n

    \n

    This function is asynchronous. When the ['connect'][] event is emitted the\nsocket is established. If there is a problem connecting, the 'connect' event\nwill not be emitted, the 'error' event will be emitted with the exception.\n\n

    \n

    The connectListener parameter will be added as an listener for the\n['connect'][] event.\n\n\n

    \n", "signatures": [ { "params": [ { "name": "path" }, { "name": "connectListener", "optional": true } ] } ] }, { "textRaw": "socket.setEncoding([encoding])", "type": "method", "name": "setEncoding", "desc": "

    Set the encoding for the socket as a Readable Stream. See\n[stream.setEncoding()][] for more information.\n\n

    \n", "signatures": [ { "params": [ { "name": "encoding", "optional": true } ] } ] }, { "textRaw": "socket.write(data, [encoding], [callback])", "type": "method", "name": "write", "desc": "

    Sends data on the socket. The second parameter specifies the encoding in the\ncase of a string--it defaults to UTF8 encoding.\n\n

    \n

    Returns true if the entire data was flushed successfully to the kernel\nbuffer. Returns false if all or part of the data was queued in user memory.\n'drain' will be emitted when the buffer is again free.\n\n

    \n

    The optional callback parameter will be executed when the data is finally\nwritten out - this may not be immediately.\n\n

    \n", "signatures": [ { "params": [ { "name": "data" }, { "name": "encoding", "optional": true }, { "name": "callback", "optional": true } ] } ] }, { "textRaw": "socket.end([data], [encoding])", "type": "method", "name": "end", "desc": "

    Half-closes the socket. i.e., it sends a FIN packet. It is possible the\nserver will still send some data.\n\n

    \n

    If data is specified, it is equivalent to calling\nsocket.write(data, encoding) followed by socket.end().\n\n

    \n", "signatures": [ { "params": [ { "name": "data", "optional": true }, { "name": "encoding", "optional": true } ] } ] }, { "textRaw": "socket.destroy()", "type": "method", "name": "destroy", "desc": "

    Ensures that no more I/O activity happens on this socket. Only necessary in\ncase of errors (parse error or so).\n\n

    \n", "signatures": [ { "params": [] } ] }, { "textRaw": "socket.pause()", "type": "method", "name": "pause", "desc": "

    Pauses the reading of data. That is, 'data' events will not be emitted.\nUseful to throttle back an upload.\n\n

    \n", "signatures": [ { "params": [] } ] }, { "textRaw": "socket.resume()", "type": "method", "name": "resume", "desc": "

    Resumes reading after a call to pause().\n\n

    \n", "signatures": [ { "params": [] } ] }, { "textRaw": "socket.setTimeout(timeout, [callback])", "type": "method", "name": "setTimeout", "desc": "

    Sets the socket to timeout after timeout milliseconds of inactivity on\nthe socket. By default net.Socket do not have a timeout.\n\n

    \n

    When an idle timeout is triggered the socket will receive a 'timeout'\nevent but the connection will not be severed. The user must manually end()\nor destroy() the socket.\n\n

    \n

    If timeout is 0, then the existing idle timeout is disabled.\n\n

    \n

    The optional callback parameter will be added as a one time listener for the\n'timeout' event.\n\n

    \n", "signatures": [ { "params": [ { "name": "timeout" }, { "name": "callback", "optional": true } ] } ] }, { "textRaw": "socket.setNoDelay([noDelay])", "type": "method", "name": "setNoDelay", "desc": "

    Disables the Nagle algorithm. By default TCP connections use the Nagle\nalgorithm, they buffer data before sending it off. Setting true for\nnoDelay will immediately fire off data each time socket.write() is called.\nnoDelay defaults to true.\n\n

    \n", "signatures": [ { "params": [ { "name": "noDelay", "optional": true } ] } ] }, { "textRaw": "socket.setKeepAlive([enable], [initialDelay])", "type": "method", "name": "setKeepAlive", "desc": "

    Enable/disable keep-alive functionality, and optionally set the initial\ndelay before the first keepalive probe is sent on an idle socket.\nenable defaults to false.\n\n

    \n

    Set initialDelay (in milliseconds) to set the delay between the last\ndata packet received and the first keepalive probe. Setting 0 for\ninitialDelay will leave the value unchanged from the default\n(or previous) setting. Defaults to 0.\n\n

    \n", "signatures": [ { "params": [ { "name": "enable", "optional": true }, { "name": "initialDelay", "optional": true } ] } ] }, { "textRaw": "socket.address()", "type": "method", "name": "address", "desc": "

    Returns the bound address, the address family name and port of the\nsocket as reported by the operating system. Returns an object with\nthree properties, e.g.\n{ port: 12346, family: 'IPv4', address: '127.0.0.1' }\n\n

    \n", "signatures": [ { "params": [] } ] }, { "textRaw": "socket.unref()", "type": "method", "name": "unref", "desc": "

    Calling unref on a socket will allow the program to exit if this is the only\nactive socket in the event system. If the socket is already unrefd calling\nunref again will have no effect.\n\n

    \n", "signatures": [ { "params": [] } ] }, { "textRaw": "socket.ref()", "type": "method", "name": "ref", "desc": "

    Opposite of unref, calling ref on a previously unrefd socket will not\nlet the program exit if it's the only socket left (the default behavior). If\nthe socket is refd calling ref again will have no effect.\n\n

    \n", "signatures": [ { "params": [] } ] } ], "properties": [ { "textRaw": "socket.bufferSize", "name": "bufferSize", "desc": "

    net.Socket has the property that socket.write() always works. This is to\nhelp users get up and running quickly. The computer cannot always keep up\nwith the amount of data that is written to a socket - the network connection\nsimply might be too slow. Node will internally queue up the data written to a\nsocket and send it out over the wire when it is possible. (Internally it is\npolling on the socket's file descriptor for being writable).\n\n

    \n

    The consequence of this internal buffering is that memory may grow. This\nproperty shows the number of characters currently buffered to be written.\n(Number of characters is approximately equal to the number of bytes to be\nwritten, but the buffer may contain strings, and the strings are lazily\nencoded, so the exact number of bytes is not known.)\n\n

    \n

    Users who experience large or growing bufferSize should attempt to\n"throttle" the data flows in their program with pause() and resume().\n\n\n

    \n" }, { "textRaw": "socket.remoteAddress", "name": "remoteAddress", "desc": "

    The string representation of the remote IP address. For example,\n'74.125.127.100' or '2001:4860:a005::68'.\n\n

    \n" }, { "textRaw": "socket.remotePort", "name": "remotePort", "desc": "

    The numeric representation of the remote port. For example,\n80 or 21.\n\n

    \n" }, { "textRaw": "socket.localAddress", "name": "localAddress", "desc": "

    The string representation of the local IP address the remote client is\nconnecting on. For example, if you are listening on '0.0.0.0' and the\nclient connects on '192.168.1.1', the value would be '192.168.1.1'.\n\n

    \n" }, { "textRaw": "socket.localPort", "name": "localPort", "desc": "

    The numeric representation of the local port. For example,\n80 or 21.\n\n

    \n" }, { "textRaw": "socket.bytesRead", "name": "bytesRead", "desc": "

    The amount of received bytes.\n\n

    \n" }, { "textRaw": "socket.bytesWritten", "name": "bytesWritten", "desc": "

    The amount of bytes sent.\n\n\n

    \n

    net.Socket instances are [EventEmitter][] with the following events:\n\n

    \n" } ], "events": [ { "textRaw": "Event: 'connect'", "type": "event", "name": "connect", "desc": "

    Emitted when a socket connection is successfully established.\nSee connect().\n\n

    \n", "params": [] }, { "textRaw": "Event: 'data'", "type": "event", "name": "data", "params": [], "desc": "

    Emitted when data is received. The argument data will be a Buffer or\nString. Encoding of data is set by socket.setEncoding().\n(See the [Readable Stream][] section for more information.)\n\n

    \n

    Note that the data will be lost if there is no listener when a Socket\nemits a 'data' event.\n\n

    \n" }, { "textRaw": "Event: 'end'", "type": "event", "name": "end", "desc": "

    Emitted when the other end of the socket sends a FIN packet.\n\n

    \n

    By default (allowHalfOpen == false) the socket will destroy its file\ndescriptor once it has written out its pending write queue. However, by\nsetting allowHalfOpen == true the socket will not automatically end()\nits side allowing the user to write arbitrary amounts of data, with the\ncaveat that the user is required to end() their side now.\n\n\n

    \n", "params": [] }, { "textRaw": "Event: 'timeout'", "type": "event", "name": "timeout", "desc": "

    Emitted if the socket times out from inactivity. This is only to notify that\nthe socket has been idle. The user must manually close the connection.\n\n

    \n

    See also: socket.setTimeout()\n\n\n

    \n", "params": [] }, { "textRaw": "Event: 'drain'", "type": "event", "name": "drain", "desc": "

    Emitted when the write buffer becomes empty. Can be used to throttle uploads.\n\n

    \n

    See also: the return values of socket.write()\n\n

    \n", "params": [] }, { "textRaw": "Event: 'error'", "type": "event", "name": "error", "params": [], "desc": "

    Emitted when an error occurs. The 'close' event will be called directly\nfollowing this event.\n\n

    \n" }, { "textRaw": "Event: 'close'", "type": "event", "name": "close", "params": [], "desc": "

    Emitted once the socket is fully closed. The argument had_error is a boolean\nwhich says if the socket was closed due to a transmission error.\n\n

    \n" } ] } ], "type": "module", "displayName": "net" }, { "textRaw": "UDP / Datagram Sockets", "name": "dgram", "stability": 3, "stabilityText": "Stable", "desc": "

    Datagram sockets are available through require('dgram').\n\n

    \n

    Important note: the behavior of dgram.Socket#bind() has changed in v0.10\nand is always asynchronous now. If you have code that looks like this:\n\n

    \n
    var s = dgram.createSocket('udp4');\ns.bind(1234);\ns.addMembership('224.0.0.114');
    \n

    You have to change it to this:\n\n

    \n
    var s = dgram.createSocket('udp4');\ns.bind(1234, function() {\n  s.addMembership('224.0.0.114');\n});
    \n", "methods": [ { "textRaw": "dgram.createSocket(type, [callback])", "type": "method", "name": "createSocket", "signatures": [ { "return": { "textRaw": "Returns: Socket object ", "name": "return", "desc": "Socket object" }, "params": [ { "textRaw": "`type` String. Either 'udp4' or 'udp6' ", "name": "type", "desc": "String. Either 'udp4' or 'udp6'" }, { "textRaw": "`callback` Function. Attached as a listener to `message` events. Optional ", "name": "callback", "optional": true, "desc": "Function. Attached as a listener to `message` events." } ] }, { "params": [ { "name": "type" }, { "name": "callback", "optional": true } ] } ], "desc": "

    Creates a datagram Socket of the specified types. Valid types are udp4\nand udp6.\n\n

    \n

    Takes an optional callback which is added as a listener for message events.\n\n

    \n

    Call socket.bind if you want to receive datagrams. socket.bind() will bind\nto the "all interfaces" address on a random port (it does the right thing for\nboth udp4 and udp6 sockets). You can then retrieve the address and port\nwith socket.address().address and socket.address().port.\n\n

    \n" } ], "classes": [ { "textRaw": "Class: dgram.Socket", "type": "class", "name": "dgram.Socket", "desc": "

    The dgram Socket class encapsulates the datagram functionality. It\nshould be created via dgram.createSocket(type, [callback]).\n\n

    \n", "events": [ { "textRaw": "Event: 'message'", "type": "event", "name": "message", "params": [], "desc": "

    Emitted when a new datagram is available on a socket. msg is a Buffer and rinfo is\nan object with the sender's address information and the number of bytes in the datagram.\n\n

    \n" }, { "textRaw": "Event: 'listening'", "type": "event", "name": "listening", "desc": "

    Emitted when a socket starts listening for datagrams. This happens as soon as UDP sockets\nare created.\n\n

    \n", "params": [] }, { "textRaw": "Event: 'close'", "type": "event", "name": "close", "desc": "

    Emitted when a socket is closed with close(). No new message events will be emitted\non this socket.\n\n

    \n", "params": [] }, { "textRaw": "Event: 'error'", "type": "event", "name": "error", "params": [], "desc": "

    Emitted when an error occurs.\n\n

    \n" } ], "methods": [ { "textRaw": "socket.send(buf, offset, length, port, address, [callback])", "type": "method", "name": "send", "signatures": [ { "params": [ { "textRaw": "`buf` Buffer object. Message to be sent ", "name": "buf", "desc": "Buffer object. Message to be sent" }, { "textRaw": "`offset` Integer. Offset in the buffer where the message starts. ", "name": "offset", "desc": "Integer. Offset in the buffer where the message starts." }, { "textRaw": "`length` Integer. Number of bytes in the message. ", "name": "length", "desc": "Integer. Number of bytes in the message." }, { "textRaw": "`port` Integer. Destination port. ", "name": "port", "desc": "Integer. Destination port." }, { "textRaw": "`address` String. Destination hostname or IP address. ", "name": "address", "desc": "String. Destination hostname or IP address." }, { "textRaw": "`callback` Function. Called when the message has been sent. Optional. ", "name": "callback", "desc": "Function. Called when the message has been sent. Optional.", "optional": true } ] }, { "params": [ { "name": "buf" }, { "name": "offset" }, { "name": "length" }, { "name": "port" }, { "name": "address" }, { "name": "callback", "optional": true } ] } ], "desc": "

    For UDP sockets, the destination port and address must be specified. A string\nmay be supplied for the address parameter, and it will be resolved with DNS.\n\n

    \n

    If the address is omitted or is an empty string, '0.0.0.0' or '::0' is used\ninstead. Depending on the network configuration, those defaults may or may not\nwork; it's best to be explicit about the destination address.\n\n

    \n

    If the socket has not been previously bound with a call to bind, it gets\nassigned a random port number and is bound to the "all interfaces" address\n('0.0.0.0' for udp4 sockets, '::0' for udp6 sockets.)\n\n

    \n

    An optional callback may be specified to detect DNS errors or for determining\nwhen it's safe to reuse the buf object. Note that DNS lookups delay the time\nto send for at least one tick. The only way to know for sure that the datagram\nhas been sent is by using a callback.\n\n

    \n

    Example of sending a UDP packet to a random port on localhost;\n\n

    \n
    var dgram = require('dgram');\nvar message = new Buffer("Some bytes");\nvar client = dgram.createSocket("udp4");\nclient.send(message, 0, message.length, 41234, "localhost", function(err, bytes) {\n  client.close();\n});
    \n

    A Note about UDP datagram size\n\n

    \n

    The maximum size of an IPv4/v6 datagram depends on the MTU (Maximum Transmission Unit)\nand on the Payload Length field size.\n\n

    \n
      \n
    • The Payload Length field is 16 bits wide, which means that a normal payload\ncannot be larger than 64K octets including internet header and data\n(65,507 bytes = 65,535 − 8 bytes UDP header − 20 bytes IP header);\nthis is generally true for loopback interfaces, but such long datagrams\nare impractical for most hosts and networks.

      \n
    • \n
    • The MTU is the largest size a given link layer technology can support for datagrams.\nFor any link, IPv4 mandates a minimum MTU of 68 octets, while the recommended MTU\nfor IPv4 is 576 (typically recommended as the MTU for dial-up type applications),\nwhether they arrive whole or in fragments.

      \n

      For IPv6, the minimum MTU is 1280 octets, however, the mandatory minimum\nfragment reassembly buffer size is 1500 octets.\nThe value of 68 octets is very small, since most current link layer technologies have\na minimum MTU of 1500 (like Ethernet).

      \n
    • \n
    \n

    Note that it's impossible to know in advance the MTU of each link through which\na packet might travel, and that generally sending a datagram greater than\nthe (receiver) MTU won't work (the packet gets silently dropped, without\ninforming the source that the data did not reach its intended recipient).\n\n

    \n" }, { "textRaw": "socket.bind(port, [address], [callback])", "type": "method", "name": "bind", "signatures": [ { "params": [ { "textRaw": "`port` Integer ", "name": "port", "desc": "Integer" }, { "textRaw": "`address` String, Optional ", "name": "address", "optional": true, "desc": "String" }, { "textRaw": "`callback` Function with no parameters, Optional. Callback when binding is done. ", "name": "callback", "desc": "Function with no parameters, Optional. Callback when binding is done.", "optional": true } ] }, { "params": [ { "name": "port" }, { "name": "address", "optional": true }, { "name": "callback", "optional": true } ] } ], "desc": "

    For UDP sockets, listen for datagrams on a named port and optional\naddress. If address is not specified, the OS will try to listen on\nall addresses. After binding is done, a "listening" event is emitted\nand the callback(if specified) is called. Specifying both a\n"listening" event listener and callback is not harmful but not very\nuseful.\n\n

    \n

    A bound datagram socket keeps the node process running to receive\ndatagrams.\n\n

    \n

    If binding fails, an "error" event is generated. In rare case (e.g.\nbinding a closed socket), an Error may be thrown by this method.\n\n

    \n

    Example of a UDP server listening on port 41234:\n\n

    \n
    var dgram = require("dgram");\n\nvar server = dgram.createSocket("udp4");\n\nserver.on("error", function (err) {\n  console.log("server error:\\n" + err.stack);\n  server.close();\n});\n\nserver.on("message", function (msg, rinfo) {\n  console.log("server got: " + msg + " from " +\n    rinfo.address + ":" + rinfo.port);\n});\n\nserver.on("listening", function () {\n  var address = server.address();\n  console.log("server listening " +\n      address.address + ":" + address.port);\n});\n\nserver.bind(41234);\n// server listening 0.0.0.0:41234
    \n" }, { "textRaw": "socket.close()", "type": "method", "name": "close", "desc": "

    Close the underlying socket and stop listening for data on it.\n\n

    \n", "signatures": [ { "params": [] } ] }, { "textRaw": "socket.address()", "type": "method", "name": "address", "desc": "

    Returns an object containing the address information for a socket. For UDP sockets,\nthis object will contain address , family and port.\n\n

    \n", "signatures": [ { "params": [] } ] }, { "textRaw": "socket.setBroadcast(flag)", "type": "method", "name": "setBroadcast", "signatures": [ { "params": [ { "textRaw": "`flag` Boolean ", "name": "flag", "desc": "Boolean" } ] }, { "params": [ { "name": "flag" } ] } ], "desc": "

    Sets or clears the SO_BROADCAST socket option. When this option is set, UDP packets\nmay be sent to a local interface's broadcast address.\n\n

    \n" }, { "textRaw": "socket.setTTL(ttl)", "type": "method", "name": "setTTL", "signatures": [ { "params": [ { "textRaw": "`ttl` Integer ", "name": "ttl", "desc": "Integer" } ] }, { "params": [ { "name": "ttl" } ] } ], "desc": "

    Sets the IP_TTL socket option. TTL stands for "Time to Live," but in this context it\nspecifies the number of IP hops that a packet is allowed to go through. Each router or\ngateway that forwards a packet decrements the TTL. If the TTL is decremented to 0 by a\nrouter, it will not be forwarded. Changing TTL values is typically done for network\nprobes or when multicasting.\n\n

    \n

    The argument to setTTL() is a number of hops between 1 and 255. The default on most\nsystems is 64.\n\n

    \n" }, { "textRaw": "socket.setMulticastTTL(ttl)", "type": "method", "name": "setMulticastTTL", "signatures": [ { "params": [ { "textRaw": "`ttl` Integer ", "name": "ttl", "desc": "Integer" } ] }, { "params": [ { "name": "ttl" } ] } ], "desc": "

    Sets the IP_MULTICAST_TTL socket option. TTL stands for "Time to Live," but in this\ncontext it specifies the number of IP hops that a packet is allowed to go through,\nspecifically for multicast traffic. Each router or gateway that forwards a packet\ndecrements the TTL. If the TTL is decremented to 0 by a router, it will not be forwarded.\n\n

    \n

    The argument to setMulticastTTL() is a number of hops between 0 and 255. The default on most\nsystems is 1.\n\n

    \n" }, { "textRaw": "socket.setMulticastLoopback(flag)", "type": "method", "name": "setMulticastLoopback", "signatures": [ { "params": [ { "textRaw": "`flag` Boolean ", "name": "flag", "desc": "Boolean" } ] }, { "params": [ { "name": "flag" } ] } ], "desc": "

    Sets or clears the IP_MULTICAST_LOOP socket option. When this option is set, multicast\npackets will also be received on the local interface.\n\n

    \n" }, { "textRaw": "socket.addMembership(multicastAddress, [multicastInterface])", "type": "method", "name": "addMembership", "signatures": [ { "params": [ { "textRaw": "`multicastAddress` String ", "name": "multicastAddress", "desc": "String" }, { "textRaw": "`multicastInterface` String, Optional ", "name": "multicastInterface", "optional": true, "desc": "String" } ] }, { "params": [ { "name": "multicastAddress" }, { "name": "multicastInterface", "optional": true } ] } ], "desc": "

    Tells the kernel to join a multicast group with IP_ADD_MEMBERSHIP socket option.\n\n

    \n

    If multicastInterface is not specified, the OS will try to add membership to all valid\ninterfaces.\n\n

    \n" }, { "textRaw": "socket.dropMembership(multicastAddress, [multicastInterface])", "type": "method", "name": "dropMembership", "signatures": [ { "params": [ { "textRaw": "`multicastAddress` String ", "name": "multicastAddress", "desc": "String" }, { "textRaw": "`multicastInterface` String, Optional ", "name": "multicastInterface", "optional": true, "desc": "String" } ] }, { "params": [ { "name": "multicastAddress" }, { "name": "multicastInterface", "optional": true } ] } ], "desc": "

    Opposite of addMembership - tells the kernel to leave a multicast group with\nIP_DROP_MEMBERSHIP socket option. This is automatically called by the kernel\nwhen the socket is closed or process terminates, so most apps will never need to call\nthis.\n\n

    \n

    If multicastInterface is not specified, the OS will try to drop membership to all valid\ninterfaces.\n\n

    \n" }, { "textRaw": "socket.unref()", "type": "method", "name": "unref", "desc": "

    Calling unref on a socket will allow the program to exit if this is the only\nactive socket in the event system. If the socket is already unrefd calling\nunref again will have no effect.\n\n

    \n", "signatures": [ { "params": [] } ] }, { "textRaw": "socket.ref()", "type": "method", "name": "ref", "desc": "

    Opposite of unref, calling ref on a previously unrefd socket will not\nlet the program exit if it's the only socket left (the default behavior). If\nthe socket is refd calling ref again will have no effect.\n\n

    \n", "signatures": [ { "params": [] } ] } ] } ], "type": "module", "displayName": "dgram" }, { "textRaw": "DNS", "name": "dns", "stability": 3, "stabilityText": "Stable", "desc": "

    Use require('dns') to access this module. All methods in the dns module\nuse C-Ares except for dns.lookup which uses getaddrinfo(3) in a thread\npool. C-Ares is much faster than getaddrinfo but the system resolver is\nmore consistent with how other programs operate. When a user does\nnet.connect(80, 'google.com') or http.get({ host: 'google.com' }) the\ndns.lookup method is used. Users who need to do a large number of lookups\nquickly should use the methods that go through C-Ares.\n\n

    \n

    Here is an example which resolves 'www.google.com' then reverse\nresolves the IP addresses which are returned.\n\n

    \n
    var dns = require('dns');\n\ndns.resolve4('www.google.com', function (err, addresses) {\n  if (err) throw err;\n\n  console.log('addresses: ' + JSON.stringify(addresses));\n\n  addresses.forEach(function (a) {\n    dns.reverse(a, function (err, domains) {\n      if (err) {\n        throw err;\n      }\n\n      console.log('reverse for ' + a + ': ' + JSON.stringify(domains));\n    });\n  });\n});
    \n", "methods": [ { "textRaw": "dns.lookup(domain, [family], callback)", "type": "method", "name": "lookup", "desc": "

    Resolves a domain (e.g. 'google.com') into the first found A (IPv4) or\nAAAA (IPv6) record.\nThe family can be the integer 4 or 6. Defaults to null that indicates\nboth Ip v4 and v6 address family.\n\n

    \n

    The callback has arguments (err, address, family). The address argument\nis a string representation of a IP v4 or v6 address. The family argument\nis either the integer 4 or 6 and denotes the family of address (not\nnecessarily the value initially passed to lookup).\n\n

    \n

    On error, err is an Error object, where err.code is the error code.\nKeep in mind that err.code will be set to 'ENOENT' not only when\nthe domain does not exist but also when the lookup fails in other ways\nsuch as no available file descriptors.\n\n\n

    \n", "signatures": [ { "params": [ { "name": "domain" }, { "name": "family", "optional": true }, { "name": "callback" } ] } ] }, { "textRaw": "dns.resolve(domain, [rrtype], callback)", "type": "method", "name": "resolve", "desc": "

    Resolves a domain (e.g. 'google.com') into an array of the record types\nspecified by rrtype. Valid rrtypes are 'A' (IPV4 addresses, default),\n'AAAA' (IPV6 addresses), 'MX' (mail exchange records), 'TXT' (text\nrecords), 'SRV' (SRV records), 'PTR' (used for reverse IP lookups),\n'NS' (name server records) and 'CNAME' (canonical name records).\n\n

    \n

    The callback has arguments (err, addresses). The type of each item\nin addresses is determined by the record type, and described in the\ndocumentation for the corresponding lookup methods below.\n\n

    \n

    On error, err is an Error object, where err.code is\none of the error codes listed below.\n\n\n

    \n", "signatures": [ { "params": [ { "name": "domain" }, { "name": "rrtype", "optional": true }, { "name": "callback" } ] } ] }, { "textRaw": "dns.resolve4(domain, callback)", "type": "method", "name": "resolve4", "desc": "

    The same as dns.resolve(), but only for IPv4 queries (A records).\naddresses is an array of IPv4 addresses (e.g.\n['74.125.79.104', '74.125.79.105', '74.125.79.106']).\n\n

    \n", "signatures": [ { "params": [ { "name": "domain" }, { "name": "callback" } ] } ] }, { "textRaw": "dns.resolve6(domain, callback)", "type": "method", "name": "resolve6", "desc": "

    The same as dns.resolve4() except for IPv6 queries (an AAAA query).\n\n\n

    \n", "signatures": [ { "params": [ { "name": "domain" }, { "name": "callback" } ] } ] }, { "textRaw": "dns.resolveMx(domain, callback)", "type": "method", "name": "resolveMx", "desc": "

    The same as dns.resolve(), but only for mail exchange queries (MX records).\n\n

    \n

    addresses is an array of MX records, each with a priority and an exchange\nattribute (e.g. [{'priority': 10, 'exchange': 'mx.example.com'},...]).\n\n

    \n", "signatures": [ { "params": [ { "name": "domain" }, { "name": "callback" } ] } ] }, { "textRaw": "dns.resolveTxt(domain, callback)", "type": "method", "name": "resolveTxt", "desc": "

    The same as dns.resolve(), but only for text queries (TXT records).\naddresses is an array of the text records available for domain (e.g.,\n['v=spf1 ip4:0.0.0.0 ~all']).\n\n

    \n", "signatures": [ { "params": [ { "name": "domain" }, { "name": "callback" } ] } ] }, { "textRaw": "dns.resolveSrv(domain, callback)", "type": "method", "name": "resolveSrv", "desc": "

    The same as dns.resolve(), but only for service records (SRV records).\naddresses is an array of the SRV records available for domain. Properties\nof SRV records are priority, weight, port, and name (e.g.,\n[{'priority': 10, {'weight': 5, 'port': 21223, 'name': 'service.example.com'}, ...]).\n\n

    \n", "signatures": [ { "params": [ { "name": "domain" }, { "name": "callback" } ] } ] }, { "textRaw": "dns.resolveNs(domain, callback)", "type": "method", "name": "resolveNs", "desc": "

    The same as dns.resolve(), but only for name server records (NS records).\naddresses is an array of the name server records available for domain\n(e.g., ['ns1.example.com', 'ns2.example.com']).\n\n

    \n", "signatures": [ { "params": [ { "name": "domain" }, { "name": "callback" } ] } ] }, { "textRaw": "dns.resolveCname(domain, callback)", "type": "method", "name": "resolveCname", "desc": "

    The same as dns.resolve(), but only for canonical name records (CNAME\nrecords). addresses is an array of the canonical name records available for\ndomain (e.g., ['bar.example.com']).\n\n

    \n", "signatures": [ { "params": [ { "name": "domain" }, { "name": "callback" } ] } ] }, { "textRaw": "dns.reverse(ip, callback)", "type": "method", "name": "reverse", "desc": "

    Reverse resolves an ip address to an array of domain names.\n\n

    \n

    The callback has arguments (err, domains).\n\n

    \n

    On error, err is an Error object, where err.code is\none of the error codes listed below.\n\n

    \n", "signatures": [ { "params": [ { "name": "ip" }, { "name": "callback" } ] } ] } ], "modules": [ { "textRaw": "Error codes", "name": "error_codes", "desc": "

    Each DNS query can return one of the following error codes:\n\n

    \n
      \n
    • dns.NODATA: DNS server returned answer with no data.
    • \n
    • dns.FORMERR: DNS server claims query was misformatted.
    • \n
    • dns.SERVFAIL: DNS server returned general failure.
    • \n
    • dns.NOTFOUND: Domain name not found.
    • \n
    • dns.NOTIMP: DNS server does not implement requested operation.
    • \n
    • dns.REFUSED: DNS server refused query.
    • \n
    • dns.BADQUERY: Misformatted DNS query.
    • \n
    • dns.BADNAME: Misformatted domain name.
    • \n
    • dns.BADFAMILY: Unsupported address family.
    • \n
    • dns.BADRESP: Misformatted DNS reply.
    • \n
    • dns.CONNREFUSED: Could not contact DNS servers.
    • \n
    • dns.TIMEOUT: Timeout while contacting DNS servers.
    • \n
    • dns.EOF: End of file.
    • \n
    • dns.FILE: Error reading file.
    • \n
    • dns.NOMEM: Out of memory.
    • \n
    • dns.DESTRUCTION: Channel is being destroyed.
    • \n
    • dns.BADSTR: Misformatted string.
    • \n
    • dns.BADFLAGS: Illegal flags specified.
    • \n
    • dns.NONAME: Given hostname is not numeric.
    • \n
    • dns.BADHINTS: Illegal hints flags specified.
    • \n
    • dns.NOTINITIALIZED: c-ares library initialization not yet performed.
    • \n
    • dns.LOADIPHLPAPI: Error loading iphlpapi.dll.
    • \n
    • dns.ADDRGETNETWORKPARAMS: Could not find GetNetworkParams function.
    • \n
    • dns.CANCELLED: DNS query cancelled.
    • \n
    \n", "type": "module", "displayName": "Error codes" } ], "type": "module", "displayName": "DNS" }, { "textRaw": "HTTP", "name": "http", "stability": 3, "stabilityText": "Stable", "desc": "

    To use the HTTP server and client one must require('http').\n\n

    \n

    The HTTP interfaces in Node are designed to support many features\nof the protocol which have been traditionally difficult to use.\nIn particular, large, possibly chunk-encoded, messages. The interface is\ncareful to never buffer entire requests or responses--the\nuser is able to stream data.\n\n

    \n

    HTTP message headers are represented by an object like this:\n\n

    \n
    { 'content-length': '123',\n  'content-type': 'text/plain',\n  'connection': 'keep-alive',\n  'accept': '*/*' }
    \n

    Keys are lowercased. Values are not modified.\n\n

    \n

    In order to support the full spectrum of possible HTTP applications, Node's\nHTTP API is very low-level. It deals with stream handling and message\nparsing only. It parses a message into headers and body but it does not\nparse the actual headers or the body.\n\n\n

    \n", "properties": [ { "textRaw": "`STATUS_CODES` {Object} ", "name": "STATUS_CODES", "desc": "

    A collection of all the standard HTTP response status codes, and the\nshort description of each. For example, http.STATUS_CODES[404] === 'Not\nFound'.\n\n

    \n" }, { "textRaw": "http.globalAgent", "name": "globalAgent", "desc": "

    Global instance of Agent which is used as the default for all http client\nrequests.\n\n\n

    \n" }, { "textRaw": "http.IncomingMessage", "name": "IncomingMessage", "desc": "

    An IncomingMessage object is created by [http.Server][] or\n[http.ClientRequest][] and passed as the first argument to the 'request'\nand 'response' event respectively. It may be used to access response status,\nheaders and data.\n\n

    \n

    It implements the [Readable Stream][] interface, as well as the\nfollowing additional events, methods, and properties.\n\n

    \n", "events": [ { "textRaw": "Event: 'close'", "type": "event", "name": "close", "desc": "

    function () { }\n\n

    \n

    Indicates that the underlaying connection was closed.\nJust like 'end', this event occurs only once per response.\n\n

    \n", "params": [] } ], "properties": [ { "textRaw": "message.httpVersion", "name": "httpVersion", "desc": "

    In case of server request, the HTTP version sent by the client. In the case of\nclient response, the HTTP version of the connected-to server.\nProbably either '1.1' or '1.0'.\n\n

    \n

    Also response.httpVersionMajor is the first integer and\nresponse.httpVersionMinor is the second.\n\n

    \n" }, { "textRaw": "message.headers", "name": "headers", "desc": "

    The request/response headers object.\n\n

    \n

    Read only map of header names and values. Header names are lower-cased.\nExample:\n\n

    \n
    // Prints something like:\n//\n// { 'user-agent': 'curl/7.22.0',\n//   host: '127.0.0.1:8000',\n//   accept: '*/*' }\nconsole.log(request.headers);
    \n" }, { "textRaw": "message.trailers", "name": "trailers", "desc": "

    The request/response trailers object. Only populated after the 'end' event.\n\n

    \n" }, { "textRaw": "message.method", "name": "method", "desc": "

    Only valid for request obtained from [http.Server][].\n\n

    \n

    The request method as a string. Read only. Example:\n'GET', 'DELETE'.\n\n

    \n" }, { "textRaw": "message.url", "name": "url", "desc": "

    Only valid for request obtained from [http.Server][].\n\n

    \n

    Request URL string. This contains only the URL that is\npresent in the actual HTTP request. If the request is:\n\n

    \n
    GET /status?name=ryan HTTP/1.1\\r\\n\nAccept: text/plain\\r\\n\n\\r\\n
    \n

    Then request.url will be:\n\n

    \n
    '/status?name=ryan'
    \n

    If you would like to parse the URL into its parts, you can use\nrequire('url').parse(request.url). Example:\n\n

    \n
    node> require('url').parse('/status?name=ryan')\n{ href: '/status?name=ryan',\n  search: '?name=ryan',\n  query: 'name=ryan',\n  pathname: '/status' }
    \n

    If you would like to extract the params from the query string,\nyou can use the require('querystring').parse function, or pass\ntrue as the second argument to require('url').parse. Example:\n\n

    \n
    node> require('url').parse('/status?name=ryan', true)\n{ href: '/status?name=ryan',\n  search: '?name=ryan',\n  query: { name: 'ryan' },\n  pathname: '/status' }
    \n" }, { "textRaw": "message.statusCode", "name": "statusCode", "desc": "

    Only valid for response obtained from http.ClientRequest.\n\n

    \n

    The 3-digit HTTP response status code. E.G. 404.\n\n

    \n" }, { "textRaw": "message.socket", "name": "socket", "desc": "

    The net.Socket object associated with the connection.\n\n

    \n

    With HTTPS support, use request.connection.verifyPeer() and\nrequest.connection.getPeerCertificate() to obtain the client's\nauthentication details.\n\n\n

    \n" } ], "methods": [ { "textRaw": "message.setTimeout(msecs, callback)", "type": "method", "name": "setTimeout", "signatures": [ { "params": [ { "textRaw": "`msecs` {Number} ", "name": "msecs", "type": "Number" }, { "textRaw": "`callback` {Function} ", "name": "callback", "type": "Function" } ] }, { "params": [ { "name": "msecs" }, { "name": "callback" } ] } ], "desc": "

    Calls message.connection.setTimeout(msecs, callback).\n\n

    \n" } ] } ], "methods": [ { "textRaw": "http.createServer([requestListener])", "type": "method", "name": "createServer", "desc": "

    Returns a new web server object.\n\n

    \n

    The requestListener is a function which is automatically\nadded to the 'request' event.\n\n

    \n", "signatures": [ { "params": [ { "name": "requestListener", "optional": true } ] } ] }, { "textRaw": "http.createClient([port], [host])", "type": "method", "name": "createClient", "desc": "

    This function is deprecated; please use [http.request()][] instead.\nConstructs a new HTTP client. port and host refer to the server to be\nconnected to.\n\n

    \n", "signatures": [ { "params": [ { "name": "port", "optional": true }, { "name": "host", "optional": true } ] } ] }, { "textRaw": "http.request(options, [callback])", "type": "method", "name": "request", "desc": "

    Node maintains several connections per server to make HTTP requests.\nThis function allows one to transparently issue requests.\n\n

    \n

    options can be an object or a string. If options is a string, it is\nautomatically parsed with [url.parse()][].\n\n

    \n

    Options:\n\n

    \n
      \n
    • host: A domain name or IP address of the server to issue the request to.\nDefaults to 'localhost'.
    • \n
    • hostname: To support url.parse() hostname is preferred over host
    • \n
    • port: Port of remote server. Defaults to 80.
    • \n
    • localAddress: Local interface to bind for network connections.
    • \n
    • socketPath: Unix Domain Socket (use one of host:port or socketPath)
    • \n
    • method: A string specifying the HTTP request method. Defaults to 'GET'.
    • \n
    • path: Request path. Defaults to '/'. Should include query string if any.\nE.G. '/index.html?page=12'
    • \n
    • headers: An object containing request headers.
    • \n
    • auth: Basic authentication i.e. 'user:password' to compute an\nAuthorization header.
    • \n
    • agent: Controls [Agent][] behavior. When an Agent is used request will\ndefault to Connection: keep-alive. Possible values:
        \n
      • undefined (default): use [global Agent][] for this host and port.
      • \n
      • Agent object: explicitly use the passed in Agent.
      • \n
      • false: opts out of connection pooling with an Agent, defaults request to\nConnection: close.
      • \n
      \n
    • \n
    \n

    The optional callback parameter will be added as a one time listener for\nthe ['response'][] event.\n\n

    \n

    http.request() returns an instance of the [http.ClientRequest][]\nclass. The ClientRequest instance is a writable stream. If one needs to\nupload a file with a POST request, then write to the ClientRequest object.\n\n

    \n

    Example:\n\n

    \n
    var options = {\n  hostname: 'www.google.com',\n  port: 80,\n  path: '/upload',\n  method: 'POST'\n};\n\nvar req = http.request(options, function(res) {\n  console.log('STATUS: ' + res.statusCode);\n  console.log('HEADERS: ' + JSON.stringify(res.headers));\n  res.setEncoding('utf8');\n  res.on('data', function (chunk) {\n    console.log('BODY: ' + chunk);\n  });\n});\n\nreq.on('error', function(e) {\n  console.log('problem with request: ' + e.message);\n});\n\n// write data to request body\nreq.write('data\\n');\nreq.write('data\\n');\nreq.end();
    \n

    Note that in the example req.end() was called. With http.request() one\nmust always call req.end() to signify that you're done with the request -\neven if there is no data being written to the request body.\n\n

    \n

    If any error is encountered during the request (be that with DNS resolution,\nTCP level errors, or actual HTTP parse errors) an 'error' event is emitted\non the returned request object.\n\n

    \n

    There are a few special headers that should be noted.\n\n

    \n
      \n
    • Sending a 'Connection: keep-alive' will notify Node that the connection to\nthe server should be persisted until the next request.

      \n
    • \n
    • Sending a 'Content-length' header will disable the default chunked encoding.

      \n
    • \n
    • Sending an 'Expect' header will immediately send the request headers.\nUsually, when sending 'Expect: 100-continue', you should both set a timeout\nand listen for the continue event. See RFC2616 Section 8.2.3 for more\ninformation.

      \n
    • \n
    • Sending an Authorization header will override using the auth option\nto compute basic authentication.

      \n
    • \n
    \n", "signatures": [ { "params": [ { "name": "options" }, { "name": "callback", "optional": true } ] } ] }, { "textRaw": "http.get(options, [callback])", "type": "method", "name": "get", "desc": "

    Since most requests are GET requests without bodies, Node provides this\nconvenience method. The only difference between this method and http.request()\nis that it sets the method to GET and calls req.end() automatically.\n\n

    \n

    Example:\n\n

    \n
    http.get("http://www.google.com/index.html", function(res) {\n  console.log("Got response: " + res.statusCode);\n}).on('error', function(e) {\n  console.log("Got error: " + e.message);\n});
    \n", "signatures": [ { "params": [ { "name": "options" }, { "name": "callback", "optional": true } ] } ] } ], "classes": [ { "textRaw": "Class: http.Server", "type": "class", "name": "http.Server", "desc": "

    This is an [EventEmitter][] with the following events:\n\n

    \n", "events": [ { "textRaw": "Event: 'request'", "type": "event", "name": "request", "desc": "

    function (request, response) { }\n\n

    \n

    Emitted each time there is a request. Note that there may be multiple requests\nper connection (in the case of keep-alive connections).\n request is an instance of [http.IncomingMessage][] and response is\nan instance of [http.ServerResponse][].\n\n

    \n", "params": [] }, { "textRaw": "Event: 'connection'", "type": "event", "name": "connection", "desc": "

    function (socket) { }\n\n

    \n

    When a new TCP stream is established. socket is an object of type\n net.Socket. Usually users will not want to access this event. In\n particular, the socket will not emit readable events because of how\n the protocol parser attaches to the socket. The socket can also be\n accessed at request.connection.\n\n

    \n", "params": [] }, { "textRaw": "Event: 'close'", "type": "event", "name": "close", "desc": "

    function () { }\n\n

    \n

    Emitted when the server closes.\n\n

    \n", "params": [] }, { "textRaw": "Event: 'checkContinue'", "type": "event", "name": "checkContinue", "desc": "

    function (request, response) { }\n\n

    \n

    Emitted each time a request with an http Expect: 100-continue is received.\nIf this event isn't listened for, the server will automatically respond\nwith a 100 Continue as appropriate.\n\n

    \n

    Handling this event involves calling [response.writeContinue()][] if the client\nshould continue to send the request body, or generating an appropriate HTTP\nresponse (e.g., 400 Bad Request) if the client should not continue to send the\nrequest body.\n\n

    \n

    Note that when this event is emitted and handled, the request event will\nnot be emitted.\n\n

    \n", "params": [] }, { "textRaw": "Event: 'connect'", "type": "event", "name": "connect", "desc": "

    function (request, socket, head) { }\n\n

    \n

    Emitted each time a client requests a http CONNECT method. If this event isn't\nlistened for, then clients requesting a CONNECT method will have their\nconnections closed.\n\n

    \n
      \n
    • request is the arguments for the http request, as it is in the request\nevent.
    • \n
    • socket is the network socket between the server and client.
    • \n
    • head is an instance of Buffer, the first packet of the tunneling stream,\nthis may be empty.
    • \n
    \n

    After this event is emitted, the request's socket will not have a data\nevent listener, meaning you will need to bind to it in order to handle data\nsent to the server on that socket.\n\n

    \n", "params": [] }, { "textRaw": "Event: 'upgrade'", "type": "event", "name": "upgrade", "desc": "

    function (request, socket, head) { }\n\n

    \n

    Emitted each time a client requests a http upgrade. If this event isn't\nlistened for, then clients requesting an upgrade will have their connections\nclosed.\n\n

    \n
      \n
    • request is the arguments for the http request, as it is in the request\nevent.
    • \n
    • socket is the network socket between the server and client.
    • \n
    • head is an instance of Buffer, the first packet of the upgraded stream,\nthis may be empty.
    • \n
    \n

    After this event is emitted, the request's socket will not have a data\nevent listener, meaning you will need to bind to it in order to handle data\nsent to the server on that socket.\n\n

    \n", "params": [] }, { "textRaw": "Event: 'clientError'", "type": "event", "name": "clientError", "desc": "

    function (exception, socket) { }\n\n

    \n

    If a client connection emits an 'error' event - it will forwarded here.\n\n

    \n

    socket is the net.Socket object that the error originated from.\n\n\n

    \n", "params": [] } ], "methods": [ { "textRaw": "server.listen(port, [hostname], [backlog], [callback])", "type": "method", "name": "listen", "desc": "

    Begin accepting connections on the specified port and hostname. If the\nhostname is omitted, the server will accept connections directed to any\nIPv4 address (INADDR_ANY).\n\n

    \n

    To listen to a unix socket, supply a filename instead of port and hostname.\n\n

    \n

    Backlog is the maximum length of the queue of pending connections.\nThe actual length will be determined by your OS through sysctl settings such as\ntcp_max_syn_backlog and somaxconn on linux. The default value of this\nparameter is 511 (not 512).\n\n

    \n

    This function is asynchronous. The last parameter callback will be added as\na listener for the ['listening'][] event. See also [net.Server.listen(port)][].\n\n\n

    \n", "signatures": [ { "params": [ { "name": "port" }, { "name": "hostname", "optional": true }, { "name": "backlog", "optional": true }, { "name": "callback", "optional": true } ] } ] }, { "textRaw": "server.listen(path, [callback])", "type": "method", "name": "listen", "desc": "

    Start a UNIX socket server listening for connections on the given path.\n\n

    \n

    This function is asynchronous. The last parameter callback will be added as\na listener for the ['listening'][] event. See also [net.Server.listen(path)][].\n\n\n

    \n", "signatures": [ { "params": [ { "name": "path" }, { "name": "callback", "optional": true } ] } ] }, { "textRaw": "server.listen(handle, [callback])", "type": "method", "name": "listen", "signatures": [ { "params": [ { "textRaw": "`handle` {Object} ", "name": "handle", "type": "Object" }, { "textRaw": "`callback` {Function} ", "name": "callback", "type": "Function", "optional": true } ] }, { "params": [ { "name": "handle" }, { "name": "callback", "optional": true } ] } ], "desc": "

    The handle object can be set to either a server or socket (anything\nwith an underlying _handle member), or a {fd: <n>} object.\n\n

    \n

    This will cause the server to accept connections on the specified\nhandle, but it is presumed that the file descriptor or handle has\nalready been bound to a port or domain socket.\n\n

    \n

    Listening on a file descriptor is not supported on Windows.\n\n

    \n

    This function is asynchronous. The last parameter callback will be added as\na listener for the 'listening' event.\nSee also net.Server.listen().\n\n

    \n" }, { "textRaw": "server.close([callback])", "type": "method", "name": "close", "desc": "

    Stops the server from accepting new connections. See [net.Server.close()][].\n\n\n

    \n", "signatures": [ { "params": [ { "name": "callback", "optional": true } ] } ] }, { "textRaw": "server.setTimeout(msecs, callback)", "type": "method", "name": "setTimeout", "signatures": [ { "params": [ { "textRaw": "`msecs` {Number} ", "name": "msecs", "type": "Number" }, { "textRaw": "`callback` {Function} ", "name": "callback", "type": "Function" } ] }, { "params": [ { "name": "msecs" }, { "name": "callback" } ] } ], "desc": "

    Sets the timeout value for sockets, and emits a 'timeout' event on\nthe Server object, passing the socket as an argument, if a timeout\noccurs.\n\n

    \n

    If there is a 'timeout' event listener on the Server object, then it\nwill be called with the timed-out socket as an argument.\n\n

    \n

    By default, the Server's timeout value is 2 minutes, and sockets are\ndestroyed automatically if they time out. However, if you assign a\ncallback to the Server's 'timeout' event, then you are responsible\nfor handling socket timeouts.\n\n

    \n" } ], "properties": [ { "textRaw": "server.maxHeadersCount", "name": "maxHeadersCount", "desc": "

    Limits maximum incoming headers count, equal to 1000 by default. If set to 0 -\nno limit will be applied.\n\n

    \n" }, { "textRaw": "`timeout` {Number} Default = 120000 (2 minutes) ", "name": "timeout", "desc": "

    The number of milliseconds of inactivity before a socket is presumed\nto have timed out.\n\n

    \n

    Note that the socket timeout logic is set up on connection, so\nchanging this value only affects new connections to the server, not\nany existing connections.\n\n

    \n

    Set to 0 to disable any kind of automatic timeout behavior on incoming\nconnections.\n\n

    \n", "shortDesc": "Default = 120000 (2 minutes)" } ] }, { "textRaw": "Class: http.ServerResponse", "type": "class", "name": "http.ServerResponse", "desc": "

    This object is created internally by a HTTP server--not by the user. It is\npassed as the second parameter to the 'request' event.\n\n

    \n

    The response implements the [Writable Stream][] interface. This is an\n[EventEmitter][] with the following events:\n\n

    \n", "events": [ { "textRaw": "Event: 'close'", "type": "event", "name": "close", "desc": "

    function () { }\n\n

    \n

    Indicates that the underlying connection was terminated before\n[response.end()][] was called or able to flush.\n\n

    \n", "params": [] }, { "textRaw": "Event: 'finish'", "type": "event", "name": "finish", "desc": "

    function () { }\n\n

    \n

    Emitted when the response has been sent. More specifically, this event is\nemitted when the last segment of the response headers and body have been\nhanded off to the operating system for transmission over the network. It\ndoes not imply that the client has received anything yet.\n\n

    \n

    After this event, no more events will be emitted on the response object.\n\n

    \n", "params": [] } ], "methods": [ { "textRaw": "response.writeContinue()", "type": "method", "name": "writeContinue", "desc": "

    Sends a HTTP/1.1 100 Continue message to the client, indicating that\nthe request body should be sent. See the ['checkContinue'][] event on Server.\n\n

    \n", "signatures": [ { "params": [] } ] }, { "textRaw": "response.writeHead(statusCode, [reasonPhrase], [headers])", "type": "method", "name": "writeHead", "desc": "

    Sends a response header to the request. The status code is a 3-digit HTTP\nstatus code, like 404. The last argument, headers, are the response headers.\nOptionally one can give a human-readable reasonPhrase as the second\nargument.\n\n

    \n

    Example:\n\n

    \n
    var body = 'hello world';\nresponse.writeHead(200, {\n  'Content-Length': body.length,\n  'Content-Type': 'text/plain' });
    \n

    This method must only be called once on a message and it must\nbe called before [response.end()][] is called.\n\n

    \n

    If you call [response.write()][] or [response.end()][] before calling this, the\nimplicit/mutable headers will be calculated and call this function for you.\n\n

    \n

    Note: that Content-Length is given in bytes not characters. The above example\nworks because the string 'hello world' contains only single byte characters.\nIf the body contains higher coded characters then Buffer.byteLength()\nshould be used to determine the number of bytes in a given encoding.\nAnd Node does not check whether Content-Length and the length of the body\nwhich has been transmitted are equal or not.\n\n

    \n", "signatures": [ { "params": [ { "name": "statusCode" }, { "name": "reasonPhrase", "optional": true }, { "name": "headers", "optional": true } ] } ] }, { "textRaw": "response.setTimeout(msecs, callback)", "type": "method", "name": "setTimeout", "signatures": [ { "params": [ { "textRaw": "`msecs` {Number} ", "name": "msecs", "type": "Number" }, { "textRaw": "`callback` {Function} ", "name": "callback", "type": "Function" } ] }, { "params": [ { "name": "msecs" }, { "name": "callback" } ] } ], "desc": "

    Sets the Socket's timeout value to msecs. If a callback is\nprovided, then it is added as a listener on the 'timeout' event on\nthe response object.\n\n

    \n

    If no 'timeout' listener is added to the request, the response, or\nthe server, then sockets are destroyed when they time out. If you\nassign a handler on the request, the response, or the server's\n'timeout' events, then it is your responsibility to handle timed out\nsockets.\n\n

    \n" }, { "textRaw": "response.setHeader(name, value)", "type": "method", "name": "setHeader", "desc": "

    Sets a single header value for implicit headers. If this header already exists\nin the to-be-sent headers, its value will be replaced. Use an array of strings\nhere if you need to send multiple headers with the same name.\n\n

    \n

    Example:\n\n

    \n
    response.setHeader("Content-Type", "text/html");
    \n

    or\n\n

    \n
    response.setHeader("Set-Cookie", ["type=ninja", "language=javascript"]);
    \n", "signatures": [ { "params": [ { "name": "name" }, { "name": "value" } ] } ] }, { "textRaw": "response.getHeader(name)", "type": "method", "name": "getHeader", "desc": "

    Reads out a header that's already been queued but not sent to the client. Note\nthat the name is case insensitive. This can only be called before headers get\nimplicitly flushed.\n\n

    \n

    Example:\n\n

    \n
    var contentType = response.getHeader('content-type');
    \n", "signatures": [ { "params": [ { "name": "name" } ] } ] }, { "textRaw": "response.removeHeader(name)", "type": "method", "name": "removeHeader", "desc": "

    Removes a header that's queued for implicit sending.\n\n

    \n

    Example:\n\n

    \n
    response.removeHeader("Content-Encoding");
    \n", "signatures": [ { "params": [ { "name": "name" } ] } ] }, { "textRaw": "response.write(chunk, [encoding])", "type": "method", "name": "write", "desc": "

    If this method is called and [response.writeHead()][] has not been called,\nit will switch to implicit header mode and flush the implicit headers.\n\n

    \n

    This sends a chunk of the response body. This method may\nbe called multiple times to provide successive parts of the body.\n\n

    \n

    chunk can be a string or a buffer. If chunk is a string,\nthe second parameter specifies how to encode it into a byte stream.\nBy default the encoding is 'utf8'.\n\n

    \n

    Note: This is the raw HTTP body and has nothing to do with\nhigher-level multi-part body encodings that may be used.\n\n

    \n

    The first time response.write() is called, it will send the buffered\nheader information and the first body to the client. The second time\nresponse.write() is called, Node assumes you're going to be streaming\ndata, and sends that separately. That is, the response is buffered up to the\nfirst chunk of body.\n\n

    \n

    Returns true if the entire data was flushed successfully to the kernel\nbuffer. Returns false if all or part of the data was queued in user memory.\n'drain' will be emitted when the buffer is again free.\n\n

    \n", "signatures": [ { "params": [ { "name": "chunk" }, { "name": "encoding", "optional": true } ] } ] }, { "textRaw": "response.addTrailers(headers)", "type": "method", "name": "addTrailers", "desc": "

    This method adds HTTP trailing headers (a header but at the end of the\nmessage) to the response.\n\n

    \n

    Trailers will only be emitted if chunked encoding is used for the\nresponse; if it is not (e.g., if the request was HTTP/1.0), they will\nbe silently discarded.\n\n

    \n

    Note that HTTP requires the Trailer header to be sent if you intend to\nemit trailers, with a list of the header fields in its value. E.g.,\n\n

    \n
    response.writeHead(200, { 'Content-Type': 'text/plain',\n                          'Trailer': 'Content-MD5' });\nresponse.write(fileData);\nresponse.addTrailers({'Content-MD5': "7895bf4b8828b55ceaf47747b4bca667"});\nresponse.end();
    \n", "signatures": [ { "params": [ { "name": "headers" } ] } ] }, { "textRaw": "response.end([data], [encoding])", "type": "method", "name": "end", "desc": "

    This method signals to the server that all of the response headers and body\nhave been sent; that server should consider this message complete.\nThe method, response.end(), MUST be called on each\nresponse.\n\n

    \n

    If data is specified, it is equivalent to calling response.write(data, encoding)\nfollowed by response.end().\n\n\n

    \n", "signatures": [ { "params": [ { "name": "data", "optional": true }, { "name": "encoding", "optional": true } ] } ] } ], "properties": [ { "textRaw": "response.statusCode", "name": "statusCode", "desc": "

    When using implicit headers (not calling [response.writeHead()][] explicitly),\nthis property controls the status code that will be sent to the client when\nthe headers get flushed.\n\n

    \n

    Example:\n\n

    \n
    response.statusCode = 404;
    \n

    After response header was sent to the client, this property indicates the\nstatus code which was sent out.\n\n

    \n" }, { "textRaw": "response.headersSent", "name": "headersSent", "desc": "

    Boolean (read-only). True if headers were sent, false otherwise.\n\n

    \n" }, { "textRaw": "response.sendDate", "name": "sendDate", "desc": "

    When true, the Date header will be automatically generated and sent in\nthe response if it is not already present in the headers. Defaults to true.\n\n

    \n

    This should only be disabled for testing; HTTP requires the Date header\nin responses.\n\n

    \n" } ] }, { "textRaw": "Class: http.Agent", "type": "class", "name": "http.Agent", "desc": "

    In node 0.5.3+ there is a new implementation of the HTTP Agent which is used\nfor pooling sockets used in HTTP client requests.\n\n

    \n

    Previously, a single agent instance helped pool for a single host+port. The\ncurrent implementation now holds sockets for any number of hosts.\n\n

    \n

    The current HTTP Agent also defaults client requests to using\nConnection:keep-alive. If no pending HTTP requests are waiting on a socket\nto become free the socket is closed. This means that node's pool has the\nbenefit of keep-alive when under load but still does not require developers\nto manually close the HTTP clients using keep-alive.\n\n

    \n

    Sockets are removed from the agent's pool when the socket emits either a\n"close" event or a special "agentRemove" event. This means that if you intend\nto keep one HTTP request open for a long time and don't want it to stay in the\npool you can do something along the lines of:\n\n

    \n
    http.get(options, function(res) {\n  // Do stuff\n}).on("socket", function (socket) {\n  socket.emit("agentRemove");\n});
    \n

    Alternatively, you could just opt out of pooling entirely using agent:false:\n\n

    \n
    http.get({hostname:'localhost', port:80, path:'/', agent:false}, function (res) {\n  // Do stuff\n})
    \n", "properties": [ { "textRaw": "agent.maxSockets", "name": "maxSockets", "desc": "

    By default set to 5. Determines how many concurrent sockets the agent can have\nopen per host.\n\n

    \n" }, { "textRaw": "agent.sockets", "name": "sockets", "desc": "

    An object which contains arrays of sockets currently in use by the Agent. Do not\nmodify.\n\n

    \n" }, { "textRaw": "agent.requests", "name": "requests", "desc": "

    An object which contains queues of requests that have not yet been assigned to\nsockets. Do not modify.\n\n

    \n" } ] }, { "textRaw": "Class: http.ClientRequest", "type": "class", "name": "http.ClientRequest", "desc": "

    This object is created internally and returned from http.request(). It\nrepresents an in-progress request whose header has already been queued. The\nheader is still mutable using the setHeader(name, value), getHeader(name),\nremoveHeader(name) API. The actual header will be sent along with the first\ndata chunk or when closing the connection.\n\n

    \n

    To get the response, add a listener for 'response' to the request object.\n'response' will be emitted from the request object when the response\nheaders have been received. The 'response' event is executed with one\nargument which is an instance of [http.IncomingMessage][].\n\n

    \n

    During the 'response' event, one can add listeners to the\nresponse object; particularly to listen for the 'data' event.\n\n

    \n

    If no 'response' handler is added, then the response will be\nentirely discarded. However, if you add a 'response' event handler,\nthen you must consume the data from the response object, either by\ncalling response.read() whenever there is a 'readable' event, or\nby adding a 'data' handler, or by calling the .resume() method.\nUntil the data is consumed, the 'end' event will not fire. Also, until\nthe data is read it will consume memory that can eventually lead to a\n'process out of memory' error.\n\n

    \n

    Note: Node does not check whether Content-Length and the length of the body\nwhich has been transmitted are equal or not.\n\n

    \n

    The request implements the [Writable Stream][] interface. This is an\n[EventEmitter][] with the following events:\n\n

    \n", "events": [ { "textRaw": "Event 'response'", "type": "event", "name": "response", "desc": "

    function (response) { }\n\n

    \n

    Emitted when a response is received to this request. This event is emitted only\nonce. The response argument will be an instance of [http.IncomingMessage][].\n\n

    \n

    Options:\n\n

    \n
      \n
    • host: A domain name or IP address of the server to issue the request to.
    • \n
    • port: Port of remote server.
    • \n
    • socketPath: Unix Domain Socket (use one of host:port or socketPath)
    • \n
    \n", "params": [] }, { "textRaw": "Event: 'socket'", "type": "event", "name": "socket", "desc": "

    function (socket) { }\n\n

    \n

    Emitted after a socket is assigned to this request.\n\n

    \n", "params": [] }, { "textRaw": "Event: 'connect'", "type": "event", "name": "connect", "desc": "

    function (response, socket, head) { }\n\n

    \n

    Emitted each time a server responds to a request with a CONNECT method. If this\nevent isn't being listened for, clients receiving a CONNECT method will have\ntheir connections closed.\n\n

    \n

    A client server pair that show you how to listen for the connect event.\n\n

    \n
    var http = require('http');\nvar net = require('net');\nvar url = require('url');\n\n// Create an HTTP tunneling proxy\nvar proxy = http.createServer(function (req, res) {\n  res.writeHead(200, {'Content-Type': 'text/plain'});\n  res.end('okay');\n});\nproxy.on('connect', function(req, cltSocket, head) {\n  // connect to an origin server\n  var srvUrl = url.parse('http://' + req.url);\n  var srvSocket = net.connect(srvUrl.port, srvUrl.hostname, function() {\n    cltSocket.write('HTTP/1.1 200 Connection Established\\r\\n' +\n                    'Proxy-agent: Node-Proxy\\r\\n' +\n                    '\\r\\n');\n    srvSocket.write(head);\n    srvSocket.pipe(cltSocket);\n    cltSocket.pipe(srvSocket);\n  });\n});\n\n// now that proxy is running\nproxy.listen(1337, '127.0.0.1', function() {\n\n  // make a request to a tunneling proxy\n  var options = {\n    port: 1337,\n    hostname: '127.0.0.1',\n    method: 'CONNECT',\n    path: 'www.google.com:80'\n  };\n\n  var req = http.request(options);\n  req.end();\n\n  req.on('connect', function(res, socket, head) {\n    console.log('got connected!');\n\n    // make a request over an HTTP tunnel\n    socket.write('GET / HTTP/1.1\\r\\n' +\n                 'Host: www.google.com:80\\r\\n' +\n                 'Connection: close\\r\\n' +\n                 '\\r\\n');\n    socket.on('data', function(chunk) {\n      console.log(chunk.toString());\n    });\n    socket.on('end', function() {\n      proxy.close();\n    });\n  });\n});
    \n", "params": [] }, { "textRaw": "Event: 'upgrade'", "type": "event", "name": "upgrade", "desc": "

    function (response, socket, head) { }\n\n

    \n

    Emitted each time a server responds to a request with an upgrade. If this\nevent isn't being listened for, clients receiving an upgrade header will have\ntheir connections closed.\n\n

    \n

    A client server pair that show you how to listen for the upgrade event.\n\n

    \n
    var http = require('http');\n\n// Create an HTTP server\nvar srv = http.createServer(function (req, res) {\n  res.writeHead(200, {'Content-Type': 'text/plain'});\n  res.end('okay');\n});\nsrv.on('upgrade', function(req, socket, head) {\n  socket.write('HTTP/1.1 101 Web Socket Protocol Handshake\\r\\n' +\n               'Upgrade: WebSocket\\r\\n' +\n               'Connection: Upgrade\\r\\n' +\n               '\\r\\n');\n\n  socket.pipe(socket); // echo back\n});\n\n// now that server is running\nsrv.listen(1337, '127.0.0.1', function() {\n\n  // make a request\n  var options = {\n    port: 1337,\n    hostname: '127.0.0.1',\n    headers: {\n      'Connection': 'Upgrade',\n      'Upgrade': 'websocket'\n    }\n  };\n\n  var req = http.request(options);\n  req.end();\n\n  req.on('upgrade', function(res, socket, upgradeHead) {\n    console.log('got upgraded!');\n    socket.end();\n    process.exit(0);\n  });\n});
    \n", "params": [] }, { "textRaw": "Event: 'continue'", "type": "event", "name": "continue", "desc": "

    function () { }\n\n

    \n

    Emitted when the server sends a '100 Continue' HTTP response, usually because\nthe request contained 'Expect: 100-continue'. This is an instruction that\nthe client should send the request body.\n\n

    \n", "params": [] } ], "methods": [ { "textRaw": "request.write(chunk, [encoding])", "type": "method", "name": "write", "desc": "

    Sends a chunk of the body. By calling this method\nmany times, the user can stream a request body to a\nserver--in that case it is suggested to use the\n['Transfer-Encoding', 'chunked'] header line when\ncreating the request.\n\n

    \n

    The chunk argument should be a [Buffer][] or a string.\n\n

    \n

    The encoding argument is optional and only applies when chunk is a string.\nDefaults to 'utf8'.\n\n\n

    \n", "signatures": [ { "params": [ { "name": "chunk" }, { "name": "encoding", "optional": true } ] } ] }, { "textRaw": "request.end([data], [encoding])", "type": "method", "name": "end", "desc": "

    Finishes sending the request. If any parts of the body are\nunsent, it will flush them to the stream. If the request is\nchunked, this will send the terminating '0\\r\\n\\r\\n'.\n\n

    \n

    If data is specified, it is equivalent to calling\nrequest.write(data, encoding) followed by request.end().\n\n

    \n", "signatures": [ { "params": [ { "name": "data", "optional": true }, { "name": "encoding", "optional": true } ] } ] }, { "textRaw": "request.abort()", "type": "method", "name": "abort", "desc": "

    Aborts a request. (New since v0.3.8.)\n\n

    \n", "signatures": [ { "params": [] } ] }, { "textRaw": "request.setTimeout(timeout, [callback])", "type": "method", "name": "setTimeout", "desc": "

    Once a socket is assigned to this request and is connected\n[socket.setTimeout()][] will be called.\n\n

    \n", "signatures": [ { "params": [ { "name": "timeout" }, { "name": "callback", "optional": true } ] } ] }, { "textRaw": "request.setNoDelay([noDelay])", "type": "method", "name": "setNoDelay", "desc": "

    Once a socket is assigned to this request and is connected\n[socket.setNoDelay()][] will be called.\n\n

    \n", "signatures": [ { "params": [ { "name": "noDelay", "optional": true } ] } ] }, { "textRaw": "request.setSocketKeepAlive([enable], [initialDelay])", "type": "method", "name": "setSocketKeepAlive", "desc": "

    Once a socket is assigned to this request and is connected\n[socket.setKeepAlive()][] will be called.\n\n\n

    \n", "signatures": [ { "params": [ { "name": "enable", "optional": true }, { "name": "initialDelay", "optional": true } ] } ] } ] } ], "type": "module", "displayName": "HTTP" }, { "textRaw": "HTTPS", "name": "https", "stability": 3, "stabilityText": "Stable", "desc": "

    HTTPS is the HTTP protocol over TLS/SSL. In Node this is implemented as a\nseparate module.\n\n

    \n", "classes": [ { "textRaw": "Class: https.Server", "type": "class", "name": "https.Server", "desc": "

    This class is a subclass of tls.Server and emits events same as\nhttp.Server. See http.Server for more information.\n\n

    \n" }, { "textRaw": "Class: https.Agent", "type": "class", "name": "https.Agent", "desc": "

    An Agent object for HTTPS similar to [http.Agent][]. See [https.request()][]\nfor more information.\n\n\n

    \n" } ], "methods": [ { "textRaw": "https.createServer(options, [requestListener])", "type": "method", "name": "createServer", "desc": "

    Returns a new HTTPS web server object. The options is similar to\n[tls.createServer()][]. The requestListener is a function which is\nautomatically added to the 'request' event.\n\n

    \n

    Example:\n\n

    \n
    // curl -k https://localhost:8000/\nvar https = require('https');\nvar fs = require('fs');\n\nvar options = {\n  key: fs.readFileSync('test/fixtures/keys/agent2-key.pem'),\n  cert: fs.readFileSync('test/fixtures/keys/agent2-cert.pem')\n};\n\nhttps.createServer(options, function (req, res) {\n  res.writeHead(200);\n  res.end("hello world\\n");\n}).listen(8000);
    \n

    Or\n\n

    \n
    var https = require('https');\nvar fs = require('fs');\n\nvar options = {\n  pfx: fs.readFileSync('server.pfx')\n};\n\nhttps.createServer(options, function (req, res) {\n  res.writeHead(200);\n  res.end("hello world\\n");\n}).listen(8000);
    \n", "methods": [ { "textRaw": "server.listen(path, [callback])", "type": "method", "name": "listen", "desc": "

    See [http.listen()][] for details.\n\n

    \n", "signatures": [ { "params": [ { "name": "handle" }, { "name": "callback", "optional": true } ] }, { "params": [ { "name": "path" }, { "name": "callback", "optional": true } ] } ] }, { "textRaw": "server.listen(handle, [callback])", "type": "method", "name": "listen", "desc": "

    See [http.listen()][] for details.\n\n

    \n", "signatures": [ { "params": [ { "name": "handle" }, { "name": "callback", "optional": true } ] } ] }, { "textRaw": "server.close([callback])", "type": "method", "name": "close", "desc": "

    See [http.close()][] for details.\n\n

    \n", "signatures": [ { "params": [ { "name": "callback", "optional": true } ] } ] } ], "signatures": [ { "params": [ { "name": "options" }, { "name": "requestListener", "optional": true } ] } ] }, { "textRaw": "https.request(options, callback)", "type": "method", "name": "request", "desc": "

    Makes a request to a secure web server.\n\n

    \n

    options can be an object or a string. If options is a string, it is\nautomatically parsed with url.parse().\n\n

    \n

    All options from [http.request()][] are valid.\n\n

    \n

    Example:\n\n

    \n
    var https = require('https');\n\nvar options = {\n  hostname: 'encrypted.google.com',\n  port: 443,\n  path: '/',\n  method: 'GET'\n};\n\nvar req = https.request(options, function(res) {\n  console.log("statusCode: ", res.statusCode);\n  console.log("headers: ", res.headers);\n\n  res.on('data', function(d) {\n    process.stdout.write(d);\n  });\n});\nreq.end();\n\nreq.on('error', function(e) {\n  console.error(e);\n});
    \n

    The options argument has the following options\n\n

    \n
      \n
    • host: A domain name or IP address of the server to issue the request to.\nDefaults to 'localhost'.
    • \n
    • hostname: To support url.parse() hostname is preferred over host
    • \n
    • port: Port of remote server. Defaults to 443.
    • \n
    • method: A string specifying the HTTP request method. Defaults to 'GET'.
    • \n
    • path: Request path. Defaults to '/'. Should include query string if any.\nE.G. '/index.html?page=12'
    • \n
    • headers: An object containing request headers.
    • \n
    • auth: Basic authentication i.e. 'user:password' to compute an\nAuthorization header.
    • \n
    • agent: Controls [Agent][] behavior. When an Agent is used request will\ndefault to Connection: keep-alive. Possible values:
        \n
      • undefined (default): use [globalAgent][] for this host and port.
      • \n
      • Agent object: explicitly use the passed in Agent.
      • \n
      • false: opts out of connection pooling with an Agent, defaults request to\nConnection: close.
      • \n
      \n
    • \n
    \n

    The following options from [tls.connect()][] can also be specified. However, a\n[globalAgent][] silently ignores these.\n\n

    \n
      \n
    • pfx: Certificate, Private key and CA certificates to use for SSL. Default null.
    • \n
    • key: Private key to use for SSL. Default null.
    • \n
    • passphrase: A string of passphrase for the private key or pfx. Default null.
    • \n
    • cert: Public x509 certificate to use. Default null.
    • \n
    • ca: An authority certificate or array of authority certificates to check\nthe remote host against.
    • \n
    • ciphers: A string describing the ciphers to use or exclude. Consult\nhttp://www.openssl.org/docs/apps/ciphers.html#CIPHER_LIST_FORMAT for\ndetails on the format.
    • \n
    • rejectUnauthorized: If true, the server certificate is verified against\nthe list of supplied CAs. An 'error' event is emitted if verification\nfails. Verification happens at the connection level, before the HTTP\nrequest is sent. Default true.
    • \n
    • secureProtocol: The SSL method to use, e.g. SSLv3_method to force\nSSL version 3. The possible values depend on your installation of\nOpenSSL and are defined in the constant [SSL_METHODS][].
    • \n
    \n

    In order to specify these options, use a custom Agent.\n\n

    \n

    Example:\n\n

    \n
    var options = {\n  hostname: 'encrypted.google.com',\n  port: 443,\n  path: '/',\n  method: 'GET',\n  key: fs.readFileSync('test/fixtures/keys/agent2-key.pem'),\n  cert: fs.readFileSync('test/fixtures/keys/agent2-cert.pem')\n};\noptions.agent = new https.Agent(options);\n\nvar req = https.request(options, function(res) {\n  ...\n}
    \n

    Or does not use an Agent.\n\n

    \n

    Example:\n\n

    \n
    var options = {\n  hostname: 'encrypted.google.com',\n  port: 443,\n  path: '/',\n  method: 'GET',\n  key: fs.readFileSync('test/fixtures/keys/agent2-key.pem'),\n  cert: fs.readFileSync('test/fixtures/keys/agent2-cert.pem'),\n  agent: false\n};\n\nvar req = https.request(options, function(res) {\n  ...\n}
    \n", "signatures": [ { "params": [ { "name": "options" }, { "name": "callback" } ] } ] }, { "textRaw": "https.get(options, callback)", "type": "method", "name": "get", "desc": "

    Like http.get() but for HTTPS.\n\n

    \n

    options can be an object or a string. If options is a string, it is\nautomatically parsed with url.parse().\n\n

    \n

    Example:\n\n

    \n
    var https = require('https');\n\nhttps.get('https://encrypted.google.com/', function(res) {\n  console.log("statusCode: ", res.statusCode);\n  console.log("headers: ", res.headers);\n\n  res.on('data', function(d) {\n    process.stdout.write(d);\n  });\n\n}).on('error', function(e) {\n  console.error(e);\n});
    \n", "signatures": [ { "params": [ { "name": "options" }, { "name": "callback" } ] } ] } ], "properties": [ { "textRaw": "https.globalAgent", "name": "globalAgent", "desc": "

    Global instance of [https.Agent][] for all HTTPS client requests.\n\n

    \n" } ], "type": "module", "displayName": "HTTPS" }, { "textRaw": "URL", "name": "url", "stability": 3, "stabilityText": "Stable", "desc": "

    This module has utilities for URL resolution and parsing.\nCall require('url') to use it.\n\n

    \n

    Parsed URL objects have some or all of the following fields, depending on\nwhether or not they exist in the URL string. Any parts that are not in the URL\nstring will not be in the parsed object. Examples are shown for the URL\n\n

    \n

    'http://user:pass@host.com:8080/p/a/t/h?query=string#hash'\n\n

    \n
      \n
    • href: The full URL that was originally parsed. Both the protocol and host are lowercased.

      \n

      Example: 'http://user:pass@host.com:8080/p/a/t/h?query=string#hash'

      \n
    • \n
    • protocol: The request protocol, lowercased.

      \n

      Example: 'http:'

      \n
    • \n
    • host: The full lowercased host portion of the URL, including port\ninformation.

      \n

      Example: 'host.com:8080'

      \n
    • \n
    • auth: The authentication information portion of a URL.

      \n

      Example: 'user:pass'

      \n
    • \n
    • hostname: Just the lowercased hostname portion of the host.

      \n

      Example: 'host.com'

      \n
    • \n
    • port: The port number portion of the host.

      \n

      Example: '8080'

      \n
    • \n
    • pathname: The path section of the URL, that comes after the host and\nbefore the query, including the initial slash if present.

      \n

      Example: '/p/a/t/h'

      \n
    • \n
    • search: The 'query string' portion of the URL, including the leading\nquestion mark.

      \n

      Example: '?query=string'

      \n
    • \n
    • path: Concatenation of pathname and search.

      \n

      Example: '/p/a/t/h?query=string'

      \n
    • \n
    • query: Either the 'params' portion of the query string, or a\nquerystring-parsed object.

      \n

      Example: 'query=string' or {'query':'string'}

      \n
    • \n
    • hash: The 'fragment' portion of the URL including the pound-sign.

      \n

      Example: '#hash'

      \n
    • \n
    \n

    The following methods are provided by the URL module:\n\n

    \n", "methods": [ { "textRaw": "url.parse(urlStr, [parseQueryString], [slashesDenoteHost])", "type": "method", "name": "parse", "desc": "

    Take a URL string, and return an object.\n\n

    \n

    Pass true as the second argument to also parse\nthe query string using the querystring module.\nDefaults to false.\n\n

    \n

    Pass true as the third argument to treat //foo/bar as\n{ host: 'foo', pathname: '/bar' } rather than\n{ pathname: '//foo/bar' }. Defaults to false.\n\n

    \n", "signatures": [ { "params": [ { "name": "urlStr" }, { "name": "parseQueryString", "optional": true }, { "name": "slashesDenoteHost", "optional": true } ] } ] }, { "textRaw": "url.format(urlObj)", "type": "method", "name": "format", "desc": "

    Take a parsed URL object, and return a formatted URL string.\n\n

    \n
      \n
    • href will be ignored.
    • \n
    • protocolis treated the same with or without the trailing : (colon).
        \n
      • The protocols http, https, ftp, gopher, file will be\npostfixed with :// (colon-slash-slash).
      • \n
      • All other protocols mailto, xmpp, aim, sftp, foo, etc will\nbe postfixed with : (colon)
      • \n
      \n
    • \n
    • auth will be used if present.
    • \n
    • hostname will only be used if host is absent.
    • \n
    • port will only be used if host is absent.
    • \n
    • host will be used in place of hostname and port
    • \n
    • pathname is treated the same with or without the leading / (slash)
    • \n
    • search will be used in place of query
    • \n
    • query (object; see querystring) will only be used if search is absent.
    • \n
    • search is treated the same with or without the leading ? (question mark)
    • \n
    • hash is treated the same with or without the leading # (pound sign, anchor)
    • \n
    \n", "signatures": [ { "params": [ { "name": "urlObj" } ] } ] }, { "textRaw": "url.resolve(from, to)", "type": "method", "name": "resolve", "desc": "

    Take a base URL, and a href URL, and resolve them as a browser would for\nan anchor tag. Examples:\n\n

    \n
    url.resolve('/one/two/three', 'four')         // '/one/two/four'\nurl.resolve('http://example.com/', '/one')    // 'http://example.com/one'\nurl.resolve('http://example.com/one', '/two') // 'http://example.com/two'
    \n", "signatures": [ { "params": [ { "name": "from" }, { "name": "to" } ] } ] } ], "type": "module", "displayName": "URL" }, { "textRaw": "Query String", "name": "querystring", "stability": 3, "stabilityText": "Stable", "desc": "

    This module provides utilities for dealing with query strings.\nIt provides the following methods:\n\n

    \n", "methods": [ { "textRaw": "querystring.stringify(obj, [sep], [eq])", "type": "method", "name": "stringify", "desc": "

    Serialize an object to a query string.\nOptionally override the default separator ('&') and assignment ('=')\ncharacters.\n\n

    \n

    Example:\n\n

    \n
    querystring.stringify({ foo: 'bar', baz: ['qux', 'quux'], corge: '' })\n// returns\n'foo=bar&baz=qux&baz=quux&corge='\n\nquerystring.stringify({foo: 'bar', baz: 'qux'}, ';', ':')\n// returns\n'foo:bar;baz:qux'
    \n", "signatures": [ { "params": [ { "name": "obj" }, { "name": "sep", "optional": true }, { "name": "eq", "optional": true } ] } ] }, { "textRaw": "querystring.parse(str, [sep], [eq], [options])", "type": "method", "name": "parse", "desc": "

    Deserialize a query string to an object.\nOptionally override the default separator ('&') and assignment ('=')\ncharacters.\n\n

    \n

    Options object may contain maxKeys property (equal to 1000 by default), it'll\nbe used to limit processed keys. Set it to 0 to remove key count limitation.\n\n

    \n

    Example:\n\n

    \n
    querystring.parse('foo=bar&baz=qux&baz=quux&corge')\n// returns\n{ foo: 'bar', baz: ['qux', 'quux'], corge: '' }
    \n", "signatures": [ { "params": [ { "name": "str" }, { "name": "sep", "optional": true }, { "name": "eq", "optional": true }, { "name": "options", "optional": true } ] } ] } ], "properties": [ { "textRaw": "querystring.escape", "name": "escape", "desc": "

    The escape function used by querystring.stringify,\nprovided so that it could be overridden if necessary.\n\n

    \n" }, { "textRaw": "querystring.unescape", "name": "unescape", "desc": "

    The unescape function used by querystring.parse,\nprovided so that it could be overridden if necessary.\n\n

    \n" } ], "type": "module", "displayName": "querystring" }, { "textRaw": "punycode", "name": "punycode", "stability": 2, "stabilityText": "Unstable", "desc": "

    Punycode.js is bundled with Node.js v0.6.2+. Use\nrequire('punycode') to access it. (To use it with other Node.js versions,\nuse npm to install the punycode module first.)\n\n

    \n", "methods": [ { "textRaw": "punycode.decode(string)", "type": "method", "name": "decode", "desc": "

    Converts a Punycode string of ASCII code points to a string of Unicode code\npoints.\n\n

    \n
    // decode domain name parts\npunycode.decode('maana-pta'); // 'mañana'\npunycode.decode('--dqo34k'); // '☃-⌘'
    \n", "signatures": [ { "params": [ { "name": "string" } ] } ] }, { "textRaw": "punycode.encode(string)", "type": "method", "name": "encode", "desc": "

    Converts a string of Unicode code points to a Punycode string of ASCII code\npoints.\n\n

    \n
    // encode domain name parts\npunycode.encode('mañana'); // 'maana-pta'\npunycode.encode('☃-⌘'); // '--dqo34k'
    \n", "signatures": [ { "params": [ { "name": "string" } ] } ] }, { "textRaw": "punycode.toUnicode(domain)", "type": "method", "name": "toUnicode", "desc": "

    Converts a Punycode string representing a domain name to Unicode. Only the\nPunycoded parts of the domain name will be converted, i.e. it doesn't matter if\nyou call it on a string that has already been converted to Unicode.\n\n

    \n
    // decode domain names\npunycode.toUnicode('xn--maana-pta.com'); // 'mañana.com'\npunycode.toUnicode('xn----dqo34k.com'); // '☃-⌘.com'
    \n", "signatures": [ { "params": [ { "name": "domain" } ] } ] }, { "textRaw": "punycode.toASCII(domain)", "type": "method", "name": "toASCII", "desc": "

    Converts a Unicode string representing a domain name to Punycode. Only the\nnon-ASCII parts of the domain name will be converted, i.e. it doesn't matter if\nyou call it with a domain that's already in ASCII.\n\n

    \n
    // encode domain names\npunycode.toASCII('mañana.com'); // 'xn--maana-pta.com'\npunycode.toASCII('☃-⌘.com'); // 'xn----dqo34k.com'
    \n", "signatures": [ { "params": [ { "name": "domain" } ] } ] } ], "properties": [ { "textRaw": "punycode.ucs2", "name": "ucs2", "modules": [ { "textRaw": "punycode.ucs2.decode(string)", "name": "punycode.ucs2.decode(string)", "desc": "

    Creates an array containing the decimal code points of each Unicode character\nin the string. While JavaScript uses UCS-2\ninternally, this function\nwill convert a pair of surrogate halves (each of which UCS-2 exposes as\nseparate characters) into a single code point, matching UTF-16.\n\n

    \n
    punycode.ucs2.decode('abc'); // [97, 98, 99]\n// surrogate pair for U+1D306 tetragram for centre:\npunycode.ucs2.decode('\\uD834\\uDF06'); // [0x1D306]
    \n", "type": "module", "displayName": "punycode.ucs2.decode(string)" }, { "textRaw": "punycode.ucs2.encode(codePoints)", "name": "punycode.ucs2.encode(codepoints)", "desc": "

    Creates a string based on an array of decimal code points.\n\n

    \n
    punycode.ucs2.encode([97, 98, 99]); // 'abc'\npunycode.ucs2.encode([0x1D306]); // '\\uD834\\uDF06'
    \n", "type": "module", "displayName": "punycode.ucs2.encode(codePoints)" } ] }, { "textRaw": "punycode.version", "name": "version", "desc": "

    A string representing the current Punycode.js version number.\n\n

    \n" } ], "type": "module", "displayName": "punycode" }, { "textRaw": "Readline", "name": "readline", "stability": 2, "stabilityText": "Unstable", "desc": "

    To use this module, do require('readline'). Readline allows reading of a\nstream (such as process.stdin) on a line-by-line basis.\n\n

    \n

    Note that once you've invoked this module, your node program will not\nterminate until you've closed the interface. Here's how to allow your\nprogram to gracefully exit:\n\n

    \n
    var readline = require('readline');\n\nvar rl = readline.createInterface({\n  input: process.stdin,\n  output: process.stdout\n});\n\nrl.question("What do you think of node.js? ", function(answer) {\n  // TODO: Log the answer in a database\n  console.log("Thank you for your valuable feedback:", answer);\n\n  rl.close();\n});
    \n", "methods": [ { "textRaw": "readline.createInterface(options)", "type": "method", "name": "createInterface", "desc": "

    Creates a readline Interface instance. Accepts an "options" Object that takes\nthe following values:\n\n

    \n
      \n
    • input - the readable stream to listen to (Required).

      \n
    • \n
    • output - the writable stream to write readline data to (Required).

      \n
    • \n
    • completer - an optional function that is used for Tab autocompletion. See\nbelow for an example of using this.

      \n
    • \n
    • terminal - pass true if the input and output streams should be\ntreated like a TTY, and have ANSI/VT100 escape codes written to it.\nDefaults to checking isTTY on the output stream upon instantiation.

      \n
    • \n
    \n

    The completer function is given a the current line entered by the user, and\nis supposed to return an Array with 2 entries:\n\n

    \n
      \n
    1. An Array with matching entries for the completion.

      \n
    2. \n
    3. The substring that was used for the matching.

      \n
    4. \n
    \n

    Which ends up looking something like:\n[[substr1, substr2, ...], originalsubstring].\n\n

    \n

    Example:\n\n

    \n
    function completer(line) {\n  var completions = '.help .error .exit .quit .q'.split(' ')\n  var hits = completions.filter(function(c) { return c.indexOf(line) == 0 })\n  // show all completions if none found\n  return [hits.length ? hits : completions, line]\n}
    \n

    Also completer can be run in async mode if it accepts two arguments:\n\n

    \n
    function completer(linePartial, callback) {\n  callback(null, [['123'], linePartial]);\n}
    \n

    createInterface is commonly used with process.stdin and\nprocess.stdout in order to accept user input:\n\n

    \n
    var readline = require('readline');\nvar rl = readline.createInterface({\n  input: process.stdin,\n  output: process.stdout\n});
    \n

    Once you have a readline instance, you most commonly listen for the\n"line" event.\n\n

    \n

    If terminal is true for this instance then the output stream will get\nthe best compatibility if it defines an output.columns property, and fires\na "resize" event on the output if/when the columns ever change\n(process.stdout does this automatically when it is a TTY).\n\n

    \n", "signatures": [ { "params": [ { "name": "options" } ] } ] } ], "classes": [ { "textRaw": "Class: Interface", "type": "class", "name": "Interface", "desc": "

    The class that represents a readline interface with an input and output\nstream.\n\n

    \n", "methods": [ { "textRaw": "rl.setPrompt(prompt, length)", "type": "method", "name": "setPrompt", "desc": "

    Sets the prompt, for example when you run node on the command line, you see\n> , which is node's prompt.\n\n

    \n", "signatures": [ { "params": [ { "name": "prompt" }, { "name": "length" } ] } ] }, { "textRaw": "rl.prompt([preserveCursor])", "type": "method", "name": "prompt", "desc": "

    Readies readline for input from the user, putting the current setPrompt\noptions on a new line, giving the user a new spot to write. Set preserveCursor\nto true to prevent the cursor placement being reset to 0.\n\n

    \n

    This will also resume the input stream used with createInterface if it has\nbeen paused.\n\n

    \n", "signatures": [ { "params": [ { "name": "preserveCursor", "optional": true } ] } ] }, { "textRaw": "rl.question(query, callback)", "type": "method", "name": "question", "desc": "

    Prepends the prompt with query and invokes callback with the user's\nresponse. Displays the query to the user, and then invokes callback\nwith the user's response after it has been typed.\n\n

    \n

    This will also resume the input stream used with createInterface if\nit has been paused.\n\n

    \n

    Example usage:\n\n

    \n
    interface.question('What is your favorite food?', function(answer) {\n  console.log('Oh, so your favorite food is ' + answer);\n});
    \n", "signatures": [ { "params": [ { "name": "query" }, { "name": "callback" } ] } ] }, { "textRaw": "rl.pause()", "type": "method", "name": "pause", "desc": "

    Pauses the readline input stream, allowing it to be resumed later if needed.\n\n

    \n", "signatures": [ { "params": [] } ] }, { "textRaw": "rl.resume()", "type": "method", "name": "resume", "desc": "

    Resumes the readline input stream.\n\n

    \n", "signatures": [ { "params": [] } ] }, { "textRaw": "rl.close()", "type": "method", "name": "close", "desc": "

    Closes the Interface instance, relinquishing control on the input and\noutput streams. The "close" event will also be emitted.\n\n

    \n", "signatures": [ { "params": [] } ] }, { "textRaw": "rl.write(data, [key])", "type": "method", "name": "write", "desc": "

    Writes data to output stream. key is an object literal to represent a key\nsequence; available if the terminal is a TTY.\n\n

    \n

    This will also resume the input stream if it has been paused.\n\n

    \n

    Example:\n\n

    \n
    rl.write('Delete me!');\n// Simulate ctrl+u to delete the line written previously\nrl.write(null, {ctrl: true, name: 'u'});
    \n", "signatures": [ { "params": [ { "name": "data" }, { "name": "key", "optional": true } ] } ] } ] } ], "modules": [ { "textRaw": "Events", "name": "events", "events": [ { "textRaw": "Event: 'line'", "type": "event", "name": "line", "desc": "

    function (line) {}\n\n

    \n

    Emitted whenever the input stream receives a \\n, usually received when the\nuser hits enter, or return. This is a good hook to listen for user input.\n\n

    \n

    Example of listening for line:\n\n

    \n
    rl.on('line', function (cmd) {\n  console.log('You just typed: '+cmd);\n});
    \n", "params": [] }, { "textRaw": "Event: 'pause'", "type": "event", "name": "pause", "desc": "

    function () {}\n\n

    \n

    Emitted whenever the input stream is paused.\n\n

    \n

    Also emitted whenever the input stream is not paused and receives the\nSIGCONT event. (See events SIGTSTP and SIGCONT)\n\n

    \n

    Example of listening for pause:\n\n

    \n
    rl.on('pause', function() {\n  console.log('Readline paused.');\n});
    \n", "params": [] }, { "textRaw": "Event: 'resume'", "type": "event", "name": "resume", "desc": "

    function () {}\n\n

    \n

    Emitted whenever the input stream is resumed.\n\n

    \n

    Example of listening for resume:\n\n

    \n
    rl.on('resume', function() {\n  console.log('Readline resumed.');\n});
    \n", "params": [] }, { "textRaw": "Event: 'close'", "type": "event", "name": "close", "desc": "

    function () {}\n\n

    \n

    Emitted when close() is called.\n\n

    \n

    Also emitted when the input stream receives its "end" event. The Interface\ninstance should be considered "finished" once this is emitted. For example, when\nthe input stream receives ^D, respectively known as EOT.\n\n

    \n

    This event is also called if there is no SIGINT event listener present when\nthe input stream receives a ^C, respectively known as SIGINT.\n\n

    \n", "params": [] }, { "textRaw": "Event: 'SIGINT'", "type": "event", "name": "SIGINT", "desc": "

    function () {}\n\n

    \n

    Emitted whenever the input stream receives a ^C, respectively known as\nSIGINT. If there is no SIGINT event listener present when the input\nstream receives a SIGINT, pause will be triggered.\n\n

    \n

    Example of listening for SIGINT:\n\n

    \n
    rl.on('SIGINT', function() {\n  rl.question('Are you sure you want to exit?', function(answer) {\n    if (answer.match(/^y(es)?$/i)) rl.pause();\n  });\n});
    \n", "params": [] }, { "textRaw": "Event: 'SIGTSTP'", "type": "event", "name": "SIGTSTP", "desc": "

    function () {}\n\n

    \n

    This does not work on Windows.\n\n

    \n

    Emitted whenever the input stream receives a ^Z, respectively known as\nSIGTSTP. If there is no SIGTSTP event listener present when the input\nstream receives a SIGTSTP, the program will be sent to the background.\n\n

    \n

    When the program is resumed with fg, the pause and SIGCONT events will be\nemitted. You can use either to resume the stream.\n\n

    \n

    The pause and SIGCONT events will not be triggered if the stream was paused\nbefore the program was sent to the background.\n\n

    \n

    Example of listening for SIGTSTP:\n\n

    \n
    rl.on('SIGTSTP', function() {\n  // This will override SIGTSTP and prevent the program from going to the\n  // background.\n  console.log('Caught SIGTSTP.');\n});
    \n", "params": [] }, { "textRaw": "Event: 'SIGCONT'", "type": "event", "name": "SIGCONT", "desc": "

    function () {}\n\n

    \n

    This does not work on Windows.\n\n

    \n

    Emitted whenever the input stream is sent to the background with ^Z,\nrespectively known as SIGTSTP, and then continued with fg(1). This event\nonly emits if the stream was not paused before sending the program to the\nbackground.\n\n

    \n

    Example of listening for SIGCONT:\n\n

    \n
    rl.on('SIGCONT', function() {\n  // `prompt` will automatically resume the stream\n  rl.prompt();\n});
    \n

    Example: Tiny CLI

    \n

    Here's an example of how to use all these together to craft a tiny command\nline interface:\n\n

    \n
    var readline = require('readline'),\n    rl = readline.createInterface(process.stdin, process.stdout);\n\nrl.setPrompt('OHAI> ');\nrl.prompt();\n\nrl.on('line', function(line) {\n  switch(line.trim()) {\n    case 'hello':\n      console.log('world!');\n      break;\n    default:\n      console.log('Say what? I might have heard `' + line.trim() + '`');\n      break;\n  }\n  rl.prompt();\n}).on('close', function() {\n  console.log('Have a great day!');\n  process.exit(0);\n});
    \n", "params": [] } ], "type": "module", "displayName": "Events" } ], "type": "module", "displayName": "Readline" }, { "textRaw": "REPL", "name": "repl", "desc": "

    A Read-Eval-Print-Loop (REPL) is available both as a standalone program and\neasily includable in other programs. The REPL provides a way to interactively\nrun JavaScript and see the results. It can be used for debugging, testing, or\njust trying things out.\n\n

    \n

    By executing node without any arguments from the command-line you will be\ndropped into the REPL. It has simplistic emacs line-editing.\n\n

    \n
    mjr:~$ node\nType '.help' for options.\n> a = [ 1, 2, 3];\n[ 1, 2, 3 ]\n> a.forEach(function (v) {\n...   console.log(v);\n...   });\n1\n2\n3
    \n

    For advanced line-editors, start node with the environmental variable\nNODE_NO_READLINE=1. This will start the main and debugger REPL in canonical\nterminal settings which will allow you to use with rlwrap.\n\n

    \n

    For example, you could add this to your bashrc file:\n\n

    \n
    alias node="env NODE_NO_READLINE=1 rlwrap node"
    \n", "methods": [ { "textRaw": "repl.start(options)", "type": "method", "name": "start", "desc": "

    Returns and starts a REPLServer instance. Accepts an "options" Object that\ntakes the following values:\n\n

    \n
      \n
    • prompt - the prompt and stream for all I/O. Defaults to > .

      \n
    • \n
    • input - the readable stream to listen to. Defaults to process.stdin.

      \n
    • \n
    • output - the writable stream to write readline data to. Defaults to\nprocess.stdout.

      \n
    • \n
    • terminal - pass true if the stream should be treated like a TTY, and\nhave ANSI/VT100 escape codes written to it. Defaults to checking isTTY\non the output stream upon instantiation.

      \n
    • \n
    • eval - function that will be used to eval each given line. Defaults to\nan async wrapper for eval(). See below for an example of a custom eval.

      \n
    • \n
    • useColors - a boolean which specifies whether or not the writer function\nshould output colors. If a different writer function is set then this does\nnothing. Defaults to the repl's terminal value.

      \n
    • \n
    • useGlobal - if set to true, then the repl will use the global object,\ninstead of running scripts in a separate context. Defaults to false.

      \n
    • \n
    • ignoreUndefined - if set to true, then the repl will not output the\nreturn value of command if it's undefined. Defaults to false.

      \n
    • \n
    • writer - the function to invoke for each command that gets evaluated which\nreturns the formatting (including coloring) to display. Defaults to\nutil.inspect.

      \n
    • \n
    \n

    You can use your own eval function if it has following signature:\n\n

    \n
    function eval(cmd, context, filename, callback) {\n  callback(null, result);\n}
    \n

    Multiple REPLs may be started against the same running instance of node. Each\nwill share the same global object but will have unique I/O.\n\n

    \n

    Here is an example that starts a REPL on stdin, a Unix socket, and a TCP socket:\n\n

    \n
    var net = require("net"),\n    repl = require("repl");\n\nconnections = 0;\n\nrepl.start({\n  prompt: "node via stdin> ",\n  input: process.stdin,\n  output: process.stdout\n});\n\nnet.createServer(function (socket) {\n  connections += 1;\n  repl.start({\n    prompt: "node via Unix socket> ",\n    input: socket,\n    output: socket\n  }).on('exit', function() {\n    socket.end();\n  })\n}).listen("/tmp/node-repl-sock");\n\nnet.createServer(function (socket) {\n  connections += 1;\n  repl.start({\n    prompt: "node via TCP socket> ",\n    input: socket,\n    output: socket\n  }).on('exit', function() {\n    socket.end();\n  });\n}).listen(5001);
    \n

    Running this program from the command line will start a REPL on stdin. Other\nREPL clients may connect through the Unix socket or TCP socket. telnet is useful\nfor connecting to TCP sockets, and socat can be used to connect to both Unix and\nTCP sockets.\n\n

    \n

    By starting a REPL from a Unix socket-based server instead of stdin, you can\nconnect to a long-running node process without restarting it.\n\n

    \n

    For an example of running a "full-featured" (terminal) REPL over\na net.Server and net.Socket instance, see: https://gist.github.com/2209310\n\n

    \n

    For an example of running a REPL instance over curl(1),\nsee: https://gist.github.com/2053342\n\n

    \n", "events": [ { "textRaw": "Event: 'exit'", "type": "event", "name": "exit", "desc": "

    function () {}\n\n

    \n

    Emitted when the user exits the REPL in any of the defined ways. Namely, typing\n.exit at the repl, pressing Ctrl+C twice to signal SIGINT, or pressing Ctrl+D\nto signal "end" on the input stream.\n\n

    \n

    Example of listening for exit:\n\n

    \n
    r.on('exit', function () {\n  console.log('Got "exit" event from repl!');\n  process.exit();\n});
    \n", "params": [] } ], "signatures": [ { "params": [ { "name": "options" } ] } ] } ], "miscs": [ { "textRaw": "REPL Features", "name": "REPL Features", "type": "misc", "desc": "

    Inside the REPL, Control+D will exit. Multi-line expressions can be input.\nTab completion is supported for both global and local variables.\n\n

    \n

    The special variable _ (underscore) contains the result of the last expression.\n\n

    \n
    > [ "a", "b", "c" ]\n[ 'a', 'b', 'c' ]\n> _.length\n3\n> _ += 1\n4
    \n

    The REPL provides access to any variables in the global scope. You can expose\na variable to the REPL explicitly by assigning it to the context object\nassociated with each REPLServer. For example:\n\n

    \n
    // repl_test.js\nvar repl = require("repl"),\n    msg = "message";\n\nrepl.start("> ").context.m = msg;
    \n

    Things in the context object appear as local within the REPL:\n\n

    \n
    mjr:~$ node repl_test.js\n> m\n'message'
    \n

    There are a few special REPL commands:\n\n

    \n
      \n
    • .break - While inputting a multi-line expression, sometimes you get lost\nor just don't care about completing it. .break will start over.
    • \n
    • .clear - Resets the context object to an empty object and clears any\nmulti-line expression.
    • \n
    • .exit - Close the I/O stream, which will cause the REPL to exit.
    • \n
    • .help - Show this list of special commands.
    • \n
    • .save - Save the current REPL session to a file
      \n

      .save ./file/to/save.js

      \n
      \n
    • \n
    • .load - Load a file into the current REPL session.
      \n

      .load ./file/to/load.js

      \n
      \n
    • \n
    \n

    The following key combinations in the REPL have these special effects:\n\n

    \n
      \n
    • <ctrl>C - Similar to the .break keyword. Terminates the current\ncommand. Press twice on a blank line to forcibly exit.
    • \n
    • <ctrl>D - Similar to the .exit keyword.
    • \n
    \n" } ], "type": "module", "displayName": "REPL" }, { "textRaw": "Executing JavaScript", "name": "vm", "stability": 2, "stabilityText": "Unstable. See Caveats, below.", "desc": "

    You can access this module with:\n\n

    \n
    var vm = require('vm');
    \n

    JavaScript code can be compiled and run immediately or compiled, saved, and run later.\n\n

    \n", "modules": [ { "textRaw": "Caveats", "name": "caveats", "desc": "

    The vm module has many known issues and edge cases. If you run into\nissues or unexpected behavior, please consult the open issues on\nGitHub.\nSome of the biggest problems are described below.\n\n

    \n", "modules": [ { "textRaw": "Sandboxes", "name": "sandboxes", "desc": "

    The sandbox argument to vm.runInNewContext and vm.createContext,\nalong with the initSandbox argument to vm.createContext, do not\nbehave as one might normally expect and their behavior varies\nbetween different versions of Node.\n\n

    \n

    The key issue to be aware of is that V8 provides no way to directly\ncontrol the global object used within a context. As a result, while\nproperties of your sandbox object will be available in the context,\nany properties from the prototypes of the sandbox may not be\navailable. Furthermore, the this expression within the global scope\nof the context evaluates to the empty object ({}) instead of to\nyour sandbox.\n\n

    \n

    Your sandbox's properties are also not shared directly with the script.\nInstead, the properties of the sandbox are copied into the context at\nthe beginning of execution, and then after execution, the properties\nare copied back out in an attempt to propagate any changes.\n\n

    \n", "type": "module", "displayName": "Sandboxes" }, { "textRaw": "Globals", "name": "globals", "desc": "

    Properties of the global object, like Array and String, have\ndifferent values inside of a context. This means that common\nexpressions like [] instanceof Array or\nObject.getPrototypeOf([]) === Array.prototype may not produce\nexpected results when used inside of scripts evaluated via the vm module.\n\n

    \n

    Some of these problems have known workarounds listed in the issues for\nvm on GitHub. for example, Array.isArray works around\nthe example problem with Array.\n\n

    \n", "type": "module", "displayName": "Globals" } ], "type": "module", "displayName": "Caveats" } ], "methods": [ { "textRaw": "vm.runInThisContext(code, [filename])", "type": "method", "name": "runInThisContext", "desc": "

    vm.runInThisContext() compiles code, runs it and returns the result. Running\ncode does not have access to local scope. filename is optional, it's used only\nin stack traces.\n\n

    \n

    Example of using vm.runInThisContext and eval to run the same code:\n\n

    \n
    var localVar = 123,\n    usingscript, evaled,\n    vm = require('vm');\n\nusingscript = vm.runInThisContext('localVar = 1;',\n  'myfile.vm');\nconsole.log('localVar: ' + localVar + ', usingscript: ' +\n  usingscript);\nevaled = eval('localVar = 1;');\nconsole.log('localVar: ' + localVar + ', evaled: ' +\n  evaled);\n\n// localVar: 123, usingscript: 1\n// localVar: 1, evaled: 1
    \n

    vm.runInThisContext does not have access to the local scope, so localVar is unchanged.\neval does have access to the local scope, so localVar is changed.\n\n

    \n

    In case of syntax error in code, vm.runInThisContext emits the syntax error to stderr\nand throws an exception.\n\n\n

    \n", "signatures": [ { "params": [ { "name": "code" }, { "name": "filename", "optional": true } ] } ] }, { "textRaw": "vm.runInNewContext(code, [sandbox], [filename])", "type": "method", "name": "runInNewContext", "desc": "

    vm.runInNewContext compiles code, then runs it in sandbox and returns the\nresult. Running code does not have access to local scope. The object sandbox\nwill be used as the global object for code.\nsandbox and filename are optional, filename is only used in stack traces.\n\n

    \n

    Example: compile and execute code that increments a global variable and sets a new one.\nThese globals are contained in the sandbox.\n\n

    \n
    var util = require('util'),\n    vm = require('vm'),\n    sandbox = {\n      animal: 'cat',\n      count: 2\n    };\n\nvm.runInNewContext('count += 1; name = "kitty"', sandbox, 'myfile.vm');\nconsole.log(util.inspect(sandbox));\n\n// { animal: 'cat', count: 3, name: 'kitty' }
    \n

    Note that running untrusted code is a tricky business requiring great care. To prevent accidental\nglobal variable leakage, vm.runInNewContext is quite useful, but safely running untrusted code\nrequires a separate process.\n\n

    \n

    In case of syntax error in code, vm.runInNewContext emits the syntax error to stderr\nand throws an exception.\n\n

    \n", "signatures": [ { "params": [ { "name": "code" }, { "name": "sandbox", "optional": true }, { "name": "filename", "optional": true } ] } ] }, { "textRaw": "vm.runInContext(code, context, [filename])", "type": "method", "name": "runInContext", "desc": "

    vm.runInContext compiles code, then runs it in context and returns the\nresult. A (V8) context comprises a global object, together with a set of\nbuilt-in objects and functions. Running code does not have access to local scope\nand the global object held within context will be used as the global object\nfor code.\nfilename is optional, it's used only in stack traces.\n\n

    \n

    Example: compile and execute code in a existing context.\n\n

    \n
    var util = require('util'),\n    vm = require('vm'),\n    initSandbox = {\n      animal: 'cat',\n      count: 2\n    },\n    context = vm.createContext(initSandbox);\n\nvm.runInContext('count += 1; name = "CATT"', context, 'myfile.vm');\nconsole.log(util.inspect(context));\n\n// { animal: 'cat', count: 3, name: 'CATT' }
    \n

    Note that createContext will perform a shallow clone of the supplied sandbox object in order to\ninitialize the global object of the freshly constructed context.\n\n

    \n

    Note that running untrusted code is a tricky business requiring great care. To prevent accidental\nglobal variable leakage, vm.runInContext is quite useful, but safely running untrusted code\nrequires a separate process.\n\n

    \n

    In case of syntax error in code, vm.runInContext emits the syntax error to stderr\nand throws an exception.\n\n

    \n", "signatures": [ { "params": [ { "name": "code" }, { "name": "context" }, { "name": "filename", "optional": true } ] } ] }, { "textRaw": "vm.createContext([initSandbox])", "type": "method", "name": "createContext", "desc": "

    vm.createContext creates a new context which is suitable for use as the 2nd argument of a subsequent\ncall to vm.runInContext. A (V8) context comprises a global object together with a set of\nbuild-in objects and functions. The optional argument initSandbox will be shallow-copied\nto seed the initial contents of the global object used by the context.\n\n

    \n", "signatures": [ { "params": [ { "name": "initSandbox", "optional": true } ] } ] }, { "textRaw": "vm.createScript(code, [filename])", "type": "method", "name": "createScript", "desc": "

    createScript compiles code but does not run it. Instead, it returns a\nvm.Script object representing this compiled code. This script can be run\nlater many times using methods below. The returned script is not bound to any\nglobal object. It is bound before each run, just for that run. filename is\noptional, it's only used in stack traces.\n\n

    \n

    In case of syntax error in code, createScript prints the syntax error to stderr\nand throws an exception.\n\n\n

    \n", "signatures": [ { "params": [ { "name": "code" }, { "name": "filename", "optional": true } ] } ] } ], "classes": [ { "textRaw": "Class: Script", "type": "class", "name": "Script", "desc": "

    A class for running scripts. Returned by vm.createScript.\n\n

    \n", "methods": [ { "textRaw": "script.runInThisContext()", "type": "method", "name": "runInThisContext", "desc": "

    Similar to vm.runInThisContext but a method of a precompiled Script object.\nscript.runInThisContext runs the code of script and returns the result.\nRunning code does not have access to local scope, but does have access to the global object\n(v8: in actual context).\n\n

    \n

    Example of using script.runInThisContext to compile code once and run it multiple times:\n\n

    \n
    var vm = require('vm');\n\nglobalVar = 0;\n\nvar script = vm.createScript('globalVar += 1', 'myfile.vm');\n\nfor (var i = 0; i < 1000 ; i += 1) {\n  script.runInThisContext();\n}\n\nconsole.log(globalVar);\n\n// 1000
    \n", "signatures": [ { "params": [] } ] }, { "textRaw": "script.runInNewContext([sandbox])", "type": "method", "name": "runInNewContext", "desc": "

    Similar to vm.runInNewContext a method of a precompiled Script object.\nscript.runInNewContext runs the code of script with sandbox as the global object and returns the result.\nRunning code does not have access to local scope. sandbox is optional.\n\n

    \n

    Example: compile code that increments a global variable and sets one, then execute this code multiple times.\nThese globals are contained in the sandbox.\n\n

    \n
    var util = require('util'),\n    vm = require('vm'),\n    sandbox = {\n      animal: 'cat',\n      count: 2\n    };\n\nvar script = vm.createScript('count += 1; name = "kitty"', 'myfile.vm');\n\nfor (var i = 0; i < 10 ; i += 1) {\n  script.runInNewContext(sandbox);\n}\n\nconsole.log(util.inspect(sandbox));\n\n// { animal: 'cat', count: 12, name: 'kitty' }
    \n

    Note that running untrusted code is a tricky business requiring great care. To prevent accidental\nglobal variable leakage, script.runInNewContext is quite useful, but safely running untrusted code\nrequires a separate process.\n\n

    \n", "signatures": [ { "params": [ { "name": "sandbox", "optional": true } ] } ] } ] } ], "type": "module", "displayName": "vm" }, { "textRaw": "Child Process", "name": "child_process", "stability": 3, "stabilityText": "Stable", "desc": "

    Node provides a tri-directional popen(3) facility through the\nchild_process module.\n\n

    \n

    It is possible to stream data through a child's stdin, stdout, and\nstderr in a fully non-blocking way. (Note that some programs use\nline-buffered I/O internally. That doesn't affect node.js but it means\ndata you send to the child process is not immediately consumed.)\n\n

    \n

    To create a child process use require('child_process').spawn() or\nrequire('child_process').fork(). The semantics of each are slightly\ndifferent, and explained below.\n\n

    \n", "classes": [ { "textRaw": "Class: ChildProcess", "type": "class", "name": "ChildProcess", "desc": "

    ChildProcess is an [EventEmitter][].\n\n

    \n

    Child processes always have three streams associated with them. child.stdin,\nchild.stdout, and child.stderr. These may be shared with the stdio\nstreams of the parent process, or they may be separate stream objects\nwhich can be piped to and from.\n\n

    \n

    The ChildProcess class is not intended to be used directly. Use the\nspawn() or fork() methods to create a Child Process instance.\n\n

    \n", "events": [ { "textRaw": "Event: 'error'", "type": "event", "name": "error", "params": [], "desc": "

    Emitted when:\n\n

    \n
      \n
    1. The process could not be spawned, or
    2. \n
    3. The process could not be killed, or
    4. \n
    5. Sending a message to the child process failed for whatever reason.
    6. \n
    \n

    Note that the exit-event may or may not fire after an error has occured. If\nyou are listening on both events to fire a function, remember to guard against\ncalling your function twice.\n\n

    \n

    See also ChildProcess#kill() and\nChildProcess#send().\n\n

    \n" }, { "textRaw": "Event: 'exit'", "type": "event", "name": "exit", "params": [], "desc": "

    This event is emitted after the child process ends. If the process terminated\nnormally, code is the final exit code of the process, otherwise null. If\nthe process terminated due to receipt of a signal, signal is the string name\nof the signal, otherwise null.\n\n

    \n

    Note that the child process stdio streams might still be open.\n\n

    \n

    Also, note that node establishes signal handlers for 'SIGINT' and 'SIGTERM',\nso it will not terminate due to receipt of those signals, it will exit.\n\n

    \n

    See waitpid(2).\n\n

    \n" }, { "textRaw": "Event: 'close'", "type": "event", "name": "close", "params": [], "desc": "

    This event is emitted when the stdio streams of a child process have all\nterminated. This is distinct from 'exit', since multiple processes\nmight share the same stdio streams.\n\n

    \n" }, { "textRaw": "Event: 'disconnect'", "type": "event", "name": "disconnect", "desc": "

    This event is emitted after calling the .disconnect() method in the parent\nor in the child. After disconnecting it is no longer possible to send messages,\nand the .connected property is false.\n\n

    \n", "params": [] }, { "textRaw": "Event: 'message'", "type": "event", "name": "message", "params": [], "desc": "

    Messages send by .send(message, [sendHandle]) are obtained using the\nmessage event.\n\n

    \n" } ], "properties": [ { "textRaw": "`stdin` {Stream object} ", "name": "stdin", "desc": "

    A Writable Stream that represents the child process's stdin.\nClosing this stream via end() often causes the child process to terminate.\n\n

    \n

    If the child stdio streams are shared with the parent, then this will\nnot be set.\n\n

    \n" }, { "textRaw": "`stdout` {Stream object} ", "name": "stdout", "desc": "

    A Readable Stream that represents the child process's stdout.\n\n

    \n

    If the child stdio streams are shared with the parent, then this will\nnot be set.\n\n

    \n" }, { "textRaw": "`stderr` {Stream object} ", "name": "stderr", "desc": "

    A Readable Stream that represents the child process's stderr.\n\n

    \n

    If the child stdio streams are shared with the parent, then this will\nnot be set.\n\n

    \n" }, { "textRaw": "`pid` {Integer} ", "name": "pid", "desc": "

    The PID of the child process.\n\n

    \n

    Example:\n\n

    \n
    var spawn = require('child_process').spawn,\n    grep  = spawn('grep', ['ssh']);\n\nconsole.log('Spawned child pid: ' + grep.pid);\ngrep.stdin.end();
    \n" }, { "textRaw": "`connected` {Boolean} Set to false after `.disconnect' is called ", "name": "connected", "desc": "

    If .connected is false, it is no longer possible to send messages.\n\n

    \n", "shortDesc": "Set to false after `.disconnect' is called" } ], "methods": [ { "textRaw": "child.kill([signal])", "type": "method", "name": "kill", "signatures": [ { "params": [ { "textRaw": "`signal` {String} ", "name": "signal", "type": "String", "optional": true } ] }, { "params": [ { "name": "signal", "optional": true } ] } ], "desc": "

    Send a signal to the child process. If no argument is given, the process will\nbe sent 'SIGTERM'. See signal(7) for a list of available signals.\n\n

    \n
    var spawn = require('child_process').spawn,\n    grep  = spawn('grep', ['ssh']);\n\ngrep.on('close', function (code, signal) {\n  console.log('child process terminated due to receipt of signal '+signal);\n});\n\n// send SIGHUP to process\ngrep.kill('SIGHUP');
    \n

    May emit an 'error' event when the signal cannot be delivered. Sending a\nsignal to a child process that has already exited is not an error but may\nhave unforeseen consequences: if the PID (the process ID) has been reassigned\nto another process, the signal will be delivered to that process instead.\nWhat happens next is anyone's guess.\n\n

    \n

    Note that while the function is called kill, the signal delivered to the\nchild process may not actually kill it. kill really just sends a signal\nto a process.\n\n

    \n

    See kill(2)\n\n

    \n" }, { "textRaw": "child.send(message, [sendHandle])", "type": "method", "name": "send", "signatures": [ { "params": [ { "textRaw": "`message` {Object} ", "name": "message", "type": "Object" }, { "textRaw": "`sendHandle` {Handle object} ", "name": "sendHandle", "type": "Handle object", "optional": true } ] }, { "params": [ { "name": "message" }, { "name": "sendHandle", "optional": true } ] } ], "desc": "

    When using child_process.fork() you can write to the child using\nchild.send(message, [sendHandle]) and messages are received by\na 'message' event on the child.\n\n

    \n

    For example:\n\n

    \n
    var cp = require('child_process');\n\nvar n = cp.fork(__dirname + '/sub.js');\n\nn.on('message', function(m) {\n  console.log('PARENT got message:', m);\n});\n\nn.send({ hello: 'world' });
    \n

    And then the child script, 'sub.js' might look like this:\n\n

    \n
    process.on('message', function(m) {\n  console.log('CHILD got message:', m);\n});\n\nprocess.send({ foo: 'bar' });
    \n

    In the child the process object will have a send() method, and process\nwill emit objects each time it receives a message on its channel.\n\n

    \n

    Please note that the send() method on both the parent and child are\nsynchronous - sending large chunks of data is not advised (pipes can be used\ninstead, see\nchild_process.spawn).\n\n

    \n

    There is a special case when sending a {cmd: 'NODE_foo'} message. All messages\ncontaining a NODE_ prefix in its cmd property will not be emitted in\nthe message event, since they are internal messages used by node core.\nMessages containing the prefix are emitted in the internalMessage event, you\nshould by all means avoid using this feature, it is subject to change without notice.\n\n

    \n

    The sendHandle option to child.send() is for sending a TCP server or\nsocket object to another process. The child will receive the object as its\nsecond argument to the message event.\n\n

    \n

    Emits an 'error' event if the message cannot be sent, for example because\nthe child process has already exited.\n\n

    \n

    Example: sending server object

    \n

    Here is an example of sending a server:\n\n

    \n
    var child = require('child_process').fork('child.js');\n\n// Open up the server object and send the handle.\nvar server = require('net').createServer();\nserver.on('connection', function (socket) {\n  socket.end('handled by parent');\n});\nserver.listen(1337, function() {\n  child.send('server', server);\n});
    \n

    And the child would the receive the server object as:\n\n

    \n
    process.on('message', function(m, server) {\n  if (m === 'server') {\n    server.on('connection', function (socket) {\n      socket.end('handled by child');\n    });\n  }\n});
    \n

    Note that the server is now shared between the parent and child, this means\nthat some connections will be handled by the parent and some by the child.\n\n

    \n

    For dgram servers the workflow is exactly the same. Here you listen on\na message event instead of connection and use server.bind instead of\nserver.listen. (Currently only supported on UNIX platforms.)\n\n

    \n

    Example: sending socket object

    \n

    Here is an example of sending a socket. It will spawn two children and handle\nconnections with the remote address 74.125.127.100 as VIP by sending the\nsocket to a "special" child process. Other sockets will go to a "normal" process.\n\n

    \n
    var normal = require('child_process').fork('child.js', ['normal']);\nvar special = require('child_process').fork('child.js', ['special']);\n\n// Open up the server and send sockets to child\nvar server = require('net').createServer();\nserver.on('connection', function (socket) {\n\n  // if this is a VIP\n  if (socket.remoteAddress === '74.125.127.100') {\n    special.send('socket', socket);\n    return;\n  }\n  // just the usual dudes\n  normal.send('socket', socket);\n});\nserver.listen(1337);
    \n

    The child.js could look like this:\n\n

    \n
    process.on('message', function(m, socket) {\n  if (m === 'socket') {\n    socket.end('You were handled as a ' + process.argv[2] + ' person');\n  }\n});
    \n

    Note that once a single socket has been sent to a child the parent can no\nlonger keep track of when the socket is destroyed. To indicate this condition\nthe .connections property becomes null.\nIt is also recommended not to use .maxConnections in this condition.\n\n

    \n" }, { "textRaw": "child.disconnect()", "type": "method", "name": "disconnect", "desc": "

    Close the IPC channel between parent and child, allowing the child to exit\ngracefully once there are no other connections keeping it alive. After calling\nthis method the .connected flag will be set to false in both the parent and\nchild, and it is no longer possible to send messages.\n\n

    \n

    The 'disconnect' event will be emitted when there are no messages in the process\nof being received, most likely immediately.\n\n

    \n

    Note that you can also call process.disconnect() in the child process.\n\n

    \n", "signatures": [ { "params": [] } ] } ] } ], "methods": [ { "textRaw": "child_process.spawn(command, [args], [options])", "type": "method", "name": "spawn", "signatures": [ { "return": { "textRaw": "return: {ChildProcess object} ", "name": "return", "type": "ChildProcess object" }, "params": [ { "textRaw": "`command` {String} The command to run ", "name": "command", "type": "String", "desc": "The command to run" }, { "textRaw": "`args` {Array} List of string arguments ", "name": "args", "type": "Array", "desc": "List of string arguments", "optional": true }, { "textRaw": "`options` {Object} ", "options": [ { "textRaw": "`cwd` {String} Current working directory of the child process ", "name": "cwd", "type": "String", "desc": "Current working directory of the child process" }, { "textRaw": "`stdio` {Array|String} Child's stdio configuration. (See below) ", "name": "stdio", "type": "Array|String", "desc": "Child's stdio configuration. (See below)" }, { "textRaw": "`customFds` {Array} **Deprecated** File descriptors for the child to use for stdio. (See below) ", "name": "customFds", "type": "Array", "desc": "**Deprecated** File descriptors for the child to use for stdio. (See below)" }, { "textRaw": "`env` {Object} Environment key-value pairs ", "name": "env", "type": "Object", "desc": "Environment key-value pairs" }, { "textRaw": "`detached` {Boolean} The child will be a process group leader. (See below) ", "name": "detached", "type": "Boolean", "desc": "The child will be a process group leader. (See below)" }, { "textRaw": "`uid` {Number} Sets the user identity of the process. (See setuid(2).) ", "name": "uid", "type": "Number", "desc": "Sets the user identity of the process. (See setuid(2).)" }, { "textRaw": "`gid` {Number} Sets the group identity of the process. (See setgid(2).) ", "name": "gid", "type": "Number", "desc": "Sets the group identity of the process. (See setgid(2).)" } ], "name": "options", "type": "Object", "optional": true } ] }, { "params": [ { "name": "command" }, { "name": "args", "optional": true }, { "name": "options", "optional": true } ] } ], "desc": "

    Launches a new process with the given command, with command line arguments in args.\nIf omitted, args defaults to an empty Array.\n\n

    \n

    The third argument is used to specify additional options, which defaults to:\n\n

    \n
    { cwd: undefined,\n  env: process.env\n}
    \n

    cwd allows you to specify the working directory from which the process is spawned.\nUse env to specify environment variables that will be visible to the new process.\n\n

    \n

    Example of running ls -lh /usr, capturing stdout, stderr, and the exit code:\n\n

    \n
    var spawn = require('child_process').spawn,\n    ls    = spawn('ls', ['-lh', '/usr']);\n\nls.stdout.on('data', function (data) {\n  console.log('stdout: ' + data);\n});\n\nls.stderr.on('data', function (data) {\n  console.log('stderr: ' + data);\n});\n\nls.on('close', function (code) {\n  console.log('child process exited with code ' + code);\n});
    \n

    Example: A very elaborate way to run 'ps ax | grep ssh'\n\n

    \n
    var spawn = require('child_process').spawn,\n    ps    = spawn('ps', ['ax']),\n    grep  = spawn('grep', ['ssh']);\n\nps.stdout.on('data', function (data) {\n  grep.stdin.write(data);\n});\n\nps.stderr.on('data', function (data) {\n  console.log('ps stderr: ' + data);\n});\n\nps.on('close', function (code) {\n  if (code !== 0) {\n    console.log('ps process exited with code ' + code);\n  }\n  grep.stdin.end();\n});\n\ngrep.stdout.on('data', function (data) {\n  console.log('' + data);\n});\n\ngrep.stderr.on('data', function (data) {\n  console.log('grep stderr: ' + data);\n});\n\ngrep.on('close', function (code) {\n  if (code !== 0) {\n    console.log('grep process exited with code ' + code);\n  }\n});
    \n

    Example of checking for failed exec:\n\n

    \n
    var spawn = require('child_process').spawn,\n    child = spawn('bad_command');\n\nchild.stderr.setEncoding('utf8');\nchild.stderr.on('data', function (data) {\n  if (/^execvp\\(\\)/.test(data)) {\n    console.log('Failed to start child process.');\n  }\n});
    \n

    Note that if spawn receives an empty options object, it will result in\nspawning the process with an empty environment rather than using\nprocess.env. This due to backwards compatibility issues with a deprecated\nAPI.\n\n

    \n

    The 'stdio' option to child_process.spawn() is an array where each\nindex corresponds to a fd in the child. The value is one of the following:\n\n

    \n
      \n
    1. 'pipe' - Create a pipe between the child process and the parent process.\nThe parent end of the pipe is exposed to the parent as a property on the\nchild_process object as ChildProcess.stdio[fd]. Pipes created for\nfds 0 - 2 are also available as ChildProcess.stdin, ChildProcess.stdout\nand ChildProcess.stderr, respectively.
    2. \n
    3. 'ipc' - Create an IPC channel for passing messages/file descriptors\nbetween parent and child. A ChildProcess may have at most one IPC stdio\nfile descriptor. Setting this option enables the ChildProcess.send() method.\nIf the child writes JSON messages to this file descriptor, then this will\ntrigger ChildProcess.on('message'). If the child is a Node.js program, then\nthe presence of an IPC channel will enable process.send() and\nprocess.on('message').
    4. \n
    5. 'ignore' - Do not set this file descriptor in the child. Note that Node\nwill always open fd 0 - 2 for the processes it spawns. When any of these is\nignored node will open /dev/null and attach it to the child's fd.
    6. \n
    7. Stream object - Share a readable or writable stream that refers to a tty,\nfile, socket, or a pipe with the child process. The stream's underlying\nfile descriptor is duplicated in the child process to the fd that \ncorresponds to the index in the stdio array. Note that the stream must\nhave an underlying descriptor (file streams do not until the 'open'\nevent has occurred).
    8. \n
    9. Positive integer - The integer value is interpreted as a file descriptor \nthat is is currently open in the parent process. It is shared with the child\nprocess, similar to how Stream objects can be shared.
    10. \n
    11. null, undefined - Use default value. For stdio fds 0, 1 and 2 (in other\nwords, stdin, stdout, and stderr) a pipe is created. For fd 3 and up, the\ndefault is 'ignore'.
    12. \n
    \n

    As a shorthand, the stdio argument may also be one of the following\nstrings, rather than an array:\n\n

    \n
      \n
    • ignore - ['ignore', 'ignore', 'ignore']
    • \n
    • pipe - ['pipe', 'pipe', 'pipe']
    • \n
    • inherit - [process.stdin, process.stdout, process.stderr] or [0,1,2]
    • \n
    \n

    Example:\n\n

    \n
    var spawn = require('child_process').spawn;\n\n// Child will use parent's stdios\nspawn('prg', [], { stdio: 'inherit' });\n\n// Spawn child sharing only stderr\nspawn('prg', [], { stdio: ['pipe', 'pipe', process.stderr] });\n\n// Open an extra fd=4, to interact with programs present a\n// startd-style interface.\nspawn('prg', [], { stdio: ['pipe', null, null, null, 'pipe'] });
    \n

    If the detached option is set, the child process will be made the leader of a\nnew process group. This makes it possible for the child to continue running \nafter the parent exits.\n\n

    \n

    By default, the parent will wait for the detached child to exit. To prevent\nthe parent from waiting for a given child, use the child.unref() method,\nand the parent's event loop will not include the child in its reference count.\n\n

    \n

    Example of detaching a long-running process and redirecting its output to a\nfile:\n\n

    \n
     var fs = require('fs'),\n     spawn = require('child_process').spawn,\n     out = fs.openSync('./out.log', 'a'),\n     err = fs.openSync('./out.log', 'a');\n\n var child = spawn('prg', [], {\n   detached: true,\n   stdio: [ 'ignore', out, err ]\n });\n\n child.unref();
    \n

    When using the detached option to start a long-running process, the process\nwill not stay running in the background unless it is provided with a stdio\nconfiguration that is not connected to the parent. If the parent's stdio is\ninherited, the child will remain attached to the controlling terminal.\n\n

    \n

    There is a deprecated option called customFds which allows one to specify\nspecific file descriptors for the stdio of the child process. This API was\nnot portable to all platforms and therefore removed.\nWith customFds it was possible to hook up the new process' [stdin, stdout,\nstderr] to existing streams; -1 meant that a new stream should be created.\nUse at your own risk.\n\n

    \n

    See also: child_process.exec() and child_process.fork()\n\n

    \n" }, { "textRaw": "child_process.exec(command, [options], callback)", "type": "method", "name": "exec", "signatures": [ { "return": { "textRaw": "Return: ChildProcess object ", "name": "return", "desc": "ChildProcess object" }, "params": [ { "textRaw": "`command` {String} The command to run, with space-separated arguments ", "name": "command", "type": "String", "desc": "The command to run, with space-separated arguments" }, { "textRaw": "`options` {Object} ", "options": [ { "textRaw": "`cwd` {String} Current working directory of the child process ", "name": "cwd", "type": "String", "desc": "Current working directory of the child process" }, { "textRaw": "`env` {Object} Environment key-value pairs ", "name": "env", "type": "Object", "desc": "Environment key-value pairs" }, { "textRaw": "`encoding` {String} (Default: 'utf8') ", "name": "encoding", "default": "utf8", "type": "String" }, { "textRaw": "`timeout` {Number} (Default: 0) ", "name": "timeout", "default": "0", "type": "Number" }, { "textRaw": "`maxBuffer` {Number} (Default: `200*1024`) ", "name": "maxBuffer", "default": "200*1024", "type": "Number" }, { "textRaw": "`killSignal` {String} (Default: 'SIGTERM') ", "name": "killSignal", "default": "SIGTERM", "type": "String" } ], "name": "options", "type": "Object", "optional": true }, { "textRaw": "`callback` {Function} called with the output when process terminates ", "options": [ { "textRaw": "`error` {Error} ", "name": "error", "type": "Error" }, { "textRaw": "`stdout` {Buffer} ", "name": "stdout", "type": "Buffer" }, { "textRaw": "`stderr` {Buffer} ", "name": "stderr", "type": "Buffer" } ], "name": "callback", "type": "Function", "desc": "called with the output when process terminates" } ] }, { "params": [ { "name": "command" }, { "name": "options", "optional": true }, { "name": "callback" } ] } ], "desc": "

    Runs a command in a shell and buffers the output.\n\n

    \n
    var exec = require('child_process').exec,\n    child;\n\nchild = exec('cat *.js bad_file | wc -l',\n  function (error, stdout, stderr) {\n    console.log('stdout: ' + stdout);\n    console.log('stderr: ' + stderr);\n    if (error !== null) {\n      console.log('exec error: ' + error);\n    }\n});
    \n

    The callback gets the arguments (error, stdout, stderr). On success, error\nwill be null. On error, error will be an instance of Error and err.code\nwill be the exit code of the child process, and err.signal will be set to the\nsignal that terminated the process.\n\n

    \n

    There is a second optional argument to specify several options. The\ndefault options are\n\n

    \n
    { encoding: 'utf8',\n  timeout: 0,\n  maxBuffer: 200*1024,\n  killSignal: 'SIGTERM',\n  cwd: null,\n  env: null }
    \n

    If timeout is greater than 0, then it will kill the child process\nif it runs longer than timeout milliseconds. The child process is killed with\nkillSignal (default: 'SIGTERM'). maxBuffer specifies the largest\namount of data allowed on stdout or stderr - if this value is exceeded then\nthe child process is killed.\n\n\n

    \n" }, { "textRaw": "child_process.execFile(file, [args], [options], [callback])", "type": "method", "name": "execFile", "signatures": [ { "return": { "textRaw": "Return: ChildProcess object ", "name": "return", "desc": "ChildProcess object" }, "params": [ { "textRaw": "`file` {String} The filename of the program to run ", "name": "file", "type": "String", "desc": "The filename of the program to run" }, { "textRaw": "`args` {Array} List of string arguments ", "name": "args", "type": "Array", "desc": "List of string arguments", "optional": true }, { "textRaw": "`options` {Object} ", "options": [ { "textRaw": "`cwd` {String} Current working directory of the child process ", "name": "cwd", "type": "String", "desc": "Current working directory of the child process" }, { "textRaw": "`env` {Object} Environment key-value pairs ", "name": "env", "type": "Object", "desc": "Environment key-value pairs" }, { "textRaw": "`encoding` {String} (Default: 'utf8') ", "name": "encoding", "default": "utf8", "type": "String" }, { "textRaw": "`timeout` {Number} (Default: 0) ", "name": "timeout", "default": "0", "type": "Number" }, { "textRaw": "`maxBuffer` {Number} (Default: 200\\*1024) ", "name": "maxBuffer", "default": "200\\*1024", "type": "Number" }, { "textRaw": "`killSignal` {String} (Default: 'SIGTERM') ", "name": "killSignal", "default": "SIGTERM", "type": "String" } ], "name": "options", "type": "Object", "optional": true }, { "textRaw": "`callback` {Function} called with the output when process terminates ", "options": [ { "textRaw": "`error` {Error} ", "name": "error", "type": "Error" }, { "textRaw": "`stdout` {Buffer} ", "name": "stdout", "type": "Buffer" }, { "textRaw": "`stderr` {Buffer} ", "name": "stderr", "type": "Buffer" } ], "name": "callback", "type": "Function", "desc": "called with the output when process terminates", "optional": true } ] }, { "params": [ { "name": "file" }, { "name": "args", "optional": true }, { "name": "options", "optional": true }, { "name": "callback", "optional": true } ] } ], "desc": "

    This is similar to child_process.exec() except it does not execute a\nsubshell but rather the specified file directly. This makes it slightly\nleaner than child_process.exec. It has the same options.\n\n\n

    \n" }, { "textRaw": "child_process.fork(modulePath, [args], [options])", "type": "method", "name": "fork", "signatures": [ { "return": { "textRaw": "Return: ChildProcess object ", "name": "return", "desc": "ChildProcess object" }, "params": [ { "textRaw": "`modulePath` {String} The module to run in the child ", "name": "modulePath", "type": "String", "desc": "The module to run in the child" }, { "textRaw": "`args` {Array} List of string arguments ", "name": "args", "type": "Array", "desc": "List of string arguments", "optional": true }, { "textRaw": "`options` {Object} ", "options": [ { "textRaw": "`cwd` {String} Current working directory of the child process ", "name": "cwd", "type": "String", "desc": "Current working directory of the child process" }, { "textRaw": "`env` {Object} Environment key-value pairs ", "name": "env", "type": "Object", "desc": "Environment key-value pairs" }, { "textRaw": "`encoding` {String} (Default: 'utf8') ", "name": "encoding", "default": "utf8", "type": "String" }, { "textRaw": "`execPath` {String} Executable used to create the child process ", "name": "execPath", "type": "String", "desc": "Executable used to create the child process" }, { "textRaw": "`execArgv` {Array} List of string arguments passed to the executable (Default: `process.execArgv`) ", "name": "execArgv", "default": "process.execArgv", "type": "Array", "desc": "List of string arguments passed to the executable" }, { "textRaw": "`silent` {Boolean} If true, stdin, stdout, and stderr of the child will be piped to the parent, otherwise they will be inherited from the parent, see the \"pipe\" and \"inherit\" options for `spawn()`'s `stdio` for more details (default is false) ", "name": "silent", "type": "Boolean", "desc": "If true, stdin, stdout, and stderr of the child will be piped to the parent, otherwise they will be inherited from the parent, see the \"pipe\" and \"inherit\" options for `spawn()`'s `stdio` for more details (default is false)" } ], "name": "options", "type": "Object", "optional": true } ] }, { "params": [ { "name": "modulePath" }, { "name": "args", "optional": true }, { "name": "options", "optional": true } ] } ], "desc": "

    This is a special case of the spawn() functionality for spawning Node\nprocesses. In addition to having all the methods in a normal ChildProcess\ninstance, the returned object has a communication channel built-in. See\nchild.send(message, [sendHandle]) for details.\n\n

    \n

    These child Nodes are still whole new instances of V8. Assume at least 30ms\nstartup and 10mb memory for each new Node. That is, you cannot create many\nthousands of them.\n\n

    \n

    The execPath property in the options object allows for a process to be\ncreated for the child rather than the current node executable. This should be\ndone with care and by default will talk over the fd represented an\nenvironmental variable NODE_CHANNEL_FD on the child process. The input and\noutput on this fd is expected to be line delimited JSON objects.\n\n

    \n" } ], "type": "module", "displayName": "Child Process" }, { "textRaw": "Assert", "name": "assert", "stability": 5, "stabilityText": "Locked", "desc": "

    This module is used for writing unit tests for your applications, you can\naccess it with require('assert').\n\n

    \n", "methods": [ { "textRaw": "assert.fail(actual, expected, message, operator)", "type": "method", "name": "fail", "desc": "

    Throws an exception that displays the values for actual and expected separated by the provided operator.\n\n

    \n", "signatures": [ { "params": [ { "name": "actual" }, { "name": "expected" }, { "name": "message" }, { "name": "operator" } ] } ] }, { "textRaw": "assert(value, message), assert.ok(value, [message])", "type": "method", "name": "ok", "desc": "

    Tests if value is truthy, it is equivalent to assert.equal(true, !!value, message);\n\n

    \n", "signatures": [ { "params": [ { "name": "value" }, { "name": "message)" }, { "name": "assert.ok(value" }, { "name": "message", "optional": true } ] } ] }, { "textRaw": "assert.equal(actual, expected, [message])", "type": "method", "name": "equal", "desc": "

    Tests shallow, coercive equality with the equal comparison operator ( == ).\n\n

    \n", "signatures": [ { "params": [ { "name": "actual" }, { "name": "expected" }, { "name": "message", "optional": true } ] } ] }, { "textRaw": "assert.notEqual(actual, expected, [message])", "type": "method", "name": "notEqual", "desc": "

    Tests shallow, coercive non-equality with the not equal comparison operator ( != ).\n\n

    \n", "signatures": [ { "params": [ { "name": "actual" }, { "name": "expected" }, { "name": "message", "optional": true } ] } ] }, { "textRaw": "assert.deepEqual(actual, expected, [message])", "type": "method", "name": "deepEqual", "desc": "

    Tests for deep equality.\n\n

    \n", "signatures": [ { "params": [ { "name": "actual" }, { "name": "expected" }, { "name": "message", "optional": true } ] } ] }, { "textRaw": "assert.notDeepEqual(actual, expected, [message])", "type": "method", "name": "notDeepEqual", "desc": "

    Tests for any deep inequality.\n\n

    \n", "signatures": [ { "params": [ { "name": "actual" }, { "name": "expected" }, { "name": "message", "optional": true } ] } ] }, { "textRaw": "assert.strictEqual(actual, expected, [message])", "type": "method", "name": "strictEqual", "desc": "

    Tests strict equality, as determined by the strict equality operator ( === )\n\n

    \n", "signatures": [ { "params": [ { "name": "actual" }, { "name": "expected" }, { "name": "message", "optional": true } ] } ] }, { "textRaw": "assert.notStrictEqual(actual, expected, [message])", "type": "method", "name": "notStrictEqual", "desc": "

    Tests strict non-equality, as determined by the strict not equal operator ( !== )\n\n

    \n", "signatures": [ { "params": [ { "name": "actual" }, { "name": "expected" }, { "name": "message", "optional": true } ] } ] }, { "textRaw": "assert.throws(block, [error], [message])", "type": "method", "name": "throws", "desc": "

    Expects block to throw an error. error can be constructor, regexp or \nvalidation function.\n\n

    \n

    Validate instanceof using constructor:\n\n

    \n
    assert.throws(\n  function() {\n    throw new Error("Wrong value");\n  },\n  Error\n);
    \n

    Validate error message using RegExp:\n\n

    \n
    assert.throws(\n  function() {\n    throw new Error("Wrong value");\n  },\n  /value/\n);
    \n

    Custom error validation:\n\n

    \n
    assert.throws(\n  function() {\n    throw new Error("Wrong value");\n  },\n  function(err) {\n    if ( (err instanceof Error) && /value/.test(err) ) {\n      return true;\n    }\n  },\n  "unexpected error"\n);
    \n", "signatures": [ { "params": [ { "name": "block" }, { "name": "error", "optional": true }, { "name": "message", "optional": true } ] } ] }, { "textRaw": "assert.doesNotThrow(block, [message])", "type": "method", "name": "doesNotThrow", "desc": "

    Expects block not to throw an error, see assert.throws for details.\n\n

    \n", "signatures": [ { "params": [ { "name": "block" }, { "name": "message", "optional": true } ] } ] }, { "textRaw": "assert.ifError(value)", "type": "method", "name": "ifError", "desc": "

    Tests if value is not a false value, throws if it is a true value. Useful when\ntesting the first argument, error in callbacks.\n\n

    \n", "signatures": [ { "params": [ { "name": "value" } ] } ] } ], "type": "module", "displayName": "Assert" }, { "textRaw": "TTY", "name": "tty", "stability": 2, "stabilityText": "Unstable", "desc": "

    The tty module houses the tty.ReadStream and tty.WriteStream classes. In\nmost cases, you will not need to use this module directly.\n\n

    \n

    When node detects that it is being run inside a TTY context, then process.stdin\nwill be a tty.ReadStream instance and process.stdout will be\na tty.WriteStream instance. The preferred way to check if node is being run in\na TTY context is to check process.stdout.isTTY:\n\n

    \n
    $ node -p -e "Boolean(process.stdout.isTTY)"\ntrue\n$ node -p -e "Boolean(process.stdout.isTTY)" | cat\nfalse
    \n", "methods": [ { "textRaw": "tty.isatty(fd)", "type": "method", "name": "isatty", "desc": "

    Returns true or false depending on if the fd is associated with a\nterminal.\n\n\n

    \n", "signatures": [ { "params": [ { "name": "fd" } ] } ] }, { "textRaw": "tty.setRawMode(mode)", "type": "method", "name": "setRawMode", "desc": "

    Deprecated. Use tty.ReadStream#setRawMode()\n(i.e. process.stdin.setRawMode()) instead.\n\n\n

    \n", "signatures": [ { "params": [ { "name": "mode" } ] } ] } ], "classes": [ { "textRaw": "Class: ReadStream", "type": "class", "name": "ReadStream", "desc": "

    A net.Socket subclass that represents the readable portion of a tty. In normal\ncircumstances, process.stdin will be the only tty.ReadStream instance in any\nnode program (only when isatty(0) is true).\n\n

    \n", "properties": [ { "textRaw": "rs.isRaw", "name": "isRaw", "desc": "

    A Boolean that is initialized to false. It represents the current "raw" state\nof the tty.ReadStream instance.\n\n

    \n" } ], "methods": [ { "textRaw": "rs.setRawMode(mode)", "type": "method", "name": "setRawMode", "desc": "

    mode should be true or false. This sets the properties of the\ntty.ReadStream to act either as a raw device or default. isRaw will be set\nto the resulting mode.\n\n\n

    \n", "signatures": [ { "params": [ { "name": "mode" } ] } ] } ] }, { "textRaw": "Class: WriteStream", "type": "class", "name": "WriteStream", "desc": "

    A net.Socket subclass that represents the writable portion of a tty. In normal\ncircumstances, process.stdout will be the only tty.WriteStream instance\never created (and only when isatty(1) is true).\n\n

    \n", "properties": [ { "textRaw": "ws.columns", "name": "columns", "desc": "

    A Number that gives the number of columns the TTY currently has. This property\ngets updated on "resize" events.\n\n

    \n" }, { "textRaw": "ws.rows", "name": "rows", "desc": "

    A Number that gives the number of rows the TTY currently has. This property\ngets updated on "resize" events.\n\n

    \n" } ], "events": [ { "textRaw": "Event: 'resize'", "type": "event", "name": "resize", "desc": "

    function () {}\n\n

    \n

    Emitted by refreshSize() when either of the columns or rows properties\nhas changed.\n\n

    \n
    process.stdout.on('resize', function() {\n  console.log('screen size has changed!');\n  console.log(process.stdout.columns + 'x' + process.stdout.rows);\n});
    \n", "params": [] } ] } ], "type": "module", "displayName": "TTY" }, { "textRaw": "Zlib", "name": "zlib", "stability": 3, "stabilityText": "Stable", "desc": "

    You can access this module with:\n\n

    \n
    var zlib = require('zlib');
    \n

    This provides bindings to Gzip/Gunzip, Deflate/Inflate, and\nDeflateRaw/InflateRaw classes. Each class takes the same options, and\nis a readable/writable Stream.\n\n

    \n

    Examples

    \n

    Compressing or decompressing a file can be done by piping an\nfs.ReadStream into a zlib stream, then into an fs.WriteStream.\n\n

    \n
    var gzip = zlib.createGzip();\nvar fs = require('fs');\nvar inp = fs.createReadStream('input.txt');\nvar out = fs.createWriteStream('input.txt.gz');\n\ninp.pipe(gzip).pipe(out);
    \n

    Compressing or decompressing data in one step can be done by using\nthe convenience methods.\n\n

    \n
    var input = '.................................';\nzlib.deflate(input, function(err, buffer) {\n  if (!err) {\n    console.log(buffer.toString('base64'));\n  }\n});\n\nvar buffer = new Buffer('eJzT0yMAAGTvBe8=', 'base64');\nzlib.unzip(buffer, function(err, buffer) {\n  if (!err) {\n    console.log(buffer.toString());\n  }\n});
    \n

    To use this module in an HTTP client or server, use the\naccept-encoding\non requests, and the\ncontent-encoding\nheader on responses.\n\n

    \n

    Note: these examples are drastically simplified to show\nthe basic concept. Zlib encoding can be expensive, and the results\nought to be cached. See Memory Usage Tuning\nbelow for more information on the speed/memory/compression\ntradeoffs involved in zlib usage.\n\n

    \n
    // client request example\nvar zlib = require('zlib');\nvar http = require('http');\nvar fs = require('fs');\nvar request = http.get({ host: 'izs.me',\n                         path: '/',\n                         port: 80,\n                         headers: { 'accept-encoding': 'gzip,deflate' } });\nrequest.on('response', function(response) {\n  var output = fs.createWriteStream('izs.me_index.html');\n\n  switch (response.headers['content-encoding']) {\n    // or, just use zlib.createUnzip() to handle both cases\n    case 'gzip':\n      response.pipe(zlib.createGunzip()).pipe(output);\n      break;\n    case 'deflate':\n      response.pipe(zlib.createInflate()).pipe(output);\n      break;\n    default:\n      response.pipe(output);\n      break;\n  }\n});\n\n// server example\n// Running a gzip operation on every request is quite expensive.\n// It would be much more efficient to cache the compressed buffer.\nvar zlib = require('zlib');\nvar http = require('http');\nvar fs = require('fs');\nhttp.createServer(function(request, response) {\n  var raw = fs.createReadStream('index.html');\n  var acceptEncoding = request.headers['accept-encoding'];\n  if (!acceptEncoding) {\n    acceptEncoding = '';\n  }\n\n  // Note: this is not a conformant accept-encoding parser.\n  // See http://www.w3.org/Protocols/rfc2616/rfc2616-sec14.html#sec14.3\n  if (acceptEncoding.match(/\\bdeflate\\b/)) {\n    response.writeHead(200, { 'content-encoding': 'deflate' });\n    raw.pipe(zlib.createDeflate()).pipe(response);\n  } else if (acceptEncoding.match(/\\bgzip\\b/)) {\n    response.writeHead(200, { 'content-encoding': 'gzip' });\n    raw.pipe(zlib.createGzip()).pipe(response);\n  } else {\n    response.writeHead(200, {});\n    raw.pipe(response);\n  }\n}).listen(1337);
    \n", "methods": [ { "textRaw": "zlib.createGzip([options])", "type": "method", "name": "createGzip", "desc": "

    Returns a new Gzip object with an\noptions.\n\n

    \n", "signatures": [ { "params": [ { "name": "options", "optional": true } ] } ] }, { "textRaw": "zlib.createGunzip([options])", "type": "method", "name": "createGunzip", "desc": "

    Returns a new Gunzip object with an\noptions.\n\n

    \n", "signatures": [ { "params": [ { "name": "options", "optional": true } ] } ] }, { "textRaw": "zlib.createDeflate([options])", "type": "method", "name": "createDeflate", "desc": "

    Returns a new Deflate object with an\noptions.\n\n

    \n", "signatures": [ { "params": [ { "name": "options", "optional": true } ] } ] }, { "textRaw": "zlib.createInflate([options])", "type": "method", "name": "createInflate", "desc": "

    Returns a new Inflate object with an\noptions.\n\n

    \n", "signatures": [ { "params": [ { "name": "options", "optional": true } ] } ] }, { "textRaw": "zlib.createDeflateRaw([options])", "type": "method", "name": "createDeflateRaw", "desc": "

    Returns a new DeflateRaw object with an\noptions.\n\n

    \n", "signatures": [ { "params": [ { "name": "options", "optional": true } ] } ] }, { "textRaw": "zlib.createInflateRaw([options])", "type": "method", "name": "createInflateRaw", "desc": "

    Returns a new InflateRaw object with an\noptions.\n\n

    \n", "signatures": [ { "params": [ { "name": "options", "optional": true } ] } ] }, { "textRaw": "zlib.createUnzip([options])", "type": "method", "name": "createUnzip", "desc": "

    Returns a new Unzip object with an\noptions.\n\n\n

    \n", "signatures": [ { "params": [ { "name": "options", "optional": true } ] } ] }, { "textRaw": "zlib.deflate(buf, callback)", "type": "method", "name": "deflate", "desc": "

    Compress a string with Deflate.\n\n

    \n", "signatures": [ { "params": [ { "name": "buf" }, { "name": "callback" } ] } ] }, { "textRaw": "zlib.deflateRaw(buf, callback)", "type": "method", "name": "deflateRaw", "desc": "

    Compress a string with DeflateRaw.\n\n

    \n", "signatures": [ { "params": [ { "name": "buf" }, { "name": "callback" } ] } ] }, { "textRaw": "zlib.gzip(buf, callback)", "type": "method", "name": "gzip", "desc": "

    Compress a string with Gzip.\n\n

    \n", "signatures": [ { "params": [ { "name": "buf" }, { "name": "callback" } ] } ] }, { "textRaw": "zlib.gunzip(buf, callback)", "type": "method", "name": "gunzip", "desc": "

    Decompress a raw Buffer with Gunzip.\n\n

    \n", "signatures": [ { "params": [ { "name": "buf" }, { "name": "callback" } ] } ] }, { "textRaw": "zlib.inflate(buf, callback)", "type": "method", "name": "inflate", "desc": "

    Decompress a raw Buffer with Inflate.\n\n

    \n", "signatures": [ { "params": [ { "name": "buf" }, { "name": "callback" } ] } ] }, { "textRaw": "zlib.inflateRaw(buf, callback)", "type": "method", "name": "inflateRaw", "desc": "

    Decompress a raw Buffer with InflateRaw.\n\n

    \n", "signatures": [ { "params": [ { "name": "buf" }, { "name": "callback" } ] } ] }, { "textRaw": "zlib.unzip(buf, callback)", "type": "method", "name": "unzip", "desc": "

    Decompress a raw Buffer with Unzip.\n\n

    \n", "signatures": [ { "params": [ { "name": "buf" }, { "name": "callback" } ] } ] } ], "classes": [ { "textRaw": "Class: zlib.Zlib", "type": "class", "name": "zlib.Zlib", "desc": "

    Not exported by the zlib module. It is documented here because it is the base\nclass of the compressor/decompressor classes.\n\n

    \n", "methods": [ { "textRaw": "zlib.flush(callback)", "type": "method", "name": "flush", "desc": "

    Flush pending data. Don't call this frivolously, premature flushes negatively\nimpact the effectiveness of the compression algorithm.\n\n

    \n", "signatures": [ { "params": [ { "name": "callback" } ] } ] }, { "textRaw": "zlib.reset()", "type": "method", "name": "reset", "desc": "

    Reset the compressor/decompressor to factory defaults. Only applicable to\nthe inflate and deflate algorithms.\n\n

    \n", "signatures": [ { "params": [] } ] } ] }, { "textRaw": "Class: zlib.Gzip", "type": "class", "name": "zlib.Gzip", "desc": "

    Compress data using gzip.\n\n

    \n" }, { "textRaw": "Class: zlib.Gunzip", "type": "class", "name": "zlib.Gunzip", "desc": "

    Decompress a gzip stream.\n\n

    \n" }, { "textRaw": "Class: zlib.Deflate", "type": "class", "name": "zlib.Deflate", "desc": "

    Compress data using deflate.\n\n

    \n" }, { "textRaw": "Class: zlib.Inflate", "type": "class", "name": "zlib.Inflate", "desc": "

    Decompress a deflate stream.\n\n

    \n" }, { "textRaw": "Class: zlib.DeflateRaw", "type": "class", "name": "zlib.DeflateRaw", "desc": "

    Compress data using deflate, and do not append a zlib header.\n\n

    \n" }, { "textRaw": "Class: zlib.InflateRaw", "type": "class", "name": "zlib.InflateRaw", "desc": "

    Decompress a raw deflate stream.\n\n

    \n" }, { "textRaw": "Class: zlib.Unzip", "type": "class", "name": "zlib.Unzip", "desc": "

    Decompress either a Gzip- or Deflate-compressed stream by auto-detecting\nthe header.\n\n

    \n" } ], "miscs": [ { "textRaw": "Convenience Methods", "name": "Convenience Methods", "type": "misc", "desc": "

    All of these take a string or buffer as the first argument, and call the\nsupplied callback with callback(error, result). The\ncompression/decompression engine is created using the default settings\nin all convenience methods. To supply different options, use the\nzlib classes directly.\n\n

    \n" }, { "textRaw": "Options", "name": "Options", "type": "misc", "desc": "

    Each class takes an options object. All options are optional. (The\nconvenience methods use the default settings for all options.)\n\n

    \n

    Note that some options are only relevant when compressing, and are\nignored by the decompression classes.\n\n

    \n
      \n
    • flush (default: zlib.Z_NO_FLUSH)
    • \n
    • chunkSize (default: 16*1024)
    • \n
    • windowBits
    • \n
    • level (compression only)
    • \n
    • memLevel (compression only)
    • \n
    • strategy (compression only)
    • \n
    • dictionary (deflate/inflate only, empty dictionary by default)
    • \n
    \n

    See the description of deflateInit2 and inflateInit2 at\n

    \n

    http://zlib.net/manual.html#Advanced for more information on these.\n\n

    \n" }, { "textRaw": "Memory Usage Tuning", "name": "Memory Usage Tuning", "type": "misc", "desc": "

    From zlib/zconf.h, modified to node's usage:\n\n

    \n

    The memory requirements for deflate are (in bytes):\n\n

    \n
    (1 << (windowBits+2)) +  (1 << (memLevel+9))
    \n

    that is: 128K for windowBits=15 + 128K for memLevel = 8\n(default values) plus a few kilobytes for small objects.\n\n

    \n

    For example, if you want to reduce\nthe default memory requirements from 256K to 128K, set the options to:\n\n

    \n
    { windowBits: 14, memLevel: 7 }
    \n

    Of course this will generally degrade compression (there's no free lunch).\n\n

    \n

    The memory requirements for inflate are (in bytes)\n\n

    \n
    1 << windowBits
    \n

    that is, 32K for windowBits=15 (default value) plus a few kilobytes\nfor small objects.\n\n

    \n

    This is in addition to a single internal output slab buffer of size\nchunkSize, which defaults to 16K.\n\n

    \n

    The speed of zlib compression is affected most dramatically by the\nlevel setting. A higher level will result in better compression, but\nwill take longer to complete. A lower level will result in less\ncompression, but will be much faster.\n\n

    \n

    In general, greater memory usage options will mean that node has to make\nfewer calls to zlib, since it'll be able to process more data in a\nsingle write operation. So, this is another factor that affects the\nspeed, at the cost of memory usage.\n\n

    \n" }, { "textRaw": "Constants", "name": "Constants", "type": "misc", "desc": "

    All of the constants defined in zlib.h are also defined on\nrequire('zlib').\nIn the normal course of operations, you will not need to ever set any of\nthese. They are documented here so that their presence is not\nsurprising. This section is taken almost directly from the zlib\ndocumentation. See\n

    \n

    http://zlib.net/manual.html#Constants for more details.\n\n

    \n

    Allowed flush values.\n\n

    \n
      \n
    • zlib.Z_NO_FLUSH
    • \n
    • zlib.Z_PARTIAL_FLUSH
    • \n
    • zlib.Z_SYNC_FLUSH
    • \n
    • zlib.Z_FULL_FLUSH
    • \n
    • zlib.Z_FINISH
    • \n
    • zlib.Z_BLOCK
    • \n
    • zlib.Z_TREES
    • \n
    \n

    Return codes for the compression/decompression functions. Negative\nvalues are errors, positive values are used for special but normal\nevents.\n\n

    \n
      \n
    • zlib.Z_OK
    • \n
    • zlib.Z_STREAM_END
    • \n
    • zlib.Z_NEED_DICT
    • \n
    • zlib.Z_ERRNO
    • \n
    • zlib.Z_STREAM_ERROR
    • \n
    • zlib.Z_DATA_ERROR
    • \n
    • zlib.Z_MEM_ERROR
    • \n
    • zlib.Z_BUF_ERROR
    • \n
    • zlib.Z_VERSION_ERROR
    • \n
    \n

    Compression levels.\n\n

    \n
      \n
    • zlib.Z_NO_COMPRESSION
    • \n
    • zlib.Z_BEST_SPEED
    • \n
    • zlib.Z_BEST_COMPRESSION
    • \n
    • zlib.Z_DEFAULT_COMPRESSION
    • \n
    \n

    Compression strategy.\n\n

    \n
      \n
    • zlib.Z_FILTERED
    • \n
    • zlib.Z_HUFFMAN_ONLY
    • \n
    • zlib.Z_RLE
    • \n
    • zlib.Z_FIXED
    • \n
    • zlib.Z_DEFAULT_STRATEGY
    • \n
    \n

    Possible values of the data_type field.\n\n

    \n
      \n
    • zlib.Z_BINARY
    • \n
    • zlib.Z_TEXT
    • \n
    • zlib.Z_ASCII
    • \n
    • zlib.Z_UNKNOWN
    • \n
    \n

    The deflate compression method (the only one supported in this version).\n\n

    \n
      \n
    • zlib.Z_DEFLATED
    • \n
    \n

    For initializing zalloc, zfree, opaque.\n\n

    \n
      \n
    • zlib.Z_NULL
    • \n
    \n" } ], "type": "module", "displayName": "Zlib" }, { "textRaw": "os", "name": "os", "stability": 4, "stabilityText": "API Frozen", "desc": "

    Provides a few basic operating-system related utility functions.\n\n

    \n

    Use require('os') to access this module.\n\n

    \n", "methods": [ { "textRaw": "os.tmpdir()", "type": "method", "name": "tmpdir", "desc": "

    Returns the operating system's default directory for temp files.\n\n

    \n", "signatures": [ { "params": [] } ] }, { "textRaw": "os.endianness()", "type": "method", "name": "endianness", "desc": "

    Returns the endianness of the CPU. Possible values are "BE" or "LE".\n\n

    \n", "signatures": [ { "params": [] } ] }, { "textRaw": "os.hostname()", "type": "method", "name": "hostname", "desc": "

    Returns the hostname of the operating system.\n\n

    \n", "signatures": [ { "params": [] } ] }, { "textRaw": "os.type()", "type": "method", "name": "type", "desc": "

    Returns the operating system name.\n\n

    \n", "signatures": [ { "params": [] } ] }, { "textRaw": "os.platform()", "type": "method", "name": "platform", "desc": "

    Returns the operating system platform.\n\n

    \n", "signatures": [ { "params": [] } ] }, { "textRaw": "os.arch()", "type": "method", "name": "arch", "desc": "

    Returns the operating system CPU architecture.\n\n

    \n", "signatures": [ { "params": [] } ] }, { "textRaw": "os.release()", "type": "method", "name": "release", "desc": "

    Returns the operating system release.\n\n

    \n", "signatures": [ { "params": [] } ] }, { "textRaw": "os.uptime()", "type": "method", "name": "uptime", "desc": "

    Returns the system uptime in seconds.\n\n

    \n", "signatures": [ { "params": [] } ] }, { "textRaw": "os.loadavg()", "type": "method", "name": "loadavg", "desc": "

    Returns an array containing the 1, 5, and 15 minute load averages.\n\n

    \n

    The load average is a measure of system activity, calculated by the operating\nsystem and expressed as a fractional number. As a rule of thumb, the load\naverage should ideally be less than the number of logical CPUs in the system.\n\n

    \n

    The load average is a very UNIX-y concept; there is no real equivalent on\nWindows platforms. That is why this function always returns [0, 0, 0] on\nWindows.\n\n

    \n", "signatures": [ { "params": [] } ] }, { "textRaw": "os.totalmem()", "type": "method", "name": "totalmem", "desc": "

    Returns the total amount of system memory in bytes.\n\n

    \n", "signatures": [ { "params": [] } ] }, { "textRaw": "os.freemem()", "type": "method", "name": "freemem", "desc": "

    Returns the amount of free system memory in bytes.\n\n

    \n", "signatures": [ { "params": [] } ] }, { "textRaw": "os.cpus()", "type": "method", "name": "cpus", "desc": "

    Returns an array of objects containing information about each CPU/core\ninstalled: model, speed (in MHz), and times (an object containing the number of\nmilliseconds the CPU/core spent in: user, nice, sys, idle, and irq).\n\n

    \n

    Example inspection of os.cpus:\n\n

    \n
    [ { model: 'Intel(R) Core(TM) i7 CPU         860  @ 2.80GHz',\n    speed: 2926,\n    times:\n     { user: 252020,\n       nice: 0,\n       sys: 30340,\n       idle: 1070356870,\n       irq: 0 } },\n  { model: 'Intel(R) Core(TM) i7 CPU         860  @ 2.80GHz',\n    speed: 2926,\n    times:\n     { user: 306960,\n       nice: 0,\n       sys: 26980,\n       idle: 1071569080,\n       irq: 0 } },\n  { model: 'Intel(R) Core(TM) i7 CPU         860  @ 2.80GHz',\n    speed: 2926,\n    times:\n     { user: 248450,\n       nice: 0,\n       sys: 21750,\n       idle: 1070919370,\n       irq: 0 } },\n  { model: 'Intel(R) Core(TM) i7 CPU         860  @ 2.80GHz',\n    speed: 2926,\n    times:\n     { user: 256880,\n       nice: 0,\n       sys: 19430,\n       idle: 1070905480,\n       irq: 20 } },\n  { model: 'Intel(R) Core(TM) i7 CPU         860  @ 2.80GHz',\n    speed: 2926,\n    times:\n     { user: 511580,\n       nice: 20,\n       sys: 40900,\n       idle: 1070842510,\n       irq: 0 } },\n  { model: 'Intel(R) Core(TM) i7 CPU         860  @ 2.80GHz',\n    speed: 2926,\n    times:\n     { user: 291660,\n       nice: 0,\n       sys: 34360,\n       idle: 1070888000,\n       irq: 10 } },\n  { model: 'Intel(R) Core(TM) i7 CPU         860  @ 2.80GHz',\n    speed: 2926,\n    times:\n     { user: 308260,\n       nice: 0,\n       sys: 55410,\n       idle: 1071129970,\n       irq: 880 } },\n  { model: 'Intel(R) Core(TM) i7 CPU         860  @ 2.80GHz',\n    speed: 2926,\n    times:\n     { user: 266450,\n       nice: 1480,\n       sys: 34920,\n       idle: 1072572010,\n       irq: 30 } } ]
    \n", "signatures": [ { "params": [] } ] }, { "textRaw": "os.networkInterfaces()", "type": "method", "name": "networkInterfaces", "desc": "

    Get a list of network interfaces:\n\n

    \n
    { lo0: \n   [ { address: '::1', family: 'IPv6', internal: true },\n     { address: 'fe80::1', family: 'IPv6', internal: true },\n     { address: '127.0.0.1', family: 'IPv4', internal: true } ],\n  en1: \n   [ { address: 'fe80::cabc:c8ff:feef:f996', family: 'IPv6',\n       internal: false },\n     { address: '10.0.1.123', family: 'IPv4', internal: false } ],\n  vmnet1: [ { address: '10.99.99.254', family: 'IPv4', internal: false } ],\n  vmnet8: [ { address: '10.88.88.1', family: 'IPv4', internal: false } ],\n  ppp0: [ { address: '10.2.0.231', family: 'IPv4', internal: false } ] }
    \n", "signatures": [ { "params": [] } ] } ], "properties": [ { "textRaw": "os.EOL", "name": "EOL", "desc": "

    A constant defining the appropriate End-of-line marker for the operating system.\n\n

    \n" } ], "type": "module", "displayName": "os" }, { "textRaw": "Cluster", "name": "cluster", "stability": 1, "stabilityText": "Experimental", "desc": "

    A single instance of Node runs in a single thread. To take advantage of\nmulti-core systems the user will sometimes want to launch a cluster of Node\nprocesses to handle the load.\n\n

    \n

    The cluster module allows you to easily create child processes that\nall share server ports.\n\n

    \n
    var cluster = require('cluster');\nvar http = require('http');\nvar numCPUs = require('os').cpus().length;\n\nif (cluster.isMaster) {\n  // Fork workers.\n  for (var i = 0; i < numCPUs; i++) {\n    cluster.fork();\n  }\n\n  cluster.on('exit', function(worker, code, signal) {\n    console.log('worker ' + worker.process.pid + ' died');\n  });\n} else {\n  // Workers can share any TCP connection\n  // In this case its a HTTP server\n  http.createServer(function(req, res) {\n    res.writeHead(200);\n    res.end("hello world\\n");\n  }).listen(8000);\n}
    \n

    Running node will now share port 8000 between the workers:\n\n

    \n
    % NODE_DEBUG=cluster node server.js\n23521,Master Worker 23524 online\n23521,Master Worker 23526 online\n23521,Master Worker 23523 online\n23521,Master Worker 23528 online
    \n

    This feature was introduced recently, and may change in future versions.\nPlease try it out and provide feedback.\n\n

    \n

    Also note that, on Windows, it is not yet possible to set up a named pipe\nserver in a worker.\n\n

    \n", "miscs": [ { "textRaw": "How It Works", "name": "How It Works", "type": "misc", "desc": "

    The worker processes are spawned using the child_process.fork method,\nso that they can communicate with the parent via IPC and pass server\nhandles back and forth.\n\n

    \n

    When you call server.listen(...) in a worker, it serializes the\narguments and passes the request to the master process. If the master\nprocess already has a listening server matching the worker's\nrequirements, then it passes the handle to the worker. If it does not\nalready have a listening server matching that requirement, then it will\ncreate one, and pass the handle to the worker.\n\n

    \n

    This causes potentially surprising behavior in three edge cases:\n\n

    \n
      \n
    1. server.listen({fd: 7}) Because the message is passed to the master,\nfile descriptor 7 in the parent will be listened on, and the\nhandle passed to the worker, rather than listening to the worker's\nidea of what the number 7 file descriptor references.
    2. \n
    3. server.listen(handle) Listening on handles explicitly will cause\nthe worker to use the supplied handle, rather than talk to the master\nprocess. If the worker already has the handle, then it's presumed\nthat you know what you are doing.
    4. \n
    5. server.listen(0) Normally, this will cause servers to listen on a\nrandom port. However, in a cluster, each worker will receive the\nsame "random" port each time they do listen(0). In essence, the\nport is random the first time, but predictable thereafter. If you\nwant to listen on a unique port, generate a port number based on the\ncluster worker ID.
    6. \n
    \n

    When multiple processes are all accept()ing on the same underlying\nresource, the operating system load-balances across them very\nefficiently. There is no routing logic in Node.js, or in your program,\nand no shared state between the workers. Therefore, it is important to\ndesign your program such that it does not rely too heavily on in-memory\ndata objects for things like sessions and login.\n\n

    \n

    Because workers are all separate processes, they can be killed or\nre-spawned depending on your program's needs, without affecting other\nworkers. As long as there are some workers still alive, the server will\ncontinue to accept connections. Node does not automatically manage the\nnumber of workers for you, however. It is your responsibility to manage\nthe worker pool for your application's needs.\n\n

    \n" } ], "properties": [ { "textRaw": "`settings` {Object} ", "name": "settings", "options": [ { "textRaw": "`execArgv` {Array} list of string arguments passed to the node executable. (Default=`process.execArgv`) ", "name": "execArgv", "default": "process.execArgv", "type": "Array", "desc": "list of string arguments passed to the node executable." }, { "textRaw": "`exec` {String} file path to worker file. (Default=`process.argv[1]`) ", "name": "exec", "default": "process.argv[1]", "type": "String", "desc": "file path to worker file." }, { "textRaw": "`args` {Array} string arguments passed to worker. (Default=`process.argv.slice(2)`) ", "name": "args", "default": "process.argv.slice(2)", "type": "Array", "desc": "string arguments passed to worker." }, { "textRaw": "`silent` {Boolean} whether or not to send output to parent's stdio. (Default=`false`) ", "name": "silent", "default": "false", "type": "Boolean", "desc": "whether or not to send output to parent's stdio." } ], "desc": "

    After calling .setupMaster() (or .fork()) this settings object will contain\nthe settings, including the default values.\n\n

    \n

    It is effectively frozen after being set, because .setupMaster() can\nonly be called once.\n\n

    \n

    This object is not supposed to be changed or set manually, by you.\n\n

    \n" }, { "textRaw": "`isMaster` {Boolean} ", "name": "isMaster", "desc": "

    True if the process is a master. This is determined\nby the process.env.NODE_UNIQUE_ID. If process.env.NODE_UNIQUE_ID is\nundefined, then isMaster is true.\n\n

    \n" }, { "textRaw": "`isWorker` {Boolean} ", "name": "isWorker", "desc": "

    True if the process is not a master (it is the negation of cluster.isMaster).\n\n

    \n" }, { "textRaw": "`worker` {Object} ", "name": "worker", "desc": "

    A reference to the current worker object. Not available in the master process.\n\n

    \n
    var cluster = require('cluster');\n\nif (cluster.isMaster) {\n  console.log('I am master');\n  cluster.fork();\n  cluster.fork();\n} else if (cluster.isWorker) {\n  console.log('I am worker #' + cluster.worker.id);\n}
    \n" }, { "textRaw": "`workers` {Object} ", "name": "workers", "desc": "

    A hash that stores the active worker objects, keyed by id field. Makes it\neasy to loop through all the workers. It is only available in the master\nprocess.\n\n

    \n

    A worker is removed from cluster.workers just before the 'disconnect' or\n'exit' event is emitted.\n\n

    \n
    // Go through all workers\nfunction eachWorker(callback) {\n  for (var id in cluster.workers) {\n    callback(cluster.workers[id]);\n  }\n}\neachWorker(function(worker) {\n  worker.send('big announcement to all workers');\n});
    \n

    Should you wish to reference a worker over a communication channel, using\nthe worker's unique id is the easiest way to find the worker.\n\n

    \n
    socket.on('data', function(id) {\n  var worker = cluster.workers[id];\n});
    \n" } ], "events": [ { "textRaw": "Event: 'fork'", "type": "event", "name": "fork", "params": [], "desc": "

    When a new worker is forked the cluster module will emit a 'fork' event.\nThis can be used to log worker activity, and create your own timeout.\n\n

    \n
    var timeouts = [];\nfunction errorMsg() {\n  console.error("Something must be wrong with the connection ...");\n}\n\ncluster.on('fork', function(worker) {\n  timeouts[worker.id] = setTimeout(errorMsg, 2000);\n});\ncluster.on('listening', function(worker, address) {\n  clearTimeout(timeouts[worker.id]);\n});\ncluster.on('exit', function(worker, code, signal) {\n  clearTimeout(timeouts[worker.id]);\n  errorMsg();\n});
    \n" }, { "textRaw": "Event: 'online'", "type": "event", "name": "online", "params": [], "desc": "

    After forking a new worker, the worker should respond with an online message.\nWhen the master receives an online message it will emit this event.\nThe difference between 'fork' and 'online' is that fork is emitted when the\nmaster forks a worker, and 'online' is emitted when the worker is running.\n\n

    \n
    cluster.on('online', function(worker) {\n  console.log("Yay, the worker responded after it was forked");\n});
    \n" }, { "textRaw": "Event: 'listening'", "type": "event", "name": "listening", "params": [], "desc": "

    After calling listen() from a worker, when the 'listening' event is emitted on\nthe server, a listening event will also be emitted on cluster in the master.\n\n

    \n

    The event handler is executed with two arguments, the worker contains the worker\nobject and the address object contains the following connection properties:\naddress, port and addressType. This is very useful if the worker is listening\non more than one address.\n\n

    \n
    cluster.on('listening', function(worker, address) {\n  console.log("A worker is now connected to " + address.address + ":" + address.port);\n});
    \n

    The addressType is one of:\n\n

    \n
      \n
    • 4 (TCPv4)
    • \n
    • 6 (TCPv6)
    • \n
    • -1 (unix domain socket)
    • \n
    • "udp4" or "udp6" (UDP v4 or v6)
    • \n
    \n" }, { "textRaw": "Event: 'disconnect'", "type": "event", "name": "disconnect", "params": [], "desc": "

    Emitted after the worker IPC channel has disconnected. This can occur when a\nworker exits gracefully, is killed, or is disconnected manually (such as with\nworker.disconnect()).\n\n

    \n

    There may be a delay between the disconnect and exit events. These events\ncan be used to detect if the process is stuck in a cleanup or if there are\nlong-living connections.\n\n

    \n
    cluster.on('disconnect', function(worker) {\n  console.log('The worker #' + worker.id + ' has disconnected');\n});
    \n" }, { "textRaw": "Event: 'exit'", "type": "event", "name": "exit", "params": [], "desc": "

    When any of the workers die the cluster module will emit the 'exit' event.\n\n

    \n

    This can be used to restart the worker by calling .fork() again.\n\n

    \n
    cluster.on('exit', function(worker, code, signal) {\n  console.log('worker %d died (%s). restarting...',\n    worker.process.pid, signal || code);\n  cluster.fork();\n});
    \n

    See child_process event: 'exit'.\n\n

    \n" }, { "textRaw": "Event: 'setup'", "type": "event", "name": "setup", "desc": "

    Emitted the first time that .setupMaster() is called.\n\n

    \n", "params": [] } ], "methods": [ { "textRaw": "cluster.setupMaster([settings])", "type": "method", "name": "setupMaster", "signatures": [ { "params": [ { "textRaw": "`settings` {Object} ", "options": [ { "textRaw": "`exec` {String} file path to worker file. (Default=`process.argv[1]`) ", "name": "exec", "default": "process.argv[1]", "type": "String", "desc": "file path to worker file." }, { "textRaw": "`args` {Array} string arguments passed to worker. (Default=`process.argv.slice(2)`) ", "name": "args", "default": "process.argv.slice(2)", "type": "Array", "desc": "string arguments passed to worker." }, { "textRaw": "`silent` {Boolean} whether or not to send output to parent's stdio. (Default=`false`) ", "name": "silent", "default": "false", "type": "Boolean", "desc": "whether or not to send output to parent's stdio." } ], "name": "settings", "type": "Object", "optional": true } ] }, { "params": [ { "name": "settings", "optional": true } ] } ], "desc": "

    setupMaster is used to change the default 'fork' behavior. Once called,\nthe settings will be present in cluster.settings.\n\n

    \n

    Note that:\n\n

    \n
      \n
    • Only the first call to .setupMaster() has any effect, subsequent calls are\nignored
    • \n
    • That because of the above, the only attribute of a worker that may be\ncustomized per-worker is the env passed to .fork()
    • \n
    • .fork() calls .setupMaster() internally to establish the defaults, so to\nhave any effect, .setupMaster() must be called before any calls to\n.fork()
    • \n
    \n

    Example:\n\n

    \n
    var cluster = require("cluster");\ncluster.setupMaster({\n  exec : "worker.js",\n  args : ["--use", "https"],\n  silent : true\n});\ncluster.fork();
    \n

    This can only be called from the master process.\n\n

    \n" }, { "textRaw": "cluster.fork([env])", "type": "method", "name": "fork", "signatures": [ { "return": { "textRaw": "return {Worker object} ", "name": "return", "type": "Worker object" }, "params": [ { "textRaw": "`env` {Object} Key/value pairs to add to worker process environment. ", "name": "env", "type": "Object", "desc": "Key/value pairs to add to worker process environment.", "optional": true } ] }, { "params": [ { "name": "env", "optional": true } ] } ], "desc": "

    Spawn a new worker process.\n\n

    \n

    This can only be called from the master process.\n\n

    \n" }, { "textRaw": "cluster.disconnect([callback])", "type": "method", "name": "disconnect", "signatures": [ { "params": [ { "textRaw": "`callback` {Function} called when all workers are disconnected and handles are closed ", "name": "callback", "type": "Function", "desc": "called when all workers are disconnected and handles are closed", "optional": true } ] }, { "params": [ { "name": "callback", "optional": true } ] } ], "desc": "

    Calls .disconnect() on each worker in cluster.workers.\n\n

    \n

    When they are disconnected all internal handles will be closed, allowing the\nmaster process to die gracefully if no other event is waiting.\n\n

    \n

    The method takes an optional callback argument which will be called when finished.\n\n

    \n

    This can only be called from the master process.\n\n

    \n" } ], "classes": [ { "textRaw": "Class: Worker", "type": "class", "name": "Worker", "desc": "

    A Worker object contains all public information and method about a worker.\nIn the master it can be obtained using cluster.workers. In a worker\nit can be obtained using cluster.worker.\n\n

    \n", "properties": [ { "textRaw": "`id` {String} ", "name": "id", "desc": "

    Each new worker is given its own unique id, this id is stored in the\nid.\n\n

    \n

    While a worker is alive, this is the key that indexes it in\ncluster.workers\n\n

    \n" }, { "textRaw": "`process` {ChildProcess object} ", "name": "process", "desc": "

    All workers are created using child_process.fork(), the returned object\nfrom this function is stored as .process. In a worker, the global process\nis stored.\n\n

    \n

    See: Child Process module\n\n

    \n

    Note that workers will call process.exit(0) if the 'disconnect' event occurs\non process and .suicide is not true. This protects against accidental\ndisconnection.\n\n

    \n" }, { "textRaw": "`suicide` {Boolean} ", "name": "suicide", "desc": "

    Set by calling .kill() or .disconnect(), until then it is undefined.\n\n

    \n

    The boolean worker.suicide lets you distinguish between voluntary and accidental\nexit, the master may choose not to respawn a worker based on this value.\n\n

    \n
    cluster.on('exit', function(worker, code, signal) {\n  if (worker.suicide === true) {\n    console.log('Oh, it was just suicide\\' – no need to worry').\n  }\n});\n\n// kill worker\nworker.kill();
    \n" } ], "methods": [ { "textRaw": "worker.send(message, [sendHandle])", "type": "method", "name": "send", "signatures": [ { "params": [ { "textRaw": "`message` {Object} ", "name": "message", "type": "Object" }, { "textRaw": "`sendHandle` {Handle object} ", "name": "sendHandle", "type": "Handle object", "optional": true } ] }, { "params": [ { "name": "message" }, { "name": "sendHandle", "optional": true } ] } ], "desc": "

    This function is equal to the send methods provided by\nchild_process.fork(). In the master you should use this function to\nsend a message to a specific worker.\n\n

    \n

    In a worker you can also use process.send(message), it is the same function.\n\n

    \n

    This example will echo back all messages from the master:\n\n

    \n
    if (cluster.isMaster) {\n  var worker = cluster.fork();\n  worker.send('hi there');\n\n} else if (cluster.isWorker) {\n  process.on('message', function(msg) {\n    process.send(msg);\n  });\n}
    \n" }, { "textRaw": "worker.kill([signal='SIGTERM'])", "type": "method", "name": "kill", "signatures": [ { "params": [ { "textRaw": "`signal` {String} Name of the kill signal to send to the worker process. ", "name": "signal", "type": "String", "desc": "Name of the kill signal to send to the worker process.", "optional": true, "default": "'SIGTERM'" } ] }, { "params": [ { "name": "signal", "optional": true, "default": "'SIGTERM'" } ] } ], "desc": "

    This function will kill the worker. In the master, it does this by disconnecting\nthe worker.process, and once disconnected, killing with signal. In the\nworker, it does it by disconnecting the channel, and then exiting with code 0.\n\n

    \n

    Causes .suicide to be set.\n\n

    \n

    This method is aliased as worker.destroy() for backwards compatibility.\n\n

    \n

    Note that in a worker, process.kill() exists, but it is not this function,\nit is kill.\n\n

    \n" }, { "textRaw": "worker.disconnect()", "type": "method", "name": "disconnect", "desc": "

    In a worker, this function will close all servers, wait for the 'close' event on\nthose servers, and then disconnect the IPC channel.\n\n

    \n

    In the master, an internal message is sent to the worker causing it to call\n.disconnect() on itself.\n\n

    \n

    Causes .suicide to be set.\n\n

    \n

    Note that after a server is closed, it will no longer accept new connections,\nbut connections may be accepted by any other listening worker. Existing\nconnections will be allowed to close as usual. When no more connections exist,\nsee server.close(), the IPC channel to the worker\nwill close allowing it to die gracefully.\n\n

    \n

    The above applies only to server connections, client connections are not\nautomatically closed by workers, and disconnect does not wait for them to close\nbefore exiting.\n\n

    \n

    Note that in a worker, process.disconnect exists, but it is not this function,\nit is disconnect.\n\n

    \n

    Because long living server connections may block workers from disconnecting, it\nmay be useful to send a message, so application specific actions may be taken to\nclose them. It also may be useful to implement a timeout, killing a worker if\nthe disconnect event has not been emitted after some time.\n\n

    \n
    if (cluster.isMaster) {\n  var worker = cluster.fork();\n  var timeout;\n\n  worker.on('listening', function(address) {\n    worker.send('shutdown');\n    worker.disconnect();\n    timeout = setTimeout(function() {\n      worker.kill();\n    }, 2000);\n  });\n\n  worker.on('disconnect', function() {\n    clearTimeout(timeout);\n  });\n\n} else if (cluster.isWorker) {\n  var net = require('net');\n  var server = net.createServer(function(socket) {\n    // connections never end\n  });\n\n  server.listen(8000);\n\n  process.on('message', function(msg) {\n    if(msg === 'shutdown') {\n      // initiate graceful close of any connections to server\n    }\n  });\n}
    \n", "signatures": [ { "params": [] } ] } ], "events": [ { "textRaw": "Event: 'message'", "type": "event", "name": "message", "params": [], "desc": "

    This event is the same as the one provided by child_process.fork().\n\n

    \n

    In a worker you can also use process.on('message').\n\n

    \n

    As an example, here is a cluster that keeps count of the number of requests\nin the master process using the message system:\n\n

    \n
    var cluster = require('cluster');\nvar http = require('http');\n\nif (cluster.isMaster) {\n\n  // Keep track of http requests\n  var numReqs = 0;\n  setInterval(function() {\n    console.log("numReqs =", numReqs);\n  }, 1000);\n\n  // Count requestes\n  function messageHandler(msg) {\n    if (msg.cmd && msg.cmd == 'notifyRequest') {\n      numReqs += 1;\n    }\n  }\n\n  // Start workers and listen for messages containing notifyRequest\n  var numCPUs = require('os').cpus().length;\n  for (var i = 0; i < numCPUs; i++) {\n    cluster.fork();\n  }\n\n  Object.keys(cluster.workers).forEach(function(id) {\n    cluster.workers[id].on('message', messageHandler);\n  });\n\n} else {\n\n  // Worker processes have a http server.\n  http.Server(function(req, res) {\n    res.writeHead(200);\n    res.end("hello world\\n");\n\n    // notify master about the request\n    process.send({ cmd: 'notifyRequest' });\n  }).listen(8000);\n}
    \n" }, { "textRaw": "Event: 'online'", "type": "event", "name": "online", "desc": "

    Similar to the cluster.on('online') event, but specific to this worker.\n\n

    \n
    cluster.fork().on('online', function() {\n  // Worker is online\n});
    \n

    It is not emitted in the worker.\n\n

    \n", "params": [] }, { "textRaw": "Event: 'listening'", "type": "event", "name": "listening", "params": [], "desc": "

    Similar to the cluster.on('listening') event, but specific to this worker.\n\n

    \n
    cluster.fork().on('listening', function(address) {\n  // Worker is listening\n});
    \n

    It is not emitted in the worker.\n\n

    \n" }, { "textRaw": "Event: 'disconnect'", "type": "event", "name": "disconnect", "desc": "

    Similar to the cluster.on('disconnect') event, but specfic to this worker.\n\n

    \n
    cluster.fork().on('disconnect', function() {\n  // Worker has disconnected\n});
    \n", "params": [] }, { "textRaw": "Event: 'exit'", "type": "event", "name": "exit", "params": [], "desc": "

    Similar to the cluster.on('exit') event, but specific to this worker.\n\n

    \n
    var worker = cluster.fork();\nworker.on('exit', function(code, signal) {\n  if( signal ) {\n    console.log("worker was killed by signal: "+signal);\n  } else if( code !== 0 ) {\n    console.log("worker exited with error code: "+code);\n  } else {\n    console.log("worker success!");\n  }\n});
    \n" }, { "textRaw": "Event: 'error'", "type": "event", "name": "error", "desc": "

    This event is the same as the one provided by child_process.fork().\n\n

    \n

    In a worker you can also use process.on('error').\n\n

    \n", "params": [] } ] } ], "type": "module", "displayName": "Cluster" } ], "stability": 3, "stabilityText": "Stable" } node-v0.10.25~dfsg2/doc/api/timers.markdown0000644000000000000000000000501512270121457017203 0ustar rootroot# Timers Stability: 5 - Locked All of the timer functions are globals. You do not need to `require()` this module in order to use them. ## setTimeout(callback, delay, [arg], [...]) To schedule execution of a one-time `callback` after `delay` milliseconds. Returns a `timeoutId` for possible use with `clearTimeout()`. Optionally you can also pass arguments to the callback. It is important to note that your callback will probably not be called in exactly `delay` milliseconds - Node.js makes no guarantees about the exact timing of when the callback will fire, nor of the ordering things will fire in. The callback will be called as close as possible to the time specified. ## clearTimeout(timeoutId) Prevents a timeout from triggering. ## setInterval(callback, delay, [arg], [...]) To schedule the repeated execution of `callback` every `delay` milliseconds. Returns a `intervalId` for possible use with `clearInterval()`. Optionally you can also pass arguments to the callback. ## clearInterval(intervalId) Stops a interval from triggering. ## unref() The opaque value returned by `setTimeout` and `setInterval` also has the method `timer.unref()` which will allow you to create a timer that is active but if it is the only item left in the event loop won't keep the program running. If the timer is already `unref`d calling `unref` again will have no effect. In the case of `setTimeout` when you `unref` you create a separate timer that will wakeup the event loop, creating too many of these may adversely effect event loop performance -- use wisely. ## ref() If you had previously `unref()`d a timer you can call `ref()` to explicitly request the timer hold the program open. If the timer is already `ref`d calling `ref` again will have no effect. ## setImmediate(callback, [arg], [...]) To schedule the "immediate" execution of `callback` after I/O events callbacks and before `setTimeout` and `setInterval` . Returns an `immediateId` for possible use with `clearImmediate()`. Optionally you can also pass arguments to the callback. Immediates are queued in the order created, and are popped off the queue once per loop iteration. This is different from `process.nextTick` which will execute `process.maxTickDepth` queued callbacks per iteration. `setImmediate` will yield to the event loop after firing a queued callback to make sure I/O is not being starved. While order is preserved for execution, other I/O events may fire between any two scheduled immediate callbacks. ## clearImmediate(immediateId) Stops an immediate from triggering. node-v0.10.25~dfsg2/doc/api/process.markdown0000644000000000000000000004435412270121457017367 0ustar rootroot# process The `process` object is a global object and can be accessed from anywhere. It is an instance of [EventEmitter][]. ## Event: 'exit' Emitted when the process is about to exit. There is no way to prevent the exiting of the event loop at this point, and once all `exit` listeners have finished running the process will exit. Therefore you **must** only perform **synchronous** operations in this handler. This is a good hook to perform checks on the module's state (like for unit tests). The callback takes one argument, the code the process is exiting with. Example of listening for `exit`: process.on('exit', function(code) { // do *NOT* do this setTimeout(function() { console.log('This will not run'); }, 0); console.log('About to exit with code:', code); }); ## Event: 'uncaughtException' Emitted when an exception bubbles all the way back to the event loop. If a listener is added for this exception, the default action (which is to print a stack trace and exit) will not occur. Example of listening for `uncaughtException`: process.on('uncaughtException', function(err) { console.log('Caught exception: ' + err); }); setTimeout(function() { console.log('This will still run.'); }, 500); // Intentionally cause an exception, but don't catch it. nonexistentFunc(); console.log('This will not run.'); Note that `uncaughtException` is a very crude mechanism for exception handling and may be removed in the future. Don't use it, use [domains](domain.html) instead. If you do use it, restart your application after every unhandled exception! Do *not* use it as the node.js equivalent of `On Error Resume Next`. An unhandled exception means your application - and by extension node.js itself - is in an undefined state. Blindly resuming means *anything* could happen. Think of resuming as pulling the power cord when you are upgrading your system. Nine out of ten times nothing happens - but the 10th time, your system is bust. You have been warned. ## Signal Events Emitted when the processes receives a signal. See sigaction(2) for a list of standard POSIX signal names such as SIGINT, SIGHUP, etc. Example of listening for `SIGINT`: // Start reading from stdin so we don't exit. process.stdin.resume(); process.on('SIGINT', function() { console.log('Got SIGINT. Press Control-D to exit.'); }); An easy way to send the `SIGINT` signal is with `Control-C` in most terminal programs. Note: - `SIGUSR1` is reserved by node.js to start the debugger. It's possible to install a listener but that won't stop the debugger from starting. - `SIGTERM` and `SIGINT` have default handlers on non-Windows platforms that resets the terminal mode before exiting with code `128 + signal number`. If one of these signals has a listener installed, its default behaviour will be removed (node will no longer exit). - `SIGPIPE` is ignored by default, it can have a listener installed. - `SIGHUP` is generated on Windows when the console window is closed, and on other platforms under various similar conditions, see signal(7). It can have a listener installed, however node will be unconditionally terminated by Windows about 10 seconds later. On non-Windows platforms, the default behaviour of `SIGHUP` is to terminate node, but once a listener has been installed its default behaviour will be removed. - `SIGTERM` is not supported on Windows, it can be listened on. - `SIGINT` from the terminal is supported on all platforms, and can usually be generated with `CTRL+C` (though this may be configurable). It is not generated when terminal raw mode is enabled. - `SIGBREAK` is delivered on Windows when `CTRL+BREAK` is pressed, on non-Windows platforms it can be listened on, but there is no way to send or generate it. - `SIGWINCH` is delivered when the console has been resized. On Windows, this will only happen on write to the console when the cursor is being moved, or when a readable tty is used in raw mode. - `SIGKILL` cannot have a listener installed, it will unconditionally terminate node on all platforms. - `SIGSTOP` cannot have a listener installed. Note that Windows does not support sending Signals, but node offers some emulation with `process.kill()`, and `child_process.kill()`: - Sending signal `0` can be used to search for the existence of a process - Sending `SIGINT`, `SIGTERM`, and `SIGKILL` cause the unconditional exit of the target process. ## process.stdout A `Writable Stream` to `stdout`. Example: the definition of `console.log` console.log = function(d) { process.stdout.write(d + '\n'); }; `process.stderr` and `process.stdout` are unlike other streams in Node in that writes to them are usually blocking. They are blocking in the case that they refer to regular files or TTY file descriptors. In the case they refer to pipes, they are non-blocking like other streams. To check if Node is being run in a TTY context, read the `isTTY` property on `process.stderr`, `process.stdout`, or `process.stdin`: $ node -p "Boolean(process.stdin.isTTY)" true $ echo "foo" | node -p "Boolean(process.stdin.isTTY)" false $ node -p "Boolean(process.stdout.isTTY)" true $ node -p "Boolean(process.stdout.isTTY)" | cat false See [the tty docs](tty.html#tty_tty) for more information. ## process.stderr A writable stream to stderr. `process.stderr` and `process.stdout` are unlike other streams in Node in that writes to them are usually blocking. They are blocking in the case that they refer to regular files or TTY file descriptors. In the case they refer to pipes, they are non-blocking like other streams. ## process.stdin A `Readable Stream` for stdin. The stdin stream is paused by default, so one must call `process.stdin.resume()` to read from it. Example of opening standard input and listening for both events: process.stdin.resume(); process.stdin.setEncoding('utf8'); process.stdin.on('data', function(chunk) { process.stdout.write('data: ' + chunk); }); process.stdin.on('end', function() { process.stdout.write('end'); }); ## process.argv An array containing the command line arguments. The first element will be 'node', the second element will be the name of the JavaScript file. The next elements will be any additional command line arguments. // print process.argv process.argv.forEach(function(val, index, array) { console.log(index + ': ' + val); }); This will generate: $ node process-2.js one two=three four 0: node 1: /Users/mjr/work/node/process-2.js 2: one 3: two=three 4: four ## process.execPath This is the absolute pathname of the executable that started the process. Example: /usr/local/bin/node ## process.execArgv This is the set of node-specific command line options from the executable that started the process. These options do not show up in `process.argv`, and do not include the node executable, the name of the script, or any options following the script name. These options are useful in order to spawn child processes with the same execution environment as the parent. Example: $ node --harmony script.js --version results in process.execArgv: ['--harmony'] and process.argv: ['/usr/local/bin/node', 'script.js', '--version'] ## process.abort() This causes node to emit an abort. This will cause node to exit and generate a core file. ## process.chdir(directory) Changes the current working directory of the process or throws an exception if that fails. console.log('Starting directory: ' + process.cwd()); try { process.chdir('/tmp'); console.log('New directory: ' + process.cwd()); } catch (err) { console.log('chdir: ' + err); } ## process.cwd() Returns the current working directory of the process. console.log('Current directory: ' + process.cwd()); ## process.env An object containing the user environment. See environ(7). ## process.exit([code]) Ends the process with the specified `code`. If omitted, exit uses the 'success' code `0`. To exit with a 'failure' code: process.exit(1); The shell that executed node should see the exit code as 1. ## process.getgid() Note: this function is only available on POSIX platforms (i.e. not Windows) Gets the group identity of the process. (See getgid(2).) This is the numerical group id, not the group name. if (process.getgid) { console.log('Current gid: ' + process.getgid()); } ## process.setgid(id) Note: this function is only available on POSIX platforms (i.e. not Windows) Sets the group identity of the process. (See setgid(2).) This accepts either a numerical ID or a groupname string. If a groupname is specified, this method blocks while resolving it to a numerical ID. if (process.getgid && process.setgid) { console.log('Current gid: ' + process.getgid()); try { process.setgid(501); console.log('New gid: ' + process.getgid()); } catch (err) { console.log('Failed to set gid: ' + err); } } ## process.getuid() Note: this function is only available on POSIX platforms (i.e. not Windows) Gets the user identity of the process. (See getuid(2).) This is the numerical userid, not the username. if (process.getuid) { console.log('Current uid: ' + process.getuid()); } ## process.setuid(id) Note: this function is only available on POSIX platforms (i.e. not Windows) Sets the user identity of the process. (See setuid(2).) This accepts either a numerical ID or a username string. If a username is specified, this method blocks while resolving it to a numerical ID. if (process.getuid && process.setuid) { console.log('Current uid: ' + process.getuid()); try { process.setuid(501); console.log('New uid: ' + process.getuid()); } catch (err) { console.log('Failed to set uid: ' + err); } } ## process.getgroups() Note: this function is only available on POSIX platforms (i.e. not Windows) Returns an array with the supplementary group IDs. POSIX leaves it unspecified if the effective group ID is included but node.js ensures it always is. ## process.setgroups(groups) Note: this function is only available on POSIX platforms (i.e. not Windows) Sets the supplementary group IDs. This is a privileged operation, meaning you need to be root or have the CAP_SETGID capability. The list can contain group IDs, group names or both. ## process.initgroups(user, extra_group) Note: this function is only available on POSIX platforms (i.e. not Windows) Reads /etc/group and initializes the group access list, using all groups of which the user is a member. This is a privileged operation, meaning you need to be root or have the CAP_SETGID capability. `user` is a user name or user ID. `extra_group` is a group name or group ID. Some care needs to be taken when dropping privileges. Example: console.log(process.getgroups()); // [ 0 ] process.initgroups('bnoordhuis', 1000); // switch user console.log(process.getgroups()); // [ 27, 30, 46, 1000, 0 ] process.setgid(1000); // drop root gid console.log(process.getgroups()); // [ 27, 30, 46, 1000 ] ## process.version A compiled-in property that exposes `NODE_VERSION`. console.log('Version: ' + process.version); ## process.versions A property exposing version strings of node and its dependencies. console.log(process.versions); Will print something like: { http_parser: '1.0', node: '0.10.4', v8: '3.14.5.8', ares: '1.9.0-DEV', uv: '0.10.3', zlib: '1.2.3', modules: '11', openssl: '1.0.1e' } ## process.config An Object containing the JavaScript representation of the configure options that were used to compile the current node executable. This is the same as the "config.gypi" file that was produced when running the `./configure` script. An example of the possible output looks like: { target_defaults: { cflags: [], default_configuration: 'Release', defines: [], include_dirs: [], libraries: [] }, variables: { host_arch: 'x64', node_install_npm: 'true', node_prefix: '', node_shared_cares: 'false', node_shared_http_parser: 'false', node_shared_libuv: 'false', node_shared_v8: 'false', node_shared_zlib: 'false', node_use_dtrace: 'false', node_use_openssl: 'true', node_shared_openssl: 'false', strict_aliasing: 'true', target_arch: 'x64', v8_use_snapshot: 'true' } } ## process.kill(pid, [signal]) Send a signal to a process. `pid` is the process id and `signal` is the string describing the signal to send. Signal names are strings like 'SIGINT' or 'SIGHUP'. If omitted, the signal will be 'SIGTERM'. See [Signal Events](#process_signal_events) and kill(2) for more information. Will throw an error if target does not exist, and as a special case, a signal of `0` can be used to test for the existence of a process. Note that just because the name of this function is `process.kill`, it is really just a signal sender, like the `kill` system call. The signal sent may do something other than kill the target process. Example of sending a signal to yourself: process.on('SIGHUP', function() { console.log('Got SIGHUP signal.'); }); setTimeout(function() { console.log('Exiting.'); process.exit(0); }, 100); process.kill(process.pid, 'SIGHUP'); Note: When SIGUSR1 is received by Node.js it starts the debugger, see [Signal Events](#process_signal_events). ## process.pid The PID of the process. console.log('This process is pid ' + process.pid); ## process.title Getter/setter to set what is displayed in 'ps'. When used as a setter, the maximum length is platform-specific and probably short. On Linux and OS X, it's limited to the size of the binary name plus the length of the command line arguments because it overwrites the argv memory. v0.8 allowed for longer process title strings by also overwriting the environ memory but that was potentially insecure/confusing in some (rather obscure) cases. ## process.arch What processor architecture you're running on: `'arm'`, `'ia32'`, or `'x64'`. console.log('This processor architecture is ' + process.arch); ## process.platform What platform you're running on: `'darwin'`, `'freebsd'`, `'linux'`, `'sunos'` or `'win32'` console.log('This platform is ' + process.platform); ## process.memoryUsage() Returns an object describing the memory usage of the Node process measured in bytes. var util = require('util'); console.log(util.inspect(process.memoryUsage())); This will generate: { rss: 4935680, heapTotal: 1826816, heapUsed: 650472 } `heapTotal` and `heapUsed` refer to V8's memory usage. ## process.nextTick(callback) On the next loop around the event loop call this callback. This is *not* a simple alias to `setTimeout(fn, 0)`, it's much more efficient. It typically runs before any other I/O events fire, but there are some exceptions. See `process.maxTickDepth` below. process.nextTick(function() { console.log('nextTick callback'); }); This is important in developing APIs where you want to give the user the chance to assign event handlers after an object has been constructed, but before any I/O has occurred. function MyThing(options) { this.setupOptions(options); process.nextTick(function() { this.startDoingStuff(); }.bind(this)); } var thing = new MyThing(); thing.getReadyForStuff(); // thing.startDoingStuff() gets called now, not before. It is very important for APIs to be either 100% synchronous or 100% asynchronous. Consider this example: // WARNING! DO NOT USE! BAD UNSAFE HAZARD! function maybeSync(arg, cb) { if (arg) { cb(); return; } fs.stat('file', cb); } This API is hazardous. If you do this: maybeSync(true, function() { foo(); }); bar(); then it's not clear whether `foo()` or `bar()` will be called first. This approach is much better: function definitelyAsync(arg, cb) { if (arg) { process.nextTick(cb); return; } fs.stat('file', cb); } ## process.maxTickDepth * {Number} Default = 1000 Callbacks passed to `process.nextTick` will *usually* be called at the end of the current flow of execution, and are thus approximately as fast as calling a function synchronously. Left unchecked, this would starve the event loop, preventing any I/O from occurring. Consider this code: process.nextTick(function foo() { process.nextTick(foo); }); In order to avoid the situation where Node is blocked by an infinite loop of recursive series of nextTick calls, it defers to allow some I/O to be done every so often. The `process.maxTickDepth` value is the maximum depth of nextTick-calling nextTick-callbacks that will be evaluated before allowing other forms of I/O to occur. ## process.umask([mask]) Sets or reads the process's file mode creation mask. Child processes inherit the mask from the parent process. Returns the old mask if `mask` argument is given, otherwise returns the current mask. var oldmask, newmask = 0644; oldmask = process.umask(newmask); console.log('Changed umask from: ' + oldmask.toString(8) + ' to ' + newmask.toString(8)); ## process.uptime() Number of seconds Node has been running. ## process.hrtime() Returns the current high-resolution real time in a `[seconds, nanoseconds]` tuple Array. It is relative to an arbitrary time in the past. It is not related to the time of day and therefore not subject to clock drift. The primary use is for measuring performance between intervals. You may pass in the result of a previous call to `process.hrtime()` to get a diff reading, useful for benchmarks and measuring intervals: var time = process.hrtime(); // [ 1800216, 25 ] setTimeout(function() { var diff = process.hrtime(time); // [ 1, 552 ] console.log('benchmark took %d nanoseconds', diff[0] * 1e9 + diff[1]); // benchmark took 1000000527 nanoseconds }, 1000); [EventEmitter]: events.html#events_class_events_eventemitter node-v0.10.25~dfsg2/doc/api/dgram.html0000644000000000000000000004502212270264601016115 0ustar rootroot UDP / Datagram Sockets Node.js v0.10.25 Manual & Documentation

    Node.js v0.10.25 Manual & Documentation


    UDP / Datagram Sockets#

    Stability: 3 - Stable

    Datagram sockets are available through require('dgram').

    Important note: the behavior of dgram.Socket#bind() has changed in v0.10 and is always asynchronous now. If you have code that looks like this:

    var s = dgram.createSocket('udp4');
    s.bind(1234);
    s.addMembership('224.0.0.114');

    You have to change it to this:

    var s = dgram.createSocket('udp4');
    s.bind(1234, function() {
      s.addMembership('224.0.0.114');
    });

    dgram.createSocket(type, [callback])#

    • type String. Either 'udp4' or 'udp6'
    • callback Function. Attached as a listener to message events. Optional
    • Returns: Socket object

    Creates a datagram Socket of the specified types. Valid types are udp4 and udp6.

    Takes an optional callback which is added as a listener for message events.

    Call socket.bind if you want to receive datagrams. socket.bind() will bind to the "all interfaces" address on a random port (it does the right thing for both udp4 and udp6 sockets). You can then retrieve the address and port with socket.address().address and socket.address().port.

    Class: dgram.Socket#

    The dgram Socket class encapsulates the datagram functionality. It should be created via dgram.createSocket(type, [callback]).

    Event: 'message'#

    • msg Buffer object. The message
    • rinfo Object. Remote address information

    Emitted when a new datagram is available on a socket. msg is a Buffer and rinfo is an object with the sender's address information and the number of bytes in the datagram.

    Event: 'listening'#

    Emitted when a socket starts listening for datagrams. This happens as soon as UDP sockets are created.

    Event: 'close'#

    Emitted when a socket is closed with close(). No new message events will be emitted on this socket.

    Event: 'error'#

    • exception Error object

    Emitted when an error occurs.

    socket.send(buf, offset, length, port, address, [callback])#

    • buf Buffer object. Message to be sent
    • offset Integer. Offset in the buffer where the message starts.
    • length Integer. Number of bytes in the message.
    • port Integer. Destination port.
    • address String. Destination hostname or IP address.
    • callback Function. Called when the message has been sent. Optional.

    For UDP sockets, the destination port and address must be specified. A string may be supplied for the address parameter, and it will be resolved with DNS.

    If the address is omitted or is an empty string, '0.0.0.0' or '::0' is used instead. Depending on the network configuration, those defaults may or may not work; it's best to be explicit about the destination address.

    If the socket has not been previously bound with a call to bind, it gets assigned a random port number and is bound to the "all interfaces" address ('0.0.0.0' for udp4 sockets, '::0' for udp6 sockets.)

    An optional callback may be specified to detect DNS errors or for determining when it's safe to reuse the buf object. Note that DNS lookups delay the time to send for at least one tick. The only way to know for sure that the datagram has been sent is by using a callback.

    Example of sending a UDP packet to a random port on localhost;

    var dgram = require('dgram');
    var message = new Buffer("Some bytes");
    var client = dgram.createSocket("udp4");
    client.send(message, 0, message.length, 41234, "localhost", function(err, bytes) {
      client.close();
    });

    A Note about UDP datagram size

    The maximum size of an IPv4/v6 datagram depends on the MTU (Maximum Transmission Unit) and on the Payload Length field size.

    • The Payload Length field is 16 bits wide, which means that a normal payload cannot be larger than 64K octets including internet header and data (65,507 bytes = 65,535 − 8 bytes UDP header − 20 bytes IP header); this is generally true for loopback interfaces, but such long datagrams are impractical for most hosts and networks.

    • The MTU is the largest size a given link layer technology can support for datagrams. For any link, IPv4 mandates a minimum MTU of 68 octets, while the recommended MTU for IPv4 is 576 (typically recommended as the MTU for dial-up type applications), whether they arrive whole or in fragments.

      For IPv6, the minimum MTU is 1280 octets, however, the mandatory minimum fragment reassembly buffer size is 1500 octets. The value of 68 octets is very small, since most current link layer technologies have a minimum MTU of 1500 (like Ethernet).

    Note that it's impossible to know in advance the MTU of each link through which a packet might travel, and that generally sending a datagram greater than the (receiver) MTU won't work (the packet gets silently dropped, without informing the source that the data did not reach its intended recipient).

    socket.bind(port, [address], [callback])#

    • port Integer
    • address String, Optional
    • callback Function with no parameters, Optional. Callback when binding is done.

    For UDP sockets, listen for datagrams on a named port and optional address. If address is not specified, the OS will try to listen on all addresses. After binding is done, a "listening" event is emitted and the callback(if specified) is called. Specifying both a "listening" event listener and callback is not harmful but not very useful.

    A bound datagram socket keeps the node process running to receive datagrams.

    If binding fails, an "error" event is generated. In rare case (e.g. binding a closed socket), an Error may be thrown by this method.

    Example of a UDP server listening on port 41234:

    var dgram = require("dgram");
    
    var server = dgram.createSocket("udp4");
    
    server.on("error", function (err) {
      console.log("server error:\n" + err.stack);
      server.close();
    });
    
    server.on("message", function (msg, rinfo) {
      console.log("server got: " + msg + " from " +
        rinfo.address + ":" + rinfo.port);
    });
    
    server.on("listening", function () {
      var address = server.address();
      console.log("server listening " +
          address.address + ":" + address.port);
    });
    
    server.bind(41234);
    // server listening 0.0.0.0:41234

    socket.close()#

    Close the underlying socket and stop listening for data on it.

    socket.address()#

    Returns an object containing the address information for a socket. For UDP sockets, this object will contain address , family and port.

    socket.setBroadcast(flag)#

    • flag Boolean

    Sets or clears the SO_BROADCAST socket option. When this option is set, UDP packets may be sent to a local interface's broadcast address.

    socket.setTTL(ttl)#

    • ttl Integer

    Sets the IP_TTL socket option. TTL stands for "Time to Live," but in this context it specifies the number of IP hops that a packet is allowed to go through. Each router or gateway that forwards a packet decrements the TTL. If the TTL is decremented to 0 by a router, it will not be forwarded. Changing TTL values is typically done for network probes or when multicasting.

    The argument to setTTL() is a number of hops between 1 and 255. The default on most systems is 64.

    socket.setMulticastTTL(ttl)#

    • ttl Integer

    Sets the IP_MULTICAST_TTL socket option. TTL stands for "Time to Live," but in this context it specifies the number of IP hops that a packet is allowed to go through, specifically for multicast traffic. Each router or gateway that forwards a packet decrements the TTL. If the TTL is decremented to 0 by a router, it will not be forwarded.

    The argument to setMulticastTTL() is a number of hops between 0 and 255. The default on most systems is 1.

    socket.setMulticastLoopback(flag)#

    • flag Boolean

    Sets or clears the IP_MULTICAST_LOOP socket option. When this option is set, multicast packets will also be received on the local interface.

    socket.addMembership(multicastAddress, [multicastInterface])#

    • multicastAddress String
    • multicastInterface String, Optional

    Tells the kernel to join a multicast group with IP_ADD_MEMBERSHIP socket option.

    If multicastInterface is not specified, the OS will try to add membership to all valid interfaces.

    socket.dropMembership(multicastAddress, [multicastInterface])#

    • multicastAddress String
    • multicastInterface String, Optional

    Opposite of addMembership - tells the kernel to leave a multicast group with IP_DROP_MEMBERSHIP socket option. This is automatically called by the kernel when the socket is closed or process terminates, so most apps will never need to call this.

    If multicastInterface is not specified, the OS will try to drop membership to all valid interfaces.

    socket.unref()#

    Calling unref on a socket will allow the program to exit if this is the only active socket in the event system. If the socket is already unrefd calling unref again will have no effect.

    socket.ref()#

    Opposite of unref, calling ref on a previously unrefd socket will not let the program exit if it's the only socket left (the default behavior). If the socket is refd calling ref again will have no effect.

    node-v0.10.25~dfsg2/doc/api/child_process.json0000644000000000000000000011745312270264601017661 0ustar rootroot{ "source": "doc/api/child_process.markdown", "modules": [ { "textRaw": "Child Process", "name": "child_process", "stability": 3, "stabilityText": "Stable", "desc": "

    Node provides a tri-directional popen(3) facility through the\nchild_process module.\n\n

    \n

    It is possible to stream data through a child's stdin, stdout, and\nstderr in a fully non-blocking way. (Note that some programs use\nline-buffered I/O internally. That doesn't affect node.js but it means\ndata you send to the child process is not immediately consumed.)\n\n

    \n

    To create a child process use require('child_process').spawn() or\nrequire('child_process').fork(). The semantics of each are slightly\ndifferent, and explained below.\n\n

    \n", "classes": [ { "textRaw": "Class: ChildProcess", "type": "class", "name": "ChildProcess", "desc": "

    ChildProcess is an [EventEmitter][].\n\n

    \n

    Child processes always have three streams associated with them. child.stdin,\nchild.stdout, and child.stderr. These may be shared with the stdio\nstreams of the parent process, or they may be separate stream objects\nwhich can be piped to and from.\n\n

    \n

    The ChildProcess class is not intended to be used directly. Use the\nspawn() or fork() methods to create a Child Process instance.\n\n

    \n", "events": [ { "textRaw": "Event: 'error'", "type": "event", "name": "error", "params": [], "desc": "

    Emitted when:\n\n

    \n
      \n
    1. The process could not be spawned, or
    2. \n
    3. The process could not be killed, or
    4. \n
    5. Sending a message to the child process failed for whatever reason.
    6. \n
    \n

    Note that the exit-event may or may not fire after an error has occured. If\nyou are listening on both events to fire a function, remember to guard against\ncalling your function twice.\n\n

    \n

    See also ChildProcess#kill() and\nChildProcess#send().\n\n

    \n" }, { "textRaw": "Event: 'exit'", "type": "event", "name": "exit", "params": [], "desc": "

    This event is emitted after the child process ends. If the process terminated\nnormally, code is the final exit code of the process, otherwise null. If\nthe process terminated due to receipt of a signal, signal is the string name\nof the signal, otherwise null.\n\n

    \n

    Note that the child process stdio streams might still be open.\n\n

    \n

    Also, note that node establishes signal handlers for 'SIGINT' and 'SIGTERM',\nso it will not terminate due to receipt of those signals, it will exit.\n\n

    \n

    See waitpid(2).\n\n

    \n" }, { "textRaw": "Event: 'close'", "type": "event", "name": "close", "params": [], "desc": "

    This event is emitted when the stdio streams of a child process have all\nterminated. This is distinct from 'exit', since multiple processes\nmight share the same stdio streams.\n\n

    \n" }, { "textRaw": "Event: 'disconnect'", "type": "event", "name": "disconnect", "desc": "

    This event is emitted after calling the .disconnect() method in the parent\nor in the child. After disconnecting it is no longer possible to send messages,\nand the .connected property is false.\n\n

    \n", "params": [] }, { "textRaw": "Event: 'message'", "type": "event", "name": "message", "params": [], "desc": "

    Messages send by .send(message, [sendHandle]) are obtained using the\nmessage event.\n\n

    \n" } ], "properties": [ { "textRaw": "`stdin` {Stream object} ", "name": "stdin", "desc": "

    A Writable Stream that represents the child process's stdin.\nClosing this stream via end() often causes the child process to terminate.\n\n

    \n

    If the child stdio streams are shared with the parent, then this will\nnot be set.\n\n

    \n" }, { "textRaw": "`stdout` {Stream object} ", "name": "stdout", "desc": "

    A Readable Stream that represents the child process's stdout.\n\n

    \n

    If the child stdio streams are shared with the parent, then this will\nnot be set.\n\n

    \n" }, { "textRaw": "`stderr` {Stream object} ", "name": "stderr", "desc": "

    A Readable Stream that represents the child process's stderr.\n\n

    \n

    If the child stdio streams are shared with the parent, then this will\nnot be set.\n\n

    \n" }, { "textRaw": "`pid` {Integer} ", "name": "pid", "desc": "

    The PID of the child process.\n\n

    \n

    Example:\n\n

    \n
    var spawn = require('child_process').spawn,\n    grep  = spawn('grep', ['ssh']);\n\nconsole.log('Spawned child pid: ' + grep.pid);\ngrep.stdin.end();
    \n" }, { "textRaw": "`connected` {Boolean} Set to false after `.disconnect' is called ", "name": "connected", "desc": "

    If .connected is false, it is no longer possible to send messages.\n\n

    \n", "shortDesc": "Set to false after `.disconnect' is called" } ], "methods": [ { "textRaw": "child.kill([signal])", "type": "method", "name": "kill", "signatures": [ { "params": [ { "textRaw": "`signal` {String} ", "name": "signal", "type": "String", "optional": true } ] }, { "params": [ { "name": "signal", "optional": true } ] } ], "desc": "

    Send a signal to the child process. If no argument is given, the process will\nbe sent 'SIGTERM'. See signal(7) for a list of available signals.\n\n

    \n
    var spawn = require('child_process').spawn,\n    grep  = spawn('grep', ['ssh']);\n\ngrep.on('close', function (code, signal) {\n  console.log('child process terminated due to receipt of signal '+signal);\n});\n\n// send SIGHUP to process\ngrep.kill('SIGHUP');
    \n

    May emit an 'error' event when the signal cannot be delivered. Sending a\nsignal to a child process that has already exited is not an error but may\nhave unforeseen consequences: if the PID (the process ID) has been reassigned\nto another process, the signal will be delivered to that process instead.\nWhat happens next is anyone's guess.\n\n

    \n

    Note that while the function is called kill, the signal delivered to the\nchild process may not actually kill it. kill really just sends a signal\nto a process.\n\n

    \n

    See kill(2)\n\n

    \n" }, { "textRaw": "child.send(message, [sendHandle])", "type": "method", "name": "send", "signatures": [ { "params": [ { "textRaw": "`message` {Object} ", "name": "message", "type": "Object" }, { "textRaw": "`sendHandle` {Handle object} ", "name": "sendHandle", "type": "Handle object", "optional": true } ] }, { "params": [ { "name": "message" }, { "name": "sendHandle", "optional": true } ] } ], "desc": "

    When using child_process.fork() you can write to the child using\nchild.send(message, [sendHandle]) and messages are received by\na 'message' event on the child.\n\n

    \n

    For example:\n\n

    \n
    var cp = require('child_process');\n\nvar n = cp.fork(__dirname + '/sub.js');\n\nn.on('message', function(m) {\n  console.log('PARENT got message:', m);\n});\n\nn.send({ hello: 'world' });
    \n

    And then the child script, 'sub.js' might look like this:\n\n

    \n
    process.on('message', function(m) {\n  console.log('CHILD got message:', m);\n});\n\nprocess.send({ foo: 'bar' });
    \n

    In the child the process object will have a send() method, and process\nwill emit objects each time it receives a message on its channel.\n\n

    \n

    Please note that the send() method on both the parent and child are\nsynchronous - sending large chunks of data is not advised (pipes can be used\ninstead, see\nchild_process.spawn).\n\n

    \n

    There is a special case when sending a {cmd: 'NODE_foo'} message. All messages\ncontaining a NODE_ prefix in its cmd property will not be emitted in\nthe message event, since they are internal messages used by node core.\nMessages containing the prefix are emitted in the internalMessage event, you\nshould by all means avoid using this feature, it is subject to change without notice.\n\n

    \n

    The sendHandle option to child.send() is for sending a TCP server or\nsocket object to another process. The child will receive the object as its\nsecond argument to the message event.\n\n

    \n

    Emits an 'error' event if the message cannot be sent, for example because\nthe child process has already exited.\n\n

    \n

    Example: sending server object

    \n

    Here is an example of sending a server:\n\n

    \n
    var child = require('child_process').fork('child.js');\n\n// Open up the server object and send the handle.\nvar server = require('net').createServer();\nserver.on('connection', function (socket) {\n  socket.end('handled by parent');\n});\nserver.listen(1337, function() {\n  child.send('server', server);\n});
    \n

    And the child would the receive the server object as:\n\n

    \n
    process.on('message', function(m, server) {\n  if (m === 'server') {\n    server.on('connection', function (socket) {\n      socket.end('handled by child');\n    });\n  }\n});
    \n

    Note that the server is now shared between the parent and child, this means\nthat some connections will be handled by the parent and some by the child.\n\n

    \n

    For dgram servers the workflow is exactly the same. Here you listen on\na message event instead of connection and use server.bind instead of\nserver.listen. (Currently only supported on UNIX platforms.)\n\n

    \n

    Example: sending socket object

    \n

    Here is an example of sending a socket. It will spawn two children and handle\nconnections with the remote address 74.125.127.100 as VIP by sending the\nsocket to a "special" child process. Other sockets will go to a "normal" process.\n\n

    \n
    var normal = require('child_process').fork('child.js', ['normal']);\nvar special = require('child_process').fork('child.js', ['special']);\n\n// Open up the server and send sockets to child\nvar server = require('net').createServer();\nserver.on('connection', function (socket) {\n\n  // if this is a VIP\n  if (socket.remoteAddress === '74.125.127.100') {\n    special.send('socket', socket);\n    return;\n  }\n  // just the usual dudes\n  normal.send('socket', socket);\n});\nserver.listen(1337);
    \n

    The child.js could look like this:\n\n

    \n
    process.on('message', function(m, socket) {\n  if (m === 'socket') {\n    socket.end('You were handled as a ' + process.argv[2] + ' person');\n  }\n});
    \n

    Note that once a single socket has been sent to a child the parent can no\nlonger keep track of when the socket is destroyed. To indicate this condition\nthe .connections property becomes null.\nIt is also recommended not to use .maxConnections in this condition.\n\n

    \n" }, { "textRaw": "child.disconnect()", "type": "method", "name": "disconnect", "desc": "

    Close the IPC channel between parent and child, allowing the child to exit\ngracefully once there are no other connections keeping it alive. After calling\nthis method the .connected flag will be set to false in both the parent and\nchild, and it is no longer possible to send messages.\n\n

    \n

    The 'disconnect' event will be emitted when there are no messages in the process\nof being received, most likely immediately.\n\n

    \n

    Note that you can also call process.disconnect() in the child process.\n\n

    \n", "signatures": [ { "params": [] } ] } ] } ], "methods": [ { "textRaw": "child_process.spawn(command, [args], [options])", "type": "method", "name": "spawn", "signatures": [ { "return": { "textRaw": "return: {ChildProcess object} ", "name": "return", "type": "ChildProcess object" }, "params": [ { "textRaw": "`command` {String} The command to run ", "name": "command", "type": "String", "desc": "The command to run" }, { "textRaw": "`args` {Array} List of string arguments ", "name": "args", "type": "Array", "desc": "List of string arguments", "optional": true }, { "textRaw": "`options` {Object} ", "options": [ { "textRaw": "`cwd` {String} Current working directory of the child process ", "name": "cwd", "type": "String", "desc": "Current working directory of the child process" }, { "textRaw": "`stdio` {Array|String} Child's stdio configuration. (See below) ", "name": "stdio", "type": "Array|String", "desc": "Child's stdio configuration. (See below)" }, { "textRaw": "`customFds` {Array} **Deprecated** File descriptors for the child to use for stdio. (See below) ", "name": "customFds", "type": "Array", "desc": "**Deprecated** File descriptors for the child to use for stdio. (See below)" }, { "textRaw": "`env` {Object} Environment key-value pairs ", "name": "env", "type": "Object", "desc": "Environment key-value pairs" }, { "textRaw": "`detached` {Boolean} The child will be a process group leader. (See below) ", "name": "detached", "type": "Boolean", "desc": "The child will be a process group leader. (See below)" }, { "textRaw": "`uid` {Number} Sets the user identity of the process. (See setuid(2).) ", "name": "uid", "type": "Number", "desc": "Sets the user identity of the process. (See setuid(2).)" }, { "textRaw": "`gid` {Number} Sets the group identity of the process. (See setgid(2).) ", "name": "gid", "type": "Number", "desc": "Sets the group identity of the process. (See setgid(2).)" } ], "name": "options", "type": "Object", "optional": true } ] }, { "params": [ { "name": "command" }, { "name": "args", "optional": true }, { "name": "options", "optional": true } ] } ], "desc": "

    Launches a new process with the given command, with command line arguments in args.\nIf omitted, args defaults to an empty Array.\n\n

    \n

    The third argument is used to specify additional options, which defaults to:\n\n

    \n
    { cwd: undefined,\n  env: process.env\n}
    \n

    cwd allows you to specify the working directory from which the process is spawned.\nUse env to specify environment variables that will be visible to the new process.\n\n

    \n

    Example of running ls -lh /usr, capturing stdout, stderr, and the exit code:\n\n

    \n
    var spawn = require('child_process').spawn,\n    ls    = spawn('ls', ['-lh', '/usr']);\n\nls.stdout.on('data', function (data) {\n  console.log('stdout: ' + data);\n});\n\nls.stderr.on('data', function (data) {\n  console.log('stderr: ' + data);\n});\n\nls.on('close', function (code) {\n  console.log('child process exited with code ' + code);\n});
    \n

    Example: A very elaborate way to run 'ps ax | grep ssh'\n\n

    \n
    var spawn = require('child_process').spawn,\n    ps    = spawn('ps', ['ax']),\n    grep  = spawn('grep', ['ssh']);\n\nps.stdout.on('data', function (data) {\n  grep.stdin.write(data);\n});\n\nps.stderr.on('data', function (data) {\n  console.log('ps stderr: ' + data);\n});\n\nps.on('close', function (code) {\n  if (code !== 0) {\n    console.log('ps process exited with code ' + code);\n  }\n  grep.stdin.end();\n});\n\ngrep.stdout.on('data', function (data) {\n  console.log('' + data);\n});\n\ngrep.stderr.on('data', function (data) {\n  console.log('grep stderr: ' + data);\n});\n\ngrep.on('close', function (code) {\n  if (code !== 0) {\n    console.log('grep process exited with code ' + code);\n  }\n});
    \n

    Example of checking for failed exec:\n\n

    \n
    var spawn = require('child_process').spawn,\n    child = spawn('bad_command');\n\nchild.stderr.setEncoding('utf8');\nchild.stderr.on('data', function (data) {\n  if (/^execvp\\(\\)/.test(data)) {\n    console.log('Failed to start child process.');\n  }\n});
    \n

    Note that if spawn receives an empty options object, it will result in\nspawning the process with an empty environment rather than using\nprocess.env. This due to backwards compatibility issues with a deprecated\nAPI.\n\n

    \n

    The 'stdio' option to child_process.spawn() is an array where each\nindex corresponds to a fd in the child. The value is one of the following:\n\n

    \n
      \n
    1. 'pipe' - Create a pipe between the child process and the parent process.\nThe parent end of the pipe is exposed to the parent as a property on the\nchild_process object as ChildProcess.stdio[fd]. Pipes created for\nfds 0 - 2 are also available as ChildProcess.stdin, ChildProcess.stdout\nand ChildProcess.stderr, respectively.
    2. \n
    3. 'ipc' - Create an IPC channel for passing messages/file descriptors\nbetween parent and child. A ChildProcess may have at most one IPC stdio\nfile descriptor. Setting this option enables the ChildProcess.send() method.\nIf the child writes JSON messages to this file descriptor, then this will\ntrigger ChildProcess.on('message'). If the child is a Node.js program, then\nthe presence of an IPC channel will enable process.send() and\nprocess.on('message').
    4. \n
    5. 'ignore' - Do not set this file descriptor in the child. Note that Node\nwill always open fd 0 - 2 for the processes it spawns. When any of these is\nignored node will open /dev/null and attach it to the child's fd.
    6. \n
    7. Stream object - Share a readable or writable stream that refers to a tty,\nfile, socket, or a pipe with the child process. The stream's underlying\nfile descriptor is duplicated in the child process to the fd that \ncorresponds to the index in the stdio array. Note that the stream must\nhave an underlying descriptor (file streams do not until the 'open'\nevent has occurred).
    8. \n
    9. Positive integer - The integer value is interpreted as a file descriptor \nthat is is currently open in the parent process. It is shared with the child\nprocess, similar to how Stream objects can be shared.
    10. \n
    11. null, undefined - Use default value. For stdio fds 0, 1 and 2 (in other\nwords, stdin, stdout, and stderr) a pipe is created. For fd 3 and up, the\ndefault is 'ignore'.
    12. \n
    \n

    As a shorthand, the stdio argument may also be one of the following\nstrings, rather than an array:\n\n

    \n
      \n
    • ignore - ['ignore', 'ignore', 'ignore']
    • \n
    • pipe - ['pipe', 'pipe', 'pipe']
    • \n
    • inherit - [process.stdin, process.stdout, process.stderr] or [0,1,2]
    • \n
    \n

    Example:\n\n

    \n
    var spawn = require('child_process').spawn;\n\n// Child will use parent's stdios\nspawn('prg', [], { stdio: 'inherit' });\n\n// Spawn child sharing only stderr\nspawn('prg', [], { stdio: ['pipe', 'pipe', process.stderr] });\n\n// Open an extra fd=4, to interact with programs present a\n// startd-style interface.\nspawn('prg', [], { stdio: ['pipe', null, null, null, 'pipe'] });
    \n

    If the detached option is set, the child process will be made the leader of a\nnew process group. This makes it possible for the child to continue running \nafter the parent exits.\n\n

    \n

    By default, the parent will wait for the detached child to exit. To prevent\nthe parent from waiting for a given child, use the child.unref() method,\nand the parent's event loop will not include the child in its reference count.\n\n

    \n

    Example of detaching a long-running process and redirecting its output to a\nfile:\n\n

    \n
     var fs = require('fs'),\n     spawn = require('child_process').spawn,\n     out = fs.openSync('./out.log', 'a'),\n     err = fs.openSync('./out.log', 'a');\n\n var child = spawn('prg', [], {\n   detached: true,\n   stdio: [ 'ignore', out, err ]\n });\n\n child.unref();
    \n

    When using the detached option to start a long-running process, the process\nwill not stay running in the background unless it is provided with a stdio\nconfiguration that is not connected to the parent. If the parent's stdio is\ninherited, the child will remain attached to the controlling terminal.\n\n

    \n

    There is a deprecated option called customFds which allows one to specify\nspecific file descriptors for the stdio of the child process. This API was\nnot portable to all platforms and therefore removed.\nWith customFds it was possible to hook up the new process' [stdin, stdout,\nstderr] to existing streams; -1 meant that a new stream should be created.\nUse at your own risk.\n\n

    \n

    See also: child_process.exec() and child_process.fork()\n\n

    \n" }, { "textRaw": "child_process.exec(command, [options], callback)", "type": "method", "name": "exec", "signatures": [ { "return": { "textRaw": "Return: ChildProcess object ", "name": "return", "desc": "ChildProcess object" }, "params": [ { "textRaw": "`command` {String} The command to run, with space-separated arguments ", "name": "command", "type": "String", "desc": "The command to run, with space-separated arguments" }, { "textRaw": "`options` {Object} ", "options": [ { "textRaw": "`cwd` {String} Current working directory of the child process ", "name": "cwd", "type": "String", "desc": "Current working directory of the child process" }, { "textRaw": "`env` {Object} Environment key-value pairs ", "name": "env", "type": "Object", "desc": "Environment key-value pairs" }, { "textRaw": "`encoding` {String} (Default: 'utf8') ", "name": "encoding", "default": "utf8", "type": "String" }, { "textRaw": "`timeout` {Number} (Default: 0) ", "name": "timeout", "default": "0", "type": "Number" }, { "textRaw": "`maxBuffer` {Number} (Default: `200*1024`) ", "name": "maxBuffer", "default": "200*1024", "type": "Number" }, { "textRaw": "`killSignal` {String} (Default: 'SIGTERM') ", "name": "killSignal", "default": "SIGTERM", "type": "String" } ], "name": "options", "type": "Object", "optional": true }, { "textRaw": "`callback` {Function} called with the output when process terminates ", "options": [ { "textRaw": "`error` {Error} ", "name": "error", "type": "Error" }, { "textRaw": "`stdout` {Buffer} ", "name": "stdout", "type": "Buffer" }, { "textRaw": "`stderr` {Buffer} ", "name": "stderr", "type": "Buffer" } ], "name": "callback", "type": "Function", "desc": "called with the output when process terminates" } ] }, { "params": [ { "name": "command" }, { "name": "options", "optional": true }, { "name": "callback" } ] } ], "desc": "

    Runs a command in a shell and buffers the output.\n\n

    \n
    var exec = require('child_process').exec,\n    child;\n\nchild = exec('cat *.js bad_file | wc -l',\n  function (error, stdout, stderr) {\n    console.log('stdout: ' + stdout);\n    console.log('stderr: ' + stderr);\n    if (error !== null) {\n      console.log('exec error: ' + error);\n    }\n});
    \n

    The callback gets the arguments (error, stdout, stderr). On success, error\nwill be null. On error, error will be an instance of Error and err.code\nwill be the exit code of the child process, and err.signal will be set to the\nsignal that terminated the process.\n\n

    \n

    There is a second optional argument to specify several options. The\ndefault options are\n\n

    \n
    { encoding: 'utf8',\n  timeout: 0,\n  maxBuffer: 200*1024,\n  killSignal: 'SIGTERM',\n  cwd: null,\n  env: null }
    \n

    If timeout is greater than 0, then it will kill the child process\nif it runs longer than timeout milliseconds. The child process is killed with\nkillSignal (default: 'SIGTERM'). maxBuffer specifies the largest\namount of data allowed on stdout or stderr - if this value is exceeded then\nthe child process is killed.\n\n\n

    \n" }, { "textRaw": "child_process.execFile(file, [args], [options], [callback])", "type": "method", "name": "execFile", "signatures": [ { "return": { "textRaw": "Return: ChildProcess object ", "name": "return", "desc": "ChildProcess object" }, "params": [ { "textRaw": "`file` {String} The filename of the program to run ", "name": "file", "type": "String", "desc": "The filename of the program to run" }, { "textRaw": "`args` {Array} List of string arguments ", "name": "args", "type": "Array", "desc": "List of string arguments", "optional": true }, { "textRaw": "`options` {Object} ", "options": [ { "textRaw": "`cwd` {String} Current working directory of the child process ", "name": "cwd", "type": "String", "desc": "Current working directory of the child process" }, { "textRaw": "`env` {Object} Environment key-value pairs ", "name": "env", "type": "Object", "desc": "Environment key-value pairs" }, { "textRaw": "`encoding` {String} (Default: 'utf8') ", "name": "encoding", "default": "utf8", "type": "String" }, { "textRaw": "`timeout` {Number} (Default: 0) ", "name": "timeout", "default": "0", "type": "Number" }, { "textRaw": "`maxBuffer` {Number} (Default: 200\\*1024) ", "name": "maxBuffer", "default": "200\\*1024", "type": "Number" }, { "textRaw": "`killSignal` {String} (Default: 'SIGTERM') ", "name": "killSignal", "default": "SIGTERM", "type": "String" } ], "name": "options", "type": "Object", "optional": true }, { "textRaw": "`callback` {Function} called with the output when process terminates ", "options": [ { "textRaw": "`error` {Error} ", "name": "error", "type": "Error" }, { "textRaw": "`stdout` {Buffer} ", "name": "stdout", "type": "Buffer" }, { "textRaw": "`stderr` {Buffer} ", "name": "stderr", "type": "Buffer" } ], "name": "callback", "type": "Function", "desc": "called with the output when process terminates", "optional": true } ] }, { "params": [ { "name": "file" }, { "name": "args", "optional": true }, { "name": "options", "optional": true }, { "name": "callback", "optional": true } ] } ], "desc": "

    This is similar to child_process.exec() except it does not execute a\nsubshell but rather the specified file directly. This makes it slightly\nleaner than child_process.exec. It has the same options.\n\n\n

    \n" }, { "textRaw": "child_process.fork(modulePath, [args], [options])", "type": "method", "name": "fork", "signatures": [ { "return": { "textRaw": "Return: ChildProcess object ", "name": "return", "desc": "ChildProcess object" }, "params": [ { "textRaw": "`modulePath` {String} The module to run in the child ", "name": "modulePath", "type": "String", "desc": "The module to run in the child" }, { "textRaw": "`args` {Array} List of string arguments ", "name": "args", "type": "Array", "desc": "List of string arguments", "optional": true }, { "textRaw": "`options` {Object} ", "options": [ { "textRaw": "`cwd` {String} Current working directory of the child process ", "name": "cwd", "type": "String", "desc": "Current working directory of the child process" }, { "textRaw": "`env` {Object} Environment key-value pairs ", "name": "env", "type": "Object", "desc": "Environment key-value pairs" }, { "textRaw": "`encoding` {String} (Default: 'utf8') ", "name": "encoding", "default": "utf8", "type": "String" }, { "textRaw": "`execPath` {String} Executable used to create the child process ", "name": "execPath", "type": "String", "desc": "Executable used to create the child process" }, { "textRaw": "`execArgv` {Array} List of string arguments passed to the executable (Default: `process.execArgv`) ", "name": "execArgv", "default": "process.execArgv", "type": "Array", "desc": "List of string arguments passed to the executable" }, { "textRaw": "`silent` {Boolean} If true, stdin, stdout, and stderr of the child will be piped to the parent, otherwise they will be inherited from the parent, see the \"pipe\" and \"inherit\" options for `spawn()`'s `stdio` for more details (default is false) ", "name": "silent", "type": "Boolean", "desc": "If true, stdin, stdout, and stderr of the child will be piped to the parent, otherwise they will be inherited from the parent, see the \"pipe\" and \"inherit\" options for `spawn()`'s `stdio` for more details (default is false)" } ], "name": "options", "type": "Object", "optional": true } ] }, { "params": [ { "name": "modulePath" }, { "name": "args", "optional": true }, { "name": "options", "optional": true } ] } ], "desc": "

    This is a special case of the spawn() functionality for spawning Node\nprocesses. In addition to having all the methods in a normal ChildProcess\ninstance, the returned object has a communication channel built-in. See\nchild.send(message, [sendHandle]) for details.\n\n

    \n

    These child Nodes are still whole new instances of V8. Assume at least 30ms\nstartup and 10mb memory for each new Node. That is, you cannot create many\nthousands of them.\n\n

    \n

    The execPath property in the options object allows for a process to be\ncreated for the child rather than the current node executable. This should be\ndone with care and by default will talk over the fd represented an\nenvironmental variable NODE_CHANNEL_FD on the child process. The input and\noutput on this fd is expected to be line delimited JSON objects.\n\n

    \n" } ], "type": "module", "displayName": "Child Process" } ] } node-v0.10.25~dfsg2/doc/api/string_decoder.markdown0000644000000000000000000000133012270121457020667 0ustar rootroot# StringDecoder Stability: 3 - Stable To use this module, do `require('string_decoder')`. StringDecoder decodes a buffer to a string. It is a simple interface to `buffer.toString()` but provides additional support for utf8. var StringDecoder = require('string_decoder').StringDecoder; var decoder = new StringDecoder('utf8'); var cent = new Buffer([0xC2, 0xA2]); console.log(decoder.write(cent)); var euro = new Buffer([0xE2, 0x82, 0xAC]); console.log(decoder.write(euro)); ## Class: StringDecoder Accepts a single argument, `encoding` which defaults to `utf8`. ### decoder.write(buffer) Returns a decoded string. ### decoder.end() Returns any trailing bytes that were left in the buffer. node-v0.10.25~dfsg2/doc/api/console.markdown0000644000000000000000000000356212270121457017347 0ustar rootroot# console Stability: 4 - API Frozen * {Object} For printing to stdout and stderr. Similar to the console object functions provided by most web browsers, here the output is sent to stdout or stderr. The console functions are synchronous when the destination is a terminal or a file (to avoid lost messages in case of premature exit) and asynchronous when it's a pipe (to avoid blocking for long periods of time). That is, in the following example, stdout is non-blocking while stderr is blocking: $ node script.js 2> error.log | tee info.log In daily use, the blocking/non-blocking dichotomy is not something you should worry about unless you log huge amounts of data. ## console.log([data], [...]) Prints to stdout with newline. This function can take multiple arguments in a `printf()`-like way. Example: console.log('count: %d', count); If formatting elements are not found in the first string then `util.inspect` is used on each argument. See [util.format()][] for more information. ## console.info([data], [...]) Same as `console.log`. ## console.error([data], [...]) Same as `console.log` but prints to stderr. ## console.warn([data], [...]) Same as `console.error`. ## console.dir(obj) Uses `util.inspect` on `obj` and prints resulting string to stdout. ## console.time(label) Mark a time. ## console.timeEnd(label) Finish timer, record output. Example: console.time('100-elements'); for (var i = 0; i < 100; i++) { ; } console.timeEnd('100-elements'); ## console.trace(label) Print a stack trace to stderr of the current position. ## console.assert(expression, [message]) Same as [assert.ok()][] where if the `expression` evaluates as `false` throw an AssertionError with `message`. [assert.ok()]: assert.html#assert_assert_value_message_assert_ok_value_message [util.format()]: util.html#util_util_format_format node-v0.10.25~dfsg2/doc/api/events.markdown0000644000000000000000000000732112270121457017206 0ustar rootroot# Events Stability: 4 - API Frozen Many objects in Node emit events: a `net.Server` emits an event each time a peer connects to it, a `fs.readStream` emits an event when the file is opened. All objects which emit events are instances of `events.EventEmitter`. You can access this module by doing: `require("events");` Typically, event names are represented by a camel-cased string, however, there aren't any strict restrictions on that, as any string will be accepted. Functions can then be attached to objects, to be executed when an event is emitted. These functions are called _listeners_. Inside a listener function, `this` refers to the `EventEmitter` that the listener was attached to. ## Class: events.EventEmitter To access the EventEmitter class, `require('events').EventEmitter`. When an `EventEmitter` instance experiences an error, the typical action is to emit an `'error'` event. Error events are treated as a special case in node. If there is no listener for it, then the default action is to print a stack trace and exit the program. All EventEmitters emit the event `'newListener'` when new listeners are added and `'removeListener'` when a listener is removed. ### emitter.addListener(event, listener) ### emitter.on(event, listener) Adds a listener to the end of the listeners array for the specified event. server.on('connection', function (stream) { console.log('someone connected!'); }); Returns emitter, so calls can be chained. ### emitter.once(event, listener) Adds a **one time** listener for the event. This listener is invoked only the next time the event is fired, after which it is removed. server.once('connection', function (stream) { console.log('Ah, we have our first user!'); }); Returns emitter, so calls can be chained. ### emitter.removeListener(event, listener) Remove a listener from the listener array for the specified event. **Caution**: changes array indices in the listener array behind the listener. var callback = function(stream) { console.log('someone connected!'); }; server.on('connection', callback); // ... server.removeListener('connection', callback); Returns emitter, so calls can be chained. ### emitter.removeAllListeners([event]) Removes all listeners, or those of the specified event. Returns emitter, so calls can be chained. ### emitter.setMaxListeners(n) By default EventEmitters will print a warning if more than 10 listeners are added for a particular event. This is a useful default which helps finding memory leaks. Obviously not all Emitters should be limited to 10. This function allows that to be increased. Set to zero for unlimited. ### emitter.listeners(event) Returns an array of listeners for the specified event. server.on('connection', function (stream) { console.log('someone connected!'); }); console.log(util.inspect(server.listeners('connection'))); // [ [Function] ] ### emitter.emit(event, [arg1], [arg2], [...]) Execute each of the listeners in order with the supplied arguments. Returns `true` if event had listeners, `false` otherwise. ### Class Method: EventEmitter.listenerCount(emitter, event) Return the number of listeners for a given event. ### Event: 'newListener' * `event` {String} The event name * `listener` {Function} The event handler function This event is emitted any time someone adds a new listener. It is unspecified if `listener` is in the list returned by `emitter.listeners(event)`. ### Event: 'removeListener' * `event` {String} The event name * `listener` {Function} The event handler function This event is emitted any time someone removes a listener. It is unspecified if `listener` is in the list returned by `emitter.listeners(event)`. node-v0.10.25~dfsg2/doc/api/buffer.markdown0000644000000000000000000005100112270121457017145 0ustar rootroot# Buffer Stability: 3 - Stable Pure JavaScript is Unicode friendly but not nice to binary data. When dealing with TCP streams or the file system, it's necessary to handle octet streams. Node has several strategies for manipulating, creating, and consuming octet streams. Raw data is stored in instances of the `Buffer` class. A `Buffer` is similar to an array of integers but corresponds to a raw memory allocation outside the V8 heap. A `Buffer` cannot be resized. The `Buffer` class is a global, making it very rare that one would need to ever `require('buffer')`. Converting between Buffers and JavaScript string objects requires an explicit encoding method. Here are the different string encodings. * `'ascii'` - for 7 bit ASCII data only. This encoding method is very fast, and will strip the high bit if set. Note that when converting from string to buffer, this encoding converts a null character (`'\0'` or `'\u0000'`) into `0x20` (character code of a space). If you want to convert a null character into `0x00`, you should use `'utf8'`. * `'utf8'` - Multibyte encoded Unicode characters. Many web pages and other document formats use UTF-8. * `'utf16le'` - 2 or 4 bytes, little endian encoded Unicode characters. Surrogate pairs (U+10000 to U+10FFFF) are supported. * `'ucs2'` - Alias of `'utf16le'`. * `'base64'` - Base64 string encoding. * `'binary'` - A way of encoding raw binary data into strings by using only the first 8 bits of each character. This encoding method is deprecated and should be avoided in favor of `Buffer` objects where possible. This encoding will be removed in future versions of Node. * `'hex'` - Encode each byte as two hexadecimal characters. A `Buffer` object can also be used with typed arrays. The buffer object is cloned to an `ArrayBuffer` that is used as the backing store for the typed array. The memory of the buffer and the `ArrayBuffer` is not shared. NOTE: Node.js v0.8 simply retained a reference to the buffer in `array.buffer` instead of cloning it. While more efficient, it introduces subtle incompatibilities with the typed arrays specification. `ArrayBuffer#slice()` makes a copy of the slice while `Buffer#slice()` creates a view. ## Class: Buffer The Buffer class is a global type for dealing with binary data directly. It can be constructed in a variety of ways. ### new Buffer(size) * `size` Number Allocates a new buffer of `size` octets. ### new Buffer(array) * `array` Array Allocates a new buffer using an `array` of octets. ### new Buffer(str, [encoding]) * `str` String - string to encode. * `encoding` String - encoding to use, Optional. Allocates a new buffer containing the given `str`. `encoding` defaults to `'utf8'`. ### Class Method: Buffer.isEncoding(encoding) * `encoding` {String} The encoding string to test Returns true if the `encoding` is a valid encoding argument, or false otherwise. ### buf.write(string, [offset], [length], [encoding]) * `string` String - data to be written to buffer * `offset` Number, Optional, Default: 0 * `length` Number, Optional, Default: `buffer.length - offset` * `encoding` String, Optional, Default: 'utf8' Writes `string` to the buffer at `offset` using the given encoding. `offset` defaults to `0`, `encoding` defaults to `'utf8'`. `length` is the number of bytes to write. Returns number of octets written. If `buffer` did not contain enough space to fit the entire string, it will write a partial amount of the string. `length` defaults to `buffer.length - offset`. The method will not write partial characters. buf = new Buffer(256); len = buf.write('\u00bd + \u00bc = \u00be', 0); console.log(len + " bytes: " + buf.toString('utf8', 0, len)); The number of characters written (which may be different than the number of bytes written) is set in `Buffer._charsWritten` and will be overwritten the next time `buf.write()` is called. ### buf.toString([encoding], [start], [end]) * `encoding` String, Optional, Default: 'utf8' * `start` Number, Optional, Default: 0 * `end` Number, Optional, Default: `buffer.length` Decodes and returns a string from buffer data encoded with `encoding` (defaults to `'utf8'`) beginning at `start` (defaults to `0`) and ending at `end` (defaults to `buffer.length`). See `buffer.write()` example, above. ### buf.toJSON() Returns a JSON-representation of the Buffer instance, which is identical to the output for JSON Arrays. `JSON.stringify` implicitly calls this function when stringifying a Buffer instance. Example: var buf = new Buffer('test'); var json = JSON.stringify(buf); console.log(json); // '[116,101,115,116]' var copy = new Buffer(JSON.parse(json)); console.log(copy); // ### buf[index] Get and set the octet at `index`. The values refer to individual bytes, so the legal range is between `0x00` and `0xFF` hex or `0` and `255`. Example: copy an ASCII string into a buffer, one byte at a time: str = "node.js"; buf = new Buffer(str.length); for (var i = 0; i < str.length ; i++) { buf[i] = str.charCodeAt(i); } console.log(buf); // node.js ### Class Method: Buffer.isBuffer(obj) * `obj` Object * Return: Boolean Tests if `obj` is a `Buffer`. ### Class Method: Buffer.byteLength(string, [encoding]) * `string` String * `encoding` String, Optional, Default: 'utf8' * Return: Number Gives the actual byte length of a string. `encoding` defaults to `'utf8'`. This is not the same as `String.prototype.length` since that returns the number of *characters* in a string. Example: str = '\u00bd + \u00bc = \u00be'; console.log(str + ": " + str.length + " characters, " + Buffer.byteLength(str, 'utf8') + " bytes"); // ½ + ¼ = ¾: 9 characters, 12 bytes ### Class Method: Buffer.concat(list, [totalLength]) * `list` {Array} List of Buffer objects to concat * `totalLength` {Number} Total length of the buffers when concatenated Returns a buffer which is the result of concatenating all the buffers in the list together. If the list has no items, or if the totalLength is 0, then it returns a zero-length buffer. If the list has exactly one item, then the first item of the list is returned. If the list has more than one item, then a new Buffer is created. If totalLength is not provided, it is read from the buffers in the list. However, this adds an additional loop to the function, so it is faster to provide the length explicitly. ### buf.length * Number The size of the buffer in bytes. Note that this is not necessarily the size of the contents. `length` refers to the amount of memory allocated for the buffer object. It does not change when the contents of the buffer are changed. buf = new Buffer(1234); console.log(buf.length); buf.write("some string", 0, "ascii"); console.log(buf.length); // 1234 // 1234 ### buf.copy(targetBuffer, [targetStart], [sourceStart], [sourceEnd]) * `targetBuffer` Buffer object - Buffer to copy into * `targetStart` Number, Optional, Default: 0 * `sourceStart` Number, Optional, Default: 0 * `sourceEnd` Number, Optional, Default: `buffer.length` Does copy between buffers. The source and target regions can be overlapped. `targetStart` and `sourceStart` default to `0`. `sourceEnd` defaults to `buffer.length`. All values passed that are `undefined`/`NaN` or are out of bounds are set equal to their respective defaults. Example: build two Buffers, then copy `buf1` from byte 16 through byte 19 into `buf2`, starting at the 8th byte in `buf2`. buf1 = new Buffer(26); buf2 = new Buffer(26); for (var i = 0 ; i < 26 ; i++) { buf1[i] = i + 97; // 97 is ASCII a buf2[i] = 33; // ASCII ! } buf1.copy(buf2, 8, 16, 20); console.log(buf2.toString('ascii', 0, 25)); // !!!!!!!!qrst!!!!!!!!!!!!! ### buf.slice([start], [end]) * `start` Number, Optional, Default: 0 * `end` Number, Optional, Default: `buffer.length` Returns a new buffer which references the same memory as the old, but offset and cropped by the `start` (defaults to `0`) and `end` (defaults to `buffer.length`) indexes. Negative indexes start from the end of the buffer. **Modifying the new buffer slice will modify memory in the original buffer!** Example: build a Buffer with the ASCII alphabet, take a slice, then modify one byte from the original Buffer. var buf1 = new Buffer(26); for (var i = 0 ; i < 26 ; i++) { buf1[i] = i + 97; // 97 is ASCII a } var buf2 = buf1.slice(0, 3); console.log(buf2.toString('ascii', 0, buf2.length)); buf1[0] = 33; console.log(buf2.toString('ascii', 0, buf2.length)); // abc // !bc ### buf.readUInt8(offset, [noAssert]) * `offset` Number * `noAssert` Boolean, Optional, Default: false * Return: Number Reads an unsigned 8 bit integer from the buffer at the specified offset. Set `noAssert` to true to skip validation of `offset`. This means that `offset` may be beyond the end of the buffer. Defaults to `false`. Example: var buf = new Buffer(4); buf[0] = 0x3; buf[1] = 0x4; buf[2] = 0x23; buf[3] = 0x42; for (ii = 0; ii < buf.length; ii++) { console.log(buf.readUInt8(ii)); } // 0x3 // 0x4 // 0x23 // 0x42 ### buf.readUInt16LE(offset, [noAssert]) ### buf.readUInt16BE(offset, [noAssert]) * `offset` Number * `noAssert` Boolean, Optional, Default: false * Return: Number Reads an unsigned 16 bit integer from the buffer at the specified offset with specified endian format. Set `noAssert` to true to skip validation of `offset`. This means that `offset` may be beyond the end of the buffer. Defaults to `false`. Example: var buf = new Buffer(4); buf[0] = 0x3; buf[1] = 0x4; buf[2] = 0x23; buf[3] = 0x42; console.log(buf.readUInt16BE(0)); console.log(buf.readUInt16LE(0)); console.log(buf.readUInt16BE(1)); console.log(buf.readUInt16LE(1)); console.log(buf.readUInt16BE(2)); console.log(buf.readUInt16LE(2)); // 0x0304 // 0x0403 // 0x0423 // 0x2304 // 0x2342 // 0x4223 ### buf.readUInt32LE(offset, [noAssert]) ### buf.readUInt32BE(offset, [noAssert]) * `offset` Number * `noAssert` Boolean, Optional, Default: false * Return: Number Reads an unsigned 32 bit integer from the buffer at the specified offset with specified endian format. Set `noAssert` to true to skip validation of `offset`. This means that `offset` may be beyond the end of the buffer. Defaults to `false`. Example: var buf = new Buffer(4); buf[0] = 0x3; buf[1] = 0x4; buf[2] = 0x23; buf[3] = 0x42; console.log(buf.readUInt32BE(0)); console.log(buf.readUInt32LE(0)); // 0x03042342 // 0x42230403 ### buf.readInt8(offset, [noAssert]) * `offset` Number * `noAssert` Boolean, Optional, Default: false * Return: Number Reads a signed 8 bit integer from the buffer at the specified offset. Set `noAssert` to true to skip validation of `offset`. This means that `offset` may be beyond the end of the buffer. Defaults to `false`. Works as `buffer.readUInt8`, except buffer contents are treated as two's complement signed values. ### buf.readInt16LE(offset, [noAssert]) ### buf.readInt16BE(offset, [noAssert]) * `offset` Number * `noAssert` Boolean, Optional, Default: false * Return: Number Reads a signed 16 bit integer from the buffer at the specified offset with specified endian format. Set `noAssert` to true to skip validation of `offset`. This means that `offset` may be beyond the end of the buffer. Defaults to `false`. Works as `buffer.readUInt16*`, except buffer contents are treated as two's complement signed values. ### buf.readInt32LE(offset, [noAssert]) ### buf.readInt32BE(offset, [noAssert]) * `offset` Number * `noAssert` Boolean, Optional, Default: false * Return: Number Reads a signed 32 bit integer from the buffer at the specified offset with specified endian format. Set `noAssert` to true to skip validation of `offset`. This means that `offset` may be beyond the end of the buffer. Defaults to `false`. Works as `buffer.readUInt32*`, except buffer contents are treated as two's complement signed values. ### buf.readFloatLE(offset, [noAssert]) ### buf.readFloatBE(offset, [noAssert]) * `offset` Number * `noAssert` Boolean, Optional, Default: false * Return: Number Reads a 32 bit float from the buffer at the specified offset with specified endian format. Set `noAssert` to true to skip validation of `offset`. This means that `offset` may be beyond the end of the buffer. Defaults to `false`. Example: var buf = new Buffer(4); buf[0] = 0x00; buf[1] = 0x00; buf[2] = 0x80; buf[3] = 0x3f; console.log(buf.readFloatLE(0)); // 0x01 ### buf.readDoubleLE(offset, [noAssert]) ### buf.readDoubleBE(offset, [noAssert]) * `offset` Number * `noAssert` Boolean, Optional, Default: false * Return: Number Reads a 64 bit double from the buffer at the specified offset with specified endian format. Set `noAssert` to true to skip validation of `offset`. This means that `offset` may be beyond the end of the buffer. Defaults to `false`. Example: var buf = new Buffer(8); buf[0] = 0x55; buf[1] = 0x55; buf[2] = 0x55; buf[3] = 0x55; buf[4] = 0x55; buf[5] = 0x55; buf[6] = 0xd5; buf[7] = 0x3f; console.log(buf.readDoubleLE(0)); // 0.3333333333333333 ### buf.writeUInt8(value, offset, [noAssert]) * `value` Number * `offset` Number * `noAssert` Boolean, Optional, Default: false Writes `value` to the buffer at the specified offset. Note, `value` must be a valid unsigned 8 bit integer. Set `noAssert` to true to skip validation of `value` and `offset`. This means that `value` may be too large for the specific function and `offset` may be beyond the end of the buffer leading to the values being silently dropped. This should not be used unless you are certain of correctness. Defaults to `false`. Example: var buf = new Buffer(4); buf.writeUInt8(0x3, 0); buf.writeUInt8(0x4, 1); buf.writeUInt8(0x23, 2); buf.writeUInt8(0x42, 3); console.log(buf); // ### buf.writeUInt16LE(value, offset, [noAssert]) ### buf.writeUInt16BE(value, offset, [noAssert]) * `value` Number * `offset` Number * `noAssert` Boolean, Optional, Default: false Writes `value` to the buffer at the specified offset with specified endian format. Note, `value` must be a valid unsigned 16 bit integer. Set `noAssert` to true to skip validation of `value` and `offset`. This means that `value` may be too large for the specific function and `offset` may be beyond the end of the buffer leading to the values being silently dropped. This should not be used unless you are certain of correctness. Defaults to `false`. Example: var buf = new Buffer(4); buf.writeUInt16BE(0xdead, 0); buf.writeUInt16BE(0xbeef, 2); console.log(buf); buf.writeUInt16LE(0xdead, 0); buf.writeUInt16LE(0xbeef, 2); console.log(buf); // // ### buf.writeUInt32LE(value, offset, [noAssert]) ### buf.writeUInt32BE(value, offset, [noAssert]) * `value` Number * `offset` Number * `noAssert` Boolean, Optional, Default: false Writes `value` to the buffer at the specified offset with specified endian format. Note, `value` must be a valid unsigned 32 bit integer. Set `noAssert` to true to skip validation of `value` and `offset`. This means that `value` may be too large for the specific function and `offset` may be beyond the end of the buffer leading to the values being silently dropped. This should not be used unless you are certain of correctness. Defaults to `false`. Example: var buf = new Buffer(4); buf.writeUInt32BE(0xfeedface, 0); console.log(buf); buf.writeUInt32LE(0xfeedface, 0); console.log(buf); // // ### buf.writeInt8(value, offset, [noAssert]) * `value` Number * `offset` Number * `noAssert` Boolean, Optional, Default: false Writes `value` to the buffer at the specified offset. Note, `value` must be a valid signed 8 bit integer. Set `noAssert` to true to skip validation of `value` and `offset`. This means that `value` may be too large for the specific function and `offset` may be beyond the end of the buffer leading to the values being silently dropped. This should not be used unless you are certain of correctness. Defaults to `false`. Works as `buffer.writeUInt8`, except value is written out as a two's complement signed integer into `buffer`. ### buf.writeInt16LE(value, offset, [noAssert]) ### buf.writeInt16BE(value, offset, [noAssert]) * `value` Number * `offset` Number * `noAssert` Boolean, Optional, Default: false Writes `value` to the buffer at the specified offset with specified endian format. Note, `value` must be a valid signed 16 bit integer. Set `noAssert` to true to skip validation of `value` and `offset`. This means that `value` may be too large for the specific function and `offset` may be beyond the end of the buffer leading to the values being silently dropped. This should not be used unless you are certain of correctness. Defaults to `false`. Works as `buffer.writeUInt16*`, except value is written out as a two's complement signed integer into `buffer`. ### buf.writeInt32LE(value, offset, [noAssert]) ### buf.writeInt32BE(value, offset, [noAssert]) * `value` Number * `offset` Number * `noAssert` Boolean, Optional, Default: false Writes `value` to the buffer at the specified offset with specified endian format. Note, `value` must be a valid signed 32 bit integer. Set `noAssert` to true to skip validation of `value` and `offset`. This means that `value` may be too large for the specific function and `offset` may be beyond the end of the buffer leading to the values being silently dropped. This should not be used unless you are certain of correctness. Defaults to `false`. Works as `buffer.writeUInt32*`, except value is written out as a two's complement signed integer into `buffer`. ### buf.writeFloatLE(value, offset, [noAssert]) ### buf.writeFloatBE(value, offset, [noAssert]) * `value` Number * `offset` Number * `noAssert` Boolean, Optional, Default: false Writes `value` to the buffer at the specified offset with specified endian format. Note, behavior is unspecified if `value` is not a 32 bit float. Set `noAssert` to true to skip validation of `value` and `offset`. This means that `value` may be too large for the specific function and `offset` may be beyond the end of the buffer leading to the values being silently dropped. This should not be used unless you are certain of correctness. Defaults to `false`. Example: var buf = new Buffer(4); buf.writeFloatBE(0xcafebabe, 0); console.log(buf); buf.writeFloatLE(0xcafebabe, 0); console.log(buf); // // ### buf.writeDoubleLE(value, offset, [noAssert]) ### buf.writeDoubleBE(value, offset, [noAssert]) * `value` Number * `offset` Number * `noAssert` Boolean, Optional, Default: false Writes `value` to the buffer at the specified offset with specified endian format. Note, `value` must be a valid 64 bit double. Set `noAssert` to true to skip validation of `value` and `offset`. This means that `value` may be too large for the specific function and `offset` may be beyond the end of the buffer leading to the values being silently dropped. This should not be used unless you are certain of correctness. Defaults to `false`. Example: var buf = new Buffer(8); buf.writeDoubleBE(0xdeadbeefcafebabe, 0); console.log(buf); buf.writeDoubleLE(0xdeadbeefcafebabe, 0); console.log(buf); // // ### buf.fill(value, [offset], [end]) * `value` * `offset` Number, Optional * `end` Number, Optional Fills the buffer with the specified value. If the `offset` (defaults to `0`) and `end` (defaults to `buffer.length`) are not given it will fill the entire buffer. var b = new Buffer(50); b.fill("h"); ## buffer.INSPECT_MAX_BYTES * Number, Default: 50 How many bytes will be returned when `buffer.inspect()` is called. This can be overridden by user modules. Note that this is a property on the buffer module returned by `require('buffer')`, not on the Buffer global, or a buffer instance. ## Class: SlowBuffer This class is primarily for internal use. JavaScript programs should use Buffer instead of using SlowBuffer. In order to avoid the overhead of allocating many C++ Buffer objects for small blocks of memory in the lifetime of a server, Node allocates memory in 8Kb (8192 byte) chunks. If a buffer is smaller than this size, then it will be backed by a parent SlowBuffer object. If it is larger than this, then Node will allocate a SlowBuffer slab for it directly. node-v0.10.25~dfsg2/doc/api/stream.markdown0000644000000000000000000013500112270121457017172 0ustar rootroot# Stream Stability: 2 - Unstable A stream is an abstract interface implemented by various objects in Node. For example a [request to an HTTP server](http.html#http_http_incomingmessage) is a stream, as is [stdout][]. Streams are readable, writable, or both. All streams are instances of [EventEmitter][] You can load the Stream base classes by doing `require('stream')`. There are base classes provided for [Readable][] streams, [Writable][] streams, [Duplex][] streams, and [Transform][] streams. This document is split up into 3 sections. The first explains the parts of the API that you need to be aware of to use streams in your programs. If you never implement a streaming API yourself, you can stop there. The second section explains the parts of the API that you need to use if you implement your own custom streams yourself. The API is designed to make this easy for you to do. The third section goes into more depth about how streams work, including some of the internal mechanisms and functions that you should probably not modify unless you definitely know what you are doing. ## API for Stream Consumers Streams can be either [Readable][], [Writable][], or both ([Duplex][]). All streams are EventEmitters, but they also have other custom methods and properties depending on whether they are Readable, Writable, or Duplex. If a stream is both Readable and Writable, then it implements all of the methods and events below. So, a [Duplex][] or [Transform][] stream is fully described by this API, though their implementation may be somewhat different. It is not necessary to implement Stream interfaces in order to consume streams in your programs. If you **are** implementing streaming interfaces in your own program, please also refer to [API for Stream Implementors][] below. Almost all Node programs, no matter how simple, use Streams in some way. Here is an example of using Streams in a Node program: ```javascript var http = require('http'); var server = http.createServer(function (req, res) { // req is an http.IncomingMessage, which is a Readable Stream // res is an http.ServerResponse, which is a Writable Stream var body = ''; // we want to get the data as utf8 strings // If you don't set an encoding, then you'll get Buffer objects req.setEncoding('utf8'); // Readable streams emit 'data' events once a listener is added req.on('data', function (chunk) { body += chunk; }) // the end event tells you that you have entire body req.on('end', function () { try { var data = JSON.parse(body); } catch (er) { // uh oh! bad json! res.statusCode = 400; return res.end('error: ' + er.message); } // write back something interesting to the user: res.write(typeof data); res.end(); }) }) server.listen(1337); // $ curl localhost:1337 -d '{}' // object // $ curl localhost:1337 -d '"foo"' // string // $ curl localhost:1337 -d 'not json' // error: Unexpected token o ``` ### Class: stream.Readable The Readable stream interface is the abstraction for a *source* of data that you are reading from. In other words, data comes *out* of a Readable stream. A Readable stream will not start emitting data until you indicate that you are ready to receive it. Readable streams have two "modes": a **flowing mode** and a **non-flowing mode**. When in flowing mode, data is read from the underlying system and provided to your program as fast as possible. In non-flowing mode, you must explicitly call `stream.read()` to get chunks of data out. Examples of readable streams include: * [http responses, on the client](http.html#http_http_incomingmessage) * [http requests, on the server](http.html#http_http_incomingmessage) * [fs read streams](fs.html#fs_class_fs_readstream) * [zlib streams][] * [crypto streams][] * [tcp sockets][] * [child process stdout and stderr][] * [process.stdin][] #### Event: 'readable' When a chunk of data can be read from the stream, it will emit a `'readable'` event. In some cases, listening for a `'readable'` event will cause some data to be read into the internal buffer from the underlying system, if it hadn't already. ```javascript var readable = getReadableStreamSomehow(); readable.on('readable', function() { // there is some data to read now }) ``` Once the internal buffer is drained, a `readable` event will fire again when more data is available. #### Event: 'data' * `chunk` {Buffer | String} The chunk of data. If you attach a `data` event listener, then it will switch the stream into flowing mode, and data will be passed to your handler as soon as it is available. If you just want to get all the data out of the stream as fast as possible, this is the best way to do so. ```javascript var readable = getReadableStreamSomehow(); readable.on('data', function(chunk) { console.log('got %d bytes of data', chunk.length); }) ``` #### Event: 'end' This event fires when no more data will be provided. Note that the `end` event **will not fire** unless the data is completely consumed. This can be done by switching into flowing mode, or by calling `read()` repeatedly until you get to the end. ```javascript var readable = getReadableStreamSomehow(); readable.on('data', function(chunk) { console.log('got %d bytes of data', chunk.length); }) readable.on('end', function() { console.log('there will be no more data.'); }); ``` #### Event: 'close' Emitted when the underlying resource (for example, the backing file descriptor) has been closed. Not all streams will emit this. #### Event: 'error' Emitted if there was an error receiving data. #### readable.read([size]) * `size` {Number} Optional argument to specify how much data to read. * Return {String | Buffer | null} The `read()` method pulls some data out of the internal buffer and returns it. If there is no data available, then it will return `null`. If you pass in a `size` argument, then it will return that many bytes. If `size` bytes are not available, then it will return `null`. If you do not specify a `size` argument, then it will return all the data in the internal buffer. This method should only be called in non-flowing mode. In flowing-mode, this method is called automatically until the internal buffer is drained. ```javascript var readable = getReadableStreamSomehow(); readable.on('readable', function() { var chunk; while (null !== (chunk = readable.read())) { console.log('got %d bytes of data', chunk.length); } }); ``` #### readable.setEncoding(encoding) * `encoding` {String} The encoding to use. Call this function to cause the stream to return strings of the specified encoding instead of Buffer objects. For example, if you do `readable.setEncoding('utf8')`, then the output data will be interpreted as UTF-8 data, and returned as strings. If you do `readable.setEncoding('hex')`, then the data will be encoded in hexadecimal string format. This properly handles multi-byte characters that would otherwise be potentially mangled if you simply pulled the Buffers directly and called `buf.toString(encoding)` on them. If you want to read the data as strings, always use this method. ```javascript var readable = getReadableStreamSomehow(); readable.setEncoding('utf8'); readable.on('data', function(chunk) { assert.equal(typeof chunk, 'string'); console.log('got %d characters of string data', chunk.length); }) ``` #### readable.resume() This method will cause the readable stream to resume emitting `data` events. This method will switch the stream into flowing-mode. If you do *not* want to consume the data from a stream, but you *do* want to get to its `end` event, you can call `readable.resume()` to open the flow of data. ```javascript var readable = getReadableStreamSomehow(); readable.resume(); readable.on('end', function(chunk) { console.log('got to the end, but did not read anything'); }) ``` #### readable.pause() This method will cause a stream in flowing-mode to stop emitting `data` events. Any data that becomes available will remain in the internal buffer. This method is only relevant in flowing mode. When called on a non-flowing stream, it will switch into flowing mode, but remain paused. ```javascript var readable = getReadableStreamSomehow(); readable.on('data', function(chunk) { console.log('got %d bytes of data', chunk.length); readable.pause(); console.log('there will be no more data for 1 second'); setTimeout(function() { console.log('now data will start flowing again'); readable.resume(); }, 1000); }) ``` #### readable.pipe(destination, [options]) * `destination` {[Writable][] Stream} The destination for writing data * `options` {Object} Pipe options * `end` {Boolean} End the writer when the reader ends. Default = `true` This method pulls all the data out of a readable stream, and writes it to the supplied destination, automatically managing the flow so that the destination is not overwhelmed by a fast readable stream. Multiple destinations can be piped to safely. ```javascript var readable = getReadableStreamSomehow(); var writable = fs.createWriteStream('file.txt'); // All the data from readable goes into 'file.txt' readable.pipe(writable); ``` This function returns the destination stream, so you can set up pipe chains like so: ```javascript var r = fs.createReadStream('file.txt'); var z = zlib.createGzip(); var w = fs.createWriteStream('file.txt.gz'); r.pipe(z).pipe(w); ``` For example, emulating the Unix `cat` command: ```javascript process.stdin.pipe(process.stdout); ``` By default [`end()`][] is called on the destination when the source stream emits `end`, so that `destination` is no longer writable. Pass `{ end: false }` as `options` to keep the destination stream open. This keeps `writer` open so that "Goodbye" can be written at the end. ```javascript reader.pipe(writer, { end: false }); reader.on('end', function() { writer.end('Goodbye\n'); }); ``` Note that `process.stderr` and `process.stdout` are never closed until the process exits, regardless of the specified options. #### readable.unpipe([destination]) * `destination` {[Writable][] Stream} Optional specific stream to unpipe This method will remove the hooks set up for a previous `pipe()` call. If the destination is not specified, then all pipes are removed. If the destination is specified, but no pipe is set up for it, then this is a no-op. ```javascript var readable = getReadableStreamSomehow(); var writable = fs.createWriteStream('file.txt'); // All the data from readable goes into 'file.txt', // but only for the first second readable.pipe(writable); setTimeout(function() { console.log('stop writing to file.txt'); readable.unpipe(writable); console.log('manually close the file stream'); writable.end(); }, 1000); ``` #### readable.unshift(chunk) * `chunk` {Buffer | String} Chunk of data to unshift onto the read queue This is useful in certain cases where a stream is being consumed by a parser, which needs to "un-consume" some data that it has optimistically pulled out of the source, so that the stream can be passed on to some other party. If you find that you must often call `stream.unshift(chunk)` in your programs, consider implementing a [Transform][] stream instead. (See API for Stream Implementors, below.) ```javascript // Pull off a header delimited by \n\n // use unshift() if we get too much // Call the callback with (error, header, stream) var StringDecoder = require('string_decoder').StringDecoder; function parseHeader(stream, callback) { stream.on('error', callback); stream.on('readable', onReadable); var decoder = new StringDecoder('utf8'); var header = ''; function onReadable() { var chunk; while (null !== (chunk = stream.read())) { var str = decoder.write(chunk); if (str.match(/\n\n/)) { // found the header boundary var split = str.split(/\n\n/); header += split.shift(); var remaining = split.join('\n\n'); var buf = new Buffer(remaining, 'utf8'); if (buf.length) stream.unshift(buf); stream.removeListener('error', callback); stream.removeListener('readable', onReadable); // now the body of the message can be read from the stream. callback(null, header, stream); } else { // still reading the header. header += str; } } } } ``` #### readable.wrap(stream) * `stream` {Stream} An "old style" readable stream Versions of Node prior to v0.10 had streams that did not implement the entire Streams API as it is today. (See "Compatibility" below for more information.) If you are using an older Node library that emits `'data'` events and has a `pause()` method that is advisory only, then you can use the `wrap()` method to create a [Readable][] stream that uses the old stream as its data source. You will very rarely ever need to call this function, but it exists as a convenience for interacting with old Node programs and libraries. For example: ```javascript var OldReader = require('./old-api-module.js').OldReader; var oreader = new OldReader; var Readable = require('stream').Readable; var myReader = new Readable().wrap(oreader); myReader.on('readable', function() { myReader.read(); // etc. }); ``` ### Class: stream.Writable The Writable stream interface is an abstraction for a *destination* that you are writing data *to*. Examples of writable streams include: * [http requests, on the client](http.html#http_class_http_clientrequest) * [http responses, on the server](http.html#http_class_http_serverresponse) * [fs write streams](fs.html#fs_class_fs_writestream) * [zlib streams][] * [crypto streams][] * [tcp sockets][] * [child process stdin](child_process.html#child_process_child_stdin) * [process.stdout][], [process.stderr][] #### writable.write(chunk, [encoding], [callback]) * `chunk` {String | Buffer} The data to write * `encoding` {String} The encoding, if `chunk` is a String * `callback` {Function} Callback for when this chunk of data is flushed * Returns: {Boolean} True if the data was handled completely. This method writes some data to the underlying system, and calls the supplied callback once the data has been fully handled. The return value indicates if you should continue writing right now. If the data had to be buffered internally, then it will return `false`. Otherwise, it will return `true`. This return value is strictly advisory. You MAY continue to write, even if it returns `false`. However, writes will be buffered in memory, so it is best not to do this excessively. Instead, wait for the `drain` event before writing more data. #### Event: 'drain' If a [`writable.write(chunk)`][] call returns false, then the `drain` event will indicate when it is appropriate to begin writing more data to the stream. ```javascript // Write the data to the supplied writable stream 1MM times. // Be attentive to back-pressure. function writeOneMillionTimes(writer, data, encoding, callback) { var i = 1000000; write(); function write() { var ok = true; do { i -= 1; if (i === 0) { // last time! writer.write(data, encoding, callback); } else { // see if we should continue, or wait // don't pass the callback, because we're not done yet. ok = writer.write(data, encoding); } } while (i > 0 && ok); if (i > 0) { // had to stop early! // write some more once it drains writer.once('drain', write); } } } ``` #### writable.end([chunk], [encoding], [callback]) * `chunk` {String | Buffer} Optional data to write * `encoding` {String} The encoding, if `chunk` is a String * `callback` {Function} Optional callback for when the stream is finished Call this method when no more data will be written to the stream. If supplied, the callback is attached as a listener on the `finish` event. Calling [`write()`][] after calling [`end()`][] will raise an error. ```javascript // write 'hello, ' and then end with 'world!' http.createServer(function (req, res) { res.write('hello, '); res.end('world!'); // writing more now is not allowed! }); ``` #### Event: 'finish' When the [`end()`][] method has been called, and all data has been flushed to the underlying system, this event is emitted. ```javascript var writer = getWritableStreamSomehow(); for (var i = 0; i < 100; i ++) { writer.write('hello, #' + i + '!\n'); } writer.end('this is the end\n'); writer.on('finish', function() { console.error('all writes are now complete.'); }); ``` #### Event: 'pipe' * `src` {[Readable][] Stream} source stream that is piping to this writable This is emitted whenever the `pipe()` method is called on a readable stream, adding this writable to its set of destinations. ```javascript var writer = getWritableStreamSomehow(); var reader = getReadableStreamSomehow(); writer.on('pipe', function(src) { console.error('something is piping into the writer'); assert.equal(src, reader); }); reader.pipe(writer); ``` #### Event: 'unpipe' * `src` {[Readable][] Stream} The source stream that [unpiped][] this writable This is emitted whenever the [`unpipe()`][] method is called on a readable stream, removing this writable from its set of destinations. ```javascript var writer = getWritableStreamSomehow(); var reader = getReadableStreamSomehow(); writer.on('unpipe', function(src) { console.error('something has stopped piping into the writer'); assert.equal(src, reader); }); reader.pipe(writer); reader.unpipe(writer); ``` #### Event: 'error' Emitted if there was an error when writing or piping data. ### Class: stream.Duplex Duplex streams are streams that implement both the [Readable][] and [Writable][] interfaces. See above for usage. Examples of Duplex streams include: * [tcp sockets][] * [zlib streams][] * [crypto streams][] ### Class: stream.Transform Transform streams are [Duplex][] streams where the output is in some way computed from the input. They implement both the [Readable][] and [Writable][] interfaces. See above for usage. Examples of Transform streams include: * [zlib streams][] * [crypto streams][] ## API for Stream Implementors To implement any sort of stream, the pattern is the same: 1. Extend the appropriate parent class in your own subclass. (The [`util.inherits`][] method is particularly helpful for this.) 2. Call the appropriate parent class constructor in your constructor, to be sure that the internal mechanisms are set up properly. 2. Implement one or more specific methods, as detailed below. The class to extend and the method(s) to implement depend on the sort of stream class you are writing:

    Use-case

    Class

    Method(s) to implement

    Reading only

    [Readable](#stream_class_stream_readable_1)

    [_read][]

    Writing only

    [Writable](#stream_class_stream_writable_1)

    [_write][]

    Reading and writing

    [Duplex](#stream_class_stream_duplex_1)

    [_read][], [_write][]

    Operate on written data, then read the result

    [Transform](#stream_class_stream_transform_1)

    _transform, _flush

    In your implementation code, it is very important to never call the methods described in [API for Stream Consumers][] above. Otherwise, you can potentially cause adverse side effects in programs that consume your streaming interfaces. ### Class: stream.Readable `stream.Readable` is an abstract class designed to be extended with an underlying implementation of the [`_read(size)`][] method. Please see above under [API for Stream Consumers][] for how to consume streams in your programs. What follows is an explanation of how to implement Readable streams in your programs. #### Example: A Counting Stream This is a basic example of a Readable stream. It emits the numerals from 1 to 1,000,000 in ascending order, and then ends. ```javascript var Readable = require('stream').Readable; var util = require('util'); util.inherits(Counter, Readable); function Counter(opt) { Readable.call(this, opt); this._max = 1000000; this._index = 1; } Counter.prototype._read = function() { var i = this._index++; if (i > this._max) this.push(null); else { var str = '' + i; var buf = new Buffer(str, 'ascii'); this.push(buf); } }; ``` #### Example: SimpleProtocol v1 (Sub-optimal) This is similar to the `parseHeader` function described above, but implemented as a custom stream. Also, note that this implementation does not convert the incoming data to a string. However, this would be better implemented as a [Transform][] stream. See below for a better implementation. ```javascript // A parser for a simple data protocol. // The "header" is a JSON object, followed by 2 \n characters, and // then a message body. // // NOTE: This can be done more simply as a Transform stream! // Using Readable directly for this is sub-optimal. See the // alternative example below under the Transform section. var Readable = require('stream').Readable; var util = require('util'); util.inherits(SimpleProtocol, Readable); function SimpleProtocol(source, options) { if (!(this instanceof SimpleProtocol)) return new SimpleProtocol(source, options); Readable.call(this, options); this._inBody = false; this._sawFirstCr = false; // source is a readable stream, such as a socket or file this._source = source; var self = this; source.on('end', function() { self.push(null); }); // give it a kick whenever the source is readable // read(0) will not consume any bytes source.on('readable', function() { self.read(0); }); this._rawHeader = []; this.header = null; } SimpleProtocol.prototype._read = function(n) { if (!this._inBody) { var chunk = this._source.read(); // if the source doesn't have data, we don't have data yet. if (chunk === null) return this.push(''); // check if the chunk has a \n\n var split = -1; for (var i = 0; i < chunk.length; i++) { if (chunk[i] === 10) { // '\n' if (this._sawFirstCr) { split = i; break; } else { this._sawFirstCr = true; } } else { this._sawFirstCr = false; } } if (split === -1) { // still waiting for the \n\n // stash the chunk, and try again. this._rawHeader.push(chunk); this.push(''); } else { this._inBody = true; var h = chunk.slice(0, split); this._rawHeader.push(h); var header = Buffer.concat(this._rawHeader).toString(); try { this.header = JSON.parse(header); } catch (er) { this.emit('error', new Error('invalid simple protocol data')); return; } // now, because we got some extra data, unshift the rest // back into the read queue so that our consumer will see it. var b = chunk.slice(split); this.unshift(b); // and let them know that we are done parsing the header. this.emit('header', this.header); } } else { // from there on, just provide the data to our consumer. // careful not to push(null), since that would indicate EOF. var chunk = this._source.read(); if (chunk) this.push(chunk); } }; // Usage: // var parser = new SimpleProtocol(source); // Now parser is a readable stream that will emit 'header' // with the parsed header data. ``` #### new stream.Readable([options]) * `options` {Object} * `highWaterMark` {Number} The maximum number of bytes to store in the internal buffer before ceasing to read from the underlying resource. Default=16kb * `encoding` {String} If specified, then buffers will be decoded to strings using the specified encoding. Default=null * `objectMode` {Boolean} Whether this stream should behave as a stream of objects. Meaning that stream.read(n) returns a single value instead of a Buffer of size n. Default=false In classes that extend the Readable class, make sure to call the Readable constructor so that the buffering settings can be properly initialized. #### readable.\_read(size) * `size` {Number} Number of bytes to read asynchronously Note: **Implement this function, but do NOT call it directly.** This function should NOT be called directly. It should be implemented by child classes, and only called by the internal Readable class methods. All Readable stream implementations must provide a `_read` method to fetch data from the underlying resource. This method is prefixed with an underscore because it is internal to the class that defines it, and should not be called directly by user programs. However, you **are** expected to override this method in your own extension classes. When data is available, put it into the read queue by calling `readable.push(chunk)`. If `push` returns false, then you should stop reading. When `_read` is called again, you should start pushing more data. The `size` argument is advisory. Implementations where a "read" is a single call that returns data can use this to know how much data to fetch. Implementations where that is not relevant, such as TCP or TLS, may ignore this argument, and simply provide data whenever it becomes available. There is no need, for example to "wait" until `size` bytes are available before calling [`stream.push(chunk)`][]. #### readable.push(chunk, [encoding]) * `chunk` {Buffer | null | String} Chunk of data to push into the read queue * `encoding` {String} Encoding of String chunks. Must be a valid Buffer encoding, such as `'utf8'` or `'ascii'` * return {Boolean} Whether or not more pushes should be performed Note: **This function should be called by Readable implementors, NOT by consumers of Readable streams.** The `_read()` function will not be called again until at least one `push(chunk)` call is made. The `Readable` class works by putting data into a read queue to be pulled out later by calling the `read()` method when the `'readable'` event fires. The `push()` method will explicitly insert some data into the read queue. If it is called with `null` then it will signal the end of the data (EOF). This API is designed to be as flexible as possible. For example, you may be wrapping a lower-level source which has some sort of pause/resume mechanism, and a data callback. In those cases, you could wrap the low-level source object by doing something like this: ```javascript // source is an object with readStop() and readStart() methods, // and an `ondata` member that gets called when it has data, and // an `onend` member that gets called when the data is over. util.inherits(SourceWrapper, Readable); function SourceWrapper(options) { Readable.call(this, options); this._source = getLowlevelSourceObject(); var self = this; // Every time there's data, we push it into the internal buffer. this._source.ondata = function(chunk) { // if push() returns false, then we need to stop reading from source if (!self.push(chunk)) self._source.readStop(); }; // When the source ends, we push the EOF-signalling `null` chunk this._source.onend = function() { self.push(null); }; } // _read will be called when the stream wants to pull more data in // the advisory size argument is ignored in this case. SourceWrapper.prototype._read = function(size) { this._source.readStart(); }; ``` ### Class: stream.Writable `stream.Writable` is an abstract class designed to be extended with an underlying implementation of the [`_write(chunk, encoding, callback)`][] method. Please see above under [API for Stream Consumers][] for how to consume writable streams in your programs. What follows is an explanation of how to implement Writable streams in your programs. #### new stream.Writable([options]) * `options` {Object} * `highWaterMark` {Number} Buffer level when [`write()`][] starts returning false. Default=16kb * `decodeStrings` {Boolean} Whether or not to decode strings into Buffers before passing them to [`_write()`][]. Default=true In classes that extend the Writable class, make sure to call the constructor so that the buffering settings can be properly initialized. #### writable.\_write(chunk, encoding, callback) * `chunk` {Buffer | String} The chunk to be written. Will always be a buffer unless the `decodeStrings` option was set to `false`. * `encoding` {String} If the chunk is a string, then this is the encoding type. Ignore chunk is a buffer. Note that chunk will **always** be a buffer unless the `decodeStrings` option is explicitly set to `false`. * `callback` {Function} Call this function (optionally with an error argument) when you are done processing the supplied chunk. All Writable stream implementations must provide a [`_write()`][] method to send data to the underlying resource. Note: **This function MUST NOT be called directly.** It should be implemented by child classes, and called by the internal Writable class methods only. Call the callback using the standard `callback(error)` pattern to signal that the write completed successfully or with an error. If the `decodeStrings` flag is set in the constructor options, then `chunk` may be a string rather than a Buffer, and `encoding` will indicate the sort of string that it is. This is to support implementations that have an optimized handling for certain string data encodings. If you do not explicitly set the `decodeStrings` option to `false`, then you can safely ignore the `encoding` argument, and assume that `chunk` will always be a Buffer. This method is prefixed with an underscore because it is internal to the class that defines it, and should not be called directly by user programs. However, you **are** expected to override this method in your own extension classes. ### Class: stream.Duplex A "duplex" stream is one that is both Readable and Writable, such as a TCP socket connection. Note that `stream.Duplex` is an abstract class designed to be extended with an underlying implementation of the `_read(size)` and [`_write(chunk, encoding, callback)`][] methods as you would with a Readable or Writable stream class. Since JavaScript doesn't have multiple prototypal inheritance, this class prototypally inherits from Readable, and then parasitically from Writable. It is thus up to the user to implement both the lowlevel `_read(n)` method as well as the lowlevel [`_write(chunk, encoding, callback)`][] method on extension duplex classes. #### new stream.Duplex(options) * `options` {Object} Passed to both Writable and Readable constructors. Also has the following fields: * `allowHalfOpen` {Boolean} Default=true. If set to `false`, then the stream will automatically end the readable side when the writable side ends and vice versa. In classes that extend the Duplex class, make sure to call the constructor so that the buffering settings can be properly initialized. ### Class: stream.Transform A "transform" stream is a duplex stream where the output is causally connected in some way to the input, such as a [zlib][] stream or a [crypto][] stream. There is no requirement that the output be the same size as the input, the same number of chunks, or arrive at the same time. For example, a Hash stream will only ever have a single chunk of output which is provided when the input is ended. A zlib stream will produce output that is either much smaller or much larger than its input. Rather than implement the [`_read()`][] and [`_write()`][] methods, Transform classes must implement the `_transform()` method, and may optionally also implement the `_flush()` method. (See below.) #### new stream.Transform([options]) * `options` {Object} Passed to both Writable and Readable constructors. In classes that extend the Transform class, make sure to call the constructor so that the buffering settings can be properly initialized. #### transform.\_transform(chunk, encoding, callback) * `chunk` {Buffer | String} The chunk to be transformed. Will always be a buffer unless the `decodeStrings` option was set to `false`. * `encoding` {String} If the chunk is a string, then this is the encoding type. (Ignore if `decodeStrings` chunk is a buffer.) * `callback` {Function} Call this function (optionally with an error argument) when you are done processing the supplied chunk. Note: **This function MUST NOT be called directly.** It should be implemented by child classes, and called by the internal Transform class methods only. All Transform stream implementations must provide a `_transform` method to accept input and produce output. `_transform` should do whatever has to be done in this specific Transform class, to handle the bytes being written, and pass them off to the readable portion of the interface. Do asynchronous I/O, process things, and so on. Call `transform.push(outputChunk)` 0 or more times to generate output from this input chunk, depending on how much data you want to output as a result of this chunk. Call the callback function only when the current chunk is completely consumed. Note that there may or may not be output as a result of any particular input chunk. This method is prefixed with an underscore because it is internal to the class that defines it, and should not be called directly by user programs. However, you **are** expected to override this method in your own extension classes. #### transform.\_flush(callback) * `callback` {Function} Call this function (optionally with an error argument) when you are done flushing any remaining data. Note: **This function MUST NOT be called directly.** It MAY be implemented by child classes, and if so, will be called by the internal Transform class methods only. In some cases, your transform operation may need to emit a bit more data at the end of the stream. For example, a `Zlib` compression stream will store up some internal state so that it can optimally compress the output. At the end, however, it needs to do the best it can with what is left, so that the data will be complete. In those cases, you can implement a `_flush` method, which will be called at the very end, after all the written data is consumed, but before emitting `end` to signal the end of the readable side. Just like with `_transform`, call `transform.push(chunk)` zero or more times, as appropriate, and call `callback` when the flush operation is complete. This method is prefixed with an underscore because it is internal to the class that defines it, and should not be called directly by user programs. However, you **are** expected to override this method in your own extension classes. #### Example: `SimpleProtocol` parser v2 The example above of a simple protocol parser can be implemented simply by using the higher level [Transform][] stream class, similar to the `parseHeader` and `SimpleProtocol v1` examples above. In this example, rather than providing the input as an argument, it would be piped into the parser, which is a more idiomatic Node stream approach. ```javascript var util = require('util'); var Transform = require('stream').Transform; util.inherits(SimpleProtocol, Transform); function SimpleProtocol(options) { if (!(this instanceof SimpleProtocol)) return new SimpleProtocol(options); Transform.call(this, options); this._inBody = false; this._sawFirstCr = false; this._rawHeader = []; this.header = null; } SimpleProtocol.prototype._transform = function(chunk, encoding, done) { if (!this._inBody) { // check if the chunk has a \n\n var split = -1; for (var i = 0; i < chunk.length; i++) { if (chunk[i] === 10) { // '\n' if (this._sawFirstCr) { split = i; break; } else { this._sawFirstCr = true; } } else { this._sawFirstCr = false; } } if (split === -1) { // still waiting for the \n\n // stash the chunk, and try again. this._rawHeader.push(chunk); } else { this._inBody = true; var h = chunk.slice(0, split); this._rawHeader.push(h); var header = Buffer.concat(this._rawHeader).toString(); try { this.header = JSON.parse(header); } catch (er) { this.emit('error', new Error('invalid simple protocol data')); return; } // and let them know that we are done parsing the header. this.emit('header', this.header); // now, because we got some extra data, emit this first. this.push(chunk.slice(split)); } } else { // from there on, just provide the data to our consumer as-is. this.push(chunk); } done(); }; // Usage: // var parser = new SimpleProtocol(); // source.pipe(parser) // Now parser is a readable stream that will emit 'header' // with the parsed header data. ``` ### Class: stream.PassThrough This is a trivial implementation of a [Transform][] stream that simply passes the input bytes across to the output. Its purpose is mainly for examples and testing, but there are occasionally use cases where it can come in handy as a building block for novel sorts of streams. ## Streams: Under the Hood ### Buffering Both Writable and Readable streams will buffer data on an internal object called `_writableState.buffer` or `_readableState.buffer`, respectively. The amount of data that will potentially be buffered depends on the `highWaterMark` option which is passed into the constructor. Buffering in Readable streams happens when the implementation calls [`stream.push(chunk)`][]. If the consumer of the Stream does not call `stream.read()`, then the data will sit in the internal queue until it is consumed. Buffering in Writable streams happens when the user calls [`stream.write(chunk)`][] repeatedly, even when `write()` returns `false`. The purpose of streams, especially with the `pipe()` method, is to limit the buffering of data to acceptable levels, so that sources and destinations of varying speed will not overwhelm the available memory. ### `stream.read(0)` There are some cases where you want to trigger a refresh of the underlying readable stream mechanisms, without actually consuming any data. In that case, you can call `stream.read(0)`, which will always return null. If the internal read buffer is below the `highWaterMark`, and the stream is not currently reading, then calling `read(0)` will trigger a low-level `_read` call. There is almost never a need to do this. However, you will see some cases in Node's internals where this is done, particularly in the Readable stream class internals. ### `stream.push('')` Pushing a zero-byte string or Buffer (when not in [Object mode][]) has an interesting side effect. Because it *is* a call to [`stream.push()`][], it will end the `reading` process. However, it does *not* add any data to the readable buffer, so there's nothing for a user to consume. Very rarely, there are cases where you have no data to provide now, but the consumer of your stream (or, perhaps, another bit of your own code) will know when to check again, by calling `stream.read(0)`. In those cases, you *may* call `stream.push('')`. So far, the only use case for this functionality is in the [tls.CryptoStream][] class, which is deprecated in Node v0.12. If you find that you have to use `stream.push('')`, please consider another approach, because it almost certainly indicates that something is horribly wrong. ### Compatibility with Older Node Versions In versions of Node prior to v0.10, the Readable stream interface was simpler, but also less powerful and less useful. * Rather than waiting for you to call the `read()` method, `'data'` events would start emitting immediately. If you needed to do some I/O to decide how to handle data, then you had to store the chunks in some kind of buffer so that they would not be lost. * The `pause()` method was advisory, rather than guaranteed. This meant that you still had to be prepared to receive `'data'` events even when the stream was in a paused state. In Node v0.10, the Readable class described below was added. For backwards compatibility with older Node programs, Readable streams switch into "flowing mode" when a `'data'` event handler is added, or when the `pause()` or `resume()` methods are called. The effect is that, even if you are not using the new `read()` method and `'readable'` event, you no longer have to worry about losing `'data'` chunks. Most programs will continue to function normally. However, this introduces an edge case in the following conditions: * No `'data'` event handler is added. * The `pause()` and `resume()` methods are never called. For example, consider the following code: ```javascript // WARNING! BROKEN! net.createServer(function(socket) { // we add an 'end' method, but never consume the data socket.on('end', function() { // It will never get here. socket.end('I got your message (but didnt read it)\n'); }); }).listen(1337); ``` In versions of node prior to v0.10, the incoming message data would be simply discarded. However, in Node v0.10 and beyond, the socket will remain paused forever. The workaround in this situation is to call the `resume()` method to trigger "old mode" behavior: ```javascript // Workaround net.createServer(function(socket) { socket.on('end', function() { socket.end('I got your message (but didnt read it)\n'); }); // start the flow of data, discarding it. socket.resume(); }).listen(1337); ``` In addition to new Readable streams switching into flowing-mode, pre-v0.10 style streams can be wrapped in a Readable class using the `wrap()` method. ### Object Mode Normally, Streams operate on Strings and Buffers exclusively. Streams that are in **object mode** can emit generic JavaScript values other than Buffers and Strings. A Readable stream in object mode will always return a single item from a call to `stream.read(size)`, regardless of what the size argument is. A Writable stream in object mode will always ignore the `encoding` argument to `stream.write(data, encoding)`. The special value `null` still retains its special value for object mode streams. That is, for object mode readable streams, `null` as a return value from `stream.read()` indicates that there is no more data, and [`stream.push(null)`][] will signal the end of stream data (`EOF`). No streams in Node core are object mode streams. This pattern is only used by userland streaming libraries. You should set `objectMode` in your stream child class constructor on the options object. Setting `objectMode` mid-stream is not safe. ### State Objects [Readable][] streams have a member object called `_readableState`. [Writable][] streams have a member object called `_writableState`. [Duplex][] streams have both. **These objects should generally not be modified in child classes.** However, if you have a Duplex or Transform stream that should be in `objectMode` on the readable side, and not in `objectMode` on the writable side, then you may do this in the constructor by setting the flag explicitly on the appropriate state object. ```javascript var util = require('util'); var StringDecoder = require('string_decoder').StringDecoder; var Transform = require('stream').Transform; util.inherits(JSONParseStream, Transform); // Gets \n-delimited JSON string data, and emits the parsed objects function JSONParseStream(options) { if (!(this instanceof JSONParseStream)) return new JSONParseStream(options); Transform.call(this, options); this._writableState.objectMode = false; this._readableState.objectMode = true; this._buffer = ''; this._decoder = new StringDecoder('utf8'); } JSONParseStream.prototype._transform = function(chunk, encoding, cb) { this._buffer += this._decoder.write(chunk); // split on newlines var lines = this._buffer.split(/\r?\n/); // keep the last partial line buffered this._buffer = lines.pop(); for (var l = 0; l < lines.length; l++) { var line = lines[l]; try { var obj = JSON.parse(line); } catch (er) { this.emit('error', er); return; } // push the parsed object out to the readable consumer this.push(obj); } cb(); }; JSONParseStream.prototype._flush = function(cb) { // Just handle any leftover var rem = this._buffer.trim(); if (rem) { try { var obj = JSON.parse(rem); } catch (er) { this.emit('error', er); return; } // push the parsed object out to the readable consumer this.push(obj); } cb(); }; ``` The state objects contain other useful information for debugging the state of streams in your programs. It is safe to look at them, but beyond setting option flags in the constructor, it is **not** safe to modify them. [EventEmitter]: events.html#events_class_events_eventemitter [Object mode]: #stream_object_mode [`stream.push(chunk)`]: #stream_readable_push_chunk_encoding [`stream.push(null)`]: #stream_readable_push_chunk_encoding [`stream.push()`]: #stream_readable_push_chunk_encoding [`unpipe()`]: #stream_readable_unpipe_destination [unpiped]: #stream_readable_unpipe_destination [tcp sockets]: net.html#net_class_net_socket [zlib streams]: zlib.html [zlib]: zlib.html [crypto streams]: crypto.html [crypto]: crypto.html [tls.CryptoStream]: tls.html#tls_class_cryptostream [process.stdin]: process.html#process_process_stdin [stdout]: process.html#process_process_stdout [process.stdout]: process.html#process_process_stdout [process.stderr]: process.html#process_process_stderr [child process stdout and stderr]: child_process.html#child_process_child_stdout [API for Stream Consumers]: #stream_api_for_stream_consumers [API for Stream Implementors]: #stream_api_for_stream_implementors [Readable]: #stream_class_stream_readable [Writable]: #stream_class_stream_writable [Duplex]: #stream_class_stream_duplex [Transform]: #stream_class_stream_transform [`_read(size)`]: #stream_readable_read_size_1 [`_read()`]: #stream_readable_read_size_1 [_read]: #stream_readable_read_size_1 [`writable.write(chunk)`]: #stream_writable_write_chunk_encoding_callback [`write(chunk, encoding, callback)`]: #stream_writable_write_chunk_encoding_callback [`write()`]: #stream_writable_write_chunk_encoding_callback [`stream.write(chunk)`]: #stream_writable_write_chunk_encoding_callback [`_write(chunk, encoding, callback)`]: #stream_writable_write_chunk_encoding_callback_1 [`_write()`]: #stream_writable_write_chunk_encoding_callback_1 [_write]: #stream_writable_write_chunk_encoding_callback_1 [`util.inherits`]: util.html#util_util_inherits_constructor_superconstructor [`end()`]: #stream_writable_end_chunk_encoding_callback node-v0.10.25~dfsg2/doc/api/net.html0000644000000000000000000010501312270264601015606 0ustar rootroot net Node.js v0.10.25 Manual & Documentation

    Node.js v0.10.25 Manual & Documentation


    net#

    Stability: 3 - Stable

    The net module provides you with an asynchronous network wrapper. It contains methods for creating both servers and clients (called streams). You can include this module with require('net');

    net.createServer([options], [connectionListener])#

    Creates a new TCP server. The connectionListener argument is automatically set as a listener for the 'connection' event.

    options is an object with the following defaults:

    { allowHalfOpen: false
    }

    If allowHalfOpen is true, then the socket won't automatically send a FIN packet when the other end of the socket sends a FIN packet. The socket becomes non-readable, but still writable. You should call the end() method explicitly. See 'end' event for more information.

    Here is an example of an echo server which listens for connections on port 8124:

    var net = require('net');
    var server = net.createServer(function(c) { //'connection' listener
      console.log('server connected');
      c.on('end', function() {
        console.log('server disconnected');
      });
      c.write('hello\r\n');
      c.pipe(c);
    });
    server.listen(8124, function() { //'listening' listener
      console.log('server bound');
    });

    Test this by using telnet:

    telnet localhost 8124

    To listen on the socket /tmp/echo.sock the third line from the last would just be changed to

    server.listen('/tmp/echo.sock', function() { //'listening' listener

    Use nc to connect to a UNIX domain socket server:

    nc -U /tmp/echo.sock

    net.connect(options, [connectionListener])#

    net.createConnection(options, [connectionListener])#

    Constructs a new socket object and opens the socket to the given location. When the socket is established, the 'connect' event will be emitted.

    For TCP sockets, options argument should be an object which specifies:

    • port: Port the client should connect to (Required).

    • host: Host the client should connect to. Defaults to 'localhost'.

    • localAddress: Local interface to bind to for network connections.

    For UNIX domain sockets, options argument should be an object which specifies:

    • path: Path the client should connect to (Required).

    Common options are:

    • allowHalfOpen: if true, the socket won't automatically send a FIN packet when the other end of the socket sends a FIN packet. Defaults to false. See 'end' event for more information.

    The connectListener parameter will be added as an listener for the 'connect' event.

    Here is an example of a client of echo server as described previously:

    var net = require('net');
    var client = net.connect({port: 8124},
        function() { //'connect' listener
      console.log('client connected');
      client.write('world!\r\n');
    });
    client.on('data', function(data) {
      console.log(data.toString());
      client.end();
    });
    client.on('end', function() {
      console.log('client disconnected');
    });

    To connect on the socket /tmp/echo.sock the second line would just be changed to

    var client = net.connect({path: '/tmp/echo.sock'});

    net.connect(port, [host], [connectListener])#

    net.createConnection(port, [host], [connectListener])#

    Creates a TCP connection to port on host. If host is omitted, 'localhost' will be assumed. The connectListener parameter will be added as an listener for the 'connect' event.

    net.connect(path, [connectListener])#

    net.createConnection(path, [connectListener])#

    Creates unix socket connection to path. The connectListener parameter will be added as an listener for the 'connect' event.

    Class: net.Server#

    This class is used to create a TCP or UNIX server.

    server.listen(port, [host], [backlog], [callback])#

    Begin accepting connections on the specified port and host. If the host is omitted, the server will accept connections directed to any IPv4 address (INADDR_ANY). A port value of zero will assign a random port.

    Backlog is the maximum length of the queue of pending connections. The actual length will be determined by your OS through sysctl settings such as tcp_max_syn_backlog and somaxconn on linux. The default value of this parameter is 511 (not 512).

    This function is asynchronous. When the server has been bound, 'listening' event will be emitted. The last parameter callback will be added as an listener for the 'listening' event.

    One issue some users run into is getting EADDRINUSE errors. This means that another server is already running on the requested port. One way of handling this would be to wait a second and then try again. This can be done with

    server.on('error', function (e) {
      if (e.code == 'EADDRINUSE') {
        console.log('Address in use, retrying...');
        setTimeout(function () {
          server.close();
          server.listen(PORT, HOST);
        }, 1000);
      }
    });

    (Note: All sockets in Node set SO_REUSEADDR already)

    server.listen(path, [callback])#

    Start a UNIX socket server listening for connections on the given path.

    This function is asynchronous. When the server has been bound, 'listening' event will be emitted. The last parameter callback will be added as an listener for the 'listening' event.

    server.listen(handle, [callback])#

    • handle Object
    • callback Function

    The handle object can be set to either a server or socket (anything with an underlying _handle member), or a {fd: <n>} object.

    This will cause the server to accept connections on the specified handle, but it is presumed that the file descriptor or handle has already been bound to a port or domain socket.

    Listening on a file descriptor is not supported on Windows.

    This function is asynchronous. When the server has been bound, 'listening' event will be emitted. the last parameter callback will be added as an listener for the 'listening' event.

    server.close([callback])#

    Stops the server from accepting new connections and keeps existing connections. This function is asynchronous, the server is finally closed when all connections are ended and the server emits a 'close' event. Optionally, you can pass a callback to listen for the 'close' event.

    server.address()#

    Returns the bound address, the address family name and port of the server as reported by the operating system. Useful to find which port was assigned when giving getting an OS-assigned address. Returns an object with three properties, e.g. { port: 12346, family: 'IPv4', address: '127.0.0.1' }

    Example:

    var server = net.createServer(function (socket) {
      socket.end("goodbye\n");
    });
    
    // grab a random port.
    server.listen(function() {
      address = server.address();
      console.log("opened server on %j", address);
    });

    Don't call server.address() until the 'listening' event has been emitted.

    server.unref()#

    Calling unref on a server will allow the program to exit if this is the only active server in the event system. If the server is already unrefd calling unref again will have no effect.

    server.ref()#

    Opposite of unref, calling ref on a previously unrefd server will not let the program exit if it's the only server left (the default behavior). If the server is refd calling ref again will have no effect.

    server.maxConnections#

    Set this property to reject connections when the server's connection count gets high.

    It is not recommended to use this option once a socket has been sent to a child with child_process.fork().

    server.connections#

    This function is deprecated; please use [server.getConnections()][] instead. The number of concurrent connections on the server.

    This becomes null when sending a socket to a child with child_process.fork(). To poll forks and get current number of active connections use asynchronous server.getConnections instead.

    net.Server is an EventEmitter with the following events:

    server.getConnections(callback)#

    Asynchronously get the number of concurrent connections on the server. Works when sockets were sent to forks.

    Callback should take two arguments err and count.

    Event: 'listening'#

    Emitted when the server has been bound after calling server.listen.

    Event: 'connection'#

    • Socket object The connection object

    Emitted when a new connection is made. socket is an instance of net.Socket.

    Event: 'close'#

    Emitted when the server closes. Note that if connections exist, this event is not emitted until all connections are ended.

    Event: 'error'#

    • Error Object

    Emitted when an error occurs. The 'close' event will be called directly following this event. See example in discussion of server.listen.

    Class: net.Socket#

    This object is an abstraction of a TCP or UNIX socket. net.Socket instances implement a duplex Stream interface. They can be created by the user and used as a client (with connect()) or they can be created by Node and passed to the user through the 'connection' event of a server.

    new net.Socket([options])#

    Construct a new socket object.

    options is an object with the following defaults:

    { fd: null
      allowHalfOpen: false,
      readable: false,
      writable: false
    }

    fd allows you to specify the existing file descriptor of socket. Set readable and/or writable to true to allow reads and/or writes on this socket (NOTE: Works only when fd is passed). About allowHalfOpen, refer to createServer() and 'end' event.

    socket.connect(port, [host], [connectListener])#

    socket.connect(path, [connectListener])#

    Opens the connection for a given socket. If port and host are given, then the socket will be opened as a TCP socket, if host is omitted, localhost will be assumed. If a path is given, the socket will be opened as a unix socket to that path.

    Normally this method is not needed, as net.createConnection opens the socket. Use this only if you are implementing a custom Socket.

    This function is asynchronous. When the 'connect' event is emitted the socket is established. If there is a problem connecting, the 'connect' event will not be emitted, the 'error' event will be emitted with the exception.

    The connectListener parameter will be added as an listener for the 'connect' event.

    socket.bufferSize#

    net.Socket has the property that socket.write() always works. This is to help users get up and running quickly. The computer cannot always keep up with the amount of data that is written to a socket - the network connection simply might be too slow. Node will internally queue up the data written to a socket and send it out over the wire when it is possible. (Internally it is polling on the socket's file descriptor for being writable).

    The consequence of this internal buffering is that memory may grow. This property shows the number of characters currently buffered to be written. (Number of characters is approximately equal to the number of bytes to be written, but the buffer may contain strings, and the strings are lazily encoded, so the exact number of bytes is not known.)

    Users who experience large or growing bufferSize should attempt to "throttle" the data flows in their program with pause() and resume().

    socket.setEncoding([encoding])#

    Set the encoding for the socket as a Readable Stream. See stream.setEncoding() for more information.

    socket.write(data, [encoding], [callback])#

    Sends data on the socket. The second parameter specifies the encoding in the case of a string--it defaults to UTF8 encoding.

    Returns true if the entire data was flushed successfully to the kernel buffer. Returns false if all or part of the data was queued in user memory. 'drain' will be emitted when the buffer is again free.

    The optional callback parameter will be executed when the data is finally written out - this may not be immediately.

    socket.end([data], [encoding])#

    Half-closes the socket. i.e., it sends a FIN packet. It is possible the server will still send some data.

    If data is specified, it is equivalent to calling socket.write(data, encoding) followed by socket.end().

    socket.destroy()#

    Ensures that no more I/O activity happens on this socket. Only necessary in case of errors (parse error or so).

    socket.pause()#

    Pauses the reading of data. That is, 'data' events will not be emitted. Useful to throttle back an upload.

    socket.resume()#

    Resumes reading after a call to pause().

    socket.setTimeout(timeout, [callback])#

    Sets the socket to timeout after timeout milliseconds of inactivity on the socket. By default net.Socket do not have a timeout.

    When an idle timeout is triggered the socket will receive a 'timeout' event but the connection will not be severed. The user must manually end() or destroy() the socket.

    If timeout is 0, then the existing idle timeout is disabled.

    The optional callback parameter will be added as a one time listener for the 'timeout' event.

    socket.setNoDelay([noDelay])#

    Disables the Nagle algorithm. By default TCP connections use the Nagle algorithm, they buffer data before sending it off. Setting true for noDelay will immediately fire off data each time socket.write() is called. noDelay defaults to true.

    socket.setKeepAlive([enable], [initialDelay])#

    Enable/disable keep-alive functionality, and optionally set the initial delay before the first keepalive probe is sent on an idle socket. enable defaults to false.

    Set initialDelay (in milliseconds) to set the delay between the last data packet received and the first keepalive probe. Setting 0 for initialDelay will leave the value unchanged from the default (or previous) setting. Defaults to 0.

    socket.address()#

    Returns the bound address, the address family name and port of the socket as reported by the operating system. Returns an object with three properties, e.g. { port: 12346, family: 'IPv4', address: '127.0.0.1' }

    socket.unref()#

    Calling unref on a socket will allow the program to exit if this is the only active socket in the event system. If the socket is already unrefd calling unref again will have no effect.

    socket.ref()#

    Opposite of unref, calling ref on a previously unrefd socket will not let the program exit if it's the only socket left (the default behavior). If the socket is refd calling ref again will have no effect.

    socket.remoteAddress#

    The string representation of the remote IP address. For example, '74.125.127.100' or '2001:4860:a005::68'.

    socket.remotePort#

    The numeric representation of the remote port. For example, 80 or 21.

    socket.localAddress#

    The string representation of the local IP address the remote client is connecting on. For example, if you are listening on '0.0.0.0' and the client connects on '192.168.1.1', the value would be '192.168.1.1'.

    socket.localPort#

    The numeric representation of the local port. For example, 80 or 21.

    socket.bytesRead#

    The amount of received bytes.

    socket.bytesWritten#

    The amount of bytes sent.

    net.Socket instances are EventEmitter with the following events:

    Event: 'connect'#

    Emitted when a socket connection is successfully established. See connect().

    Event: 'data'#

    • Buffer object

    Emitted when data is received. The argument data will be a Buffer or String. Encoding of data is set by socket.setEncoding(). (See the Readable Stream section for more information.)

    Note that the data will be lost if there is no listener when a Socket emits a 'data' event.

    Event: 'end'#

    Emitted when the other end of the socket sends a FIN packet.

    By default (allowHalfOpen == false) the socket will destroy its file descriptor once it has written out its pending write queue. However, by setting allowHalfOpen == true the socket will not automatically end() its side allowing the user to write arbitrary amounts of data, with the caveat that the user is required to end() their side now.

    Event: 'timeout'#

    Emitted if the socket times out from inactivity. This is only to notify that the socket has been idle. The user must manually close the connection.

    See also: socket.setTimeout()

    Event: 'drain'#

    Emitted when the write buffer becomes empty. Can be used to throttle uploads.

    See also: the return values of socket.write()

    Event: 'error'#

    • Error object

    Emitted when an error occurs. The 'close' event will be called directly following this event.

    Event: 'close'#

    • had_error Boolean true if the socket had a transmission error

    Emitted once the socket is fully closed. The argument had_error is a boolean which says if the socket was closed due to a transmission error.

    net.isIP(input)#

    Tests if input is an IP address. Returns 0 for invalid strings, returns 4 for IP version 4 addresses, and returns 6 for IP version 6 addresses.

    net.isIPv4(input)#

    Returns true if input is a version 4 IP address, otherwise returns false.

    net.isIPv6(input)#

    Returns true if input is a version 6 IP address, otherwise returns false.

    node-v0.10.25~dfsg2/doc/api/addons.json0000644000000000000000000005554412270264601016312 0ustar rootroot{ "source": "doc/api/addons.markdown", "modules": [ { "textRaw": "Addons", "name": "addons", "desc": "

    Addons are dynamically linked shared objects. They can provide glue to C and\nC++ libraries. The API (at the moment) is rather complex, involving\nknowledge of several libraries:\n\n

    \n
      \n
    • V8 JavaScript, a C++ library. Used for interfacing with JavaScript:\ncreating objects, calling functions, etc. Documented mostly in the\nv8.h header file (deps/v8/include/v8.h in the Node source\ntree), which is also available\nonline.

      \n
    • \n
    • libuv, C event loop library.\nAnytime one needs to wait for a file descriptor to become readable,\nwait for a timer, or wait for a signal to be received one will need\nto interface with libuv. That is, if you perform any I/O, libuv will\nneed to be used.

      \n
    • \n
    • Internal Node libraries. Most importantly is the node::ObjectWrap\nclass which you will likely want to derive from.

      \n
    • \n
    • Others. Look in deps/ for what else is available.

      \n
    • \n
    \n

    Node statically compiles all its dependencies into the executable.\nWhen compiling your module, you don't need to worry about linking to\nany of these libraries.\n\n

    \n

    All of the following examples are available for\ndownload and may be\nused as a starting-point for your own Addon.\n\n

    \n", "modules": [ { "textRaw": "Hello world", "name": "hello_world", "desc": "

    To get started let's make a small Addon which is the C++ equivalent of\nthe following JavaScript code:\n\n

    \n
    module.exports.hello = function() { return 'world'; };
    \n

    First we create a file hello.cc:\n\n

    \n
    #include <node.h>\n#include <v8.h>\n\nusing namespace v8;\n\nHandle<Value> Method(const Arguments& args) {\n  HandleScope scope;\n  return scope.Close(String::New("world"));\n}\n\nvoid init(Handle<Object> exports) {\n  exports->Set(String::NewSymbol("hello"),\n      FunctionTemplate::New(Method)->GetFunction());\n}\n\nNODE_MODULE(hello, init)
    \n

    Note that all Node addons must export an initialization function:\n\n

    \n
    void Initialize (Handle<Object> exports);\nNODE_MODULE(module_name, Initialize)
    \n

    There is no semi-colon after NODE_MODULE as it's not a function (see node.h).\n\n

    \n

    The module_name needs to match the filename of the final binary (minus the\n.node suffix).\n\n

    \n

    The source code needs to be built into hello.node, the binary Addon. To\ndo this we create a file called binding.gyp which describes the configuration\nto build your module in a JSON-like format. This file gets compiled by\nnode-gyp.\n\n

    \n
    {\n  "targets": [\n    {\n      "target_name": "hello",\n      "sources": [ "hello.cc" ]\n    }\n  ]\n}
    \n

    The next step is to generate the appropriate project build files for the\ncurrent platform. Use node-gyp configure for that.\n\n

    \n

    Now you will have either a Makefile (on Unix platforms) or a vcxproj file\n(on Windows) in the build/ directory. Next invoke the node-gyp build\ncommand.\n\n

    \n

    Now you have your compiled .node bindings file! The compiled bindings end up\nin build/Release/.\n\n

    \n

    You can now use the binary addon in a Node project hello.js by pointing require to\nthe recently built hello.node module:\n\n

    \n
    var addon = require('./build/Release/hello');\n\nconsole.log(addon.hello()); // 'world'
    \n

    Please see patterns below for further information or\n

    \n

    https://github.com/arturadib/node-qt for an example in production.\n\n\n

    \n", "type": "module", "displayName": "Hello world" }, { "textRaw": "Addon patterns", "name": "addon_patterns", "desc": "

    Below are some addon patterns to help you get started. Consult the online\nv8 reference for help with the various v8\ncalls, and v8's Embedder's Guide\nfor an explanation of several concepts used such as handles, scopes,\nfunction templates, etc.\n\n

    \n

    In order to use these examples you need to compile them using node-gyp.\nCreate the following binding.gyp file:\n\n

    \n
    {\n  "targets": [\n    {\n      "target_name": "addon",\n      "sources": [ "addon.cc" ]\n    }\n  ]\n}
    \n

    In cases where there is more than one .cc file, simply add the file name to the\nsources array, e.g.:\n\n

    \n
    "sources": ["addon.cc", "myexample.cc"]
    \n

    Now that you have your binding.gyp ready, you can configure and build the\naddon:\n\n

    \n
    $ node-gyp configure build
    \n", "modules": [ { "textRaw": "Function arguments", "name": "function_arguments", "desc": "

    The following pattern illustrates how to read arguments from JavaScript\nfunction calls and return a result. This is the main and only needed source\naddon.cc:\n\n

    \n
    #define BUILDING_NODE_EXTENSION\n#include <node.h>\n\nusing namespace v8;\n\nHandle<Value> Add(const Arguments& args) {\n  HandleScope scope;\n\n  if (args.Length() < 2) {\n    ThrowException(Exception::TypeError(String::New("Wrong number of arguments")));\n    return scope.Close(Undefined());\n  }\n\n  if (!args[0]->IsNumber() || !args[1]->IsNumber()) {\n    ThrowException(Exception::TypeError(String::New("Wrong arguments")));\n    return scope.Close(Undefined());\n  }\n\n  Local<Number> num = Number::New(args[0]->NumberValue() +\n      args[1]->NumberValue());\n  return scope.Close(num);\n}\n\nvoid Init(Handle<Object> exports) {\n  exports->Set(String::NewSymbol("add"),\n      FunctionTemplate::New(Add)->GetFunction());\n}\n\nNODE_MODULE(addon, Init)
    \n

    You can test it with the following JavaScript snippet:\n\n

    \n
    var addon = require('./build/Release/addon');\n\nconsole.log( 'This should be eight:', addon.add(3,5) );
    \n", "type": "module", "displayName": "Function arguments" }, { "textRaw": "Callbacks", "name": "callbacks", "desc": "

    You can pass JavaScript functions to a C++ function and execute them from\nthere. Here's addon.cc:\n\n

    \n
    #define BUILDING_NODE_EXTENSION\n#include <node.h>\n\nusing namespace v8;\n\nHandle<Value> RunCallback(const Arguments& args) {\n  HandleScope scope;\n\n  Local<Function> cb = Local<Function>::Cast(args[0]);\n  const unsigned argc = 1;\n  Local<Value> argv[argc] = { Local<Value>::New(String::New("hello world")) };\n  cb->Call(Context::GetCurrent()->Global(), argc, argv);\n\n  return scope.Close(Undefined());\n}\n\nvoid Init(Handle<Object> exports, Handle<Object> module) {\n  module->Set(String::NewSymbol("exports"),\n      FunctionTemplate::New(RunCallback)->GetFunction());\n}\n\nNODE_MODULE(addon, Init)
    \n

    Note that this example uses a two-argument form of Init() that receives\nthe full module object as the second argument. This allows the addon\nto completely overwrite exports with a single function instead of\nadding the function as a property of exports.\n\n

    \n

    To test it run the following JavaScript snippet:\n\n

    \n
    var addon = require('./build/Release/addon');\n\naddon(function(msg){\n  console.log(msg); // 'hello world'\n});
    \n", "type": "module", "displayName": "Callbacks" }, { "textRaw": "Object factory", "name": "object_factory", "desc": "

    You can create and return new objects from within a C++ function with this\naddon.cc pattern, which returns an object with property msg that echoes\nthe string passed to createObject():\n\n

    \n
    #define BUILDING_NODE_EXTENSION\n#include <node.h>\n\nusing namespace v8;\n\nHandle<Value> CreateObject(const Arguments& args) {\n  HandleScope scope;\n\n  Local<Object> obj = Object::New();\n  obj->Set(String::NewSymbol("msg"), args[0]->ToString());\n\n  return scope.Close(obj);\n}\n\nvoid Init(Handle<Object> exports, Handle<Object> module) {\n  module->Set(String::NewSymbol("exports"),\n      FunctionTemplate::New(CreateObject)->GetFunction());\n}\n\nNODE_MODULE(addon, Init)
    \n

    To test it in JavaScript:\n\n

    \n
    var addon = require('./build/Release/addon');\n\nvar obj1 = addon('hello');\nvar obj2 = addon('world');\nconsole.log(obj1.msg+' '+obj2.msg); // 'hello world'
    \n", "type": "module", "displayName": "Object factory" }, { "textRaw": "Function factory", "name": "function_factory", "desc": "

    This pattern illustrates how to create and return a JavaScript function that\nwraps a C++ function:\n\n

    \n
    #define BUILDING_NODE_EXTENSION\n#include <node.h>\n\nusing namespace v8;\n\nHandle<Value> MyFunction(const Arguments& args) {\n  HandleScope scope;\n  return scope.Close(String::New("hello world"));\n}\n\nHandle<Value> CreateFunction(const Arguments& args) {\n  HandleScope scope;\n\n  Local<FunctionTemplate> tpl = FunctionTemplate::New(MyFunction);\n  Local<Function> fn = tpl->GetFunction();\n  fn->SetName(String::NewSymbol("theFunction")); // omit this to make it anonymous\n\n  return scope.Close(fn);\n}\n\nvoid Init(Handle<Object> exports, Handle<Object> module) {\n  module->Set(String::NewSymbol("exports"),\n      FunctionTemplate::New(CreateFunction)->GetFunction());\n}\n\nNODE_MODULE(addon, Init)
    \n

    To test:\n\n

    \n
    var addon = require('./build/Release/addon');\n\nvar fn = addon();\nconsole.log(fn()); // 'hello world'
    \n", "type": "module", "displayName": "Function factory" }, { "textRaw": "Wrapping C++ objects", "name": "wrapping_c++_objects", "desc": "

    Here we will create a wrapper for a C++ object/class MyObject that can be\ninstantiated in JavaScript through the new operator. First prepare the main\nmodule addon.cc:\n\n

    \n
    #define BUILDING_NODE_EXTENSION\n#include <node.h>\n#include "myobject.h"\n\nusing namespace v8;\n\nvoid InitAll(Handle<Object> exports) {\n  MyObject::Init(exports);\n}\n\nNODE_MODULE(addon, InitAll)
    \n

    Then in myobject.h make your wrapper inherit from node::ObjectWrap:\n\n

    \n
    #ifndef MYOBJECT_H\n#define MYOBJECT_H\n\n#include <node.h>\n\nclass MyObject : public node::ObjectWrap {\n public:\n  static void Init(v8::Handle<v8::Object> exports);\n\n private:\n  explicit MyObject(double value = 0);\n  ~MyObject();\n\n  static v8::Handle<v8::Value> New(const v8::Arguments& args);\n  static v8::Handle<v8::Value> PlusOne(const v8::Arguments& args);\n  static v8::Persistent<v8::Function> constructor;\n  double value_;\n};\n\n#endif
    \n

    And in myobject.cc implement the various methods that you want to expose.\nHere we expose the method plusOne by adding it to the constructor's\nprototype:\n\n

    \n
    #define BUILDING_NODE_EXTENSION\n#include <node.h>\n#include "myobject.h"\n\nusing namespace v8;\n\nPersistent<Function> MyObject::constructor;\n\nMyObject::MyObject(double value) : value_(value) {\n}\n\nMyObject::~MyObject() {\n}\n\nvoid MyObject::Init(Handle<Object> exports) {\n  // Prepare constructor template\n  Local<FunctionTemplate> tpl = FunctionTemplate::New(New);\n  tpl->SetClassName(String::NewSymbol("MyObject"));\n  tpl->InstanceTemplate()->SetInternalFieldCount(1);\n  // Prototype\n  tpl->PrototypeTemplate()->Set(String::NewSymbol("plusOne"),\n      FunctionTemplate::New(PlusOne)->GetFunction());\n  constructor = Persistent<Function>::New(tpl->GetFunction());\n  exports->Set(String::NewSymbol("MyObject"), constructor);\n}\n\nHandle<Value> MyObject::New(const Arguments& args) {\n  HandleScope scope;\n\n  if (args.IsConstructCall()) {\n    // Invoked as constructor: `new MyObject(...)`\n    double value = args[0]->IsUndefined() ? 0 : args[0]->NumberValue();\n    MyObject* obj = new MyObject(value);\n    obj->Wrap(args.This());\n    return args.This();\n  } else {\n    // Invoked as plain function `MyObject(...)`, turn into construct call.\n    const int argc = 1;\n    Local<Value> argv[argc] = { args[0] };\n    return scope.Close(constructor->NewInstance(argc, argv));\n  }\n}\n\nHandle<Value> MyObject::PlusOne(const Arguments& args) {\n  HandleScope scope;\n\n  MyObject* obj = ObjectWrap::Unwrap<MyObject>(args.This());\n  obj->value_ += 1;\n\n  return scope.Close(Number::New(obj->value_));\n}
    \n

    Test it with:\n\n

    \n
    var addon = require('./build/Release/addon');\n\nvar obj = new addon.MyObject(10);\nconsole.log( obj.plusOne() ); // 11\nconsole.log( obj.plusOne() ); // 12\nconsole.log( obj.plusOne() ); // 13
    \n", "type": "module", "displayName": "Wrapping C++ objects" }, { "textRaw": "Factory of wrapped objects", "name": "factory_of_wrapped_objects", "desc": "

    This is useful when you want to be able to create native objects without\nexplicitly instantiating them with the new operator in JavaScript, e.g.\n\n

    \n
    var obj = addon.createObject();\n// instead of:\n// var obj = new addon.Object();
    \n

    Let's register our createObject method in addon.cc:\n\n

    \n
    #define BUILDING_NODE_EXTENSION\n#include <node.h>\n#include "myobject.h"\n\nusing namespace v8;\n\nHandle<Value> CreateObject(const Arguments& args) {\n  HandleScope scope;\n  return scope.Close(MyObject::NewInstance(args));\n}\n\nvoid InitAll(Handle<Object> exports, Handle<Object> module) {\n  MyObject::Init();\n\n  module->Set(String::NewSymbol("exports"),\n      FunctionTemplate::New(CreateObject)->GetFunction());\n}\n\nNODE_MODULE(addon, InitAll)
    \n

    In myobject.h we now introduce the static method NewInstance that takes\ncare of instantiating the object (i.e. it does the job of new in JavaScript):\n\n

    \n
    #define BUILDING_NODE_EXTENSION\n#ifndef MYOBJECT_H\n#define MYOBJECT_H\n\n#include <node.h>\n\nclass MyObject : public node::ObjectWrap {\n public:\n  static void Init();\n  static v8::Handle<v8::Value> NewInstance(const v8::Arguments& args);\n\n private:\n  explicit MyObject(double value = 0);\n  ~MyObject();\n\n  static v8::Handle<v8::Value> New(const v8::Arguments& args);\n  static v8::Handle<v8::Value> PlusOne(const v8::Arguments& args);\n  static v8::Persistent<v8::Function> constructor;\n  double value_;\n};\n\n#endif
    \n

    The implementation is similar to the above in myobject.cc:\n\n

    \n
    #define BUILDING_NODE_EXTENSION\n#include <node.h>\n#include "myobject.h"\n\nusing namespace v8;\n\nPersistent<Function> MyObject::constructor;\n\nMyObject::MyObject(double value) : value_(value) {\n}\n\nMyObject::~MyObject() {\n}\n\nvoid MyObject::Init() {\n  // Prepare constructor template\n  Local<FunctionTemplate> tpl = FunctionTemplate::New(New);\n  tpl->SetClassName(String::NewSymbol("MyObject"));\n  tpl->InstanceTemplate()->SetInternalFieldCount(1);\n  // Prototype\n  tpl->PrototypeTemplate()->Set(String::NewSymbol("plusOne"),\n      FunctionTemplate::New(PlusOne)->GetFunction());\n  constructor = Persistent<Function>::New(tpl->GetFunction());\n}\n\nHandle<Value> MyObject::New(const Arguments& args) {\n  HandleScope scope;\n\n  if (args.IsConstructCall()) {\n    // Invoked as constructor: `new MyObject(...)`\n    double value = args[0]->IsUndefined() ? 0 : args[0]->NumberValue();\n    MyObject* obj = new MyObject(value);\n    obj->Wrap(args.This());\n    return args.This();\n  } else {\n    // Invoked as plain function `MyObject(...)`, turn into construct call.\n    const int argc = 1;\n    Local<Value> argv[argc] = { args[0] };\n    return scope.Close(constructor->NewInstance(argc, argv));\n  }\n}\n\nHandle<Value> MyObject::NewInstance(const Arguments& args) {\n  HandleScope scope;\n\n  const unsigned argc = 1;\n  Handle<Value> argv[argc] = { args[0] };\n  Local<Object> instance = constructor->NewInstance(argc, argv);\n\n  return scope.Close(instance);\n}\n\nHandle<Value> MyObject::PlusOne(const Arguments& args) {\n  HandleScope scope;\n\n  MyObject* obj = ObjectWrap::Unwrap<MyObject>(args.This());\n  obj->value_ += 1;\n\n  return scope.Close(Number::New(obj->value_));\n}
    \n

    Test it with:\n\n

    \n
    var createObject = require('./build/Release/addon');\n\nvar obj = createObject(10);\nconsole.log( obj.plusOne() ); // 11\nconsole.log( obj.plusOne() ); // 12\nconsole.log( obj.plusOne() ); // 13\n\nvar obj2 = createObject(20);\nconsole.log( obj2.plusOne() ); // 21\nconsole.log( obj2.plusOne() ); // 22\nconsole.log( obj2.plusOne() ); // 23
    \n", "type": "module", "displayName": "Factory of wrapped objects" }, { "textRaw": "Passing wrapped objects around", "name": "passing_wrapped_objects_around", "desc": "

    In addition to wrapping and returning C++ objects, you can pass them around\nby unwrapping them with Node's node::ObjectWrap::Unwrap helper function.\nIn the following addon.cc we introduce a function add() that can take on two\nMyObject objects:\n\n

    \n
    #define BUILDING_NODE_EXTENSION\n#include <node.h>\n#include "myobject.h"\n\nusing namespace v8;\n\nHandle<Value> CreateObject(const Arguments& args) {\n  HandleScope scope;\n  return scope.Close(MyObject::NewInstance(args));\n}\n\nHandle<Value> Add(const Arguments& args) {\n  HandleScope scope;\n\n  MyObject* obj1 = node::ObjectWrap::Unwrap<MyObject>(\n      args[0]->ToObject());\n  MyObject* obj2 = node::ObjectWrap::Unwrap<MyObject>(\n      args[1]->ToObject());\n\n  double sum = obj1->Value() + obj2->Value();\n  return scope.Close(Number::New(sum));\n}\n\nvoid InitAll(Handle<Object> exports) {\n  MyObject::Init();\n\n  exports->Set(String::NewSymbol("createObject"),\n      FunctionTemplate::New(CreateObject)->GetFunction());\n\n  exports->Set(String::NewSymbol("add"),\n      FunctionTemplate::New(Add)->GetFunction());\n}\n\nNODE_MODULE(addon, InitAll)
    \n

    To make things interesting we introduce a public method in myobject.h so we\ncan probe private values after unwrapping the object:\n\n

    \n
    #define BUILDING_NODE_EXTENSION\n#ifndef MYOBJECT_H\n#define MYOBJECT_H\n\n#include <node.h>\n\nclass MyObject : public node::ObjectWrap {\n public:\n  static void Init();\n  static v8::Handle<v8::Value> NewInstance(const v8::Arguments& args);\n  double Value() const { return value_; }\n\n private:\n  explicit MyObject(double value = 0);\n  ~MyObject();\n\n  static v8::Handle<v8::Value> New(const v8::Arguments& args);\n  static v8::Persistent<v8::Function> constructor;\n  double value_;\n};\n\n#endif
    \n

    The implementation of myobject.cc is similar as before:\n\n

    \n
    #define BUILDING_NODE_EXTENSION\n#include <node.h>\n#include "myobject.h"\n\nusing namespace v8;\n\nPersistent<Function> MyObject::constructor;\n\nMyObject::MyObject(double value) : value_(value) {\n}\n\nMyObject::~MyObject() {\n}\n\nvoid MyObject::Init() {\n  // Prepare constructor template\n  Local<FunctionTemplate> tpl = FunctionTemplate::New(New);\n  tpl->SetClassName(String::NewSymbol("MyObject"));\n  tpl->InstanceTemplate()->SetInternalFieldCount(1);\n  constructor = Persistent<Function>::New(tpl->GetFunction());\n}\n\nHandle<Value> MyObject::New(const Arguments& args) {\n  HandleScope scope;\n\n  if (args.IsConstructCall()) {\n    // Invoked as constructor: `new MyObject(...)`\n    double value = args[0]->IsUndefined() ? 0 : args[0]->NumberValue();\n    MyObject* obj = new MyObject(value);\n    obj->Wrap(args.This());\n    return args.This();\n  } else {\n    // Invoked as plain function `MyObject(...)`, turn into construct call.\n    const int argc = 1;\n    Local<Value> argv[argc] = { args[0] };\n    return scope.Close(constructor->NewInstance(argc, argv));\n  }\n}\n\nHandle<Value> MyObject::NewInstance(const Arguments& args) {\n  HandleScope scope;\n\n  const unsigned argc = 1;\n  Handle<Value> argv[argc] = { args[0] };\n  Local<Object> instance = constructor->NewInstance(argc, argv);\n\n  return scope.Close(instance);\n}
    \n

    Test it with:\n\n

    \n
    var addon = require('./build/Release/addon');\n\nvar obj1 = addon.createObject(10);\nvar obj2 = addon.createObject(20);\nvar result = addon.add(obj1, obj2);\n\nconsole.log(result); // 30
    \n", "type": "module", "displayName": "Passing wrapped objects around" } ], "type": "module", "displayName": "Addon patterns" } ], "type": "module", "displayName": "Addons" } ] } node-v0.10.25~dfsg2/doc/api/tty.html0000644000000000000000000001705112270264601015644 0ustar rootroot TTY Node.js v0.10.25 Manual & Documentation

    Node.js v0.10.25 Manual & Documentation


    TTY#

    Stability: 2 - Unstable

    The tty module houses the tty.ReadStream and tty.WriteStream classes. In most cases, you will not need to use this module directly.

    When node detects that it is being run inside a TTY context, then process.stdin will be a tty.ReadStream instance and process.stdout will be a tty.WriteStream instance. The preferred way to check if node is being run in a TTY context is to check process.stdout.isTTY:

    $ node -p -e "Boolean(process.stdout.isTTY)"
    true
    $ node -p -e "Boolean(process.stdout.isTTY)" | cat
    false

    tty.isatty(fd)#

    Returns true or false depending on if the fd is associated with a terminal.

    tty.setRawMode(mode)#

    Deprecated. Use tty.ReadStream#setRawMode() (i.e. process.stdin.setRawMode()) instead.

    Class: ReadStream#

    A net.Socket subclass that represents the readable portion of a tty. In normal circumstances, process.stdin will be the only tty.ReadStream instance in any node program (only when isatty(0) is true).

    rs.isRaw#

    A Boolean that is initialized to false. It represents the current "raw" state of the tty.ReadStream instance.

    rs.setRawMode(mode)#

    mode should be true or false. This sets the properties of the tty.ReadStream to act either as a raw device or default. isRaw will be set to the resulting mode.

    Class: WriteStream#

    A net.Socket subclass that represents the writable portion of a tty. In normal circumstances, process.stdout will be the only tty.WriteStream instance ever created (and only when isatty(1) is true).

    ws.columns#

    A Number that gives the number of columns the TTY currently has. This property gets updated on "resize" events.

    ws.rows#

    A Number that gives the number of rows the TTY currently has. This property gets updated on "resize" events.

    Event: 'resize'#

    function () {}

    Emitted by refreshSize() when either of the columns or rows properties has changed.

    process.stdout.on('resize', function() {
      console.log('screen size has changed!');
      console.log(process.stdout.columns + 'x' + process.stdout.rows);
    });
    node-v0.10.25~dfsg2/doc/api/domain.html0000644000000000000000000005462512270264601016303 0ustar rootroot Domain Node.js v0.10.25 Manual & Documentation

    Node.js v0.10.25 Manual & Documentation


    Domain#

    Stability: 2 - Unstable

    Domains provide a way to handle multiple different IO operations as a single group. If any of the event emitters or callbacks registered to a domain emit an error event, or throw an error, then the domain object will be notified, rather than losing the context of the error in the process.on('uncaughtException') handler, or causing the program to exit immediately with an error code.

    Warning: Don't Ignore Errors!#

    Domain error handlers are not a substitute for closing down your process when an error occurs.

    By the very nature of how throw works in JavaScript, there is almost never any way to safely "pick up where you left off", without leaking references, or creating some other sort of undefined brittle state.

    The safest way to respond to a thrown error is to shut down the process. Of course, in a normal web server, you might have many connections open, and it is not reasonable to abruptly shut those down because an error was triggered by someone else.

    The better approach is send an error response to the request that triggered the error, while letting the others finish in their normal time, and stop listening for new requests in that worker.

    In this way, domain usage goes hand-in-hand with the cluster module, since the master process can fork a new worker when a worker encounters an error. For node programs that scale to multiple machines, the terminating proxy or service registry can take note of the failure, and react accordingly.

    For example, this is not a good idea:

    // XXX WARNING!  BAD IDEA!
    
    var d = require('domain').create();
    d.on('error', function(er) {
      // The error won't crash the process, but what it does is worse!
      // Though we've prevented abrupt process restarting, we are leaking
      // resources like crazy if this ever happens.
      // This is no better than process.on('uncaughtException')!
      console.log('error, but oh well', er.message);
    });
    d.run(function() {
      require('http').createServer(function(req, res) {
        handleRequest(req, res);
      }).listen(PORT);
    });

    By using the context of a domain, and the resilience of separating our program into multiple worker processes, we can react more appropriately, and handle errors with much greater safety.

    // Much better!
    
    var cluster = require('cluster');
    var PORT = +process.env.PORT || 1337;
    
    if (cluster.isMaster) {
      // In real life, you'd probably use more than just 2 workers,
      // and perhaps not put the master and worker in the same file.
      //
      // You can also of course get a bit fancier about logging, and
      // implement whatever custom logic you need to prevent DoS
      // attacks and other bad behavior.
      //
      // See the options in the cluster documentation.
      //
      // The important thing is that the master does very little,
      // increasing our resilience to unexpected errors.
    
      cluster.fork();
      cluster.fork();
    
      cluster.on('disconnect', function(worker) {
        console.error('disconnect!');
        cluster.fork();
      });
    
    } else {
      // the worker
      //
      // This is where we put our bugs!
    
      var domain = require('domain');
    
      // See the cluster documentation for more details about using
      // worker processes to serve requests.  How it works, caveats, etc.
    
      var server = require('http').createServer(function(req, res) {
        var d = domain.create();
        d.on('error', function(er) {
          console.error('error', er.stack);
    
          // Note: we're in dangerous territory!
          // By definition, something unexpected occurred,
          // which we probably didn't want.
          // Anything can happen now!  Be very careful!
    
          try {
            // make sure we close down within 30 seconds
            var killtimer = setTimeout(function() {
              process.exit(1);
            }, 30000);
            // But don't keep the process open just for that!
            killtimer.unref();
    
            // stop taking new requests.
            server.close();
    
            // Let the master know we're dead.  This will trigger a
            // 'disconnect' in the cluster master, and then it will fork
            // a new worker.
            cluster.worker.disconnect();
    
            // try to send an error to the request that triggered the problem
            res.statusCode = 500;
            res.setHeader('content-type', 'text/plain');
            res.end('Oops, there was a problem!\n');
          } catch (er2) {
            // oh well, not much we can do at this point.
            console.error('Error sending 500!', er2.stack);
          }
        });
    
        // Because req and res were created before this domain existed,
        // we need to explicitly add them.
        // See the explanation of implicit vs explicit binding below.
        d.add(req);
        d.add(res);
    
        // Now run the handler function in the domain.
        d.run(function() {
          handleRequest(req, res);
        });
      });
      server.listen(PORT);
    }
    
    // This part isn't important.  Just an example routing thing.
    // You'd put your fancy application logic here.
    function handleRequest(req, res) {
      switch(req.url) {
        case '/error':
          // We do some async stuff, and then...
          setTimeout(function() {
            // Whoops!
            flerb.bark();
          });
          break;
        default:
          res.end('ok');
      }
    }

    Additions to Error objects#

    Any time an Error object is routed through a domain, a few extra fields are added to it.

    • error.domain The domain that first handled the error.
    • error.domainEmitter The event emitter that emitted an 'error' event with the error object.
    • error.domainBound The callback function which was bound to the domain, and passed an error as its first argument.
    • error.domainThrown A boolean indicating whether the error was thrown, emitted, or passed to a bound callback function.

    Implicit Binding#

    If domains are in use, then all new EventEmitter objects (including Stream objects, requests, responses, etc.) will be implicitly bound to the active domain at the time of their creation.

    Additionally, callbacks passed to lowlevel event loop requests (such as to fs.open, or other callback-taking methods) will automatically be bound to the active domain. If they throw, then the domain will catch the error.

    In order to prevent excessive memory usage, Domain objects themselves are not implicitly added as children of the active domain. If they were, then it would be too easy to prevent request and response objects from being properly garbage collected.

    If you want to nest Domain objects as children of a parent Domain, then you must explicitly add them.

    Implicit binding routes thrown errors and 'error' events to the Domain's error event, but does not register the EventEmitter on the Domain, so domain.dispose() will not shut down the EventEmitter. Implicit binding only takes care of thrown errors and 'error' events.

    Explicit Binding#

    Sometimes, the domain in use is not the one that ought to be used for a specific event emitter. Or, the event emitter could have been created in the context of one domain, but ought to instead be bound to some other domain.

    For example, there could be one domain in use for an HTTP server, but perhaps we would like to have a separate domain to use for each request.

    That is possible via explicit binding.

    For example:

    // create a top-level domain for the server
    var serverDomain = domain.create();
    
    serverDomain.run(function() {
      // server is created in the scope of serverDomain
      http.createServer(function(req, res) {
        // req and res are also created in the scope of serverDomain
        // however, we'd prefer to have a separate domain for each request.
        // create it first thing, and add req and res to it.
        var reqd = domain.create();
        reqd.add(req);
        reqd.add(res);
        reqd.on('error', function(er) {
          console.error('Error', er, req.url);
          try {
            res.writeHead(500);
            res.end('Error occurred, sorry.');
          } catch (er) {
            console.error('Error sending 500', er, req.url);
          }
        });
      }).listen(1337);
    });

    domain.create()#

    • return: Domain

    Returns a new Domain object.

    Class: Domain#

    The Domain class encapsulates the functionality of routing errors and uncaught exceptions to the active Domain object.

    Domain is a child class of EventEmitter. To handle the errors that it catches, listen to its error event.

    domain.run(fn)#

    • fn Function

    Run the supplied function in the context of the domain, implicitly binding all event emitters, timers, and lowlevel requests that are created in that context.

    This is the most basic way to use a domain.

    Example:

    var d = domain.create();
    d.on('error', function(er) {
      console.error('Caught error!', er);
    });
    d.run(function() {
      process.nextTick(function() {
        setTimeout(function() { // simulating some various async stuff
          fs.open('non-existent file', 'r', function(er, fd) {
            if (er) throw er;
            // proceed...
          });
        }, 100);
      });
    });

    In this example, the d.on('error') handler will be triggered, rather than crashing the program.

    domain.members#

    • Array

    An array of timers and event emitters that have been explicitly added to the domain.

    domain.add(emitter)#

    • emitter EventEmitter | Timer emitter or timer to be added to the domain

    Explicitly adds an emitter to the domain. If any event handlers called by the emitter throw an error, or if the emitter emits an error event, it will be routed to the domain's error event, just like with implicit binding.

    This also works with timers that are returned from setInterval and setTimeout. If their callback function throws, it will be caught by the domain 'error' handler.

    If the Timer or EventEmitter was already bound to a domain, it is removed from that one, and bound to this one instead.

    domain.remove(emitter)#

    • emitter EventEmitter | Timer emitter or timer to be removed from the domain

    The opposite of domain.add(emitter). Removes domain handling from the specified emitter.

    domain.bind(callback)#

    • callback Function The callback function
    • return: Function The bound function

    The returned function will be a wrapper around the supplied callback function. When the returned function is called, any errors that are thrown will be routed to the domain's error event.

    Example#

    var d = domain.create();
    
    function readSomeFile(filename, cb) {
      fs.readFile(filename, 'utf8', d.bind(function(er, data) {
        // if this throws, it will also be passed to the domain
        return cb(er, data ? JSON.parse(data) : null);
      }));
    }
    
    d.on('error', function(er) {
      // an error occurred somewhere.
      // if we throw it now, it will crash the program
      // with the normal line number and stack message.
    });

    domain.intercept(callback)#

    • callback Function The callback function
    • return: Function The intercepted function

    This method is almost identical to domain.bind(callback). However, in addition to catching thrown errors, it will also intercept Error objects sent as the first argument to the function.

    In this way, the common if (er) return callback(er); pattern can be replaced with a single error handler in a single place.

    Example#

    var d = domain.create();
    
    function readSomeFile(filename, cb) {
      fs.readFile(filename, 'utf8', d.intercept(function(data) {
        // note, the first argument is never passed to the
        // callback since it is assumed to be the 'Error' argument
        // and thus intercepted by the domain.
    
        // if this throws, it will also be passed to the domain
        // so the error-handling logic can be moved to the 'error'
        // event on the domain instead of being repeated throughout
        // the program.
        return cb(null, JSON.parse(data));
      }));
    }
    
    d.on('error', function(er) {
      // an error occurred somewhere.
      // if we throw it now, it will crash the program
      // with the normal line number and stack message.
    });

    domain.enter()#

    The enter method is plumbing used by the run, bind, and intercept methods to set the active domain. It sets domain.active and process.domain to the domain, and implicitly pushes the domain onto the domain stack managed by the domain module (see domain.exit() for details on the domain stack). The call to enter delimits the beginning of a chain of asynchronous calls and I/O operations bound to a domain.

    Calling enter changes only the active domain, and does not alter the domain itself. Enter and exit can be called an arbitrary number of times on a single domain.

    If the domain on which enter is called has been disposed, enter will return without setting the domain.

    domain.exit()#

    The exit method exits the current domain, popping it off the domain stack. Any time execution is going to switch to the context of a different chain of asynchronous calls, it's important to ensure that the current domain is exited. The call to exit delimits either the end of or an interruption to the chain of asynchronous calls and I/O operations bound to a domain.

    If there are multiple, nested domains bound to the current execution context, exit will exit any domains nested within this domain.

    Calling exit changes only the active domain, and does not alter the domain itself. Enter and exit can be called an arbitrary number of times on a single domain.

    If the domain on which exit is called has been disposed, exit will return without exiting the domain.

    domain.dispose()#

    The dispose method destroys a domain, and makes a best effort attempt to clean up any and all IO that is associated with the domain. Streams are aborted, ended, closed, and/or destroyed. Timers are cleared. Explicitly bound callbacks are no longer called. Any error events that are raised as a result of this are ignored.

    The intention of calling dispose is generally to prevent cascading errors when a critical part of the Domain context is found to be in an error state.

    Once the domain is disposed the dispose event will emit.

    Note that IO might still be performed. However, to the highest degree possible, once a domain is disposed, further errors from the emitters in that set will be ignored. So, even if some remaining actions are still in flight, Node.js will not communicate further about them.

    node-v0.10.25~dfsg2/doc/api/all.html0000644000000000000000000225267712270264601015615 0ustar rootroot About this Documentation Node.js v0.10.25 Manual & Documentation

    Node.js v0.10.25 Manual & Documentation


    Table of Contents

    About this Documentation#

    The goal of this documentation is to comprehensively explain the Node.js API, both from a reference as well as a conceptual point of view. Each section describes a built-in module or high-level concept.

    Where appropriate, property types, method arguments, and the arguments provided to event handlers are detailed in a list underneath the topic heading.

    Every .html document has a corresponding .json document presenting the same information in a structured manner. This feature is experimental, and added for the benefit of IDEs and other utilities that wish to do programmatic things with the documentation.

    Every .html and .json file is generated based on the corresponding .markdown file in the doc/api/ folder in node's source tree. The documentation is generated using the tools/doc/generate.js program. The HTML template is located at doc/template.html.

    Stability Index#

    Throughout the documentation, you will see indications of a section's stability. The Node.js API is still somewhat changing, and as it matures, certain parts are more reliable than others. Some are so proven, and so relied upon, that they are unlikely to ever change at all. Others are brand new and experimental, or known to be hazardous and in the process of being redesigned.

    The stability indices are as follows:

    Stability: 0 - Deprecated
    This feature is known to be problematic, and changes are
    planned.  Do not rely on it.  Use of the feature may cause warnings.  Backwards
    compatibility should not be expected.
    Stability: 1 - Experimental
    This feature was introduced recently, and may change
    or be removed in future versions.  Please try it out and provide feedback.
    If it addresses a use-case that is important to you, tell the node core team.
    Stability: 2 - Unstable
    The API is in the process of settling, but has not yet had
    sufficient real-world testing to be considered stable. Backwards-compatibility
    will be maintained if reasonable.
    Stability: 3 - Stable
    The API has proven satisfactory, but cleanup in the underlying
    code may cause minor changes.  Backwards-compatibility is guaranteed.
    Stability: 4 - API Frozen
    This API has been tested extensively in production and is
    unlikely to ever have to change.
    Stability: 5 - Locked
    Unless serious bugs are found, this code will not ever
    change.  Please do not suggest changes in this area; they will be refused.

    JSON Output#

    Stability: 1 - Experimental

    Every HTML file in the markdown has a corresponding JSON file with the same data.

    This feature is new as of node v0.6.12. It is experimental.

    Synopsis#

    An example of a web server written with Node which responds with 'Hello World':

    var http = require('http');
    
    http.createServer(function (request, response) {
      response.writeHead(200, {'Content-Type': 'text/plain'});
      response.end('Hello World\n');
    }).listen(8124);
    
    console.log('Server running at http://127.0.0.1:8124/');

    To run the server, put the code into a file called example.js and execute it with the node program

    > node example.js
    Server running at http://127.0.0.1:8124/

    All of the examples in the documentation can be run similarly.

    Global Objects#

    These objects are available in all modules. Some of these objects aren't actually in the global scope but in the module scope - this will be noted.

    global#

    • {Object} The global namespace object.

    In browsers, the top-level scope is the global scope. That means that in browsers if you're in the global scope var something will define a global variable. In Node this is different. The top-level scope is not the global scope; var something inside a Node module will be local to that module.

    process#

    • {Object}

    The process object. See the process object section.

    console#

    • {Object}

    Used to print to stdout and stderr. See the console section.

    Class: Buffer#

    • {Function}

    Used to handle binary data. See the buffer section

    require()#

    • {Function}

    To require modules. See the Modules section. require isn't actually a global but rather local to each module.

    require.resolve()#

    Use the internal require() machinery to look up the location of a module, but rather than loading the module, just return the resolved filename.

    require.cache#

    • Object

    Modules are cached in this object when they are required. By deleting a key value from this object, the next require will reload the module.

    require.extensions#

    Stability: 0 - Deprecated
    • Object

    Instruct require on how to handle certain file extensions.

    Process files with the extension .sjs as .js:

    require.extensions['.sjs'] = require.extensions['.js'];

    Deprecated In the past, this list has been used to load non-JavaScript modules into Node by compiling them on-demand. However, in practice, there are much better ways to do this, such as loading modules via some other Node program, or compiling them to JavaScript ahead of time.

    Since the Module system is locked, this feature will probably never go away. However, it may have subtle bugs and complexities that are best left untouched.

    __filename#

    • {String}

    The filename of the code being executed. This is the resolved absolute path of this code file. For a main program this is not necessarily the same filename used in the command line. The value inside a module is the path to that module file.

    Example: running node example.js from /Users/mjr

    console.log(__filename);
    // /Users/mjr/example.js

    __filename isn't actually a global but rather local to each module.

    __dirname#

    • {String}

    The name of the directory that the currently executing script resides in.

    Example: running node example.js from /Users/mjr

    console.log(__dirname);
    // /Users/mjr

    __dirname isn't actually a global but rather local to each module.

    module#

    • {Object}

    A reference to the current module. In particular module.exports is used for defining what a module exports and makes available through require().

    module isn't actually a global but rather local to each module.

    See the module system documentation for more information.

    exports#

    A reference to the module.exports that is shorter to type. See module system documentation for details on when to use exports and when to use module.exports.

    exports isn't actually a global but rather local to each module.

    See the module system documentation for more information.

    See the module section for more information.

    setTimeout(cb, ms)#

    Run callback cb after at least ms milliseconds. The actual delay depends on external factors like OS timer granularity and system load.

    The timeout must be in the range of 1-2,147,483,647 inclusive. If the value is outside that range, it's changed to 1 millisecond. Broadly speaking, a timer cannot span more than 24.8 days.

    Returns an opaque value that represents the timer.

    clearTimeout(t)#

    Stop a timer that was previously created with setTimeout(). The callback will not execute.

    setInterval(cb, ms)#

    Run callback cb repeatedly every ms milliseconds. Note that the actual interval may vary, depending on external factors like OS timer granularity and system load. It's never less than ms but it may be longer.

    The interval must be in the range of 1-2,147,483,647 inclusive. If the value is outside that range, it's changed to 1 millisecond. Broadly speaking, a timer cannot span more than 24.8 days.

    Returns an opaque value that represents the timer.

    clearInterval(t)#

    Stop a timer that was previously created with setInterval(). The callback will not execute.

    The timer functions are global variables. See the timers section.

    console#

    Stability: 4 - API Frozen
    • Object

    For printing to stdout and stderr. Similar to the console object functions provided by most web browsers, here the output is sent to stdout or stderr.

    The console functions are synchronous when the destination is a terminal or a file (to avoid lost messages in case of premature exit) and asynchronous when it's a pipe (to avoid blocking for long periods of time).

    That is, in the following example, stdout is non-blocking while stderr is blocking:

    $ node script.js 2> error.log | tee info.log

    In daily use, the blocking/non-blocking dichotomy is not something you should worry about unless you log huge amounts of data.

    console.log([data], [...])#

    Prints to stdout with newline. This function can take multiple arguments in a printf()-like way. Example:

    console.log('count: %d', count);

    If formatting elements are not found in the first string then util.inspect is used on each argument. See util.format() for more information.

    console.info([data], [...])#

    Same as console.log.

    console.error([data], [...])#

    Same as console.log but prints to stderr.

    console.warn([data], [...])#

    Same as console.error.

    console.dir(obj)#

    Uses util.inspect on obj and prints resulting string to stdout.

    console.time(label)#

    Mark a time.

    console.timeEnd(label)#

    Finish timer, record output. Example:

    console.time('100-elements');
    for (var i = 0; i < 100; i++) {
      ;
    }
    console.timeEnd('100-elements');

    console.trace(label)#

    Print a stack trace to stderr of the current position.

    console.assert(expression, [message])#

    Same as assert.ok() where if the expression evaluates as false throw an AssertionError with message.

    Timers#

    Stability: 5 - Locked

    All of the timer functions are globals. You do not need to require() this module in order to use them.

    setTimeout(callback, delay, [arg], [...])#

    To schedule execution of a one-time callback after delay milliseconds. Returns a timeoutId for possible use with clearTimeout(). Optionally you can also pass arguments to the callback.

    It is important to note that your callback will probably not be called in exactly delay milliseconds - Node.js makes no guarantees about the exact timing of when the callback will fire, nor of the ordering things will fire in. The callback will be called as close as possible to the time specified.

    clearTimeout(timeoutId)#

    Prevents a timeout from triggering.

    setInterval(callback, delay, [arg], [...])#

    To schedule the repeated execution of callback every delay milliseconds. Returns a intervalId for possible use with clearInterval(). Optionally you can also pass arguments to the callback.

    clearInterval(intervalId)#

    Stops a interval from triggering.

    unref()#

    The opaque value returned by setTimeout and setInterval also has the method timer.unref() which will allow you to create a timer that is active but if it is the only item left in the event loop won't keep the program running. If the timer is already unrefd calling unref again will have no effect.

    In the case of setTimeout when you unref you create a separate timer that will wakeup the event loop, creating too many of these may adversely effect event loop performance -- use wisely.

    ref()#

    If you had previously unref()d a timer you can call ref() to explicitly request the timer hold the program open. If the timer is already refd calling ref again will have no effect.

    setImmediate(callback, [arg], [...])#

    To schedule the "immediate" execution of callback after I/O events callbacks and before setTimeout and setInterval . Returns an immediateId for possible use with clearImmediate(). Optionally you can also pass arguments to the callback.

    Immediates are queued in the order created, and are popped off the queue once per loop iteration. This is different from process.nextTick which will execute process.maxTickDepth queued callbacks per iteration. setImmediate will yield to the event loop after firing a queued callback to make sure I/O is not being starved. While order is preserved for execution, other I/O events may fire between any two scheduled immediate callbacks.

    clearImmediate(immediateId)#

    Stops an immediate from triggering.

    Modules#

    Stability: 5 - Locked

    Node has a simple module loading system. In Node, files and modules are in one-to-one correspondence. As an example, foo.js loads the module circle.js in the same directory.

    The contents of foo.js:

    var circle = require('./circle.js');
    console.log( 'The area of a circle of radius 4 is '
               + circle.area(4));

    The contents of circle.js:

    var PI = Math.PI;
    
    exports.area = function (r) {
      return PI * r * r;
    };
    
    exports.circumference = function (r) {
      return 2 * PI * r;
    };

    The module circle.js has exported the functions area() and circumference(). To add functions and objects to the root of your module, you can add them to the special exports object.

    Variables local to the module will be private, as though the module was wrapped in a function. In this example the variable PI is private to circle.js.

    If you want the root of your module's export to be a function (such as a constructor) or if you want to export a complete object in one assignment instead of building it one property at a time, assign it to module.exports instead of exports.

    Below, bar.js makes use of the square module, which exports a constructor:

    var square = require('./square.js');
    var mySquare = square(2);
    console.log('The area of my square is ' + mySquare.area());

    The square module is defined in square.js:

    // assigning to exports will not modify module, must use module.exports
    module.exports = function(width) {
      return {
        area: function() {
          return width * width;
        }
      };
    }

    The module system is implemented in the require("module") module.

    Cycles#

    When there are circular require() calls, a module might not be done being executed when it is returned.

    Consider this situation:

    a.js:

    console.log('a starting');
    exports.done = false;
    var b = require('./b.js');
    console.log('in a, b.done = %j', b.done);
    exports.done = true;
    console.log('a done');

    b.js:

    console.log('b starting');
    exports.done = false;
    var a = require('./a.js');
    console.log('in b, a.done = %j', a.done);
    exports.done = true;
    console.log('b done');

    main.js:

    console.log('main starting');
    var a = require('./a.js');
    var b = require('./b.js');
    console.log('in main, a.done=%j, b.done=%j', a.done, b.done);

    When main.js loads a.js, then a.js in turn loads b.js. At that point, b.js tries to load a.js. In order to prevent an infinite loop an unfinished copy of the a.js exports object is returned to the b.js module. b.js then finishes loading, and its exports object is provided to the a.js module.

    By the time main.js has loaded both modules, they're both finished. The output of this program would thus be:

    $ node main.js
    main starting
    a starting
    b starting
    in b, a.done = false
    b done
    in a, b.done = true
    a done
    in main, a.done=true, b.done=true

    If you have cyclic module dependencies in your program, make sure to plan accordingly.

    Core Modules#

    Node has several modules compiled into the binary. These modules are described in greater detail elsewhere in this documentation.

    The core modules are defined in node's source in the lib/ folder.

    Core modules are always preferentially loaded if their identifier is passed to require(). For instance, require('http') will always return the built in HTTP module, even if there is a file by that name.

    File Modules#

    If the exact filename is not found, then node will attempt to load the required filename with the added extension of .js, .json, and then .node.

    .js files are interpreted as JavaScript text files, and .json files are parsed as JSON text files. .node files are interpreted as compiled addon modules loaded with dlopen.

    A module prefixed with '/' is an absolute path to the file. For example, require('/home/marco/foo.js') will load the file at /home/marco/foo.js.

    A module prefixed with './' is relative to the file calling require(). That is, circle.js must be in the same directory as foo.js for require('./circle') to find it.

    Without a leading '/' or './' to indicate a file, the module is either a "core module" or is loaded from a node_modules folder.

    If the given path does not exist, require() will throw an Error with its code property set to 'MODULE_NOT_FOUND'.

    Loading from node_modules Folders#

    If the module identifier passed to require() is not a native module, and does not begin with '/', '../', or './', then node starts at the parent directory of the current module, and adds /node_modules, and attempts to load the module from that location.

    If it is not found there, then it moves to the parent directory, and so on, until the root of the tree is reached.

    For example, if the file at '/home/ry/projects/foo.js' called require('bar.js'), then node would look in the following locations, in this order:

    • /home/ry/projects/node_modules/bar.js
    • /home/ry/node_modules/bar.js
    • /home/node_modules/bar.js
    • /node_modules/bar.js

    This allows programs to localize their dependencies, so that they do not clash.

    Folders as Modules#

    It is convenient to organize programs and libraries into self-contained directories, and then provide a single entry point to that library. There are three ways in which a folder may be passed to require() as an argument.

    The first is to create a package.json file in the root of the folder, which specifies a main module. An example package.json file might look like this:

    { "name" : "some-library",
      "main" : "./lib/some-library.js" }

    If this was in a folder at ./some-library, then require('./some-library') would attempt to load ./some-library/lib/some-library.js.

    This is the extent of Node's awareness of package.json files.

    If there is no package.json file present in the directory, then node will attempt to load an index.js or index.node file out of that directory. For example, if there was no package.json file in the above example, then require('./some-library') would attempt to load:

    • ./some-library/index.js
    • ./some-library/index.node

    Caching#

    Modules are cached after the first time they are loaded. This means (among other things) that every call to require('foo') will get exactly the same object returned, if it would resolve to the same file.

    Multiple calls to require('foo') may not cause the module code to be executed multiple times. This is an important feature. With it, "partially done" objects can be returned, thus allowing transitive dependencies to be loaded even when they would cause cycles.

    If you want to have a module execute code multiple times, then export a function, and call that function.

    Module Caching Caveats#

    Modules are cached based on their resolved filename. Since modules may resolve to a different filename based on the location of the calling module (loading from node_modules folders), it is not a guarantee that require('foo') will always return the exact same object, if it would resolve to different files.

    The module Object#

    • {Object}

    In each module, the module free variable is a reference to the object representing the current module. For convenience, module.exports is also accessible via the exports module-global. module isn't actually a global but rather local to each module.

    module.exports#

    • Object

    The module.exports object is created by the Module system. Sometimes this is not acceptable; many want their module to be an instance of some class. To do this assign the desired export object to module.exports. Note that assigning the desired object to exports will simply rebind the local exports variable, which is probably not what you want to do.

    For example suppose we were making a module called a.js

    var EventEmitter = require('events').EventEmitter;
    
    module.exports = new EventEmitter();
    
    // Do some work, and after some time emit
    // the 'ready' event from the module itself.
    setTimeout(function() {
      module.exports.emit('ready');
    }, 1000);

    Then in another file we could do

    var a = require('./a');
    a.on('ready', function() {
      console.log('module a is ready');
    });

    Note that assignment to module.exports must be done immediately. It cannot be done in any callbacks. This does not work:

    x.js:

    setTimeout(function() {
      module.exports = { a: "hello" };
    }, 0);

    y.js:

    var x = require('./x');
    console.log(x.a);

    exports alias#

    The exports variable that is available within a module starts as a reference to module.exports. As with any variable, if you assign a new value to it, it is no longer bound to the previous value.

    To illustrate the behaviour, imagine this hypothetical implementation of require():

    function require(...) {
      // ...
      function (module, exports) {
        // Your module code here
        exports = some_func;        // re-assigns exports, exports is no longer
                                    // a shortcut, and nothing is exported.
        module.exports = some_func; // makes your module export 0
      } (module, module.exports);
      return module;
    }

    As a guideline, if the relationship between exports and module.exports seems like magic to you, ignore exports and only use module.exports.

    module.require(id)#

    • id String
    • Return: Object module.exports from the resolved module

    The module.require method provides a way to load a module as if require() was called from the original module.

    Note that in order to do this, you must get a reference to the module object. Since require() returns the module.exports, and the module is typically only available within a specific module's code, it must be explicitly exported in order to be used.

    module.id#

    • String

    The identifier for the module. Typically this is the fully resolved filename.

    module.filename#

    • String

    The fully resolved filename to the module.

    module.loaded#

    • Boolean

    Whether or not the module is done loading, or is in the process of loading.

    module.parent#

    • Module Object

    The module that required this one.

    module.children#

    • Array

    The module objects required by this one.

    All Together...#

    To get the exact filename that will be loaded when require() is called, use the require.resolve() function.

    Putting together all of the above, here is the high-level algorithm in pseudocode of what require.resolve does:

    require(X) from module at path Y
    1. If X is a core module,
       a. return the core module
       b. STOP
    2. If X begins with './' or '/' or '../'
       a. LOAD_AS_FILE(Y + X)
       b. LOAD_AS_DIRECTORY(Y + X)
    3. LOAD_NODE_MODULES(X, dirname(Y))
    4. THROW "not found"
    
    LOAD_AS_FILE(X)
    1. If X is a file, load X as JavaScript text.  STOP
    2. If X.js is a file, load X.js as JavaScript text.  STOP
    3. If X.node is a file, load X.node as binary addon.  STOP
    
    LOAD_AS_DIRECTORY(X)
    1. If X/package.json is a file,
       a. Parse X/package.json, and look for "main" field.
       b. let M = X + (json main field)
       c. LOAD_AS_FILE(M)
    2. If X/index.js is a file, load X/index.js as JavaScript text.  STOP
    3. If X/index.node is a file, load X/index.node as binary addon.  STOP
    
    LOAD_NODE_MODULES(X, START)
    1. let DIRS=NODE_MODULES_PATHS(START)
    2. for each DIR in DIRS:
       a. LOAD_AS_FILE(DIR/X)
       b. LOAD_AS_DIRECTORY(DIR/X)
    
    NODE_MODULES_PATHS(START)
    1. let PARTS = path split(START)
    2. let ROOT = index of first instance of "node_modules" in PARTS, or 0
    3. let I = count of PARTS - 1
    4. let DIRS = []
    5. while I > ROOT,
       a. if PARTS[I] = "node_modules" CONTINUE
       c. DIR = path join(PARTS[0 .. I] + "node_modules")
       b. DIRS = DIRS + DIR
       c. let I = I - 1
    6. return DIRS

    Loading from the global folders#

    If the NODE_PATH environment variable is set to a colon-delimited list of absolute paths, then node will search those paths for modules if they are not found elsewhere. (Note: On Windows, NODE_PATH is delimited by semicolons instead of colons.)

    Additionally, node will search in the following locations:

    • 1: $HOME/.node_modules
    • 2: $HOME/.node_libraries
    • 3: $PREFIX/lib/node

    Where $HOME is the user's home directory, and $PREFIX is node's configured node_prefix.

    These are mostly for historic reasons. You are highly encouraged to place your dependencies locally in node_modules folders. They will be loaded faster, and more reliably.

    Accessing the main module#

    When a file is run directly from Node, require.main is set to its module. That means that you can determine whether a file has been run directly by testing

    require.main === module

    For a file foo.js, this will be true if run via node foo.js, but false if run by require('./foo').

    Because module provides a filename property (normally equivalent to __filename), the entry point of the current application can be obtained by checking require.main.filename.

    Addenda: Package Manager Tips#

    The semantics of Node's require() function were designed to be general enough to support a number of sane directory structures. Package manager programs such as dpkg, rpm, and npm will hopefully find it possible to build native packages from Node modules without modification.

    Below we give a suggested directory structure that could work:

    Let's say that we wanted to have the folder at /usr/lib/node/<some-package>/<some-version> hold the contents of a specific version of a package.

    Packages can depend on one another. In order to install package foo, you may have to install a specific version of package bar. The bar package may itself have dependencies, and in some cases, these dependencies may even collide or form cycles.

    Since Node looks up the realpath of any modules it loads (that is, resolves symlinks), and then looks for their dependencies in the node_modules folders as described above, this situation is very simple to resolve with the following architecture:

    • /usr/lib/node/foo/1.2.3/ - Contents of the foo package, version 1.2.3.
    • /usr/lib/node/bar/4.3.2/ - Contents of the bar package that foo depends on.
    • /usr/lib/node/foo/1.2.3/node_modules/bar - Symbolic link to /usr/lib/node/bar/4.3.2/.
    • /usr/lib/node/bar/4.3.2/node_modules/* - Symbolic links to the packages that bar depends on.

    Thus, even if a cycle is encountered, or if there are dependency conflicts, every module will be able to get a version of its dependency that it can use.

    When the code in the foo package does require('bar'), it will get the version that is symlinked into /usr/lib/node/foo/1.2.3/node_modules/bar. Then, when the code in the bar package calls require('quux'), it'll get the version that is symlinked into /usr/lib/node/bar/4.3.2/node_modules/quux.

    Furthermore, to make the module lookup process even more optimal, rather than putting packages directly in /usr/lib/node, we could put them in /usr/lib/node_modules/<name>/<version>. Then node will not bother looking for missing dependencies in /usr/node_modules or /node_modules.

    In order to make modules available to the node REPL, it might be useful to also add the /usr/lib/node_modules folder to the $NODE_PATH environment variable. Since the module lookups using node_modules folders are all relative, and based on the real path of the files making the calls to require(), the packages themselves can be anywhere.

    Addons#

    Addons are dynamically linked shared objects. They can provide glue to C and C++ libraries. The API (at the moment) is rather complex, involving knowledge of several libraries:

    • V8 JavaScript, a C++ library. Used for interfacing with JavaScript: creating objects, calling functions, etc. Documented mostly in the v8.h header file (deps/v8/include/v8.h in the Node source tree), which is also available online.

    • libuv, C event loop library. Anytime one needs to wait for a file descriptor to become readable, wait for a timer, or wait for a signal to be received one will need to interface with libuv. That is, if you perform any I/O, libuv will need to be used.

    • Internal Node libraries. Most importantly is the node::ObjectWrap class which you will likely want to derive from.

    • Others. Look in deps/ for what else is available.

    Node statically compiles all its dependencies into the executable. When compiling your module, you don't need to worry about linking to any of these libraries.

    All of the following examples are available for download and may be used as a starting-point for your own Addon.

    Hello world#

    To get started let's make a small Addon which is the C++ equivalent of the following JavaScript code:

    module.exports.hello = function() { return 'world'; };

    First we create a file hello.cc:

    #include <node.h>
    #include <v8.h>
    
    using namespace v8;
    
    Handle<Value> Method(const Arguments& args) {
      HandleScope scope;
      return scope.Close(String::New("world"));
    }
    
    void init(Handle<Object> exports) {
      exports->Set(String::NewSymbol("hello"),
          FunctionTemplate::New(Method)->GetFunction());
    }
    
    NODE_MODULE(hello, init)

    Note that all Node addons must export an initialization function:

    void Initialize (Handle<Object> exports);
    NODE_MODULE(module_name, Initialize)

    There is no semi-colon after NODE_MODULE as it's not a function (see node.h).

    The module_name needs to match the filename of the final binary (minus the .node suffix).

    The source code needs to be built into hello.node, the binary Addon. To do this we create a file called binding.gyp which describes the configuration to build your module in a JSON-like format. This file gets compiled by node-gyp.

    {
      "targets": [
        {
          "target_name": "hello",
          "sources": [ "hello.cc" ]
        }
      ]
    }

    The next step is to generate the appropriate project build files for the current platform. Use node-gyp configure for that.

    Now you will have either a Makefile (on Unix platforms) or a vcxproj file (on Windows) in the build/ directory. Next invoke the node-gyp build command.

    Now you have your compiled .node bindings file! The compiled bindings end up in build/Release/.

    You can now use the binary addon in a Node project hello.js by pointing require to the recently built hello.node module:

    var addon = require('./build/Release/hello');
    
    console.log(addon.hello()); // 'world'

    Please see patterns below for further information or

    https://github.com/arturadib/node-qt for an example in production.

    Addon patterns#

    Below are some addon patterns to help you get started. Consult the online v8 reference for help with the various v8 calls, and v8's Embedder's Guide for an explanation of several concepts used such as handles, scopes, function templates, etc.

    In order to use these examples you need to compile them using node-gyp. Create the following binding.gyp file:

    {
      "targets": [
        {
          "target_name": "addon",
          "sources": [ "addon.cc" ]
        }
      ]
    }

    In cases where there is more than one .cc file, simply add the file name to the sources array, e.g.:

    "sources": ["addon.cc", "myexample.cc"]

    Now that you have your binding.gyp ready, you can configure and build the addon:

    $ node-gyp configure build

    Function arguments#

    The following pattern illustrates how to read arguments from JavaScript function calls and return a result. This is the main and only needed source addon.cc:

    #define BUILDING_NODE_EXTENSION
    #include <node.h>
    
    using namespace v8;
    
    Handle<Value> Add(const Arguments& args) {
      HandleScope scope;
    
      if (args.Length() < 2) {
        ThrowException(Exception::TypeError(String::New("Wrong number of arguments")));
        return scope.Close(Undefined());
      }
    
      if (!args[0]->IsNumber() || !args[1]->IsNumber()) {
        ThrowException(Exception::TypeError(String::New("Wrong arguments")));
        return scope.Close(Undefined());
      }
    
      Local<Number> num = Number::New(args[0]->NumberValue() +
          args[1]->NumberValue());
      return scope.Close(num);
    }
    
    void Init(Handle<Object> exports) {
      exports->Set(String::NewSymbol("add"),
          FunctionTemplate::New(Add)->GetFunction());
    }
    
    NODE_MODULE(addon, Init)

    You can test it with the following JavaScript snippet:

    var addon = require('./build/Release/addon');
    
    console.log( 'This should be eight:', addon.add(3,5) );

    Callbacks#

    You can pass JavaScript functions to a C++ function and execute them from there. Here's addon.cc:

    #define BUILDING_NODE_EXTENSION
    #include <node.h>
    
    using namespace v8;
    
    Handle<Value> RunCallback(const Arguments& args) {
      HandleScope scope;
    
      Local<Function> cb = Local<Function>::Cast(args[0]);
      const unsigned argc = 1;
      Local<Value> argv[argc] = { Local<Value>::New(String::New("hello world")) };
      cb->Call(Context::GetCurrent()->Global(), argc, argv);
    
      return scope.Close(Undefined());
    }
    
    void Init(Handle<Object> exports, Handle<Object> module) {
      module->Set(String::NewSymbol("exports"),
          FunctionTemplate::New(RunCallback)->GetFunction());
    }
    
    NODE_MODULE(addon, Init)

    Note that this example uses a two-argument form of Init() that receives the full module object as the second argument. This allows the addon to completely overwrite exports with a single function instead of adding the function as a property of exports.

    To test it run the following JavaScript snippet:

    var addon = require('./build/Release/addon');
    
    addon(function(msg){
      console.log(msg); // 'hello world'
    });

    Object factory#

    You can create and return new objects from within a C++ function with this addon.cc pattern, which returns an object with property msg that echoes the string passed to createObject():

    #define BUILDING_NODE_EXTENSION
    #include <node.h>
    
    using namespace v8;
    
    Handle<Value> CreateObject(const Arguments& args) {
      HandleScope scope;
    
      Local<Object> obj = Object::New();
      obj->Set(String::NewSymbol("msg"), args[0]->ToString());
    
      return scope.Close(obj);
    }
    
    void Init(Handle<Object> exports, Handle<Object> module) {
      module->Set(String::NewSymbol("exports"),
          FunctionTemplate::New(CreateObject)->GetFunction());
    }
    
    NODE_MODULE(addon, Init)

    To test it in JavaScript:

    var addon = require('./build/Release/addon');
    
    var obj1 = addon('hello');
    var obj2 = addon('world');
    console.log(obj1.msg+' '+obj2.msg); // 'hello world'

    Function factory#

    This pattern illustrates how to create and return a JavaScript function that wraps a C++ function:

    #define BUILDING_NODE_EXTENSION
    #include <node.h>
    
    using namespace v8;
    
    Handle<Value> MyFunction(const Arguments& args) {
      HandleScope scope;
      return scope.Close(String::New("hello world"));
    }
    
    Handle<Value> CreateFunction(const Arguments& args) {
      HandleScope scope;
    
      Local<FunctionTemplate> tpl = FunctionTemplate::New(MyFunction);
      Local<Function> fn = tpl->GetFunction();
      fn->SetName(String::NewSymbol("theFunction")); // omit this to make it anonymous
    
      return scope.Close(fn);
    }
    
    void Init(Handle<Object> exports, Handle<Object> module) {
      module->Set(String::NewSymbol("exports"),
          FunctionTemplate::New(CreateFunction)->GetFunction());
    }
    
    NODE_MODULE(addon, Init)

    To test:

    var addon = require('./build/Release/addon');
    
    var fn = addon();
    console.log(fn()); // 'hello world'

    Wrapping C++ objects#

    Here we will create a wrapper for a C++ object/class MyObject that can be instantiated in JavaScript through the new operator. First prepare the main module addon.cc:

    #define BUILDING_NODE_EXTENSION
    #include <node.h>
    #include "myobject.h"
    
    using namespace v8;
    
    void InitAll(Handle<Object> exports) {
      MyObject::Init(exports);
    }
    
    NODE_MODULE(addon, InitAll)

    Then in myobject.h make your wrapper inherit from node::ObjectWrap:

    #ifndef MYOBJECT_H
    #define MYOBJECT_H
    
    #include <node.h>
    
    class MyObject : public node::ObjectWrap {
     public:
      static void Init(v8::Handle<v8::Object> exports);
    
     private:
      explicit MyObject(double value = 0);
      ~MyObject();
    
      static v8::Handle<v8::Value> New(const v8::Arguments& args);
      static v8::Handle<v8::Value> PlusOne(const v8::Arguments& args);
      static v8::Persistent<v8::Function> constructor;
      double value_;
    };
    
    #endif

    And in myobject.cc implement the various methods that you want to expose. Here we expose the method plusOne by adding it to the constructor's prototype:

    #define BUILDING_NODE_EXTENSION
    #include <node.h>
    #include "myobject.h"
    
    using namespace v8;
    
    Persistent<Function> MyObject::constructor;
    
    MyObject::MyObject(double value) : value_(value) {
    }
    
    MyObject::~MyObject() {
    }
    
    void MyObject::Init(Handle<Object> exports) {
      // Prepare constructor template
      Local<FunctionTemplate> tpl = FunctionTemplate::New(New);
      tpl->SetClassName(String::NewSymbol("MyObject"));
      tpl->InstanceTemplate()->SetInternalFieldCount(1);
      // Prototype
      tpl->PrototypeTemplate()->Set(String::NewSymbol("plusOne"),
          FunctionTemplate::New(PlusOne)->GetFunction());
      constructor = Persistent<Function>::New(tpl->GetFunction());
      exports->Set(String::NewSymbol("MyObject"), constructor);
    }
    
    Handle<Value> MyObject::New(const Arguments& args) {
      HandleScope scope;
    
      if (args.IsConstructCall()) {
        // Invoked as constructor: `new MyObject(...)`
        double value = args[0]->IsUndefined() ? 0 : args[0]->NumberValue();
        MyObject* obj = new MyObject(value);
        obj->Wrap(args.This());
        return args.This();
      } else {
        // Invoked as plain function `MyObject(...)`, turn into construct call.
        const int argc = 1;
        Local<Value> argv[argc] = { args[0] };
        return scope.Close(constructor->NewInstance(argc, argv));
      }
    }
    
    Handle<Value> MyObject::PlusOne(const Arguments& args) {
      HandleScope scope;
    
      MyObject* obj = ObjectWrap::Unwrap<MyObject>(args.This());
      obj->value_ += 1;
    
      return scope.Close(Number::New(obj->value_));
    }

    Test it with:

    var addon = require('./build/Release/addon');
    
    var obj = new addon.MyObject(10);
    console.log( obj.plusOne() ); // 11
    console.log( obj.plusOne() ); // 12
    console.log( obj.plusOne() ); // 13

    Factory of wrapped objects#

    This is useful when you want to be able to create native objects without explicitly instantiating them with the new operator in JavaScript, e.g.

    var obj = addon.createObject();
    // instead of:
    // var obj = new addon.Object();

    Let's register our createObject method in addon.cc:

    #define BUILDING_NODE_EXTENSION
    #include <node.h>
    #include "myobject.h"
    
    using namespace v8;
    
    Handle<Value> CreateObject(const Arguments& args) {
      HandleScope scope;
      return scope.Close(MyObject::NewInstance(args));
    }
    
    void InitAll(Handle<Object> exports, Handle<Object> module) {
      MyObject::Init();
    
      module->Set(String::NewSymbol("exports"),
          FunctionTemplate::New(CreateObject)->GetFunction());
    }
    
    NODE_MODULE(addon, InitAll)

    In myobject.h we now introduce the static method NewInstance that takes care of instantiating the object (i.e. it does the job of new in JavaScript):

    #define BUILDING_NODE_EXTENSION
    #ifndef MYOBJECT_H
    #define MYOBJECT_H
    
    #include <node.h>
    
    class MyObject : public node::ObjectWrap {
     public:
      static void Init();
      static v8::Handle<v8::Value> NewInstance(const v8::Arguments& args);
    
     private:
      explicit MyObject(double value = 0);
      ~MyObject();
    
      static v8::Handle<v8::Value> New(const v8::Arguments& args);
      static v8::Handle<v8::Value> PlusOne(const v8::Arguments& args);
      static v8::Persistent<v8::Function> constructor;
      double value_;
    };
    
    #endif

    The implementation is similar to the above in myobject.cc:

    #define BUILDING_NODE_EXTENSION
    #include <node.h>
    #include "myobject.h"
    
    using namespace v8;
    
    Persistent<Function> MyObject::constructor;
    
    MyObject::MyObject(double value) : value_(value) {
    }
    
    MyObject::~MyObject() {
    }
    
    void MyObject::Init() {
      // Prepare constructor template
      Local<FunctionTemplate> tpl = FunctionTemplate::New(New);
      tpl->SetClassName(String::NewSymbol("MyObject"));
      tpl->InstanceTemplate()->SetInternalFieldCount(1);
      // Prototype
      tpl->PrototypeTemplate()->Set(String::NewSymbol("plusOne"),
          FunctionTemplate::New(PlusOne)->GetFunction());
      constructor = Persistent<Function>::New(tpl->GetFunction());
    }
    
    Handle<Value> MyObject::New(const Arguments& args) {
      HandleScope scope;
    
      if (args.IsConstructCall()) {
        // Invoked as constructor: `new MyObject(...)`
        double value = args[0]->IsUndefined() ? 0 : args[0]->NumberValue();
        MyObject* obj = new MyObject(value);
        obj->Wrap(args.This());
        return args.This();
      } else {
        // Invoked as plain function `MyObject(...)`, turn into construct call.
        const int argc = 1;
        Local<Value> argv[argc] = { args[0] };
        return scope.Close(constructor->NewInstance(argc, argv));
      }
    }
    
    Handle<Value> MyObject::NewInstance(const Arguments& args) {
      HandleScope scope;
    
      const unsigned argc = 1;
      Handle<Value> argv[argc] = { args[0] };
      Local<Object> instance = constructor->NewInstance(argc, argv);
    
      return scope.Close(instance);
    }
    
    Handle<Value> MyObject::PlusOne(const Arguments& args) {
      HandleScope scope;
    
      MyObject* obj = ObjectWrap::Unwrap<MyObject>(args.This());
      obj->value_ += 1;
    
      return scope.Close(Number::New(obj->value_));
    }

    Test it with:

    var createObject = require('./build/Release/addon');
    
    var obj = createObject(10);
    console.log( obj.plusOne() ); // 11
    console.log( obj.plusOne() ); // 12
    console.log( obj.plusOne() ); // 13
    
    var obj2 = createObject(20);
    console.log( obj2.plusOne() ); // 21
    console.log( obj2.plusOne() ); // 22
    console.log( obj2.plusOne() ); // 23

    Passing wrapped objects around#

    In addition to wrapping and returning C++ objects, you can pass them around by unwrapping them with Node's node::ObjectWrap::Unwrap helper function. In the following addon.cc we introduce a function add() that can take on two MyObject objects:

    #define BUILDING_NODE_EXTENSION
    #include <node.h>
    #include "myobject.h"
    
    using namespace v8;
    
    Handle<Value> CreateObject(const Arguments& args) {
      HandleScope scope;
      return scope.Close(MyObject::NewInstance(args));
    }
    
    Handle<Value> Add(const Arguments& args) {
      HandleScope scope;
    
      MyObject* obj1 = node::ObjectWrap::Unwrap<MyObject>(
          args[0]->ToObject());
      MyObject* obj2 = node::ObjectWrap::Unwrap<MyObject>(
          args[1]->ToObject());
    
      double sum = obj1->Value() + obj2->Value();
      return scope.Close(Number::New(sum));
    }
    
    void InitAll(Handle<Object> exports) {
      MyObject::Init();
    
      exports->Set(String::NewSymbol("createObject"),
          FunctionTemplate::New(CreateObject)->GetFunction());
    
      exports->Set(String::NewSymbol("add"),
          FunctionTemplate::New(Add)->GetFunction());
    }
    
    NODE_MODULE(addon, InitAll)

    To make things interesting we introduce a public method in myobject.h so we can probe private values after unwrapping the object:

    #define BUILDING_NODE_EXTENSION
    #ifndef MYOBJECT_H
    #define MYOBJECT_H
    
    #include <node.h>
    
    class MyObject : public node::ObjectWrap {
     public:
      static void Init();
      static v8::Handle<v8::Value> NewInstance(const v8::Arguments& args);
      double Value() const { return value_; }
    
     private:
      explicit MyObject(double value = 0);
      ~MyObject();
    
      static v8::Handle<v8::Value> New(const v8::Arguments& args);
      static v8::Persistent<v8::Function> constructor;
      double value_;
    };
    
    #endif

    The implementation of myobject.cc is similar as before:

    #define BUILDING_NODE_EXTENSION
    #include <node.h>
    #include "myobject.h"
    
    using namespace v8;
    
    Persistent<Function> MyObject::constructor;
    
    MyObject::MyObject(double value) : value_(value) {
    }
    
    MyObject::~MyObject() {
    }
    
    void MyObject::Init() {
      // Prepare constructor template
      Local<FunctionTemplate> tpl = FunctionTemplate::New(New);
      tpl->SetClassName(String::NewSymbol("MyObject"));
      tpl->InstanceTemplate()->SetInternalFieldCount(1);
      constructor = Persistent<Function>::New(tpl->GetFunction());
    }
    
    Handle<Value> MyObject::New(const Arguments& args) {
      HandleScope scope;
    
      if (args.IsConstructCall()) {
        // Invoked as constructor: `new MyObject(...)`
        double value = args[0]->IsUndefined() ? 0 : args[0]->NumberValue();
        MyObject* obj = new MyObject(value);
        obj->Wrap(args.This());
        return args.This();
      } else {
        // Invoked as plain function `MyObject(...)`, turn into construct call.
        const int argc = 1;
        Local<Value> argv[argc] = { args[0] };
        return scope.Close(constructor->NewInstance(argc, argv));
      }
    }
    
    Handle<Value> MyObject::NewInstance(const Arguments& args) {
      HandleScope scope;
    
      const unsigned argc = 1;
      Handle<Value> argv[argc] = { args[0] };
      Local<Object> instance = constructor->NewInstance(argc, argv);
    
      return scope.Close(instance);
    }

    Test it with:

    var addon = require('./build/Release/addon');
    
    var obj1 = addon.createObject(10);
    var obj2 = addon.createObject(20);
    var result = addon.add(obj1, obj2);
    
    console.log(result); // 30

    process#

    The process object is a global object and can be accessed from anywhere. It is an instance of EventEmitter.

    Event: 'exit'#

    Emitted when the process is about to exit. There is no way to prevent the exiting of the event loop at this point, and once all exit listeners have finished running the process will exit. Therefore you must only perform synchronous operations in this handler. This is a good hook to perform checks on the module's state (like for unit tests). The callback takes one argument, the code the process is exiting with.

    Example of listening for exit:

    process.on('exit', function(code) {
      // do *NOT* do this
      setTimeout(function() {
        console.log('This will not run');
      }, 0);
      console.log('About to exit with code:', code);
    });

    Event: 'uncaughtException'#

    Emitted when an exception bubbles all the way back to the event loop. If a listener is added for this exception, the default action (which is to print a stack trace and exit) will not occur.

    Example of listening for uncaughtException:

    process.on('uncaughtException', function(err) {
      console.log('Caught exception: ' + err);
    });
    
    setTimeout(function() {
      console.log('This will still run.');
    }, 500);
    
    // Intentionally cause an exception, but don't catch it.
    nonexistentFunc();
    console.log('This will not run.');

    Note that uncaughtException is a very crude mechanism for exception handling and may be removed in the future.

    Don't use it, use domains instead. If you do use it, restart your application after every unhandled exception!

    Do not use it as the node.js equivalent of On Error Resume Next. An unhandled exception means your application - and by extension node.js itself - is in an undefined state. Blindly resuming means anything could happen.

    Think of resuming as pulling the power cord when you are upgrading your system. Nine out of ten times nothing happens - but the 10th time, your system is bust.

    You have been warned.

    Signal Events#

    Emitted when the processes receives a signal. See sigaction(2) for a list of standard POSIX signal names such as SIGINT, SIGHUP, etc.

    Example of listening for SIGINT:

    // Start reading from stdin so we don't exit.
    process.stdin.resume();
    
    process.on('SIGINT', function() {
      console.log('Got SIGINT.  Press Control-D to exit.');
    });

    An easy way to send the SIGINT signal is with Control-C in most terminal programs.

    Note:

    • SIGUSR1 is reserved by node.js to start the debugger. It's possible to install a listener but that won't stop the debugger from starting.
    • SIGTERM and SIGINT have default handlers on non-Windows platforms that resets the terminal mode before exiting with code 128 + signal number. If one of these signals has a listener installed, its default behaviour will be removed (node will no longer exit).
    • SIGPIPE is ignored by default, it can have a listener installed.
    • SIGHUP is generated on Windows when the console window is closed, and on other platforms under various similar conditions, see signal(7). It can have a listener installed, however node will be unconditionally terminated by Windows about 10 seconds later. On non-Windows platforms, the default behaviour of SIGHUP is to terminate node, but once a listener has been installed its default behaviour will be removed.
    • SIGTERM is not supported on Windows, it can be listened on.
    • SIGINT from the terminal is supported on all platforms, and can usually be generated with CTRL+C (though this may be configurable). It is not generated when terminal raw mode is enabled.
    • SIGBREAK is delivered on Windows when CTRL+BREAK is pressed, on non-Windows platforms it can be listened on, but there is no way to send or generate it.
    • SIGWINCH is delivered when the console has been resized. On Windows, this will only happen on write to the console when the cursor is being moved, or when a readable tty is used in raw mode.
    • SIGKILL cannot have a listener installed, it will unconditionally terminate node on all platforms.
    • SIGSTOP cannot have a listener installed.

    Note that Windows does not support sending Signals, but node offers some emulation with process.kill(), and child_process.kill(): - Sending signal 0 can be used to search for the existence of a process - Sending SIGINT, SIGTERM, and SIGKILL cause the unconditional exit of the target process.

    process.stdout#

    A Writable Stream to stdout.

    Example: the definition of console.log

    console.log = function(d) {
      process.stdout.write(d + '\n');
    };

    process.stderr and process.stdout are unlike other streams in Node in that writes to them are usually blocking. They are blocking in the case that they refer to regular files or TTY file descriptors. In the case they refer to pipes, they are non-blocking like other streams.

    To check if Node is being run in a TTY context, read the isTTY property on process.stderr, process.stdout, or process.stdin:

    $ node -p "Boolean(process.stdin.isTTY)"
    true
    $ echo "foo" | node -p "Boolean(process.stdin.isTTY)"
    false
    
    $ node -p "Boolean(process.stdout.isTTY)"
    true
    $ node -p "Boolean(process.stdout.isTTY)" | cat
    false

    See the tty docs for more information.

    process.stderr#

    A writable stream to stderr.

    process.stderr and process.stdout are unlike other streams in Node in that writes to them are usually blocking. They are blocking in the case that they refer to regular files or TTY file descriptors. In the case they refer to pipes, they are non-blocking like other streams.

    process.stdin#

    A Readable Stream for stdin. The stdin stream is paused by default, so one must call process.stdin.resume() to read from it.

    Example of opening standard input and listening for both events:

    process.stdin.resume();
    process.stdin.setEncoding('utf8');
    
    process.stdin.on('data', function(chunk) {
      process.stdout.write('data: ' + chunk);
    });
    
    process.stdin.on('end', function() {
      process.stdout.write('end');
    });

    process.argv#

    An array containing the command line arguments. The first element will be 'node', the second element will be the name of the JavaScript file. The next elements will be any additional command line arguments.

    // print process.argv
    process.argv.forEach(function(val, index, array) {
      console.log(index + ': ' + val);
    });

    This will generate:

    $ node process-2.js one two=three four
    0: node
    1: /Users/mjr/work/node/process-2.js
    2: one
    3: two=three
    4: four

    process.execPath#

    This is the absolute pathname of the executable that started the process.

    Example:

    /usr/local/bin/node

    process.execArgv#

    This is the set of node-specific command line options from the executable that started the process. These options do not show up in process.argv, and do not include the node executable, the name of the script, or any options following the script name. These options are useful in order to spawn child processes with the same execution environment as the parent.

    Example:

    $ node --harmony script.js --version

    results in process.execArgv:

    ['--harmony']

    and process.argv:

    ['/usr/local/bin/node', 'script.js', '--version']

    process.abort()#

    This causes node to emit an abort. This will cause node to exit and generate a core file.

    process.chdir(directory)#

    Changes the current working directory of the process or throws an exception if that fails.

    console.log('Starting directory: ' + process.cwd());
    try {
      process.chdir('/tmp');
      console.log('New directory: ' + process.cwd());
    }
    catch (err) {
      console.log('chdir: ' + err);
    }

    process.cwd()#

    Returns the current working directory of the process.

    console.log('Current directory: ' + process.cwd());

    process.env#

    An object containing the user environment. See environ(7).

    process.exit([code])#

    Ends the process with the specified code. If omitted, exit uses the 'success' code 0.

    To exit with a 'failure' code:

    process.exit(1);

    The shell that executed node should see the exit code as 1.

    process.getgid()#

    Note: this function is only available on POSIX platforms (i.e. not Windows)

    Gets the group identity of the process. (See getgid(2).) This is the numerical group id, not the group name.

    if (process.getgid) {
      console.log('Current gid: ' + process.getgid());
    }

    process.setgid(id)#

    Note: this function is only available on POSIX platforms (i.e. not Windows)

    Sets the group identity of the process. (See setgid(2).) This accepts either a numerical ID or a groupname string. If a groupname is specified, this method blocks while resolving it to a numerical ID.

    if (process.getgid && process.setgid) {
      console.log('Current gid: ' + process.getgid());
      try {
        process.setgid(501);
        console.log('New gid: ' + process.getgid());
      }
      catch (err) {
        console.log('Failed to set gid: ' + err);
      }
    }

    process.getuid()#

    Note: this function is only available on POSIX platforms (i.e. not Windows)

    Gets the user identity of the process. (See getuid(2).) This is the numerical userid, not the username.

    if (process.getuid) {
      console.log('Current uid: ' + process.getuid());
    }

    process.setuid(id)#

    Note: this function is only available on POSIX platforms (i.e. not Windows)

    Sets the user identity of the process. (See setuid(2).) This accepts either a numerical ID or a username string. If a username is specified, this method blocks while resolving it to a numerical ID.

    if (process.getuid && process.setuid) {
      console.log('Current uid: ' + process.getuid());
      try {
        process.setuid(501);
        console.log('New uid: ' + process.getuid());
      }
      catch (err) {
        console.log('Failed to set uid: ' + err);
      }
    }

    process.getgroups()#

    Note: this function is only available on POSIX platforms (i.e. not Windows)

    Returns an array with the supplementary group IDs. POSIX leaves it unspecified if the effective group ID is included but node.js ensures it always is.

    process.setgroups(groups)#

    Note: this function is only available on POSIX platforms (i.e. not Windows)

    Sets the supplementary group IDs. This is a privileged operation, meaning you need to be root or have the CAP_SETGID capability.

    The list can contain group IDs, group names or both.

    process.initgroups(user, extra_group)#

    Note: this function is only available on POSIX platforms (i.e. not Windows)

    Reads /etc/group and initializes the group access list, using all groups of which the user is a member. This is a privileged operation, meaning you need to be root or have the CAP_SETGID capability.

    user is a user name or user ID. extra_group is a group name or group ID.

    Some care needs to be taken when dropping privileges. Example:

    console.log(process.getgroups());         // [ 0 ]
    process.initgroups('bnoordhuis', 1000);   // switch user
    console.log(process.getgroups());         // [ 27, 30, 46, 1000, 0 ]
    process.setgid(1000);                     // drop root gid
    console.log(process.getgroups());         // [ 27, 30, 46, 1000 ]

    process.version#

    A compiled-in property that exposes NODE_VERSION.

    console.log('Version: ' + process.version);

    process.versions#

    A property exposing version strings of node and its dependencies.

    console.log(process.versions);

    Will print something like:

    { http_parser: '1.0',
      node: '0.10.4',
      v8: '3.14.5.8',
      ares: '1.9.0-DEV',
      uv: '0.10.3',
      zlib: '1.2.3',
      modules: '11',
      openssl: '1.0.1e' }

    process.config#

    An Object containing the JavaScript representation of the configure options that were used to compile the current node executable. This is the same as the "config.gypi" file that was produced when running the ./configure script.

    An example of the possible output looks like:

    { target_defaults:
       { cflags: [],
         default_configuration: 'Release',
         defines: [],
         include_dirs: [],
         libraries: [] },
      variables:
       { host_arch: 'x64',
         node_install_npm: 'true',
         node_prefix: '',
         node_shared_cares: 'false',
         node_shared_http_parser: 'false',
         node_shared_libuv: 'false',
         node_shared_v8: 'false',
         node_shared_zlib: 'false',
         node_use_dtrace: 'false',
         node_use_openssl: 'true',
         node_shared_openssl: 'false',
         strict_aliasing: 'true',
         target_arch: 'x64',
         v8_use_snapshot: 'true' } }

    process.kill(pid, [signal])#

    Send a signal to a process. pid is the process id and signal is the string describing the signal to send. Signal names are strings like 'SIGINT' or 'SIGHUP'. If omitted, the signal will be 'SIGTERM'. See Signal Events and kill(2) for more information.

    Will throw an error if target does not exist, and as a special case, a signal of 0 can be used to test for the existence of a process.

    Note that just because the name of this function is process.kill, it is really just a signal sender, like the kill system call. The signal sent may do something other than kill the target process.

    Example of sending a signal to yourself:

    process.on('SIGHUP', function() {
      console.log('Got SIGHUP signal.');
    });
    
    setTimeout(function() {
      console.log('Exiting.');
      process.exit(0);
    }, 100);
    
    process.kill(process.pid, 'SIGHUP');

    Note: When SIGUSR1 is received by Node.js it starts the debugger, see Signal Events.

    process.pid#

    The PID of the process.

    console.log('This process is pid ' + process.pid);

    process.title#

    Getter/setter to set what is displayed in 'ps'.

    When used as a setter, the maximum length is platform-specific and probably short.

    On Linux and OS X, it's limited to the size of the binary name plus the length of the command line arguments because it overwrites the argv memory.

    v0.8 allowed for longer process title strings by also overwriting the environ memory but that was potentially insecure/confusing in some (rather obscure) cases.

    process.arch#

    What processor architecture you're running on: 'arm', 'ia32', or 'x64'.

    console.log('This processor architecture is ' + process.arch);

    process.platform#

    What platform you're running on: 'darwin', 'freebsd', 'linux', 'sunos' or 'win32'

    console.log('This platform is ' + process.platform);

    process.memoryUsage()#

    Returns an object describing the memory usage of the Node process measured in bytes.

    var util = require('util');
    
    console.log(util.inspect(process.memoryUsage()));

    This will generate:

    { rss: 4935680,
      heapTotal: 1826816,
      heapUsed: 650472 }

    heapTotal and heapUsed refer to V8's memory usage.

    process.nextTick(callback)#

    On the next loop around the event loop call this callback. This is not a simple alias to setTimeout(fn, 0), it's much more efficient. It typically runs before any other I/O events fire, but there are some exceptions. See process.maxTickDepth below.

    process.nextTick(function() {
      console.log('nextTick callback');
    });

    This is important in developing APIs where you want to give the user the chance to assign event handlers after an object has been constructed, but before any I/O has occurred.

    function MyThing(options) {
      this.setupOptions(options);
    
      process.nextTick(function() {
        this.startDoingStuff();
      }.bind(this));
    }
    
    var thing = new MyThing();
    thing.getReadyForStuff();
    
    // thing.startDoingStuff() gets called now, not before.

    It is very important for APIs to be either 100% synchronous or 100% asynchronous. Consider this example:

    // WARNING!  DO NOT USE!  BAD UNSAFE HAZARD!
    function maybeSync(arg, cb) {
      if (arg) {
        cb();
        return;
      }
    
      fs.stat('file', cb);
    }

    This API is hazardous. If you do this:

    maybeSync(true, function() {
      foo();
    });
    bar();

    then it's not clear whether foo() or bar() will be called first.

    This approach is much better:

    function definitelyAsync(arg, cb) {
      if (arg) {
        process.nextTick(cb);
        return;
      }
    
      fs.stat('file', cb);
    }

    process.maxTickDepth#

    • Number Default = 1000

    Callbacks passed to process.nextTick will usually be called at the end of the current flow of execution, and are thus approximately as fast as calling a function synchronously. Left unchecked, this would starve the event loop, preventing any I/O from occurring.

    Consider this code:

    process.nextTick(function foo() {
      process.nextTick(foo);
    });

    In order to avoid the situation where Node is blocked by an infinite loop of recursive series of nextTick calls, it defers to allow some I/O to be done every so often.

    The process.maxTickDepth value is the maximum depth of nextTick-calling nextTick-callbacks that will be evaluated before allowing other forms of I/O to occur.

    process.umask([mask])#

    Sets or reads the process's file mode creation mask. Child processes inherit the mask from the parent process. Returns the old mask if mask argument is given, otherwise returns the current mask.

    var oldmask, newmask = 0644;
    
    oldmask = process.umask(newmask);
    console.log('Changed umask from: ' + oldmask.toString(8) +
                ' to ' + newmask.toString(8));

    process.uptime()#

    Number of seconds Node has been running.

    process.hrtime()#

    Returns the current high-resolution real time in a [seconds, nanoseconds] tuple Array. It is relative to an arbitrary time in the past. It is not related to the time of day and therefore not subject to clock drift. The primary use is for measuring performance between intervals.

    You may pass in the result of a previous call to process.hrtime() to get a diff reading, useful for benchmarks and measuring intervals:

    var time = process.hrtime();
    // [ 1800216, 25 ]
    
    setTimeout(function() {
      var diff = process.hrtime(time);
      // [ 1, 552 ]
    
      console.log('benchmark took %d nanoseconds', diff[0] * 1e9 + diff[1]);
      // benchmark took 1000000527 nanoseconds
    }, 1000);

    util#

    Stability: 4 - API Frozen

    These functions are in the module 'util'. Use require('util') to access them.

    util.format(format, [...])#

    Returns a formatted string using the first argument as a printf-like format.

    The first argument is a string that contains zero or more placeholders. Each placeholder is replaced with the converted value from its corresponding argument. Supported placeholders are:

    • %s - String.
    • %d - Number (both integer and float).
    • %j - JSON.
    • % - single percent sign ('%'). This does not consume an argument.

    If the placeholder does not have a corresponding argument, the placeholder is not replaced.

    util.format('%s:%s', 'foo'); // 'foo:%s'

    If there are more arguments than placeholders, the extra arguments are converted to strings with util.inspect() and these strings are concatenated, delimited by a space.

    util.format('%s:%s', 'foo', 'bar', 'baz'); // 'foo:bar baz'

    If the first argument is not a format string then util.format() returns a string that is the concatenation of all its arguments separated by spaces. Each argument is converted to a string with util.inspect().

    util.format(1, 2, 3); // '1 2 3'

    util.debug(string)#

    A synchronous output function. Will block the process and output string immediately to stderr.

    require('util').debug('message on stderr');

    util.error([...])#

    Same as util.debug() except this will output all arguments immediately to stderr.

    util.puts([...])#

    A synchronous output function. Will block the process and output all arguments to stdout with newlines after each argument.

    util.print([...])#

    A synchronous output function. Will block the process, cast each argument to a string then output to stdout. Does not place newlines after each argument.

    util.log(string)#

    Output with timestamp on stdout.

    require('util').log('Timestamped message.');

    util.inspect(object, [options])#

    Return a string representation of object, which is useful for debugging.

    An optional options object may be passed that alters certain aspects of the formatted string:

    • showHidden - if true then the object's non-enumerable properties will be shown too. Defaults to false.

    • depth - tells inspect how many times to recurse while formatting the object. This is useful for inspecting large complicated objects. Defaults to 2. To make it recurse indefinitely pass null.

    • colors - if true, then the output will be styled with ANSI color codes. Defaults to false. Colors are customizable, see below.

    • customInspect - if false, then custom inspect() functions defined on the objects being inspected won't be called. Defaults to true.

    Example of inspecting all properties of the util object:

    var util = require('util');
    
    console.log(util.inspect(util, { showHidden: true, depth: null }));

    Customizing util.inspect colors#

    Color output (if enabled) of util.inspect is customizable globally via util.inspect.styles and util.inspect.colors objects.

    util.inspect.styles is a map assigning each style a color from util.inspect.colors. Highlighted styles and their default values are: number (yellow) boolean (yellow) string (green) date (magenta) regexp (red) null (bold) undefined (grey) special - only function at this time (cyan) * name (intentionally no styling)

    Predefined color codes are: white, grey, black, blue, cyan, green, magenta, red and yellow. There are also bold, italic, underline and inverse codes.

    Objects also may define their own inspect(depth) function which util.inspect() will invoke and use the result of when inspecting the object:

    var util = require('util');
    
    var obj = { name: 'nate' };
    obj.inspect = function(depth) {
      return '{' + this.name + '}';
    };
    
    util.inspect(obj);
      // "{nate}"

    util.isArray(object)#

    Returns true if the given "object" is an Array. false otherwise.

    var util = require('util');
    
    util.isArray([])
      // true
    util.isArray(new Array)
      // true
    util.isArray({})
      // false

    util.isRegExp(object)#

    Returns true if the given "object" is a RegExp. false otherwise.

    var util = require('util');
    
    util.isRegExp(/some regexp/)
      // true
    util.isRegExp(new RegExp('another regexp'))
      // true
    util.isRegExp({})
      // false

    util.isDate(object)#

    Returns true if the given "object" is a Date. false otherwise.

    var util = require('util');
    
    util.isDate(new Date())
      // true
    util.isDate(Date())
      // false (without 'new' returns a String)
    util.isDate({})
      // false

    util.isError(object)#

    Returns true if the given "object" is an Error. false otherwise.

    var util = require('util');
    
    util.isError(new Error())
      // true
    util.isError(new TypeError())
      // true
    util.isError({ name: 'Error', message: 'an error occurred' })
      // false

    util.pump(readableStream, writableStream, [callback])#

    Stability: 0 - Deprecated: Use readableStream.pipe(writableStream)

    Read the data from readableStream and send it to the writableStream. When writableStream.write(data) returns false readableStream will be paused until the drain event occurs on the writableStream. callback gets an error as its only argument and is called when writableStream is closed or when an error occurs.

    util.inherits(constructor, superConstructor)#

    Inherit the prototype methods from one constructor into another. The prototype of constructor will be set to a new object created from superConstructor.

    As an additional convenience, superConstructor will be accessible through the constructor.super_ property.

    var util = require("util");
    var events = require("events");
    
    function MyStream() {
        events.EventEmitter.call(this);
    }
    
    util.inherits(MyStream, events.EventEmitter);
    
    MyStream.prototype.write = function(data) {
        this.emit("data", data);
    }
    
    var stream = new MyStream();
    
    console.log(stream instanceof events.EventEmitter); // true
    console.log(MyStream.super_ === events.EventEmitter); // true
    
    stream.on("data", function(data) {
        console.log('Received data: "' + data + '"');
    })
    stream.write("It works!"); // Received data: "It works!"

    Events#

    Stability: 4 - API Frozen

    Many objects in Node emit events: a net.Server emits an event each time a peer connects to it, a fs.readStream emits an event when the file is opened. All objects which emit events are instances of events.EventEmitter. You can access this module by doing: require("events");

    Typically, event names are represented by a camel-cased string, however, there aren't any strict restrictions on that, as any string will be accepted.

    Functions can then be attached to objects, to be executed when an event is emitted. These functions are called listeners. Inside a listener function, this refers to the EventEmitter that the listener was attached to.

    Class: events.EventEmitter#

    To access the EventEmitter class, require('events').EventEmitter.

    When an EventEmitter instance experiences an error, the typical action is to emit an 'error' event. Error events are treated as a special case in node. If there is no listener for it, then the default action is to print a stack trace and exit the program.

    All EventEmitters emit the event 'newListener' when new listeners are added and 'removeListener' when a listener is removed.

    emitter.addListener(event, listener)#

    emitter.on(event, listener)#

    Adds a listener to the end of the listeners array for the specified event.

    server.on('connection', function (stream) {
      console.log('someone connected!');
    });

    Returns emitter, so calls can be chained.

    emitter.once(event, listener)#

    Adds a one time listener for the event. This listener is invoked only the next time the event is fired, after which it is removed.

    server.once('connection', function (stream) {
      console.log('Ah, we have our first user!');
    });

    Returns emitter, so calls can be chained.

    emitter.removeListener(event, listener)#

    Remove a listener from the listener array for the specified event. Caution: changes array indices in the listener array behind the listener.

    var callback = function(stream) {
      console.log('someone connected!');
    };
    server.on('connection', callback);
    // ...
    server.removeListener('connection', callback);

    Returns emitter, so calls can be chained.

    emitter.removeAllListeners([event])#

    Removes all listeners, or those of the specified event.

    Returns emitter, so calls can be chained.

    emitter.setMaxListeners(n)#

    By default EventEmitters will print a warning if more than 10 listeners are added for a particular event. This is a useful default which helps finding memory leaks. Obviously not all Emitters should be limited to 10. This function allows that to be increased. Set to zero for unlimited.

    emitter.listeners(event)#

    Returns an array of listeners for the specified event.

    server.on('connection', function (stream) {
      console.log('someone connected!');
    });
    console.log(util.inspect(server.listeners('connection'))); // [ [Function] ]

    emitter.emit(event, [arg1], [arg2], [...])#

    Execute each of the listeners in order with the supplied arguments.

    Returns true if event had listeners, false otherwise.

    Class Method: EventEmitter.listenerCount(emitter, event)#

    Return the number of listeners for a given event.

    Event: 'newListener'#

    • event String The event name
    • listener Function The event handler function

    This event is emitted any time someone adds a new listener. It is unspecified if listener is in the list returned by emitter.listeners(event).

    Event: 'removeListener'#

    • event String The event name
    • listener Function The event handler function

    This event is emitted any time someone removes a listener. It is unspecified if listener is in the list returned by emitter.listeners(event).

    Domain#

    Stability: 2 - Unstable

    Domains provide a way to handle multiple different IO operations as a single group. If any of the event emitters or callbacks registered to a domain emit an error event, or throw an error, then the domain object will be notified, rather than losing the context of the error in the process.on('uncaughtException') handler, or causing the program to exit immediately with an error code.

    Warning: Don't Ignore Errors!#

    Domain error handlers are not a substitute for closing down your process when an error occurs.

    By the very nature of how throw works in JavaScript, there is almost never any way to safely "pick up where you left off", without leaking references, or creating some other sort of undefined brittle state.

    The safest way to respond to a thrown error is to shut down the process. Of course, in a normal web server, you might have many connections open, and it is not reasonable to abruptly shut those down because an error was triggered by someone else.

    The better approach is send an error response to the request that triggered the error, while letting the others finish in their normal time, and stop listening for new requests in that worker.

    In this way, domain usage goes hand-in-hand with the cluster module, since the master process can fork a new worker when a worker encounters an error. For node programs that scale to multiple machines, the terminating proxy or service registry can take note of the failure, and react accordingly.

    For example, this is not a good idea:

    // XXX WARNING!  BAD IDEA!
    
    var d = require('domain').create();
    d.on('error', function(er) {
      // The error won't crash the process, but what it does is worse!
      // Though we've prevented abrupt process restarting, we are leaking
      // resources like crazy if this ever happens.
      // This is no better than process.on('uncaughtException')!
      console.log('error, but oh well', er.message);
    });
    d.run(function() {
      require('http').createServer(function(req, res) {
        handleRequest(req, res);
      }).listen(PORT);
    });

    By using the context of a domain, and the resilience of separating our program into multiple worker processes, we can react more appropriately, and handle errors with much greater safety.

    // Much better!
    
    var cluster = require('cluster');
    var PORT = +process.env.PORT || 1337;
    
    if (cluster.isMaster) {
      // In real life, you'd probably use more than just 2 workers,
      // and perhaps not put the master and worker in the same file.
      //
      // You can also of course get a bit fancier about logging, and
      // implement whatever custom logic you need to prevent DoS
      // attacks and other bad behavior.
      //
      // See the options in the cluster documentation.
      //
      // The important thing is that the master does very little,
      // increasing our resilience to unexpected errors.
    
      cluster.fork();
      cluster.fork();
    
      cluster.on('disconnect', function(worker) {
        console.error('disconnect!');
        cluster.fork();
      });
    
    } else {
      // the worker
      //
      // This is where we put our bugs!
    
      var domain = require('domain');
    
      // See the cluster documentation for more details about using
      // worker processes to serve requests.  How it works, caveats, etc.
    
      var server = require('http').createServer(function(req, res) {
        var d = domain.create();
        d.on('error', function(er) {
          console.error('error', er.stack);
    
          // Note: we're in dangerous territory!
          // By definition, something unexpected occurred,
          // which we probably didn't want.
          // Anything can happen now!  Be very careful!
    
          try {
            // make sure we close down within 30 seconds
            var killtimer = setTimeout(function() {
              process.exit(1);
            }, 30000);
            // But don't keep the process open just for that!
            killtimer.unref();
    
            // stop taking new requests.
            server.close();
    
            // Let the master know we're dead.  This will trigger a
            // 'disconnect' in the cluster master, and then it will fork
            // a new worker.
            cluster.worker.disconnect();
    
            // try to send an error to the request that triggered the problem
            res.statusCode = 500;
            res.setHeader('content-type', 'text/plain');
            res.end('Oops, there was a problem!\n');
          } catch (er2) {
            // oh well, not much we can do at this point.
            console.error('Error sending 500!', er2.stack);
          }
        });
    
        // Because req and res were created before this domain existed,
        // we need to explicitly add them.
        // See the explanation of implicit vs explicit binding below.
        d.add(req);
        d.add(res);
    
        // Now run the handler function in the domain.
        d.run(function() {
          handleRequest(req, res);
        });
      });
      server.listen(PORT);
    }
    
    // This part isn't important.  Just an example routing thing.
    // You'd put your fancy application logic here.
    function handleRequest(req, res) {
      switch(req.url) {
        case '/error':
          // We do some async stuff, and then...
          setTimeout(function() {
            // Whoops!
            flerb.bark();
          });
          break;
        default:
          res.end('ok');
      }
    }

    Additions to Error objects#

    Any time an Error object is routed through a domain, a few extra fields are added to it.

    • error.domain The domain that first handled the error.
    • error.domainEmitter The event emitter that emitted an 'error' event with the error object.
    • error.domainBound The callback function which was bound to the domain, and passed an error as its first argument.
    • error.domainThrown A boolean indicating whether the error was thrown, emitted, or passed to a bound callback function.

    Implicit Binding#

    If domains are in use, then all new EventEmitter objects (including Stream objects, requests, responses, etc.) will be implicitly bound to the active domain at the time of their creation.

    Additionally, callbacks passed to lowlevel event loop requests (such as to fs.open, or other callback-taking methods) will automatically be bound to the active domain. If they throw, then the domain will catch the error.

    In order to prevent excessive memory usage, Domain objects themselves are not implicitly added as children of the active domain. If they were, then it would be too easy to prevent request and response objects from being properly garbage collected.

    If you want to nest Domain objects as children of a parent Domain, then you must explicitly add them.

    Implicit binding routes thrown errors and 'error' events to the Domain's error event, but does not register the EventEmitter on the Domain, so domain.dispose() will not shut down the EventEmitter. Implicit binding only takes care of thrown errors and 'error' events.

    Explicit Binding#

    Sometimes, the domain in use is not the one that ought to be used for a specific event emitter. Or, the event emitter could have been created in the context of one domain, but ought to instead be bound to some other domain.

    For example, there could be one domain in use for an HTTP server, but perhaps we would like to have a separate domain to use for each request.

    That is possible via explicit binding.

    For example:

    // create a top-level domain for the server
    var serverDomain = domain.create();
    
    serverDomain.run(function() {
      // server is created in the scope of serverDomain
      http.createServer(function(req, res) {
        // req and res are also created in the scope of serverDomain
        // however, we'd prefer to have a separate domain for each request.
        // create it first thing, and add req and res to it.
        var reqd = domain.create();
        reqd.add(req);
        reqd.add(res);
        reqd.on('error', function(er) {
          console.error('Error', er, req.url);
          try {
            res.writeHead(500);
            res.end('Error occurred, sorry.');
          } catch (er) {
            console.error('Error sending 500', er, req.url);
          }
        });
      }).listen(1337);
    });

    domain.create()#

    • return: Domain

    Returns a new Domain object.

    Class: Domain#

    The Domain class encapsulates the functionality of routing errors and uncaught exceptions to the active Domain object.

    Domain is a child class of EventEmitter. To handle the errors that it catches, listen to its error event.

    domain.run(fn)#

    • fn Function

    Run the supplied function in the context of the domain, implicitly binding all event emitters, timers, and lowlevel requests that are created in that context.

    This is the most basic way to use a domain.

    Example:

    var d = domain.create();
    d.on('error', function(er) {
      console.error('Caught error!', er);
    });
    d.run(function() {
      process.nextTick(function() {
        setTimeout(function() { // simulating some various async stuff
          fs.open('non-existent file', 'r', function(er, fd) {
            if (er) throw er;
            // proceed...
          });
        }, 100);
      });
    });

    In this example, the d.on('error') handler will be triggered, rather than crashing the program.

    domain.members#

    • Array

    An array of timers and event emitters that have been explicitly added to the domain.

    domain.add(emitter)#

    • emitter EventEmitter | Timer emitter or timer to be added to the domain

    Explicitly adds an emitter to the domain. If any event handlers called by the emitter throw an error, or if the emitter emits an error event, it will be routed to the domain's error event, just like with implicit binding.

    This also works with timers that are returned from setInterval and setTimeout. If their callback function throws, it will be caught by the domain 'error' handler.

    If the Timer or EventEmitter was already bound to a domain, it is removed from that one, and bound to this one instead.

    domain.remove(emitter)#

    • emitter EventEmitter | Timer emitter or timer to be removed from the domain

    The opposite of domain.add(emitter). Removes domain handling from the specified emitter.

    domain.bind(callback)#

    • callback Function The callback function
    • return: Function The bound function

    The returned function will be a wrapper around the supplied callback function. When the returned function is called, any errors that are thrown will be routed to the domain's error event.

    Example#

    var d = domain.create();
    
    function readSomeFile(filename, cb) {
      fs.readFile(filename, 'utf8', d.bind(function(er, data) {
        // if this throws, it will also be passed to the domain
        return cb(er, data ? JSON.parse(data) : null);
      }));
    }
    
    d.on('error', function(er) {
      // an error occurred somewhere.
      // if we throw it now, it will crash the program
      // with the normal line number and stack message.
    });

    domain.intercept(callback)#

    • callback Function The callback function
    • return: Function The intercepted function

    This method is almost identical to domain.bind(callback). However, in addition to catching thrown errors, it will also intercept Error objects sent as the first argument to the function.

    In this way, the common if (er) return callback(er); pattern can be replaced with a single error handler in a single place.

    Example#

    var d = domain.create();
    
    function readSomeFile(filename, cb) {
      fs.readFile(filename, 'utf8', d.intercept(function(data) {
        // note, the first argument is never passed to the
        // callback since it is assumed to be the 'Error' argument
        // and thus intercepted by the domain.
    
        // if this throws, it will also be passed to the domain
        // so the error-handling logic can be moved to the 'error'
        // event on the domain instead of being repeated throughout
        // the program.
        return cb(null, JSON.parse(data));
      }));
    }
    
    d.on('error', function(er) {
      // an error occurred somewhere.
      // if we throw it now, it will crash the program
      // with the normal line number and stack message.
    });

    domain.enter()#

    The enter method is plumbing used by the run, bind, and intercept methods to set the active domain. It sets domain.active and process.domain to the domain, and implicitly pushes the domain onto the domain stack managed by the domain module (see domain.exit() for details on the domain stack). The call to enter delimits the beginning of a chain of asynchronous calls and I/O operations bound to a domain.

    Calling enter changes only the active domain, and does not alter the domain itself. Enter and exit can be called an arbitrary number of times on a single domain.

    If the domain on which enter is called has been disposed, enter will return without setting the domain.

    domain.exit()#

    The exit method exits the current domain, popping it off the domain stack. Any time execution is going to switch to the context of a different chain of asynchronous calls, it's important to ensure that the current domain is exited. The call to exit delimits either the end of or an interruption to the chain of asynchronous calls and I/O operations bound to a domain.

    If there are multiple, nested domains bound to the current execution context, exit will exit any domains nested within this domain.

    Calling exit changes only the active domain, and does not alter the domain itself. Enter and exit can be called an arbitrary number of times on a single domain.

    If the domain on which exit is called has been disposed, exit will return without exiting the domain.

    domain.dispose()#

    The dispose method destroys a domain, and makes a best effort attempt to clean up any and all IO that is associated with the domain. Streams are aborted, ended, closed, and/or destroyed. Timers are cleared. Explicitly bound callbacks are no longer called. Any error events that are raised as a result of this are ignored.

    The intention of calling dispose is generally to prevent cascading errors when a critical part of the Domain context is found to be in an error state.

    Once the domain is disposed the dispose event will emit.

    Note that IO might still be performed. However, to the highest degree possible, once a domain is disposed, further errors from the emitters in that set will be ignored. So, even if some remaining actions are still in flight, Node.js will not communicate further about them.

    Buffer#

    Stability: 3 - Stable

    Pure JavaScript is Unicode friendly but not nice to binary data. When dealing with TCP streams or the file system, it's necessary to handle octet streams. Node has several strategies for manipulating, creating, and consuming octet streams.

    Raw data is stored in instances of the Buffer class. A Buffer is similar to an array of integers but corresponds to a raw memory allocation outside the V8 heap. A Buffer cannot be resized.

    The Buffer class is a global, making it very rare that one would need to ever require('buffer').

    Converting between Buffers and JavaScript string objects requires an explicit encoding method. Here are the different string encodings.

    • 'ascii' - for 7 bit ASCII data only. This encoding method is very fast, and will strip the high bit if set.

      Note that when converting from string to buffer, this encoding converts a null character ('\0' or '\u0000') into 0x20 (character code of a space). If you want to convert a null character into 0x00, you should use 'utf8'.

    • 'utf8' - Multibyte encoded Unicode characters. Many web pages and other document formats use UTF-8.

    • 'utf16le' - 2 or 4 bytes, little endian encoded Unicode characters. Surrogate pairs (U+10000 to U+10FFFF) are supported.

    • 'ucs2' - Alias of 'utf16le'.

    • 'base64' - Base64 string encoding.

    • 'binary' - A way of encoding raw binary data into strings by using only the first 8 bits of each character. This encoding method is deprecated and should be avoided in favor of Buffer objects where possible. This encoding will be removed in future versions of Node.

    • 'hex' - Encode each byte as two hexadecimal characters.

    A Buffer object can also be used with typed arrays. The buffer object is cloned to an ArrayBuffer that is used as the backing store for the typed array. The memory of the buffer and the ArrayBuffer is not shared.

    NOTE: Node.js v0.8 simply retained a reference to the buffer in array.buffer instead of cloning it.

    While more efficient, it introduces subtle incompatibilities with the typed arrays specification. ArrayBuffer#slice() makes a copy of the slice while Buffer#slice() creates a view.

    Class: Buffer#

    The Buffer class is a global type for dealing with binary data directly. It can be constructed in a variety of ways.

    new Buffer(size)#

    • size Number

    Allocates a new buffer of size octets.

    new Buffer(array)#

    • array Array

    Allocates a new buffer using an array of octets.

    new Buffer(str, [encoding])#

    • str String - string to encode.
    • encoding String - encoding to use, Optional.

    Allocates a new buffer containing the given str. encoding defaults to 'utf8'.

    Class Method: Buffer.isEncoding(encoding)#

    • encoding String The encoding string to test

    Returns true if the encoding is a valid encoding argument, or false otherwise.

    buf.write(string, [offset], [length], [encoding])#

    • string String - data to be written to buffer
    • offset Number, Optional, Default: 0
    • length Number, Optional, Default: buffer.length - offset
    • encoding String, Optional, Default: 'utf8'

    Writes string to the buffer at offset using the given encoding. offset defaults to 0, encoding defaults to 'utf8'. length is the number of bytes to write. Returns number of octets written. If buffer did not contain enough space to fit the entire string, it will write a partial amount of the string. length defaults to buffer.length - offset. The method will not write partial characters.

    buf = new Buffer(256);
    len = buf.write('\u00bd + \u00bc = \u00be', 0);
    console.log(len + " bytes: " + buf.toString('utf8', 0, len));

    The number of characters written (which may be different than the number of bytes written) is set in Buffer._charsWritten and will be overwritten the next time buf.write() is called.

    buf.toString([encoding], [start], [end])#

    • encoding String, Optional, Default: 'utf8'
    • start Number, Optional, Default: 0
    • end Number, Optional, Default: buffer.length

    Decodes and returns a string from buffer data encoded with encoding (defaults to 'utf8') beginning at start (defaults to 0) and ending at end (defaults to buffer.length).

    See buffer.write() example, above.

    buf.toJSON()#

    Returns a JSON-representation of the Buffer instance, which is identical to the output for JSON Arrays. JSON.stringify implicitly calls this function when stringifying a Buffer instance.

    Example:

    var buf = new Buffer('test');
    var json = JSON.stringify(buf);
    
    console.log(json);
    // '[116,101,115,116]'
    
    var copy = new Buffer(JSON.parse(json));
    
    console.log(copy);
    // <Buffer 74 65 73 74>

    buf[index]#

    Get and set the octet at index. The values refer to individual bytes, so the legal range is between 0x00 and 0xFF hex or 0 and 255.

    Example: copy an ASCII string into a buffer, one byte at a time:

    str = "node.js";
    buf = new Buffer(str.length);
    
    for (var i = 0; i < str.length ; i++) {
      buf[i] = str.charCodeAt(i);
    }
    
    console.log(buf);
    
    // node.js

    Class Method: Buffer.isBuffer(obj)#

    • obj Object
    • Return: Boolean

    Tests if obj is a Buffer.

    Class Method: Buffer.byteLength(string, [encoding])#

    • string String
    • encoding String, Optional, Default: 'utf8'
    • Return: Number

    Gives the actual byte length of a string. encoding defaults to 'utf8'. This is not the same as String.prototype.length since that returns the number of characters in a string.

    Example:

    str = '\u00bd + \u00bc = \u00be';
    
    console.log(str + ": " + str.length + " characters, " +
      Buffer.byteLength(str, 'utf8') + " bytes");
    
    // ½ + ¼ = ¾: 9 characters, 12 bytes

    Class Method: Buffer.concat(list, [totalLength])#

    • list Array List of Buffer objects to concat
    • totalLength Number Total length of the buffers when concatenated

    Returns a buffer which is the result of concatenating all the buffers in the list together.

    If the list has no items, or if the totalLength is 0, then it returns a zero-length buffer.

    If the list has exactly one item, then the first item of the list is returned.

    If the list has more than one item, then a new Buffer is created.

    If totalLength is not provided, it is read from the buffers in the list. However, this adds an additional loop to the function, so it is faster to provide the length explicitly.

    buf.length#

    • Number

    The size of the buffer in bytes. Note that this is not necessarily the size of the contents. length refers to the amount of memory allocated for the buffer object. It does not change when the contents of the buffer are changed.

    buf = new Buffer(1234);
    
    console.log(buf.length);
    buf.write("some string", 0, "ascii");
    console.log(buf.length);
    
    // 1234
    // 1234

    buf.copy(targetBuffer, [targetStart], [sourceStart], [sourceEnd])#

    • targetBuffer Buffer object - Buffer to copy into
    • targetStart Number, Optional, Default: 0
    • sourceStart Number, Optional, Default: 0
    • sourceEnd Number, Optional, Default: buffer.length

    Does copy between buffers. The source and target regions can be overlapped. targetStart and sourceStart default to 0. sourceEnd defaults to buffer.length.

    All values passed that are undefined/NaN or are out of bounds are set equal to their respective defaults.

    Example: build two Buffers, then copy buf1 from byte 16 through byte 19 into buf2, starting at the 8th byte in buf2.

    buf1 = new Buffer(26);
    buf2 = new Buffer(26);
    
    for (var i = 0 ; i < 26 ; i++) {
      buf1[i] = i + 97; // 97 is ASCII a
      buf2[i] = 33; // ASCII !
    }
    
    buf1.copy(buf2, 8, 16, 20);
    console.log(buf2.toString('ascii', 0, 25));
    
    // !!!!!!!!qrst!!!!!!!!!!!!!

    buf.slice([start], [end])#

    • start Number, Optional, Default: 0
    • end Number, Optional, Default: buffer.length

    Returns a new buffer which references the same memory as the old, but offset and cropped by the start (defaults to 0) and end (defaults to buffer.length) indexes. Negative indexes start from the end of the buffer.

    Modifying the new buffer slice will modify memory in the original buffer!

    Example: build a Buffer with the ASCII alphabet, take a slice, then modify one byte from the original Buffer.

    var buf1 = new Buffer(26);
    
    for (var i = 0 ; i < 26 ; i++) {
      buf1[i] = i + 97; // 97 is ASCII a
    }
    
    var buf2 = buf1.slice(0, 3);
    console.log(buf2.toString('ascii', 0, buf2.length));
    buf1[0] = 33;
    console.log(buf2.toString('ascii', 0, buf2.length));
    
    // abc
    // !bc

    buf.readUInt8(offset, [noAssert])#

    • offset Number
    • noAssert Boolean, Optional, Default: false
    • Return: Number

    Reads an unsigned 8 bit integer from the buffer at the specified offset.

    Set noAssert to true to skip validation of offset. This means that offset may be beyond the end of the buffer. Defaults to false.

    Example:

    var buf = new Buffer(4);
    
    buf[0] = 0x3;
    buf[1] = 0x4;
    buf[2] = 0x23;
    buf[3] = 0x42;
    
    for (ii = 0; ii < buf.length; ii++) {
      console.log(buf.readUInt8(ii));
    }
    
    // 0x3
    // 0x4
    // 0x23
    // 0x42

    buf.readUInt16LE(offset, [noAssert])#

    buf.readUInt16BE(offset, [noAssert])#

    • offset Number
    • noAssert Boolean, Optional, Default: false
    • Return: Number

    Reads an unsigned 16 bit integer from the buffer at the specified offset with specified endian format.

    Set noAssert to true to skip validation of offset. This means that offset may be beyond the end of the buffer. Defaults to false.

    Example:

    var buf = new Buffer(4);
    
    buf[0] = 0x3;
    buf[1] = 0x4;
    buf[2] = 0x23;
    buf[3] = 0x42;
    
    console.log(buf.readUInt16BE(0));
    console.log(buf.readUInt16LE(0));
    console.log(buf.readUInt16BE(1));
    console.log(buf.readUInt16LE(1));
    console.log(buf.readUInt16BE(2));
    console.log(buf.readUInt16LE(2));
    
    // 0x0304
    // 0x0403
    // 0x0423
    // 0x2304
    // 0x2342
    // 0x4223

    buf.readUInt32LE(offset, [noAssert])#

    buf.readUInt32BE(offset, [noAssert])#

    • offset Number
    • noAssert Boolean, Optional, Default: false
    • Return: Number

    Reads an unsigned 32 bit integer from the buffer at the specified offset with specified endian format.

    Set noAssert to true to skip validation of offset. This means that offset may be beyond the end of the buffer. Defaults to false.

    Example:

    var buf = new Buffer(4);
    
    buf[0] = 0x3;
    buf[1] = 0x4;
    buf[2] = 0x23;
    buf[3] = 0x42;
    
    console.log(buf.readUInt32BE(0));
    console.log(buf.readUInt32LE(0));
    
    // 0x03042342
    // 0x42230403

    buf.readInt8(offset, [noAssert])#

    • offset Number
    • noAssert Boolean, Optional, Default: false
    • Return: Number

    Reads a signed 8 bit integer from the buffer at the specified offset.

    Set noAssert to true to skip validation of offset. This means that offset may be beyond the end of the buffer. Defaults to false.

    Works as buffer.readUInt8, except buffer contents are treated as two's complement signed values.

    buf.readInt16LE(offset, [noAssert])#

    buf.readInt16BE(offset, [noAssert])#

    • offset Number
    • noAssert Boolean, Optional, Default: false
    • Return: Number

    Reads a signed 16 bit integer from the buffer at the specified offset with specified endian format.

    Set noAssert to true to skip validation of offset. This means that offset may be beyond the end of the buffer. Defaults to false.

    Works as buffer.readUInt16*, except buffer contents are treated as two's complement signed values.

    buf.readInt32LE(offset, [noAssert])#

    buf.readInt32BE(offset, [noAssert])#

    • offset Number
    • noAssert Boolean, Optional, Default: false
    • Return: Number

    Reads a signed 32 bit integer from the buffer at the specified offset with specified endian format.

    Set noAssert to true to skip validation of offset. This means that offset may be beyond the end of the buffer. Defaults to false.

    Works as buffer.readUInt32*, except buffer contents are treated as two's complement signed values.

    buf.readFloatLE(offset, [noAssert])#

    buf.readFloatBE(offset, [noAssert])#

    • offset Number
    • noAssert Boolean, Optional, Default: false
    • Return: Number

    Reads a 32 bit float from the buffer at the specified offset with specified endian format.

    Set noAssert to true to skip validation of offset. This means that offset may be beyond the end of the buffer. Defaults to false.

    Example:

    var buf = new Buffer(4);
    
    buf[0] = 0x00;
    buf[1] = 0x00;
    buf[2] = 0x80;
    buf[3] = 0x3f;
    
    console.log(buf.readFloatLE(0));
    
    // 0x01

    buf.readDoubleLE(offset, [noAssert])#

    buf.readDoubleBE(offset, [noAssert])#

    • offset Number
    • noAssert Boolean, Optional, Default: false
    • Return: Number

    Reads a 64 bit double from the buffer at the specified offset with specified endian format.

    Set noAssert to true to skip validation of offset. This means that offset may be beyond the end of the buffer. Defaults to false.

    Example:

    var buf = new Buffer(8);
    
    buf[0] = 0x55;
    buf[1] = 0x55;
    buf[2] = 0x55;
    buf[3] = 0x55;
    buf[4] = 0x55;
    buf[5] = 0x55;
    buf[6] = 0xd5;
    buf[7] = 0x3f;
    
    console.log(buf.readDoubleLE(0));
    
    // 0.3333333333333333

    buf.writeUInt8(value, offset, [noAssert])#

    • value Number
    • offset Number
    • noAssert Boolean, Optional, Default: false

    Writes value to the buffer at the specified offset. Note, value must be a valid unsigned 8 bit integer.

    Set noAssert to true to skip validation of value and offset. This means that value may be too large for the specific function and offset may be beyond the end of the buffer leading to the values being silently dropped. This should not be used unless you are certain of correctness. Defaults to false.

    Example:

    var buf = new Buffer(4);
    buf.writeUInt8(0x3, 0);
    buf.writeUInt8(0x4, 1);
    buf.writeUInt8(0x23, 2);
    buf.writeUInt8(0x42, 3);
    
    console.log(buf);
    
    // <Buffer 03 04 23 42>

    buf.writeUInt16LE(value, offset, [noAssert])#

    buf.writeUInt16BE(value, offset, [noAssert])#

    • value Number
    • offset Number
    • noAssert Boolean, Optional, Default: false

    Writes value to the buffer at the specified offset with specified endian format. Note, value must be a valid unsigned 16 bit integer.

    Set noAssert to true to skip validation of value and offset. This means that value may be too large for the specific function and offset may be beyond the end of the buffer leading to the values being silently dropped. This should not be used unless you are certain of correctness. Defaults to false.

    Example:

    var buf = new Buffer(4);
    buf.writeUInt16BE(0xdead, 0);
    buf.writeUInt16BE(0xbeef, 2);
    
    console.log(buf);
    
    buf.writeUInt16LE(0xdead, 0);
    buf.writeUInt16LE(0xbeef, 2);
    
    console.log(buf);
    
    // <Buffer de ad be ef>
    // <Buffer ad de ef be>

    buf.writeUInt32LE(value, offset, [noAssert])#

    buf.writeUInt32BE(value, offset, [noAssert])#

    • value Number
    • offset Number
    • noAssert Boolean, Optional, Default: false

    Writes value to the buffer at the specified offset with specified endian format. Note, value must be a valid unsigned 32 bit integer.

    Set noAssert to true to skip validation of value and offset. This means that value may be too large for the specific function and offset may be beyond the end of the buffer leading to the values being silently dropped. This should not be used unless you are certain of correctness. Defaults to false.

    Example:

    var buf = new Buffer(4);
    buf.writeUInt32BE(0xfeedface, 0);
    
    console.log(buf);
    
    buf.writeUInt32LE(0xfeedface, 0);
    
    console.log(buf);
    
    // <Buffer fe ed fa ce>
    // <Buffer ce fa ed fe>

    buf.writeInt8(value, offset, [noAssert])#

    • value Number
    • offset Number
    • noAssert Boolean, Optional, Default: false

    Writes value to the buffer at the specified offset. Note, value must be a valid signed 8 bit integer.

    Set noAssert to true to skip validation of value and offset. This means that value may be too large for the specific function and offset may be beyond the end of the buffer leading to the values being silently dropped. This should not be used unless you are certain of correctness. Defaults to false.

    Works as buffer.writeUInt8, except value is written out as a two's complement signed integer into buffer.

    buf.writeInt16LE(value, offset, [noAssert])#

    buf.writeInt16BE(value, offset, [noAssert])#

    • value Number
    • offset Number
    • noAssert Boolean, Optional, Default: false

    Writes value to the buffer at the specified offset with specified endian format. Note, value must be a valid signed 16 bit integer.

    Set noAssert to true to skip validation of value and offset. This means that value may be too large for the specific function and offset may be beyond the end of the buffer leading to the values being silently dropped. This should not be used unless you are certain of correctness. Defaults to false.

    Works as buffer.writeUInt16*, except value is written out as a two's complement signed integer into buffer.

    buf.writeInt32LE(value, offset, [noAssert])#

    buf.writeInt32BE(value, offset, [noAssert])#

    • value Number
    • offset Number
    • noAssert Boolean, Optional, Default: false

    Writes value to the buffer at the specified offset with specified endian format. Note, value must be a valid signed 32 bit integer.

    Set noAssert to true to skip validation of value and offset. This means that value may be too large for the specific function and offset may be beyond the end of the buffer leading to the values being silently dropped. This should not be used unless you are certain of correctness. Defaults to false.

    Works as buffer.writeUInt32*, except value is written out as a two's complement signed integer into buffer.

    buf.writeFloatLE(value, offset, [noAssert])#

    buf.writeFloatBE(value, offset, [noAssert])#

    • value Number
    • offset Number
    • noAssert Boolean, Optional, Default: false

    Writes value to the buffer at the specified offset with specified endian format. Note, behavior is unspecified if value is not a 32 bit float.

    Set noAssert to true to skip validation of value and offset. This means that value may be too large for the specific function and offset may be beyond the end of the buffer leading to the values being silently dropped. This should not be used unless you are certain of correctness. Defaults to false.

    Example:

    var buf = new Buffer(4);
    buf.writeFloatBE(0xcafebabe, 0);
    
    console.log(buf);
    
    buf.writeFloatLE(0xcafebabe, 0);
    
    console.log(buf);
    
    // <Buffer 4f 4a fe bb>
    // <Buffer bb fe 4a 4f>

    buf.writeDoubleLE(value, offset, [noAssert])#

    buf.writeDoubleBE(value, offset, [noAssert])#

    • value Number
    • offset Number
    • noAssert Boolean, Optional, Default: false

    Writes value to the buffer at the specified offset with specified endian format. Note, value must be a valid 64 bit double.

    Set noAssert to true to skip validation of value and offset. This means that value may be too large for the specific function and offset may be beyond the end of the buffer leading to the values being silently dropped. This should not be used unless you are certain of correctness. Defaults to false.

    Example:

    var buf = new Buffer(8);
    buf.writeDoubleBE(0xdeadbeefcafebabe, 0);
    
    console.log(buf);
    
    buf.writeDoubleLE(0xdeadbeefcafebabe, 0);
    
    console.log(buf);
    
    // <Buffer 43 eb d5 b7 dd f9 5f d7>
    // <Buffer d7 5f f9 dd b7 d5 eb 43>

    buf.fill(value, [offset], [end])#

    • value
    • offset Number, Optional
    • end Number, Optional

    Fills the buffer with the specified value. If the offset (defaults to 0) and end (defaults to buffer.length) are not given it will fill the entire buffer.

    var b = new Buffer(50);
    b.fill("h");

    buffer.INSPECT_MAX_BYTES#

    • Number, Default: 50

    How many bytes will be returned when buffer.inspect() is called. This can be overridden by user modules.

    Note that this is a property on the buffer module returned by require('buffer'), not on the Buffer global, or a buffer instance.

    Class: SlowBuffer#

    This class is primarily for internal use. JavaScript programs should use Buffer instead of using SlowBuffer.

    In order to avoid the overhead of allocating many C++ Buffer objects for small blocks of memory in the lifetime of a server, Node allocates memory in 8Kb (8192 byte) chunks. If a buffer is smaller than this size, then it will be backed by a parent SlowBuffer object. If it is larger than this, then Node will allocate a SlowBuffer slab for it directly.

    Stream#

    Stability: 2 - Unstable

    A stream is an abstract interface implemented by various objects in Node. For example a request to an HTTP server is a stream, as is stdout. Streams are readable, writable, or both. All streams are instances of EventEmitter

    You can load the Stream base classes by doing require('stream'). There are base classes provided for Readable streams, Writable streams, Duplex streams, and Transform streams.

    This document is split up into 3 sections. The first explains the parts of the API that you need to be aware of to use streams in your programs. If you never implement a streaming API yourself, you can stop there.

    The second section explains the parts of the API that you need to use if you implement your own custom streams yourself. The API is designed to make this easy for you to do.

    The third section goes into more depth about how streams work, including some of the internal mechanisms and functions that you should probably not modify unless you definitely know what you are doing.

    API for Stream Consumers#

    Streams can be either Readable, Writable, or both (Duplex).

    All streams are EventEmitters, but they also have other custom methods and properties depending on whether they are Readable, Writable, or Duplex.

    If a stream is both Readable and Writable, then it implements all of the methods and events below. So, a Duplex or Transform stream is fully described by this API, though their implementation may be somewhat different.

    It is not necessary to implement Stream interfaces in order to consume streams in your programs. If you are implementing streaming interfaces in your own program, please also refer to API for Stream Implementors below.

    Almost all Node programs, no matter how simple, use Streams in some way. Here is an example of using Streams in a Node program:

    var http = require('http');
    
    var server = http.createServer(function (req, res) {
      // req is an http.IncomingMessage, which is a Readable Stream
      // res is an http.ServerResponse, which is a Writable Stream
    
      var body = '';
      // we want to get the data as utf8 strings
      // If you don't set an encoding, then you'll get Buffer objects
      req.setEncoding('utf8');
    
      // Readable streams emit 'data' events once a listener is added
      req.on('data', function (chunk) {
        body += chunk;
      })
    
      // the end event tells you that you have entire body
      req.on('end', function () {
        try {
          var data = JSON.parse(body);
        } catch (er) {
          // uh oh!  bad json!
          res.statusCode = 400;
          return res.end('error: ' + er.message);
        }
    
        // write back something interesting to the user:
        res.write(typeof data);
        res.end();
      })
    })
    
    server.listen(1337);
    
    // $ curl localhost:1337 -d '{}'
    // object
    // $ curl localhost:1337 -d '"foo"'
    // string
    // $ curl localhost:1337 -d 'not json'
    // error: Unexpected token o

    Class: stream.Readable#

    The Readable stream interface is the abstraction for a source of data that you are reading from. In other words, data comes out of a Readable stream.

    A Readable stream will not start emitting data until you indicate that you are ready to receive it.

    Readable streams have two "modes": a flowing mode and a non-flowing mode. When in flowing mode, data is read from the underlying system and provided to your program as fast as possible. In non-flowing mode, you must explicitly call stream.read() to get chunks of data out.

    Examples of readable streams include:

    Event: 'readable'#

    When a chunk of data can be read from the stream, it will emit a 'readable' event.

    In some cases, listening for a 'readable' event will cause some data to be read into the internal buffer from the underlying system, if it hadn't already.

    var readable = getReadableStreamSomehow();
    readable.on('readable', function() {
      // there is some data to read now
    })

    Once the internal buffer is drained, a readable event will fire again when more data is available.

    Event: 'data'#

    • chunk Buffer | String The chunk of data.

    If you attach a data event listener, then it will switch the stream into flowing mode, and data will be passed to your handler as soon as it is available.

    If you just want to get all the data out of the stream as fast as possible, this is the best way to do so.

    var readable = getReadableStreamSomehow();
    readable.on('data', function(chunk) {
      console.log('got %d bytes of data', chunk.length);
    })

    Event: 'end'#

    This event fires when no more data will be provided.

    Note that the end event will not fire unless the data is completely consumed. This can be done by switching into flowing mode, or by calling read() repeatedly until you get to the end.

    var readable = getReadableStreamSomehow();
    readable.on('data', function(chunk) {
      console.log('got %d bytes of data', chunk.length);
    })
    readable.on('end', function() {
      console.log('there will be no more data.');
    });

    Event: 'close'#

    Emitted when the underlying resource (for example, the backing file descriptor) has been closed. Not all streams will emit this.

    Event: 'error'#

    Emitted if there was an error receiving data.

    readable.read([size])#

    • size Number Optional argument to specify how much data to read.
    • Return String | Buffer | null

    The read() method pulls some data out of the internal buffer and returns it. If there is no data available, then it will return null.

    If you pass in a size argument, then it will return that many bytes. If size bytes are not available, then it will return null.

    If you do not specify a size argument, then it will return all the data in the internal buffer.

    This method should only be called in non-flowing mode. In flowing-mode, this method is called automatically until the internal buffer is drained.

    var readable = getReadableStreamSomehow();
    readable.on('readable', function() {
      var chunk;
      while (null !== (chunk = readable.read())) {
        console.log('got %d bytes of data', chunk.length);
      }
    });

    readable.setEncoding(encoding)#

    • encoding String The encoding to use.

    Call this function to cause the stream to return strings of the specified encoding instead of Buffer objects. For example, if you do readable.setEncoding('utf8'), then the output data will be interpreted as UTF-8 data, and returned as strings. If you do readable.setEncoding('hex'), then the data will be encoded in hexadecimal string format.

    This properly handles multi-byte characters that would otherwise be potentially mangled if you simply pulled the Buffers directly and called buf.toString(encoding) on them. If you want to read the data as strings, always use this method.

    var readable = getReadableStreamSomehow();
    readable.setEncoding('utf8');
    readable.on('data', function(chunk) {
      assert.equal(typeof chunk, 'string');
      console.log('got %d characters of string data', chunk.length);
    })

    readable.resume()#

    This method will cause the readable stream to resume emitting data events.

    This method will switch the stream into flowing-mode. If you do not want to consume the data from a stream, but you do want to get to its end event, you can call readable.resume() to open the flow of data.

    var readable = getReadableStreamSomehow();
    readable.resume();
    readable.on('end', function(chunk) {
      console.log('got to the end, but did not read anything');
    })

    readable.pause()#

    This method will cause a stream in flowing-mode to stop emitting data events. Any data that becomes available will remain in the internal buffer.

    This method is only relevant in flowing mode. When called on a non-flowing stream, it will switch into flowing mode, but remain paused.

    var readable = getReadableStreamSomehow();
    readable.on('data', function(chunk) {
      console.log('got %d bytes of data', chunk.length);
      readable.pause();
      console.log('there will be no more data for 1 second');
      setTimeout(function() {
        console.log('now data will start flowing again');
        readable.resume();
      }, 1000);
    })

    readable.pipe(destination, [options])#

    • destination Writable Stream The destination for writing data
    • options Object Pipe options
      • end Boolean End the writer when the reader ends. Default = true

    This method pulls all the data out of a readable stream, and writes it to the supplied destination, automatically managing the flow so that the destination is not overwhelmed by a fast readable stream.

    Multiple destinations can be piped to safely.

    var readable = getReadableStreamSomehow();
    var writable = fs.createWriteStream('file.txt');
    // All the data from readable goes into 'file.txt'
    readable.pipe(writable);

    This function returns the destination stream, so you can set up pipe chains like so:

    var r = fs.createReadStream('file.txt');
    var z = zlib.createGzip();
    var w = fs.createWriteStream('file.txt.gz');
    r.pipe(z).pipe(w);

    For example, emulating the Unix cat command:

    process.stdin.pipe(process.stdout);

    By default end() is called on the destination when the source stream emits end, so that destination is no longer writable. Pass { end: false } as options to keep the destination stream open.

    This keeps writer open so that "Goodbye" can be written at the end.

    reader.pipe(writer, { end: false });
    reader.on('end', function() {
      writer.end('Goodbye\n');
    });

    Note that process.stderr and process.stdout are never closed until the process exits, regardless of the specified options.

    readable.unpipe([destination])#

    • destination Writable Stream Optional specific stream to unpipe

    This method will remove the hooks set up for a previous pipe() call.

    If the destination is not specified, then all pipes are removed.

    If the destination is specified, but no pipe is set up for it, then this is a no-op.

    var readable = getReadableStreamSomehow();
    var writable = fs.createWriteStream('file.txt');
    // All the data from readable goes into 'file.txt',
    // but only for the first second
    readable.pipe(writable);
    setTimeout(function() {
      console.log('stop writing to file.txt');
      readable.unpipe(writable);
      console.log('manually close the file stream');
      writable.end();
    }, 1000);

    readable.unshift(chunk)#

    • chunk Buffer | String Chunk of data to unshift onto the read queue

    This is useful in certain cases where a stream is being consumed by a parser, which needs to "un-consume" some data that it has optimistically pulled out of the source, so that the stream can be passed on to some other party.

    If you find that you must often call stream.unshift(chunk) in your programs, consider implementing a Transform stream instead. (See API for Stream Implementors, below.)

    // Pull off a header delimited by \n\n
    // use unshift() if we get too much
    // Call the callback with (error, header, stream)
    var StringDecoder = require('string_decoder').StringDecoder;
    function parseHeader(stream, callback) {
      stream.on('error', callback);
      stream.on('readable', onReadable);
      var decoder = new StringDecoder('utf8');
      var header = '';
      function onReadable() {
        var chunk;
        while (null !== (chunk = stream.read())) {
          var str = decoder.write(chunk);
          if (str.match(/\n\n/)) {
            // found the header boundary
            var split = str.split(/\n\n/);
            header += split.shift();
            var remaining = split.join('\n\n');
            var buf = new Buffer(remaining, 'utf8');
            if (buf.length)
              stream.unshift(buf);
            stream.removeListener('error', callback);
            stream.removeListener('readable', onReadable);
            // now the body of the message can be read from the stream.
            callback(null, header, stream);
          } else {
            // still reading the header.
            header += str;
          }
        }
      }
    }

    readable.wrap(stream)#

    • stream Stream An "old style" readable stream

    Versions of Node prior to v0.10 had streams that did not implement the entire Streams API as it is today. (See "Compatibility" below for more information.)

    If you are using an older Node library that emits 'data' events and has a pause() method that is advisory only, then you can use the wrap() method to create a Readable stream that uses the old stream as its data source.

    You will very rarely ever need to call this function, but it exists as a convenience for interacting with old Node programs and libraries.

    For example:

    var OldReader = require('./old-api-module.js').OldReader;
    var oreader = new OldReader;
    var Readable = require('stream').Readable;
    var myReader = new Readable().wrap(oreader);
    
    myReader.on('readable', function() {
      myReader.read(); // etc.
    });

    Class: stream.Writable#

    The Writable stream interface is an abstraction for a destination that you are writing data to.

    Examples of writable streams include:

    writable.write(chunk, [encoding], [callback])#

    • chunk String | Buffer The data to write
    • encoding String The encoding, if chunk is a String
    • callback Function Callback for when this chunk of data is flushed
    • Returns: Boolean True if the data was handled completely.

    This method writes some data to the underlying system, and calls the supplied callback once the data has been fully handled.

    The return value indicates if you should continue writing right now. If the data had to be buffered internally, then it will return false. Otherwise, it will return true.

    This return value is strictly advisory. You MAY continue to write, even if it returns false. However, writes will be buffered in memory, so it is best not to do this excessively. Instead, wait for the drain event before writing more data.

    Event: 'drain'#

    If a writable.write(chunk) call returns false, then the drain event will indicate when it is appropriate to begin writing more data to the stream.

    // Write the data to the supplied writable stream 1MM times.
    // Be attentive to back-pressure.
    function writeOneMillionTimes(writer, data, encoding, callback) {
      var i = 1000000;
      write();
      function write() {
        var ok = true;
        do {
          i -= 1;
          if (i === 0) {
            // last time!
            writer.write(data, encoding, callback);
          } else {
            // see if we should continue, or wait
            // don't pass the callback, because we're not done yet.
            ok = writer.write(data, encoding);
          }
        } while (i > 0 && ok);
        if (i > 0) {
          // had to stop early!
          // write some more once it drains
          writer.once('drain', write);
        }
      }
    }

    writable.end([chunk], [encoding], [callback])#

    • chunk String | Buffer Optional data to write
    • encoding String The encoding, if chunk is a String
    • callback Function Optional callback for when the stream is finished

    Call this method when no more data will be written to the stream. If supplied, the callback is attached as a listener on the finish event.

    Calling write() after calling end() will raise an error.

    // write 'hello, ' and then end with 'world!'
    http.createServer(function (req, res) {
      res.write('hello, ');
      res.end('world!');
      // writing more now is not allowed!
    });

    Event: 'finish'#

    When the end() method has been called, and all data has been flushed to the underlying system, this event is emitted.

    var writer = getWritableStreamSomehow();
    for (var i = 0; i < 100; i ++) {
      writer.write('hello, #' + i + '!\n');
    }
    writer.end('this is the end\n');
    writer.on('finish', function() {
      console.error('all writes are now complete.');
    });

    Event: 'pipe'#

    • src Readable Stream source stream that is piping to this writable

    This is emitted whenever the pipe() method is called on a readable stream, adding this writable to its set of destinations.

    var writer = getWritableStreamSomehow();
    var reader = getReadableStreamSomehow();
    writer.on('pipe', function(src) {
      console.error('something is piping into the writer');
      assert.equal(src, reader);
    });
    reader.pipe(writer);

    Event: 'unpipe'#

    This is emitted whenever the unpipe() method is called on a readable stream, removing this writable from its set of destinations.

    var writer = getWritableStreamSomehow();
    var reader = getReadableStreamSomehow();
    writer.on('unpipe', function(src) {
      console.error('something has stopped piping into the writer');
      assert.equal(src, reader);
    });
    reader.pipe(writer);
    reader.unpipe(writer);

    Event: 'error'#

    Emitted if there was an error when writing or piping data.

    Class: stream.Duplex#

    Duplex streams are streams that implement both the Readable and Writable interfaces. See above for usage.

    Examples of Duplex streams include:

    Class: stream.Transform#

    Transform streams are Duplex streams where the output is in some way computed from the input. They implement both the Readable and Writable interfaces. See above for usage.

    Examples of Transform streams include:

    API for Stream Implementors#

    To implement any sort of stream, the pattern is the same:

    1. Extend the appropriate parent class in your own subclass. (The util.inherits method is particularly helpful for this.)
    2. Call the appropriate parent class constructor in your constructor, to be sure that the internal mechanisms are set up properly.
    3. Implement one or more specific methods, as detailed below.

    The class to extend and the method(s) to implement depend on the sort of stream class you are writing:

    Use-case

    Class

    Method(s) to implement

    Reading only

    Readable

    _read

    Writing only

    Writable

    _write

    Reading and writing

    Duplex

    _read, _write

    Operate on written data, then read the result

    Transform

    _transform, _flush

    In your implementation code, it is very important to never call the methods described in API for Stream Consumers above. Otherwise, you can potentially cause adverse side effects in programs that consume your streaming interfaces.

    Class: stream.Readable#

    stream.Readable is an abstract class designed to be extended with an underlying implementation of the _read(size) method.

    Please see above under API for Stream Consumers for how to consume streams in your programs. What follows is an explanation of how to implement Readable streams in your programs.

    Example: A Counting Stream#

    This is a basic example of a Readable stream. It emits the numerals from 1 to 1,000,000 in ascending order, and then ends.

    var Readable = require('stream').Readable;
    var util = require('util');
    util.inherits(Counter, Readable);
    
    function Counter(opt) {
      Readable.call(this, opt);
      this._max = 1000000;
      this._index = 1;
    }
    
    Counter.prototype._read = function() {
      var i = this._index++;
      if (i > this._max)
        this.push(null);
      else {
        var str = '' + i;
        var buf = new Buffer(str, 'ascii');
        this.push(buf);
      }
    };

    Example: SimpleProtocol v1 (Sub-optimal)#

    This is similar to the parseHeader function described above, but implemented as a custom stream. Also, note that this implementation does not convert the incoming data to a string.

    However, this would be better implemented as a Transform stream. See below for a better implementation.

    // A parser for a simple data protocol.
    // The "header" is a JSON object, followed by 2 \n characters, and
    // then a message body.
    //
    // NOTE: This can be done more simply as a Transform stream!
    // Using Readable directly for this is sub-optimal.  See the
    // alternative example below under the Transform section.
    
    var Readable = require('stream').Readable;
    var util = require('util');
    
    util.inherits(SimpleProtocol, Readable);
    
    function SimpleProtocol(source, options) {
      if (!(this instanceof SimpleProtocol))
        return new SimpleProtocol(source, options);
    
      Readable.call(this, options);
      this._inBody = false;
      this._sawFirstCr = false;
    
      // source is a readable stream, such as a socket or file
      this._source = source;
    
      var self = this;
      source.on('end', function() {
        self.push(null);
      });
    
      // give it a kick whenever the source is readable
      // read(0) will not consume any bytes
      source.on('readable', function() {
        self.read(0);
      });
    
      this._rawHeader = [];
      this.header = null;
    }
    
    SimpleProtocol.prototype._read = function(n) {
      if (!this._inBody) {
        var chunk = this._source.read();
    
        // if the source doesn't have data, we don't have data yet.
        if (chunk === null)
          return this.push('');
    
        // check if the chunk has a \n\n
        var split = -1;
        for (var i = 0; i < chunk.length; i++) {
          if (chunk[i] === 10) { // '\n'
            if (this._sawFirstCr) {
              split = i;
              break;
            } else {
              this._sawFirstCr = true;
            }
          } else {
            this._sawFirstCr = false;
          }
        }
    
        if (split === -1) {
          // still waiting for the \n\n
          // stash the chunk, and try again.
          this._rawHeader.push(chunk);
          this.push('');
        } else {
          this._inBody = true;
          var h = chunk.slice(0, split);
          this._rawHeader.push(h);
          var header = Buffer.concat(this._rawHeader).toString();
          try {
            this.header = JSON.parse(header);
          } catch (er) {
            this.emit('error', new Error('invalid simple protocol data'));
            return;
          }
          // now, because we got some extra data, unshift the rest
          // back into the read queue so that our consumer will see it.
          var b = chunk.slice(split);
          this.unshift(b);
    
          // and let them know that we are done parsing the header.
          this.emit('header', this.header);
        }
      } else {
        // from there on, just provide the data to our consumer.
        // careful not to push(null), since that would indicate EOF.
        var chunk = this._source.read();
        if (chunk) this.push(chunk);
      }
    };
    
    // Usage:
    // var parser = new SimpleProtocol(source);
    // Now parser is a readable stream that will emit 'header'
    // with the parsed header data.

    new stream.Readable([options])#

    • options Object
      • highWaterMark Number The maximum number of bytes to store in the internal buffer before ceasing to read from the underlying resource. Default=16kb
      • encoding String If specified, then buffers will be decoded to strings using the specified encoding. Default=null
      • objectMode Boolean Whether this stream should behave as a stream of objects. Meaning that stream.read(n) returns a single value instead of a Buffer of size n. Default=false

    In classes that extend the Readable class, make sure to call the Readable constructor so that the buffering settings can be properly initialized.

    readable._read(size)#

    • size Number Number of bytes to read asynchronously

    Note: Implement this function, but do NOT call it directly.

    This function should NOT be called directly. It should be implemented by child classes, and only called by the internal Readable class methods.

    All Readable stream implementations must provide a _read method to fetch data from the underlying resource.

    This method is prefixed with an underscore because it is internal to the class that defines it, and should not be called directly by user programs. However, you are expected to override this method in your own extension classes.

    When data is available, put it into the read queue by calling readable.push(chunk). If push returns false, then you should stop reading. When _read is called again, you should start pushing more data.

    The size argument is advisory. Implementations where a "read" is a single call that returns data can use this to know how much data to fetch. Implementations where that is not relevant, such as TCP or TLS, may ignore this argument, and simply provide data whenever it becomes available. There is no need, for example to "wait" until size bytes are available before calling stream.push(chunk).

    readable.push(chunk, [encoding])#

    • chunk Buffer | null | String Chunk of data to push into the read queue
    • encoding String Encoding of String chunks. Must be a valid Buffer encoding, such as 'utf8' or 'ascii'
    • return Boolean Whether or not more pushes should be performed

    Note: This function should be called by Readable implementors, NOT by consumers of Readable streams.

    The _read() function will not be called again until at least one push(chunk) call is made.

    The Readable class works by putting data into a read queue to be pulled out later by calling the read() method when the 'readable' event fires.

    The push() method will explicitly insert some data into the read queue. If it is called with null then it will signal the end of the data (EOF).

    This API is designed to be as flexible as possible. For example, you may be wrapping a lower-level source which has some sort of pause/resume mechanism, and a data callback. In those cases, you could wrap the low-level source object by doing something like this:

    // source is an object with readStop() and readStart() methods,
    // and an `ondata` member that gets called when it has data, and
    // an `onend` member that gets called when the data is over.
    
    util.inherits(SourceWrapper, Readable);
    
    function SourceWrapper(options) {
      Readable.call(this, options);
    
      this._source = getLowlevelSourceObject();
      var self = this;
    
      // Every time there's data, we push it into the internal buffer.
      this._source.ondata = function(chunk) {
        // if push() returns false, then we need to stop reading from source
        if (!self.push(chunk))
          self._source.readStop();
      };
    
      // When the source ends, we push the EOF-signalling `null` chunk
      this._source.onend = function() {
        self.push(null);
      };
    }
    
    // _read will be called when the stream wants to pull more data in
    // the advisory size argument is ignored in this case.
    SourceWrapper.prototype._read = function(size) {
      this._source.readStart();
    };

    Class: stream.Writable#

    stream.Writable is an abstract class designed to be extended with an underlying implementation of the _write(chunk, encoding, callback) method.

    Please see above under API for Stream Consumers for how to consume writable streams in your programs. What follows is an explanation of how to implement Writable streams in your programs.

    new stream.Writable([options])#

    • options Object
      • highWaterMark Number Buffer level when write() starts returning false. Default=16kb
      • decodeStrings Boolean Whether or not to decode strings into Buffers before passing them to _write(). Default=true

    In classes that extend the Writable class, make sure to call the constructor so that the buffering settings can be properly initialized.

    writable._write(chunk, encoding, callback)#

    • chunk Buffer | String The chunk to be written. Will always be a buffer unless the decodeStrings option was set to false.
    • encoding String If the chunk is a string, then this is the encoding type. Ignore chunk is a buffer. Note that chunk will always be a buffer unless the decodeStrings option is explicitly set to false.
    • callback Function Call this function (optionally with an error argument) when you are done processing the supplied chunk.

    All Writable stream implementations must provide a _write() method to send data to the underlying resource.

    Note: This function MUST NOT be called directly. It should be implemented by child classes, and called by the internal Writable class methods only.

    Call the callback using the standard callback(error) pattern to signal that the write completed successfully or with an error.

    If the decodeStrings flag is set in the constructor options, then chunk may be a string rather than a Buffer, and encoding will indicate the sort of string that it is. This is to support implementations that have an optimized handling for certain string data encodings. If you do not explicitly set the decodeStrings option to false, then you can safely ignore the encoding argument, and assume that chunk will always be a Buffer.

    This method is prefixed with an underscore because it is internal to the class that defines it, and should not be called directly by user programs. However, you are expected to override this method in your own extension classes.

    Class: stream.Duplex#

    A "duplex" stream is one that is both Readable and Writable, such as a TCP socket connection.

    Note that stream.Duplex is an abstract class designed to be extended with an underlying implementation of the _read(size) and _write(chunk, encoding, callback) methods as you would with a Readable or Writable stream class.

    Since JavaScript doesn't have multiple prototypal inheritance, this class prototypally inherits from Readable, and then parasitically from Writable. It is thus up to the user to implement both the lowlevel _read(n) method as well as the lowlevel _write(chunk, encoding, callback) method on extension duplex classes.

    new stream.Duplex(options)#

    • options Object Passed to both Writable and Readable constructors. Also has the following fields:
      • allowHalfOpen Boolean Default=true. If set to false, then the stream will automatically end the readable side when the writable side ends and vice versa.

    In classes that extend the Duplex class, make sure to call the constructor so that the buffering settings can be properly initialized.

    Class: stream.Transform#

    A "transform" stream is a duplex stream where the output is causally connected in some way to the input, such as a zlib stream or a crypto stream.

    There is no requirement that the output be the same size as the input, the same number of chunks, or arrive at the same time. For example, a Hash stream will only ever have a single chunk of output which is provided when the input is ended. A zlib stream will produce output that is either much smaller or much larger than its input.

    Rather than implement the _read() and _write() methods, Transform classes must implement the _transform() method, and may optionally also implement the _flush() method. (See below.)

    new stream.Transform([options])#

    • options Object Passed to both Writable and Readable constructors.

    In classes that extend the Transform class, make sure to call the constructor so that the buffering settings can be properly initialized.

    transform._transform(chunk, encoding, callback)#

    • chunk Buffer | String The chunk to be transformed. Will always be a buffer unless the decodeStrings option was set to false.
    • encoding String If the chunk is a string, then this is the encoding type. (Ignore if decodeStrings chunk is a buffer.)
    • callback Function Call this function (optionally with an error argument) when you are done processing the supplied chunk.

    Note: This function MUST NOT be called directly. It should be implemented by child classes, and called by the internal Transform class methods only.

    All Transform stream implementations must provide a _transform method to accept input and produce output.

    _transform should do whatever has to be done in this specific Transform class, to handle the bytes being written, and pass them off to the readable portion of the interface. Do asynchronous I/O, process things, and so on.

    Call transform.push(outputChunk) 0 or more times to generate output from this input chunk, depending on how much data you want to output as a result of this chunk.

    Call the callback function only when the current chunk is completely consumed. Note that there may or may not be output as a result of any particular input chunk.

    This method is prefixed with an underscore because it is internal to the class that defines it, and should not be called directly by user programs. However, you are expected to override this method in your own extension classes.

    transform._flush(callback)#

    • callback Function Call this function (optionally with an error argument) when you are done flushing any remaining data.

    Note: This function MUST NOT be called directly. It MAY be implemented by child classes, and if so, will be called by the internal Transform class methods only.

    In some cases, your transform operation may need to emit a bit more data at the end of the stream. For example, a Zlib compression stream will store up some internal state so that it can optimally compress the output. At the end, however, it needs to do the best it can with what is left, so that the data will be complete.

    In those cases, you can implement a _flush method, which will be called at the very end, after all the written data is consumed, but before emitting end to signal the end of the readable side. Just like with _transform, call transform.push(chunk) zero or more times, as appropriate, and call callback when the flush operation is complete.

    This method is prefixed with an underscore because it is internal to the class that defines it, and should not be called directly by user programs. However, you are expected to override this method in your own extension classes.

    Example: SimpleProtocol parser v2#

    The example above of a simple protocol parser can be implemented simply by using the higher level Transform stream class, similar to the parseHeader and SimpleProtocol v1 examples above.

    In this example, rather than providing the input as an argument, it would be piped into the parser, which is a more idiomatic Node stream approach.

    var util = require('util');
    var Transform = require('stream').Transform;
    util.inherits(SimpleProtocol, Transform);
    
    function SimpleProtocol(options) {
      if (!(this instanceof SimpleProtocol))
        return new SimpleProtocol(options);
    
      Transform.call(this, options);
      this._inBody = false;
      this._sawFirstCr = false;
      this._rawHeader = [];
      this.header = null;
    }
    
    SimpleProtocol.prototype._transform = function(chunk, encoding, done) {
      if (!this._inBody) {
        // check if the chunk has a \n\n
        var split = -1;
        for (var i = 0; i < chunk.length; i++) {
          if (chunk[i] === 10) { // '\n'
            if (this._sawFirstCr) {
              split = i;
              break;
            } else {
              this._sawFirstCr = true;
            }
          } else {
            this._sawFirstCr = false;
          }
        }
    
        if (split === -1) {
          // still waiting for the \n\n
          // stash the chunk, and try again.
          this._rawHeader.push(chunk);
        } else {
          this._inBody = true;
          var h = chunk.slice(0, split);
          this._rawHeader.push(h);
          var header = Buffer.concat(this._rawHeader).toString();
          try {
            this.header = JSON.parse(header);
          } catch (er) {
            this.emit('error', new Error('invalid simple protocol data'));
            return;
          }
          // and let them know that we are done parsing the header.
          this.emit('header', this.header);
    
          // now, because we got some extra data, emit this first.
          this.push(chunk.slice(split));
        }
      } else {
        // from there on, just provide the data to our consumer as-is.
        this.push(chunk);
      }
      done();
    };
    
    // Usage:
    // var parser = new SimpleProtocol();
    // source.pipe(parser)
    // Now parser is a readable stream that will emit 'header'
    // with the parsed header data.

    Class: stream.PassThrough#

    This is a trivial implementation of a Transform stream that simply passes the input bytes across to the output. Its purpose is mainly for examples and testing, but there are occasionally use cases where it can come in handy as a building block for novel sorts of streams.

    Streams: Under the Hood#

    Buffering#

    Both Writable and Readable streams will buffer data on an internal object called _writableState.buffer or _readableState.buffer, respectively.

    The amount of data that will potentially be buffered depends on the highWaterMark option which is passed into the constructor.

    Buffering in Readable streams happens when the implementation calls stream.push(chunk). If the consumer of the Stream does not call stream.read(), then the data will sit in the internal queue until it is consumed.

    Buffering in Writable streams happens when the user calls stream.write(chunk) repeatedly, even when write() returns false.

    The purpose of streams, especially with the pipe() method, is to limit the buffering of data to acceptable levels, so that sources and destinations of varying speed will not overwhelm the available memory.

    stream.read(0)#

    There are some cases where you want to trigger a refresh of the underlying readable stream mechanisms, without actually consuming any data. In that case, you can call stream.read(0), which will always return null.

    If the internal read buffer is below the highWaterMark, and the stream is not currently reading, then calling read(0) will trigger a low-level _read call.

    There is almost never a need to do this. However, you will see some cases in Node's internals where this is done, particularly in the Readable stream class internals.

    stream.push('')#

    Pushing a zero-byte string or Buffer (when not in Object mode) has an interesting side effect. Because it is a call to stream.push(), it will end the reading process. However, it does not add any data to the readable buffer, so there's nothing for a user to consume.

    Very rarely, there are cases where you have no data to provide now, but the consumer of your stream (or, perhaps, another bit of your own code) will know when to check again, by calling stream.read(0). In those cases, you may call stream.push('').

    So far, the only use case for this functionality is in the tls.CryptoStream class, which is deprecated in Node v0.12. If you find that you have to use stream.push(''), please consider another approach, because it almost certainly indicates that something is horribly wrong.

    Compatibility with Older Node Versions#

    In versions of Node prior to v0.10, the Readable stream interface was simpler, but also less powerful and less useful.

    • Rather than waiting for you to call the read() method, 'data' events would start emitting immediately. If you needed to do some I/O to decide how to handle data, then you had to store the chunks in some kind of buffer so that they would not be lost.
    • The pause() method was advisory, rather than guaranteed. This meant that you still had to be prepared to receive 'data' events even when the stream was in a paused state.

    In Node v0.10, the Readable class described below was added. For backwards compatibility with older Node programs, Readable streams switch into "flowing mode" when a 'data' event handler is added, or when the pause() or resume() methods are called. The effect is that, even if you are not using the new read() method and 'readable' event, you no longer have to worry about losing 'data' chunks.

    Most programs will continue to function normally. However, this introduces an edge case in the following conditions:

    • No 'data' event handler is added.
    • The pause() and resume() methods are never called.

    For example, consider the following code:

    // WARNING!  BROKEN!
    net.createServer(function(socket) {
    
      // we add an 'end' method, but never consume the data
      socket.on('end', function() {
        // It will never get here.
        socket.end('I got your message (but didnt read it)\n');
      });
    
    }).listen(1337);

    In versions of node prior to v0.10, the incoming message data would be simply discarded. However, in Node v0.10 and beyond, the socket will remain paused forever.

    The workaround in this situation is to call the resume() method to trigger "old mode" behavior:

    // Workaround
    net.createServer(function(socket) {
    
      socket.on('end', function() {
        socket.end('I got your message (but didnt read it)\n');
      });
    
      // start the flow of data, discarding it.
      socket.resume();
    
    }).listen(1337);

    In addition to new Readable streams switching into flowing-mode, pre-v0.10 style streams can be wrapped in a Readable class using the wrap() method.

    Object Mode#

    Normally, Streams operate on Strings and Buffers exclusively.

    Streams that are in object mode can emit generic JavaScript values other than Buffers and Strings.

    A Readable stream in object mode will always return a single item from a call to stream.read(size), regardless of what the size argument is.

    A Writable stream in object mode will always ignore the encoding argument to stream.write(data, encoding).

    The special value null still retains its special value for object mode streams. That is, for object mode readable streams, null as a return value from stream.read() indicates that there is no more data, and stream.push(null) will signal the end of stream data (EOF).

    No streams in Node core are object mode streams. This pattern is only used by userland streaming libraries.

    You should set objectMode in your stream child class constructor on the options object. Setting objectMode mid-stream is not safe.

    State Objects#

    Readable streams have a member object called _readableState. Writable streams have a member object called _writableState. Duplex streams have both.

    These objects should generally not be modified in child classes. However, if you have a Duplex or Transform stream that should be in objectMode on the readable side, and not in objectMode on the writable side, then you may do this in the constructor by setting the flag explicitly on the appropriate state object.

    var util = require('util');
    var StringDecoder = require('string_decoder').StringDecoder;
    var Transform = require('stream').Transform;
    util.inherits(JSONParseStream, Transform);
    
    // Gets \n-delimited JSON string data, and emits the parsed objects
    function JSONParseStream(options) {
      if (!(this instanceof JSONParseStream))
        return new JSONParseStream(options);
    
      Transform.call(this, options);
      this._writableState.objectMode = false;
      this._readableState.objectMode = true;
      this._buffer = '';
      this._decoder = new StringDecoder('utf8');
    }
    
    JSONParseStream.prototype._transform = function(chunk, encoding, cb) {
      this._buffer += this._decoder.write(chunk);
      // split on newlines
      var lines = this._buffer.split(/\r?\n/);
      // keep the last partial line buffered
      this._buffer = lines.pop();
      for (var l = 0; l < lines.length; l++) {
        var line = lines[l];
        try {
          var obj = JSON.parse(line);
        } catch (er) {
          this.emit('error', er);
          return;
        }
        // push the parsed object out to the readable consumer
        this.push(obj);
      }
      cb();
    };
    
    JSONParseStream.prototype._flush = function(cb) {
      // Just handle any leftover
      var rem = this._buffer.trim();
      if (rem) {
        try {
          var obj = JSON.parse(rem);
        } catch (er) {
          this.emit('error', er);
          return;
        }
        // push the parsed object out to the readable consumer
        this.push(obj);
      }
      cb();
    };

    The state objects contain other useful information for debugging the state of streams in your programs. It is safe to look at them, but beyond setting option flags in the constructor, it is not safe to modify them.

    Crypto#

    Stability: 2 - Unstable; API changes are being discussed for
    future versions.  Breaking changes will be minimized.  See below.

    Use require('crypto') to access this module.

    The crypto module offers a way of encapsulating secure credentials to be used as part of a secure HTTPS net or http connection.

    It also offers a set of wrappers for OpenSSL's hash, hmac, cipher, decipher, sign and verify methods.

    crypto.getCiphers()#

    Returns an array with the names of the supported ciphers.

    Example:

    var ciphers = crypto.getCiphers();
    console.log(ciphers); // ['AES-128-CBC', 'AES-128-CBC-HMAC-SHA1', ...]

    crypto.getHashes()#

    Returns an array with the names of the supported hash algorithms.

    Example:

    var hashes = crypto.getHashes();
    console.log(hashes); // ['sha', 'sha1', 'sha1WithRSAEncryption', ...]

    crypto.createCredentials(details)#

    Creates a credentials object, with the optional details being a dictionary with keys:

    • pfx : A string or buffer holding the PFX or PKCS12 encoded private key, certificate and CA certificates
    • key : A string holding the PEM encoded private key
    • passphrase : A string of passphrase for the private key or pfx
    • cert : A string holding the PEM encoded certificate
    • ca : Either a string or list of strings of PEM encoded CA certificates to trust.
    • crl : Either a string or list of strings of PEM encoded CRLs (Certificate Revocation List)
    • ciphers: A string describing the ciphers to use or exclude. Consult http://www.openssl.org/docs/apps/ciphers.html#CIPHER_LIST_FORMAT for details on the format.

    If no 'ca' details are given, then node.js will use the default publicly trusted list of CAs as given in

    http://mxr.mozilla.org/mozilla/source/security/nss/lib/ckfw/builtins/certdata.txt.

    crypto.createHash(algorithm)#

    Creates and returns a hash object, a cryptographic hash with the given algorithm which can be used to generate hash digests.

    algorithm is dependent on the available algorithms supported by the version of OpenSSL on the platform. Examples are 'sha1', 'md5', 'sha256', 'sha512', etc. On recent releases, openssl list-message-digest-algorithms will display the available digest algorithms.

    Example: this program that takes the sha1 sum of a file

    var filename = process.argv[2];
    var crypto = require('crypto');
    var fs = require('fs');
    
    var shasum = crypto.createHash('sha1');
    
    var s = fs.ReadStream(filename);
    s.on('data', function(d) {
      shasum.update(d);
    });
    
    s.on('end', function() {
      var d = shasum.digest('hex');
      console.log(d + '  ' + filename);
    });

    Class: Hash#

    The class for creating hash digests of data.

    It is a stream that is both readable and writable. The written data is used to compute the hash. Once the writable side of the stream is ended, use the read() method to get the computed hash digest. The legacy update and digest methods are also supported.

    Returned by crypto.createHash.

    hash.update(data, [input_encoding])#

    Updates the hash content with the given data, the encoding of which is given in input_encoding and can be 'utf8', 'ascii' or 'binary'. If no encoding is provided and the input is a string an encoding of 'binary' is enforced. If data is a Buffer then input_encoding is ignored.

    This can be called many times with new data as it is streamed.

    hash.digest([encoding])#

    Calculates the digest of all of the passed data to be hashed. The encoding can be 'hex', 'binary' or 'base64'. If no encoding is provided, then a buffer is returned.

    Note: hash object can not be used after digest() method has been called.

    crypto.createHmac(algorithm, key)#

    Creates and returns a hmac object, a cryptographic hmac with the given algorithm and key.

    It is a stream that is both readable and writable. The written data is used to compute the hmac. Once the writable side of the stream is ended, use the read() method to get the computed digest. The legacy update and digest methods are also supported.

    algorithm is dependent on the available algorithms supported by OpenSSL - see createHash above. key is the hmac key to be used.

    Class: Hmac#

    Class for creating cryptographic hmac content.

    Returned by crypto.createHmac.

    hmac.update(data)#

    Update the hmac content with the given data. This can be called many times with new data as it is streamed.

    hmac.digest([encoding])#

    Calculates the digest of all of the passed data to the hmac. The encoding can be 'hex', 'binary' or 'base64'. If no encoding is provided, then a buffer is returned.

    Note: hmac object can not be used after digest() method has been called.

    crypto.createCipher(algorithm, password)#

    Creates and returns a cipher object, with the given algorithm and password.

    algorithm is dependent on OpenSSL, examples are 'aes192', etc. On recent releases, openssl list-cipher-algorithms will display the available cipher algorithms. password is used to derive key and IV, which must be a 'binary' encoded string or a buffer.

    It is a stream that is both readable and writable. The written data is used to compute the hash. Once the writable side of the stream is ended, use the read() method to get the computed hash digest. The legacy update and digest methods are also supported.

    crypto.createCipheriv(algorithm, key, iv)#

    Creates and returns a cipher object, with the given algorithm, key and iv.

    algorithm is the same as the argument to createCipher(). key is the raw key used by the algorithm. iv is an initialization vector.

    key and iv must be 'binary' encoded strings or buffers.

    Class: Cipher#

    Class for encrypting data.

    Returned by crypto.createCipher and crypto.createCipheriv.

    Cipher objects are streams that are both readable and writable. The written plain text data is used to produce the encrypted data on the readable side. The legacy update and final methods are also supported.

    cipher.update(data, [input_encoding], [output_encoding])#

    Updates the cipher with data, the encoding of which is given in input_encoding and can be 'utf8', 'ascii' or 'binary'. If no encoding is provided, then a buffer is expected. If data is a Buffer then input_encoding is ignored.

    The output_encoding specifies the output format of the enciphered data, and can be 'binary', 'base64' or 'hex'. If no encoding is provided, then a buffer is returned.

    Returns the enciphered contents, and can be called many times with new data as it is streamed.

    cipher.final([output_encoding])#

    Returns any remaining enciphered contents, with output_encoding being one of: 'binary', 'base64' or 'hex'. If no encoding is provided, then a buffer is returned.

    Note: cipher object can not be used after final() method has been called.

    cipher.setAutoPadding(auto_padding=true)#

    You can disable automatic padding of the input data to block size. If auto_padding is false, the length of the entire input data must be a multiple of the cipher's block size or final will fail. Useful for non-standard padding, e.g. using 0x0 instead of PKCS padding. You must call this before cipher.final.

    crypto.createDecipher(algorithm, password)#

    Creates and returns a decipher object, with the given algorithm and key. This is the mirror of the createCipher() above.

    crypto.createDecipheriv(algorithm, key, iv)#

    Creates and returns a decipher object, with the given algorithm, key and iv. This is the mirror of the createCipheriv() above.

    Class: Decipher#

    Class for decrypting data.

    Returned by crypto.createDecipher and crypto.createDecipheriv.

    Decipher objects are streams that are both readable and writable. The written enciphered data is used to produce the plain-text data on the the readable side. The legacy update and final methods are also supported.

    decipher.update(data, [input_encoding], [output_encoding])#

    Updates the decipher with data, which is encoded in 'binary', 'base64' or 'hex'. If no encoding is provided, then a buffer is expected. If data is a Buffer then input_encoding is ignored.

    The output_decoding specifies in what format to return the deciphered plaintext: 'binary', 'ascii' or 'utf8'. If no encoding is provided, then a buffer is returned.

    decipher.final([output_encoding])#

    Returns any remaining plaintext which is deciphered, with output_encoding being one of: 'binary', 'ascii' or 'utf8'. If no encoding is provided, then a buffer is returned.

    Note: decipher object can not be used after final() method has been called.

    decipher.setAutoPadding(auto_padding=true)#

    You can disable auto padding if the data has been encrypted without standard block padding to prevent decipher.final from checking and removing it. Can only work if the input data's length is a multiple of the ciphers block size. You must call this before streaming data to decipher.update.

    crypto.createSign(algorithm)#

    Creates and returns a signing object, with the given algorithm. On recent OpenSSL releases, openssl list-public-key-algorithms will display the available signing algorithms. Examples are 'RSA-SHA256'.

    Class: Sign#

    Class for generating signatures.

    Returned by crypto.createSign.

    Sign objects are writable streams. The written data is used to generate the signature. Once all of the data has been written, the sign method will return the signature. The legacy update method is also supported.

    sign.update(data)#

    Updates the sign object with data. This can be called many times with new data as it is streamed.

    sign.sign(private_key, [output_format])#

    Calculates the signature on all the updated data passed through the sign. private_key is a string containing the PEM encoded private key for signing.

    Returns the signature in output_format which can be 'binary', 'hex' or 'base64'. If no encoding is provided, then a buffer is returned.

    Note: sign object can not be used after sign() method has been called.

    crypto.createVerify(algorithm)#

    Creates and returns a verification object, with the given algorithm. This is the mirror of the signing object above.

    Class: Verify#

    Class for verifying signatures.

    Returned by crypto.createVerify.

    Verify objects are writable streams. The written data is used to validate against the supplied signature. Once all of the data has been written, the verify method will return true if the supplied signature is valid. The legacy update method is also supported.

    verifier.update(data)#

    Updates the verifier object with data. This can be called many times with new data as it is streamed.

    verifier.verify(object, signature, [signature_format])#

    Verifies the signed data by using the object and signature. object is a string containing a PEM encoded object, which can be one of RSA public key, DSA public key, or X.509 certificate. signature is the previously calculated signature for the data, in the signature_format which can be 'binary', 'hex' or 'base64'. If no encoding is specified, then a buffer is expected.

    Returns true or false depending on the validity of the signature for the data and public key.

    Note: verifier object can not be used after verify() method has been called.

    crypto.createDiffieHellman(prime_length)#

    Creates a Diffie-Hellman key exchange object and generates a prime of the given bit length. The generator used is 2.

    crypto.createDiffieHellman(prime, [encoding])#

    Creates a Diffie-Hellman key exchange object using the supplied prime. The generator used is 2. Encoding can be 'binary', 'hex', or 'base64'. If no encoding is specified, then a buffer is expected.

    Class: DiffieHellman#

    The class for creating Diffie-Hellman key exchanges.

    Returned by crypto.createDiffieHellman.

    diffieHellman.generateKeys([encoding])#

    Generates private and public Diffie-Hellman key values, and returns the public key in the specified encoding. This key should be transferred to the other party. Encoding can be 'binary', 'hex', or 'base64'. If no encoding is provided, then a buffer is returned.

    diffieHellman.computeSecret(other_public_key, [input_encoding], [output_encoding])#

    Computes the shared secret using other_public_key as the other party's public key and returns the computed shared secret. Supplied key is interpreted using specified input_encoding, and secret is encoded using specified output_encoding. Encodings can be 'binary', 'hex', or 'base64'. If the input encoding is not provided, then a buffer is expected.

    If no output encoding is given, then a buffer is returned.

    diffieHellman.getPrime([encoding])#

    Returns the Diffie-Hellman prime in the specified encoding, which can be 'binary', 'hex', or 'base64'. If no encoding is provided, then a buffer is returned.

    diffieHellman.getGenerator([encoding])#

    Returns the Diffie-Hellman prime in the specified encoding, which can be 'binary', 'hex', or 'base64'. If no encoding is provided, then a buffer is returned.

    diffieHellman.getPublicKey([encoding])#

    Returns the Diffie-Hellman public key in the specified encoding, which can be 'binary', 'hex', or 'base64'. If no encoding is provided, then a buffer is returned.

    diffieHellman.getPrivateKey([encoding])#

    Returns the Diffie-Hellman private key in the specified encoding, which can be 'binary', 'hex', or 'base64'. If no encoding is provided, then a buffer is returned.

    diffieHellman.setPublicKey(public_key, [encoding])#

    Sets the Diffie-Hellman public key. Key encoding can be 'binary', 'hex' or 'base64'. If no encoding is provided, then a buffer is expected.

    diffieHellman.setPrivateKey(private_key, [encoding])#

    Sets the Diffie-Hellman private key. Key encoding can be 'binary', 'hex' or 'base64'. If no encoding is provided, then a buffer is expected.

    crypto.getDiffieHellman(group_name)#

    Creates a predefined Diffie-Hellman key exchange object. The supported groups are: 'modp1', 'modp2', 'modp5' (defined in RFC 2412) and 'modp14', 'modp15', 'modp16', 'modp17', 'modp18' (defined in RFC 3526). The returned object mimics the interface of objects created by crypto.createDiffieHellman() above, but will not allow to change the keys (with diffieHellman.setPublicKey() for example). The advantage of using this routine is that the parties don't have to generate nor exchange group modulus beforehand, saving both processor and communication time.

    Example (obtaining a shared secret):

    var crypto = require('crypto');
    var alice = crypto.getDiffieHellman('modp5');
    var bob = crypto.getDiffieHellman('modp5');
    
    alice.generateKeys();
    bob.generateKeys();
    
    var alice_secret = alice.computeSecret(bob.getPublicKey(), null, 'hex');
    var bob_secret = bob.computeSecret(alice.getPublicKey(), null, 'hex');
    
    /* alice_secret and bob_secret should be the same */
    console.log(alice_secret == bob_secret);

    crypto.pbkdf2(password, salt, iterations, keylen, callback)#

    Asynchronous PBKDF2 applies pseudorandom function HMAC-SHA1 to derive a key of given length from the given password, salt and iterations. The callback gets two arguments (err, derivedKey).

    crypto.pbkdf2Sync(password, salt, iterations, keylen)#

    Synchronous PBKDF2 function. Returns derivedKey or throws error.

    crypto.randomBytes(size, [callback])#

    Generates cryptographically strong pseudo-random data. Usage:

    // async
    crypto.randomBytes(256, function(ex, buf) {
      if (ex) throw ex;
      console.log('Have %d bytes of random data: %s', buf.length, buf);
    });
    
    // sync
    try {
      var buf = crypto.randomBytes(256);
      console.log('Have %d bytes of random data: %s', buf.length, buf);
    } catch (ex) {
      // handle error
      // most likely, entropy sources are drained
    }

    NOTE: Will throw error or invoke callback with error, if there is not enough accumulated entropy to generate cryptographically strong data. In other words, crypto.randomBytes without callback will not block even if all entropy sources are drained.

    crypto.pseudoRandomBytes(size, [callback])#

    Generates non-cryptographically strong pseudo-random data. The data returned will be unique if it is sufficiently long, but is not necessarily unpredictable. For this reason, the output of this function should never be used where unpredictability is important, such as in the generation of encryption keys.

    Usage is otherwise identical to crypto.randomBytes.

    crypto.DEFAULT_ENCODING#

    The default encoding to use for functions that can take either strings or buffers. The default value is 'buffer', which makes it default to using Buffer objects. This is here to make the crypto module more easily compatible with legacy programs that expected 'binary' to be the default encoding.

    Note that new programs will probably expect buffers, so only use this as a temporary measure.

    Recent API Changes#

    The Crypto module was added to Node before there was the concept of a unified Stream API, and before there were Buffer objects for handling binary data.

    As such, the streaming classes don't have the typical methods found on other Node classes, and many methods accepted and returned Binary-encoded strings by default rather than Buffers. This was changed to use Buffers by default instead.

    This is a breaking change for some use cases, but not all.

    For example, if you currently use the default arguments to the Sign class, and then pass the results to the Verify class, without ever inspecting the data, then it will continue to work as before. Where you once got a binary string and then presented the binary string to the Verify object, you'll now get a Buffer, and present the Buffer to the Verify object.

    However, if you were doing things with the string data that will not work properly on Buffers (such as, concatenating them, storing in databases, etc.), or you are passing binary strings to the crypto functions without an encoding argument, then you will need to start providing encoding arguments to specify which encoding you'd like to use. To switch to the previous style of using binary strings by default, set the crypto.DEFAULT_ENCODING field to 'binary'. Note that new programs will probably expect buffers, so only use this as a temporary measure.

    TLS (SSL)#

    Stability: 3 - Stable

    Use require('tls') to access this module.

    The tls module uses OpenSSL to provide Transport Layer Security and/or Secure Socket Layer: encrypted stream communication.

    TLS/SSL is a public/private key infrastructure. Each client and each server must have a private key. A private key is created like this

    openssl genrsa -out ryans-key.pem 1024

    All severs and some clients need to have a certificate. Certificates are public keys signed by a Certificate Authority or self-signed. The first step to getting a certificate is to create a "Certificate Signing Request" (CSR) file. This is done with:

    openssl req -new -key ryans-key.pem -out ryans-csr.pem

    To create a self-signed certificate with the CSR, do this:

    openssl x509 -req -in ryans-csr.pem -signkey ryans-key.pem -out ryans-cert.pem

    Alternatively you can send the CSR to a Certificate Authority for signing.

    (TODO: docs on creating a CA, for now interested users should just look at test/fixtures/keys/Makefile in the Node source code)

    To create .pfx or .p12, do this:

    openssl pkcs12 -export -in agent5-cert.pem -inkey agent5-key.pem \
        -certfile ca-cert.pem -out agent5.pfx
    • in: certificate
    • inkey: private key
    • certfile: all CA certs concatenated in one file like cat ca1-cert.pem ca2-cert.pem > ca-cert.pem

    Client-initiated renegotiation attack mitigation#

    The TLS protocol lets the client renegotiate certain aspects of the TLS session. Unfortunately, session renegotiation requires a disproportional amount of server-side resources, which makes it a potential vector for denial-of-service attacks.

    To mitigate this, renegotiations are limited to three times every 10 minutes. An error is emitted on the CleartextStream instance when the threshold is exceeded. The limits are configurable:

    • tls.CLIENT_RENEG_LIMIT: renegotiation limit, default is 3.

    • tls.CLIENT_RENEG_WINDOW: renegotiation window in seconds, default is 10 minutes.

    Don't change the defaults unless you know what you are doing.

    To test your server, connect to it with openssl s_client -connect address:port and tap R<CR> (that's the letter R followed by a carriage return) a few times.

    NPN and SNI#

    NPN (Next Protocol Negotiation) and SNI (Server Name Indication) are TLS handshake extensions allowing you:

    • NPN - to use one TLS server for multiple protocols (HTTP, SPDY)
    • SNI - to use one TLS server for multiple hostnames with different SSL certificates.

    tls.getCiphers()#

    Returns an array with the names of the supported SSL ciphers.

    Example:

    var ciphers = tls.getCiphers();
    console.log(ciphers); // ['AES128-SHA', 'AES256-SHA', ...]

    tls.createServer(options, [secureConnectionListener])#

    Creates a new tls.Server. The connectionListener argument is automatically set as a listener for the secureConnection event. The options object has these possibilities:

    • pfx: A string or Buffer containing the private key, certificate and CA certs of the server in PFX or PKCS12 format. (Mutually exclusive with the key, cert and ca options.)

    • key: A string or Buffer containing the private key of the server in PEM format. (Required)

    • passphrase: A string of passphrase for the private key or pfx.

    • cert: A string or Buffer containing the certificate key of the server in PEM format. (Required)

    • ca: An array of strings or Buffers of trusted certificates in PEM format. If this is omitted several well known "root" CAs will be used, like VeriSign. These are used to authorize connections.

    • crl : Either a string or list of strings of PEM encoded CRLs (Certificate Revocation List)

    • ciphers: A string describing the ciphers to use or exclude.

      To mitigate BEAST attacks it is recommended that you use this option in conjunction with the honorCipherOrder option described below to prioritize the non-CBC cipher.

      Defaults to AES128-GCM-SHA256:RC4:HIGH:!MD5:!aNULL:!EDH. Consult the OpenSSL cipher list format documentation for details on the format. ECDH (Elliptic Curve Diffie-Hellman) ciphers are not yet supported.

    `AES128-GCM-SHA256` is used when node.js is linked against OpenSSL 1.0.1
    or newer and the client speaks TLS 1.2, RC4 is used as a secure fallback.
    
    **NOTE**: Previous revisions of this section suggested `AES256-SHA` as an
    acceptable cipher. Unfortunately, `AES256-SHA` is a CBC cipher and therefore
    susceptible to BEAST attacks. Do *not* use it.
    • handshakeTimeout: Abort the connection if the SSL/TLS handshake does not finish in this many milliseconds. The default is 120 seconds.

      A 'clientError' is emitted on the tls.Server object whenever a handshake times out.

    • honorCipherOrder : When choosing a cipher, use the server's preferences instead of the client preferences.

      Note that if SSLv2 is used, the server will send its list of preferences to the client, and the client chooses the cipher.

      Although, this option is disabled by default, it is recommended that you use this option in conjunction with the ciphers option to mitigate BEAST attacks.

    • requestCert: If true the server will request a certificate from clients that connect and attempt to verify that certificate. Default: false.

    • rejectUnauthorized: If true the server will reject any connection which is not authorized with the list of supplied CAs. This option only has an effect if requestCert is true. Default: false.

    • NPNProtocols: An array or Buffer of possible NPN protocols. (Protocols should be ordered by their priority).

    • SNICallback: A function that will be called if client supports SNI TLS extension. Only one argument will be passed to it: servername. And SNICallback should return SecureContext instance. (You can use crypto.createCredentials(...).context to get proper SecureContext). If SNICallback wasn't provided - default callback with high-level API will be used (see below).

    • sessionIdContext: A string containing a opaque identifier for session resumption. If requestCert is true, the default is MD5 hash value generated from command-line. Otherwise, the default is not provided.

    • secureProtocol: The SSL method to use, e.g. SSLv3_method to force SSL version 3. The possible values depend on your installation of OpenSSL and are defined in the constant SSL_METHODS.

    Here is a simple example echo server:

    var tls = require('tls');
    var fs = require('fs');
    
    var options = {
      key: fs.readFileSync('server-key.pem'),
      cert: fs.readFileSync('server-cert.pem'),
    
      // This is necessary only if using the client certificate authentication.
      requestCert: true,
    
      // This is necessary only if the client uses the self-signed certificate.
      ca: [ fs.readFileSync('client-cert.pem') ]
    };
    
    var server = tls.createServer(options, function(cleartextStream) {
      console.log('server connected',
                  cleartextStream.authorized ? 'authorized' : 'unauthorized');
      cleartextStream.write("welcome!\n");
      cleartextStream.setEncoding('utf8');
      cleartextStream.pipe(cleartextStream);
    });
    server.listen(8000, function() {
      console.log('server bound');
    });

    Or

    var tls = require('tls');
    var fs = require('fs');
    
    var options = {
      pfx: fs.readFileSync('server.pfx'),
    
      // This is necessary only if using the client certificate authentication.
      requestCert: true,
    
    };
    
    var server = tls.createServer(options, function(cleartextStream) {
      console.log('server connected',
                  cleartextStream.authorized ? 'authorized' : 'unauthorized');
      cleartextStream.write("welcome!\n");
      cleartextStream.setEncoding('utf8');
      cleartextStream.pipe(cleartextStream);
    });
    server.listen(8000, function() {
      console.log('server bound');
    });

    You can test this server by connecting to it with openssl s_client:

    openssl s_client -connect 127.0.0.1:8000

    tls.SLAB_BUFFER_SIZE#

    Size of slab buffer used by all tls servers and clients. Default: 10 * 1024 * 1024.

    Don't change the defaults unless you know what you are doing.

    tls.connect(options, [callback])#

    tls.connect(port, [host], [options], [callback])#

    Creates a new client connection to the given port and host (old API) or options.port and options.host. (If host is omitted, it defaults to localhost.) options should be an object which specifies:

    • host: Host the client should connect to

    • port: Port the client should connect to

    • socket: Establish secure connection on a given socket rather than creating a new socket. If this option is specified, host and port are ignored.

    • pfx: A string or Buffer containing the private key, certificate and CA certs of the server in PFX or PKCS12 format.

    • key: A string or Buffer containing the private key of the client in PEM format.

    • passphrase: A string of passphrase for the private key or pfx.

    • cert: A string or Buffer containing the certificate key of the client in PEM format.

    • ca: An array of strings or Buffers of trusted certificates in PEM format. If this is omitted several well known "root" CAs will be used, like VeriSign. These are used to authorize connections.

    • rejectUnauthorized: If true, the server certificate is verified against the list of supplied CAs. An 'error' event is emitted if verification fails. Default: true.

    • NPNProtocols: An array of strings or Buffers containing supported NPN protocols. Buffers should have following format: 0x05hello0x05world, where first byte is next protocol name's length. (Passing array should usually be much simpler: ['hello', 'world'].)

    • servername: Servername for SNI (Server Name Indication) TLS extension.

    • secureProtocol: The SSL method to use, e.g. SSLv3_method to force SSL version 3. The possible values depend on your installation of OpenSSL and are defined in the constant SSL_METHODS.

    The callback parameter will be added as a listener for the 'secureConnect' event.

    tls.connect() returns a CleartextStream object.

    Here is an example of a client of echo server as described previously:

    var tls = require('tls');
    var fs = require('fs');
    
    var options = {
      // These are necessary only if using the client certificate authentication
      key: fs.readFileSync('client-key.pem'),
      cert: fs.readFileSync('client-cert.pem'),
    
      // This is necessary only if the server uses the self-signed certificate
      ca: [ fs.readFileSync('server-cert.pem') ]
    };
    
    var cleartextStream = tls.connect(8000, options, function() {
      console.log('client connected',
                  cleartextStream.authorized ? 'authorized' : 'unauthorized');
      process.stdin.pipe(cleartextStream);
      process.stdin.resume();
    });
    cleartextStream.setEncoding('utf8');
    cleartextStream.on('data', function(data) {
      console.log(data);
    });
    cleartextStream.on('end', function() {
      server.close();
    });

    Or

    var tls = require('tls');
    var fs = require('fs');
    
    var options = {
      pfx: fs.readFileSync('client.pfx')
    };
    
    var cleartextStream = tls.connect(8000, options, function() {
      console.log('client connected',
                  cleartextStream.authorized ? 'authorized' : 'unauthorized');
      process.stdin.pipe(cleartextStream);
      process.stdin.resume();
    });
    cleartextStream.setEncoding('utf8');
    cleartextStream.on('data', function(data) {
      console.log(data);
    });
    cleartextStream.on('end', function() {
      server.close();
    });

    tls.createSecurePair([credentials], [isServer], [requestCert], [rejectUnauthorized])#

    Creates a new secure pair object with two streams, one of which reads/writes encrypted data, and one reads/writes cleartext data. Generally the encrypted one is piped to/from an incoming encrypted data stream, and the cleartext one is used as a replacement for the initial encrypted stream.

    • credentials: A credentials object from crypto.createCredentials( ... )

    • isServer: A boolean indicating whether this tls connection should be opened as a server or a client.

    • requestCert: A boolean indicating whether a server should request a certificate from a connecting client. Only applies to server connections.

    • rejectUnauthorized: A boolean indicating whether a server should automatically reject clients with invalid certificates. Only applies to servers with requestCert enabled.

    tls.createSecurePair() returns a SecurePair object with [cleartext][] and encrypted stream properties.

    Class: SecurePair#

    Returned by tls.createSecurePair.

    Event: 'secure'#

    The event is emitted from the SecurePair once the pair has successfully established a secure connection.

    Similarly to the checking for the server 'secureConnection' event, pair.cleartext.authorized should be checked to confirm whether the certificate used properly authorized.

    Class: tls.Server#

    This class is a subclass of net.Server and has the same methods on it. Instead of accepting just raw TCP connections, this accepts encrypted connections using TLS or SSL.

    Event: 'secureConnection'#

    function (cleartextStream) {}

    This event is emitted after a new connection has been successfully handshaked. The argument is a instance of CleartextStream. It has all the common stream methods and events.

    cleartextStream.authorized is a boolean value which indicates if the client has verified by one of the supplied certificate authorities for the server. If cleartextStream.authorized is false, then cleartextStream.authorizationError is set to describe how authorization failed. Implied but worth mentioning: depending on the settings of the TLS server, you unauthorized connections may be accepted. cleartextStream.npnProtocol is a string containing selected NPN protocol. cleartextStream.servername is a string containing servername requested with SNI.

    Event: 'clientError'#

    function (exception, securePair) { }

    When a client connection emits an 'error' event before secure connection is established - it will be forwarded here.

    securePair is the tls.SecurePair that the error originated from.

    Event: 'newSession'#

    function (sessionId, sessionData) { }

    Emitted on creation of TLS session. May be used to store sessions in external storage.

    Event: 'resumeSession'#

    function (sessionId, callback) { }

    Emitted when client wants to resume previous TLS session. Event listener may perform lookup in external storage using given sessionId, and invoke callback(null, sessionData) once finished. If session can't be resumed (i.e. doesn't exist in storage) one may call callback(null, null). Calling callback(err) will terminate incoming connection and destroy socket.

    server.listen(port, [host], [callback])#

    Begin accepting connections on the specified port and host. If the host is omitted, the server will accept connections directed to any IPv4 address (INADDR_ANY).

    This function is asynchronous. The last parameter callback will be called when the server has been bound.

    See net.Server for more information.

    server.close()#

    Stops the server from accepting new connections. This function is asynchronous, the server is finally closed when the server emits a 'close' event.

    server.address()#

    Returns the bound address, the address family name and port of the server as reported by the operating system. See net.Server.address() for more information.

    server.addContext(hostname, credentials)#

    Add secure context that will be used if client request's SNI hostname is matching passed hostname (wildcards can be used). credentials can contain key, cert and ca.

    server.maxConnections#

    Set this property to reject connections when the server's connection count gets high.

    server.connections#

    The number of concurrent connections on the server.

    Class: CryptoStream#

    This is an encrypted stream.

    cryptoStream.bytesWritten#

    A proxy to the underlying socket's bytesWritten accessor, this will return the total bytes written to the socket, including the TLS overhead.

    Class: tls.CleartextStream#

    This is a stream on top of the Encrypted stream that makes it possible to read/write an encrypted data as a cleartext data.

    This instance implements a duplex Stream interfaces. It has all the common stream methods and events.

    A ClearTextStream is the clear member of a SecurePair object.

    Event: 'secureConnect'#

    This event is emitted after a new connection has been successfully handshaked. The listener will be called no matter if the server's certificate was authorized or not. It is up to the user to test cleartextStream.authorized to see if the server certificate was signed by one of the specified CAs. If cleartextStream.authorized === false then the error can be found in cleartextStream.authorizationError. Also if NPN was used - you can check cleartextStream.npnProtocol for negotiated protocol.

    cleartextStream.authorized#

    A boolean that is true if the peer certificate was signed by one of the specified CAs, otherwise false

    cleartextStream.authorizationError#

    The reason why the peer's certificate has not been verified. This property becomes available only when cleartextStream.authorized === false.

    cleartextStream.getPeerCertificate()#

    Returns an object representing the peer's certificate. The returned object has some properties corresponding to the field of the certificate.

    Example:

    { subject: 
       { C: 'UK',
         ST: 'Acknack Ltd',
         L: 'Rhys Jones',
         O: 'node.js',
         OU: 'Test TLS Certificate',
         CN: 'localhost' },
      issuer: 
       { C: 'UK',
         ST: 'Acknack Ltd',
         L: 'Rhys Jones',
         O: 'node.js',
         OU: 'Test TLS Certificate',
         CN: 'localhost' },
      valid_from: 'Nov 11 09:52:22 2009 GMT',
      valid_to: 'Nov  6 09:52:22 2029 GMT',
      fingerprint: '2A:7A:C2:DD:E5:F9:CC:53:72:35:99:7A:02:5A:71:38:52:EC:8A:DF' }

    If the peer does not provide a certificate, it returns null or an empty object.

    cleartextStream.getCipher()#

    Returns an object representing the cipher name and the SSL/TLS protocol version of the current connection.

    Example: { name: 'AES256-SHA', version: 'TLSv1/SSLv3' }

    See SSL_CIPHER_get_name() and SSL_CIPHER_get_version() in http://www.openssl.org/docs/ssl/ssl.html#DEALING_WITH_CIPHERS for more information.

    cleartextStream.address()#

    Returns the bound address, the address family name and port of the underlying socket as reported by the operating system. Returns an object with three properties, e.g. { port: 12346, family: 'IPv4', address: '127.0.0.1' }

    cleartextStream.remoteAddress#

    The string representation of the remote IP address. For example, '74.125.127.100' or '2001:4860:a005::68'.

    cleartextStream.remotePort#

    The numeric representation of the remote port. For example, 443.

    StringDecoder#

    Stability: 3 - Stable

    To use this module, do require('string_decoder'). StringDecoder decodes a buffer to a string. It is a simple interface to buffer.toString() but provides additional support for utf8.

    var StringDecoder = require('string_decoder').StringDecoder;
    var decoder = new StringDecoder('utf8');
    
    var cent = new Buffer([0xC2, 0xA2]);
    console.log(decoder.write(cent));
    
    var euro = new Buffer([0xE2, 0x82, 0xAC]);
    console.log(decoder.write(euro));

    Class: StringDecoder#

    Accepts a single argument, encoding which defaults to utf8.

    decoder.write(buffer)#

    Returns a decoded string.

    decoder.end()#

    Returns any trailing bytes that were left in the buffer.

    File System#

    Stability: 3 - Stable

    File I/O is provided by simple wrappers around standard POSIX functions. To use this module do require('fs'). All the methods have asynchronous and synchronous forms.

    The asynchronous form always take a completion callback as its last argument. The arguments passed to the completion callback depend on the method, but the first argument is always reserved for an exception. If the operation was completed successfully, then the first argument will be null or undefined.

    When using the synchronous form any exceptions are immediately thrown. You can use try/catch to handle exceptions or allow them to bubble up.

    Here is an example of the asynchronous version:

    var fs = require('fs');
    
    fs.unlink('/tmp/hello', function (err) {
      if (err) throw err;
      console.log('successfully deleted /tmp/hello');
    });

    Here is the synchronous version:

    var fs = require('fs');
    
    fs.unlinkSync('/tmp/hello')
    console.log('successfully deleted /tmp/hello');

    With the asynchronous methods there is no guaranteed ordering. So the following is prone to error:

    fs.rename('/tmp/hello', '/tmp/world', function (err) {
      if (err) throw err;
      console.log('renamed complete');
    });
    fs.stat('/tmp/world', function (err, stats) {
      if (err) throw err;
      console.log('stats: ' + JSON.stringify(stats));
    });

    It could be that fs.stat is executed before fs.rename. The correct way to do this is to chain the callbacks.

    fs.rename('/tmp/hello', '/tmp/world', function (err) {
      if (err) throw err;
      fs.stat('/tmp/world', function (err, stats) {
        if (err) throw err;
        console.log('stats: ' + JSON.stringify(stats));
      });
    });

    In busy processes, the programmer is strongly encouraged to use the asynchronous versions of these calls. The synchronous versions will block the entire process until they complete--halting all connections.

    Relative path to filename can be used, remember however that this path will be relative to process.cwd().

    Most fs functions let you omit the callback argument. If you do, a default callback is used that ignores errors, but prints a deprecation warning.

    IMPORTANT: Omitting the callback is deprecated. v0.12 will throw the errors as exceptions.

    fs.rename(oldPath, newPath, callback)#

    Asynchronous rename(2). No arguments other than a possible exception are given to the completion callback.

    fs.renameSync(oldPath, newPath)#

    Synchronous rename(2).

    fs.ftruncate(fd, len, callback)#

    Asynchronous ftruncate(2). No arguments other than a possible exception are given to the completion callback.

    fs.ftruncateSync(fd, len)#

    Synchronous ftruncate(2).

    fs.truncate(path, len, callback)#

    Asynchronous truncate(2). No arguments other than a possible exception are given to the completion callback.

    fs.truncateSync(path, len)#

    Synchronous truncate(2).

    fs.chown(path, uid, gid, callback)#

    Asynchronous chown(2). No arguments other than a possible exception are given to the completion callback.

    fs.chownSync(path, uid, gid)#

    Synchronous chown(2).

    fs.fchown(fd, uid, gid, callback)#

    Asynchronous fchown(2). No arguments other than a possible exception are given to the completion callback.

    fs.fchownSync(fd, uid, gid)#

    Synchronous fchown(2).

    fs.lchown(path, uid, gid, callback)#

    Asynchronous lchown(2). No arguments other than a possible exception are given to the completion callback.

    fs.lchownSync(path, uid, gid)#

    Synchronous lchown(2).

    fs.chmod(path, mode, callback)#

    Asynchronous chmod(2). No arguments other than a possible exception are given to the completion callback.

    fs.chmodSync(path, mode)#

    Synchronous chmod(2).

    fs.fchmod(fd, mode, callback)#

    Asynchronous fchmod(2). No arguments other than a possible exception are given to the completion callback.

    fs.fchmodSync(fd, mode)#

    Synchronous fchmod(2).

    fs.lchmod(path, mode, callback)#

    Asynchronous lchmod(2). No arguments other than a possible exception are given to the completion callback.

    Only available on Mac OS X.

    fs.lchmodSync(path, mode)#

    Synchronous lchmod(2).

    fs.stat(path, callback)#

    Asynchronous stat(2). The callback gets two arguments (err, stats) where stats is a fs.Stats object. See the fs.Stats section below for more information.

    fs.lstat(path, callback)#

    Asynchronous lstat(2). The callback gets two arguments (err, stats) where stats is a fs.Stats object. lstat() is identical to stat(), except that if path is a symbolic link, then the link itself is stat-ed, not the file that it refers to.

    fs.fstat(fd, callback)#

    Asynchronous fstat(2). The callback gets two arguments (err, stats) where stats is a fs.Stats object. fstat() is identical to stat(), except that the file to be stat-ed is specified by the file descriptor fd.

    fs.statSync(path)#

    Synchronous stat(2). Returns an instance of fs.Stats.

    fs.lstatSync(path)#

    Synchronous lstat(2). Returns an instance of fs.Stats.

    fs.fstatSync(fd)#

    Synchronous fstat(2). Returns an instance of fs.Stats.

    fs.link(srcpath, dstpath, callback)#

    Asynchronous link(2). No arguments other than a possible exception are given to the completion callback.

    fs.linkSync(srcpath, dstpath)#

    Synchronous link(2).

    fs.symlink(srcpath, dstpath, [type], callback)#

    Asynchronous symlink(2). No arguments other than a possible exception are given to the completion callback. The type argument can be set to 'dir', 'file', or 'junction' (default is 'file') and is only available on Windows (ignored on other platforms). Note that Windows junction points require the destination path to be absolute. When using 'junction', the destination argument will automatically be normalized to absolute path.

    fs.symlinkSync(srcpath, dstpath, [type])#

    Synchronous symlink(2).

    fs.readlink(path, callback)#

    Asynchronous readlink(2). The callback gets two arguments (err, linkString).

    fs.readlinkSync(path)#

    Synchronous readlink(2). Returns the symbolic link's string value.

    fs.realpath(path, [cache], callback)#

    Asynchronous realpath(2). The callback gets two arguments (err, resolvedPath). May use process.cwd to resolve relative paths. cache is an object literal of mapped paths that can be used to force a specific path resolution or avoid additional fs.stat calls for known real paths.

    Example:

    var cache = {'/etc':'/private/etc'};
    fs.realpath('/etc/passwd', cache, function (err, resolvedPath) {
      if (err) throw err;
      console.log(resolvedPath);
    });

    fs.realpathSync(path, [cache])#

    Synchronous realpath(2). Returns the resolved path.

    fs.unlink(path, callback)#

    Asynchronous unlink(2). No arguments other than a possible exception are given to the completion callback.

    fs.unlinkSync(path)#

    Synchronous unlink(2).

    fs.rmdir(path, callback)#

    Asynchronous rmdir(2). No arguments other than a possible exception are given to the completion callback.

    fs.rmdirSync(path)#

    Synchronous rmdir(2).

    fs.mkdir(path, [mode], callback)#

    Asynchronous mkdir(2). No arguments other than a possible exception are given to the completion callback. mode defaults to 0777.

    fs.mkdirSync(path, [mode])#

    Synchronous mkdir(2).

    fs.readdir(path, callback)#

    Asynchronous readdir(3). Reads the contents of a directory. The callback gets two arguments (err, files) where files is an array of the names of the files in the directory excluding '.' and '..'.

    fs.readdirSync(path)#

    Synchronous readdir(3). Returns an array of filenames excluding '.' and '..'.

    fs.close(fd, callback)#

    Asynchronous close(2). No arguments other than a possible exception are given to the completion callback.

    fs.closeSync(fd)#

    Synchronous close(2).

    fs.open(path, flags, [mode], callback)#

    Asynchronous file open. See open(2). flags can be:

    • 'r' - Open file for reading. An exception occurs if the file does not exist.

    • 'r+' - Open file for reading and writing. An exception occurs if the file does not exist.

    • 'rs' - Open file for reading in synchronous mode. Instructs the operating system to bypass the local file system cache.

      This is primarily useful for opening files on NFS mounts as it allows you to skip the potentially stale local cache. It has a very real impact on I/O performance so don't use this flag unless you need it.

      Note that this doesn't turn fs.open() into a synchronous blocking call. If that's what you want then you should be using fs.openSync()

    • 'rs+' - Open file for reading and writing, telling the OS to open it synchronously. See notes for 'rs' about using this with caution.

    • 'w' - Open file for writing. The file is created (if it does not exist) or truncated (if it exists).

    • 'wx' - Like 'w' but fails if path exists.

    • 'w+' - Open file for reading and writing. The file is created (if it does not exist) or truncated (if it exists).

    • 'wx+' - Like 'w+' but fails if path exists.

    • 'a' - Open file for appending. The file is created if it does not exist.

    • 'ax' - Like 'a' but fails if path exists.

    • 'a+' - Open file for reading and appending. The file is created if it does not exist.

    • 'ax+' - Like 'a+' but fails if path exists.

    mode sets the file mode (permission and sticky bits), but only if the file was created. It defaults to 0666, readable and writeable.

    The callback gets two arguments (err, fd).

    The exclusive flag 'x' (O_EXCL flag in open(2)) ensures that path is newly created. On POSIX systems, path is considered to exist even if it is a symlink to a non-existent file. The exclusive flag may or may not work with network file systems.

    On Linux, positional writes don't work when the file is opened in append mode. The kernel ignores the position argument and always appends the data to the end of the file.

    fs.openSync(path, flags, [mode])#

    Synchronous version of fs.open().

    fs.utimes(path, atime, mtime, callback)#

    fs.utimesSync(path, atime, mtime)#

    Change file timestamps of the file referenced by the supplied path.

    fs.futimes(fd, atime, mtime, callback)#

    fs.futimesSync(fd, atime, mtime)#

    Change the file timestamps of a file referenced by the supplied file descriptor.

    fs.fsync(fd, callback)#

    Asynchronous fsync(2). No arguments other than a possible exception are given to the completion callback.

    fs.fsyncSync(fd)#

    Synchronous fsync(2).

    fs.write(fd, buffer, offset, length, position, callback)#

    Write buffer to the file specified by fd.

    offset and length determine the part of the buffer to be written.

    position refers to the offset from the beginning of the file where this data should be written. If position is null, the data will be written at the current position. See pwrite(2).

    The callback will be given three arguments (err, written, buffer) where written specifies how many bytes were written from buffer.

    Note that it is unsafe to use fs.write multiple times on the same file without waiting for the callback. For this scenario, fs.createWriteStream is strongly recommended.

    On Linux, positional writes don't work when the file is opened in append mode. The kernel ignores the position argument and always appends the data to the end of the file.

    fs.writeSync(fd, buffer, offset, length, position)#

    Synchronous version of fs.write(). Returns the number of bytes written.

    fs.read(fd, buffer, offset, length, position, callback)#

    Read data from the file specified by fd.

    buffer is the buffer that the data will be written to.

    offset is the offset in the buffer to start writing at.

    length is an integer specifying the number of bytes to read.

    position is an integer specifying where to begin reading from in the file. If position is null, data will be read from the current file position.

    The callback is given the three arguments, (err, bytesRead, buffer).

    fs.readSync(fd, buffer, offset, length, position)#

    Synchronous version of fs.read. Returns the number of bytesRead.

    fs.readFile(filename, [options], callback)#

    • filename String
    • options Object
      • encoding String | Null default = null
      • flag String default = 'r'
    • callback Function

    Asynchronously reads the entire contents of a file. Example:

    fs.readFile('/etc/passwd', function (err, data) {
      if (err) throw err;
      console.log(data);
    });

    The callback is passed two arguments (err, data), where data is the contents of the file.

    If no encoding is specified, then the raw buffer is returned.

    fs.readFileSync(filename, [options])#

    Synchronous version of fs.readFile. Returns the contents of the filename.

    If the encoding option is specified then this function returns a string. Otherwise it returns a buffer.

    fs.writeFile(filename, data, [options], callback)#

    • filename String
    • data String | Buffer
    • options Object
      • encoding String | Null default = 'utf8'
      • mode Number default = 438 (aka 0666 in Octal)
      • flag String default = 'w'
    • callback Function

    Asynchronously writes data to a file, replacing the file if it already exists. data can be a string or a buffer.

    The encoding option is ignored if data is a buffer. It defaults to 'utf8'.

    Example:

    fs.writeFile('message.txt', 'Hello Node', function (err) {
      if (err) throw err;
      console.log('It\'s saved!');
    });

    fs.writeFileSync(filename, data, [options])#

    The synchronous version of fs.writeFile.

    fs.appendFile(filename, data, [options], callback)#

    • filename String
    • data String | Buffer
    • options Object
      • encoding String | Null default = 'utf8'
      • mode Number default = 438 (aka 0666 in Octal)
      • flag String default = 'a'
    • callback Function

    Asynchronously append data to a file, creating the file if it not yet exists. data can be a string or a buffer.

    Example:

    fs.appendFile('message.txt', 'data to append', function (err) {
      if (err) throw err;
      console.log('The "data to append" was appended to file!');
    });

    fs.appendFileSync(filename, data, [options])#

    The synchronous version of fs.appendFile.

    fs.watchFile(filename, [options], listener)#

    Stability: 2 - Unstable.  Use fs.watch instead, if possible.

    Watch for changes on filename. The callback listener will be called each time the file is accessed.

    The second argument is optional. The options if provided should be an object containing two members a boolean, persistent, and interval. persistent indicates whether the process should continue to run as long as files are being watched. interval indicates how often the target should be polled, in milliseconds. The default is { persistent: true, interval: 5007 }.

    The listener gets two arguments the current stat object and the previous stat object:

    fs.watchFile('message.text', function (curr, prev) {
      console.log('the current mtime is: ' + curr.mtime);
      console.log('the previous mtime was: ' + prev.mtime);
    });

    These stat objects are instances of fs.Stat.

    If you want to be notified when the file was modified, not just accessed you need to compare curr.mtime and prev.mtime.

    fs.unwatchFile(filename, [listener])#

    Stability: 2 - Unstable.  Use fs.watch instead, if possible.

    Stop watching for changes on filename. If listener is specified, only that particular listener is removed. Otherwise, all listeners are removed and you have effectively stopped watching filename.

    Calling fs.unwatchFile() with a filename that is not being watched is a no-op, not an error.

    fs.watch(filename, [options], [listener])#

    Stability: 2 - Unstable.

    Watch for changes on filename, where filename is either a file or a directory. The returned object is a fs.FSWatcher.

    The second argument is optional. The options if provided should be an object containing a boolean member persistent, which indicates whether the process should continue to run as long as files are being watched. The default is { persistent: true }.

    The listener callback gets two arguments (event, filename). event is either 'rename' or 'change', and filename is the name of the file which triggered the event.

    Caveats#

    The fs.watch API is not 100% consistent across platforms, and is unavailable in some situations.

    Availability#

    This feature depends on the underlying operating system providing a way to be notified of filesystem changes.

    • On Linux systems, this uses inotify.
    • On BSD systems (including OS X), this uses kqueue.
    • On SunOS systems (including Solaris and SmartOS), this uses event ports.
    • On Windows systems, this feature depends on ReadDirectoryChangesW.

    If the underlying functionality is not available for some reason, then fs.watch will not be able to function. For example, watching files or directories on network file systems (NFS, SMB, etc.) often doesn't work reliably or at all.

    You can still use fs.watchFile, which uses stat polling, but it is slower and less reliable.

    Filename Argument#

    Providing filename argument in the callback is not supported on every platform (currently it's only supported on Linux and Windows). Even on supported platforms filename is not always guaranteed to be provided. Therefore, don't assume that filename argument is always provided in the callback, and have some fallback logic if it is null.

    fs.watch('somedir', function (event, filename) {
      console.log('event is: ' + event);
      if (filename) {
        console.log('filename provided: ' + filename);
      } else {
        console.log('filename not provided');
      }
    });

    fs.exists(path, callback)#

    Test whether or not the given path exists by checking with the file system. Then call the callback argument with either true or false. Example:

    fs.exists('/etc/passwd', function (exists) {
      util.debug(exists ? "it's there" : "no passwd!");
    });

    fs.exists() is an anachronism and exists only for historical reasons. There should almost never be a reason to use it in your own code.

    In particular, checking if a file exists before opening it is an anti-pattern that leaves you vulnerable to race conditions: another process may remove the file between the calls to fs.exists() and fs.open(). Just open the file and handle the error when it's not there.

    fs.existsSync(path)#

    Synchronous version of fs.exists.

    Class: fs.Stats#

    Objects returned from fs.stat(), fs.lstat() and fs.fstat() and their synchronous counterparts are of this type.

    • stats.isFile()
    • stats.isDirectory()
    • stats.isBlockDevice()
    • stats.isCharacterDevice()
    • stats.isSymbolicLink() (only valid with fs.lstat())
    • stats.isFIFO()
    • stats.isSocket()

    For a regular file util.inspect(stats) would return a string very similar to this:

    { dev: 2114,
      ino: 48064969,
      mode: 33188,
      nlink: 1,
      uid: 85,
      gid: 100,
      rdev: 0,
      size: 527,
      blksize: 4096,
      blocks: 8,
      atime: Mon, 10 Oct 2011 23:24:11 GMT,
      mtime: Mon, 10 Oct 2011 23:24:11 GMT,
      ctime: Mon, 10 Oct 2011 23:24:11 GMT }

    Please note that atime, mtime and ctime are instances of Date object and to compare the values of these objects you should use appropriate methods. For most general uses getTime() will return the number of milliseconds elapsed since 1 January 1970 00:00:00 UTC and this integer should be sufficient for any comparison, however there additional methods which can be used for displaying fuzzy information. More details can be found in the MDN JavaScript Reference page.

    fs.createReadStream(path, [options])#

    Returns a new ReadStream object (See Readable Stream).

    options is an object with the following defaults:

    { flags: 'r',
      encoding: null,
      fd: null,
      mode: 0666,
      autoClose: true
    }

    options can include start and end values to read a range of bytes from the file instead of the entire file. Both start and end are inclusive and start at 0. The encoding can be 'utf8', 'ascii', or 'base64'.

    If autoClose is false, then the file descriptor won't be closed, even if there's an error. It is your responsiblity to close it and make sure there's no file descriptor leak. If autoClose is set to true (default behavior), on error or end the file descriptor will be closed automatically.

    An example to read the last 10 bytes of a file which is 100 bytes long:

    fs.createReadStream('sample.txt', {start: 90, end: 99});

    Class: fs.ReadStream#

    ReadStream is a Readable Stream.

    Event: 'open'#

    • fd Integer file descriptor used by the ReadStream.

    Emitted when the ReadStream's file is opened.

    fs.createWriteStream(path, [options])#

    Returns a new WriteStream object (See Writable Stream).

    options is an object with the following defaults:

    { flags: 'w',
      encoding: null,
      mode: 0666 }

    options may also include a start option to allow writing data at some position past the beginning of the file. Modifying a file rather than replacing it may require a flags mode of r+ rather than the default mode w.

    Class: fs.WriteStream#

    WriteStream is a Writable Stream.

    Event: 'open'#

    • fd Integer file descriptor used by the WriteStream.

    Emitted when the WriteStream's file is opened.

    file.bytesWritten#

    The number of bytes written so far. Does not include data that is still queued for writing.

    Class: fs.FSWatcher#

    Objects returned from fs.watch() are of this type.

    watcher.close()#

    Stop watching for changes on the given fs.FSWatcher.

    Event: 'change'#

    • event String The type of fs change
    • filename String The filename that changed (if relevant/available)

    Emitted when something changes in a watched directory or file. See more details in fs.watch.

    Event: 'error'#

    • error Error object

    Emitted when an error occurs.

    Path#

    Stability: 3 - Stable

    This module contains utilities for handling and transforming file paths. Almost all these methods perform only string transformations. The file system is not consulted to check whether paths are valid.

    Use require('path') to use this module. The following methods are provided:

    path.normalize(p)#

    Normalize a string path, taking care of '..' and '.' parts.

    When multiple slashes are found, they're replaced by a single one; when the path contains a trailing slash, it is preserved. On Windows backslashes are used.

    Example:

    path.normalize('/foo/bar//baz/asdf/quux/..')
    // returns
    '/foo/bar/baz/asdf'

    path.join([path1], [path2], [...])#

    Join all arguments together and normalize the resulting path.

    Arguments must be strings. In v0.8, non-string arguments were silently ignored. In v0.10 and up, an exception is thrown.

    Example:

    path.join('/foo', 'bar', 'baz/asdf', 'quux', '..')
    // returns
    '/foo/bar/baz/asdf'
    
    path.join('foo', {}, 'bar')
    // throws exception
    TypeError: Arguments to path.join must be strings

    path.resolve([from ...], to)#

    Resolves to to an absolute path.

    If to isn't already absolute from arguments are prepended in right to left order, until an absolute path is found. If after using all from paths still no absolute path is found, the current working directory is used as well. The resulting path is normalized, and trailing slashes are removed unless the path gets resolved to the root directory. Non-string arguments are ignored.

    Another way to think of it is as a sequence of cd commands in a shell.

    path.resolve('foo/bar', '/tmp/file/', '..', 'a/../subfile')

    Is similar to:

    cd foo/bar
    cd /tmp/file/
    cd ..
    cd a/../subfile
    pwd

    The difference is that the different paths don't need to exist and may also be files.

    Examples:

    path.resolve('/foo/bar', './baz')
    // returns
    '/foo/bar/baz'
    
    path.resolve('/foo/bar', '/tmp/file/')
    // returns
    '/tmp/file'
    
    path.resolve('wwwroot', 'static_files/png/', '../gif/image.gif')
    // if currently in /home/myself/node, it returns
    '/home/myself/node/wwwroot/static_files/gif/image.gif'

    path.relative(from, to)#

    Solve the relative path from from to to.

    At times we have two absolute paths, and we need to derive the relative path from one to the other. This is actually the reverse transform of path.resolve, which means we see that:

    path.resolve(from, path.relative(from, to)) == path.resolve(to)

    Examples:

    path.relative('C:\\orandea\\test\\aaa', 'C:\\orandea\\impl\\bbb')
    // returns
    '..\\..\\impl\\bbb'
    
    path.relative('/data/orandea/test/aaa', '/data/orandea/impl/bbb')
    // returns
    '../../impl/bbb'

    path.dirname(p)#

    Return the directory name of a path. Similar to the Unix dirname command.

    Example:

    path.dirname('/foo/bar/baz/asdf/quux')
    // returns
    '/foo/bar/baz/asdf'

    path.basename(p, [ext])#

    Return the last portion of a path. Similar to the Unix basename command.

    Example:

    path.basename('/foo/bar/baz/asdf/quux.html')
    // returns
    'quux.html'
    
    path.basename('/foo/bar/baz/asdf/quux.html', '.html')
    // returns
    'quux'

    path.extname(p)#

    Return the extension of the path, from the last '.' to end of string in the last portion of the path. If there is no '.' in the last portion of the path or the first character of it is '.', then it returns an empty string. Examples:

    path.extname('index.html')
    // returns
    '.html'
    
    path.extname('index.')
    // returns
    '.'
    
    path.extname('index')
    // returns
    ''

    path.sep#

    The platform-specific file separator. '\\' or '/'.

    An example on *nix:

    'foo/bar/baz'.split(path.sep)
    // returns
    ['foo', 'bar', 'baz']

    An example on Windows:

    'foo\\bar\\baz'.split(path.sep)
    // returns
    ['foo', 'bar', 'baz']

    path.delimiter#

    The platform-specific path delimiter, ; or ':'.

    An example on *nix:

    console.log(process.env.PATH)
    // '/usr/bin:/bin:/usr/sbin:/sbin:/usr/local/bin'
    
    process.env.PATH.split(path.delimiter)
    // returns
    ['/usr/bin', '/bin', '/usr/sbin', '/sbin', '/usr/local/bin']

    An example on Windows:

    console.log(process.env.PATH)
    // 'C:\Windows\system32;C:\Windows;C:\Program Files\nodejs\'
    
    process.env.PATH.split(path.delimiter)
    // returns
    ['C:\Windows\system32', 'C:\Windows', 'C:\Program Files\nodejs\']

    net#

    Stability: 3 - Stable

    The net module provides you with an asynchronous network wrapper. It contains methods for creating both servers and clients (called streams). You can include this module with require('net');

    net.createServer([options], [connectionListener])#

    Creates a new TCP server. The connectionListener argument is automatically set as a listener for the 'connection' event.

    options is an object with the following defaults:

    { allowHalfOpen: false
    }

    If allowHalfOpen is true, then the socket won't automatically send a FIN packet when the other end of the socket sends a FIN packet. The socket becomes non-readable, but still writable. You should call the end() method explicitly. See 'end' event for more information.

    Here is an example of an echo server which listens for connections on port 8124:

    var net = require('net');
    var server = net.createServer(function(c) { //'connection' listener
      console.log('server connected');
      c.on('end', function() {
        console.log('server disconnected');
      });
      c.write('hello\r\n');
      c.pipe(c);
    });
    server.listen(8124, function() { //'listening' listener
      console.log('server bound');
    });

    Test this by using telnet:

    telnet localhost 8124

    To listen on the socket /tmp/echo.sock the third line from the last would just be changed to

    server.listen('/tmp/echo.sock', function() { //'listening' listener

    Use nc to connect to a UNIX domain socket server:

    nc -U /tmp/echo.sock

    net.connect(options, [connectionListener])#

    net.createConnection(options, [connectionListener])#

    Constructs a new socket object and opens the socket to the given location. When the socket is established, the 'connect' event will be emitted.

    For TCP sockets, options argument should be an object which specifies:

    • port: Port the client should connect to (Required).

    • host: Host the client should connect to. Defaults to 'localhost'.

    • localAddress: Local interface to bind to for network connections.

    For UNIX domain sockets, options argument should be an object which specifies:

    • path: Path the client should connect to (Required).

    Common options are:

    • allowHalfOpen: if true, the socket won't automatically send a FIN packet when the other end of the socket sends a FIN packet. Defaults to false. See 'end' event for more information.

    The connectListener parameter will be added as an listener for the 'connect' event.

    Here is an example of a client of echo server as described previously:

    var net = require('net');
    var client = net.connect({port: 8124},
        function() { //'connect' listener
      console.log('client connected');
      client.write('world!\r\n');
    });
    client.on('data', function(data) {
      console.log(data.toString());
      client.end();
    });
    client.on('end', function() {
      console.log('client disconnected');
    });

    To connect on the socket /tmp/echo.sock the second line would just be changed to

    var client = net.connect({path: '/tmp/echo.sock'});

    net.connect(port, [host], [connectListener])#

    net.createConnection(port, [host], [connectListener])#

    Creates a TCP connection to port on host. If host is omitted, 'localhost' will be assumed. The connectListener parameter will be added as an listener for the 'connect' event.

    net.connect(path, [connectListener])#

    net.createConnection(path, [connectListener])#

    Creates unix socket connection to path. The connectListener parameter will be added as an listener for the 'connect' event.

    Class: net.Server#

    This class is used to create a TCP or UNIX server.

    server.listen(port, [host], [backlog], [callback])#

    Begin accepting connections on the specified port and host. If the host is omitted, the server will accept connections directed to any IPv4 address (INADDR_ANY). A port value of zero will assign a random port.

    Backlog is the maximum length of the queue of pending connections. The actual length will be determined by your OS through sysctl settings such as tcp_max_syn_backlog and somaxconn on linux. The default value of this parameter is 511 (not 512).

    This function is asynchronous. When the server has been bound, 'listening' event will be emitted. The last parameter callback will be added as an listener for the 'listening' event.

    One issue some users run into is getting EADDRINUSE errors. This means that another server is already running on the requested port. One way of handling this would be to wait a second and then try again. This can be done with

    server.on('error', function (e) {
      if (e.code == 'EADDRINUSE') {
        console.log('Address in use, retrying...');
        setTimeout(function () {
          server.close();
          server.listen(PORT, HOST);
        }, 1000);
      }
    });

    (Note: All sockets in Node set SO_REUSEADDR already)

    server.listen(path, [callback])#

    Start a UNIX socket server listening for connections on the given path.

    This function is asynchronous. When the server has been bound, 'listening' event will be emitted. The last parameter callback will be added as an listener for the 'listening' event.

    server.listen(handle, [callback])#

    • handle Object
    • callback Function

    The handle object can be set to either a server or socket (anything with an underlying _handle member), or a {fd: <n>} object.

    This will cause the server to accept connections on the specified handle, but it is presumed that the file descriptor or handle has already been bound to a port or domain socket.

    Listening on a file descriptor is not supported on Windows.

    This function is asynchronous. When the server has been bound, 'listening' event will be emitted. the last parameter callback will be added as an listener for the 'listening' event.

    server.close([callback])#

    Stops the server from accepting new connections and keeps existing connections. This function is asynchronous, the server is finally closed when all connections are ended and the server emits a 'close' event. Optionally, you can pass a callback to listen for the 'close' event.

    server.address()#

    Returns the bound address, the address family name and port of the server as reported by the operating system. Useful to find which port was assigned when giving getting an OS-assigned address. Returns an object with three properties, e.g. { port: 12346, family: 'IPv4', address: '127.0.0.1' }

    Example:

    var server = net.createServer(function (socket) {
      socket.end("goodbye\n");
    });
    
    // grab a random port.
    server.listen(function() {
      address = server.address();
      console.log("opened server on %j", address);
    });

    Don't call server.address() until the 'listening' event has been emitted.

    server.unref()#

    Calling unref on a server will allow the program to exit if this is the only active server in the event system. If the server is already unrefd calling unref again will have no effect.

    server.ref()#

    Opposite of unref, calling ref on a previously unrefd server will not let the program exit if it's the only server left (the default behavior). If the server is refd calling ref again will have no effect.

    server.maxConnections#

    Set this property to reject connections when the server's connection count gets high.

    It is not recommended to use this option once a socket has been sent to a child with child_process.fork().

    server.connections#

    This function is deprecated; please use [server.getConnections()][] instead. The number of concurrent connections on the server.

    This becomes null when sending a socket to a child with child_process.fork(). To poll forks and get current number of active connections use asynchronous server.getConnections instead.

    net.Server is an EventEmitter with the following events:

    server.getConnections(callback)#

    Asynchronously get the number of concurrent connections on the server. Works when sockets were sent to forks.

    Callback should take two arguments err and count.

    Event: 'listening'#

    Emitted when the server has been bound after calling server.listen.

    Event: 'connection'#

    • Socket object The connection object

    Emitted when a new connection is made. socket is an instance of net.Socket.

    Event: 'close'#

    Emitted when the server closes. Note that if connections exist, this event is not emitted until all connections are ended.

    Event: 'error'#

    • Error Object

    Emitted when an error occurs. The 'close' event will be called directly following this event. See example in discussion of server.listen.

    Class: net.Socket#

    This object is an abstraction of a TCP or UNIX socket. net.Socket instances implement a duplex Stream interface. They can be created by the user and used as a client (with connect()) or they can be created by Node and passed to the user through the 'connection' event of a server.

    new net.Socket([options])#

    Construct a new socket object.

    options is an object with the following defaults:

    { fd: null
      allowHalfOpen: false,
      readable: false,
      writable: false
    }

    fd allows you to specify the existing file descriptor of socket. Set readable and/or writable to true to allow reads and/or writes on this socket (NOTE: Works only when fd is passed). About allowHalfOpen, refer to createServer() and 'end' event.

    socket.connect(port, [host], [connectListener])#

    socket.connect(path, [connectListener])#

    Opens the connection for a given socket. If port and host are given, then the socket will be opened as a TCP socket, if host is omitted, localhost will be assumed. If a path is given, the socket will be opened as a unix socket to that path.

    Normally this method is not needed, as net.createConnection opens the socket. Use this only if you are implementing a custom Socket.

    This function is asynchronous. When the 'connect' event is emitted the socket is established. If there is a problem connecting, the 'connect' event will not be emitted, the 'error' event will be emitted with the exception.

    The connectListener parameter will be added as an listener for the 'connect' event.

    socket.bufferSize#

    net.Socket has the property that socket.write() always works. This is to help users get up and running quickly. The computer cannot always keep up with the amount of data that is written to a socket - the network connection simply might be too slow. Node will internally queue up the data written to a socket and send it out over the wire when it is possible. (Internally it is polling on the socket's file descriptor for being writable).

    The consequence of this internal buffering is that memory may grow. This property shows the number of characters currently buffered to be written. (Number of characters is approximately equal to the number of bytes to be written, but the buffer may contain strings, and the strings are lazily encoded, so the exact number of bytes is not known.)

    Users who experience large or growing bufferSize should attempt to "throttle" the data flows in their program with pause() and resume().

    socket.setEncoding([encoding])#

    Set the encoding for the socket as a Readable Stream. See stream.setEncoding() for more information.

    socket.write(data, [encoding], [callback])#

    Sends data on the socket. The second parameter specifies the encoding in the case of a string--it defaults to UTF8 encoding.

    Returns true if the entire data was flushed successfully to the kernel buffer. Returns false if all or part of the data was queued in user memory. 'drain' will be emitted when the buffer is again free.

    The optional callback parameter will be executed when the data is finally written out - this may not be immediately.

    socket.end([data], [encoding])#

    Half-closes the socket. i.e., it sends a FIN packet. It is possible the server will still send some data.

    If data is specified, it is equivalent to calling socket.write(data, encoding) followed by socket.end().

    socket.destroy()#

    Ensures that no more I/O activity happens on this socket. Only necessary in case of errors (parse error or so).

    socket.pause()#

    Pauses the reading of data. That is, 'data' events will not be emitted. Useful to throttle back an upload.

    socket.resume()#

    Resumes reading after a call to pause().

    socket.setTimeout(timeout, [callback])#

    Sets the socket to timeout after timeout milliseconds of inactivity on the socket. By default net.Socket do not have a timeout.

    When an idle timeout is triggered the socket will receive a 'timeout' event but the connection will not be severed. The user must manually end() or destroy() the socket.

    If timeout is 0, then the existing idle timeout is disabled.

    The optional callback parameter will be added as a one time listener for the 'timeout' event.

    socket.setNoDelay([noDelay])#

    Disables the Nagle algorithm. By default TCP connections use the Nagle algorithm, they buffer data before sending it off. Setting true for noDelay will immediately fire off data each time socket.write() is called. noDelay defaults to true.

    socket.setKeepAlive([enable], [initialDelay])#

    Enable/disable keep-alive functionality, and optionally set the initial delay before the first keepalive probe is sent on an idle socket. enable defaults to false.

    Set initialDelay (in milliseconds) to set the delay between the last data packet received and the first keepalive probe. Setting 0 for initialDelay will leave the value unchanged from the default (or previous) setting. Defaults to 0.

    socket.address()#

    Returns the bound address, the address family name and port of the socket as reported by the operating system. Returns an object with three properties, e.g. { port: 12346, family: 'IPv4', address: '127.0.0.1' }

    socket.unref()#

    Calling unref on a socket will allow the program to exit if this is the only active socket in the event system. If the socket is already unrefd calling unref again will have no effect.

    socket.ref()#

    Opposite of unref, calling ref on a previously unrefd socket will not let the program exit if it's the only socket left (the default behavior). If the socket is refd calling ref again will have no effect.

    socket.remoteAddress#

    The string representation of the remote IP address. For example, '74.125.127.100' or '2001:4860:a005::68'.

    socket.remotePort#

    The numeric representation of the remote port. For example, 80 or 21.

    socket.localAddress#

    The string representation of the local IP address the remote client is connecting on. For example, if you are listening on '0.0.0.0' and the client connects on '192.168.1.1', the value would be '192.168.1.1'.

    socket.localPort#

    The numeric representation of the local port. For example, 80 or 21.

    socket.bytesRead#

    The amount of received bytes.

    socket.bytesWritten#

    The amount of bytes sent.

    net.Socket instances are EventEmitter with the following events:

    Event: 'connect'#

    Emitted when a socket connection is successfully established. See connect().

    Event: 'data'#

    • Buffer object

    Emitted when data is received. The argument data will be a Buffer or String. Encoding of data is set by socket.setEncoding(). (See the Readable Stream section for more information.)

    Note that the data will be lost if there is no listener when a Socket emits a 'data' event.

    Event: 'end'#

    Emitted when the other end of the socket sends a FIN packet.

    By default (allowHalfOpen == false) the socket will destroy its file descriptor once it has written out its pending write queue. However, by setting allowHalfOpen == true the socket will not automatically end() its side allowing the user to write arbitrary amounts of data, with the caveat that the user is required to end() their side now.

    Event: 'timeout'#

    Emitted if the socket times out from inactivity. This is only to notify that the socket has been idle. The user must manually close the connection.

    See also: socket.setTimeout()

    Event: 'drain'#

    Emitted when the write buffer becomes empty. Can be used to throttle uploads.

    See also: the return values of socket.write()

    Event: 'error'#

    • Error object

    Emitted when an error occurs. The 'close' event will be called directly following this event.

    Event: 'close'#

    • had_error Boolean true if the socket had a transmission error

    Emitted once the socket is fully closed. The argument had_error is a boolean which says if the socket was closed due to a transmission error.

    net.isIP(input)#

    Tests if input is an IP address. Returns 0 for invalid strings, returns 4 for IP version 4 addresses, and returns 6 for IP version 6 addresses.

    net.isIPv4(input)#

    Returns true if input is a version 4 IP address, otherwise returns false.

    net.isIPv6(input)#

    Returns true if input is a version 6 IP address, otherwise returns false.

    UDP / Datagram Sockets#

    Stability: 3 - Stable

    Datagram sockets are available through require('dgram').

    Important note: the behavior of dgram.Socket#bind() has changed in v0.10 and is always asynchronous now. If you have code that looks like this:

    var s = dgram.createSocket('udp4');
    s.bind(1234);
    s.addMembership('224.0.0.114');

    You have to change it to this:

    var s = dgram.createSocket('udp4');
    s.bind(1234, function() {
      s.addMembership('224.0.0.114');
    });

    dgram.createSocket(type, [callback])#

    • type String. Either 'udp4' or 'udp6'
    • callback Function. Attached as a listener to message events. Optional
    • Returns: Socket object

    Creates a datagram Socket of the specified types. Valid types are udp4 and udp6.

    Takes an optional callback which is added as a listener for message events.

    Call socket.bind if you want to receive datagrams. socket.bind() will bind to the "all interfaces" address on a random port (it does the right thing for both udp4 and udp6 sockets). You can then retrieve the address and port with socket.address().address and socket.address().port.

    Class: dgram.Socket#

    The dgram Socket class encapsulates the datagram functionality. It should be created via dgram.createSocket(type, [callback]).

    Event: 'message'#

    • msg Buffer object. The message
    • rinfo Object. Remote address information

    Emitted when a new datagram is available on a socket. msg is a Buffer and rinfo is an object with the sender's address information and the number of bytes in the datagram.

    Event: 'listening'#

    Emitted when a socket starts listening for datagrams. This happens as soon as UDP sockets are created.

    Event: 'close'#

    Emitted when a socket is closed with close(). No new message events will be emitted on this socket.

    Event: 'error'#

    • exception Error object

    Emitted when an error occurs.

    socket.send(buf, offset, length, port, address, [callback])#

    • buf Buffer object. Message to be sent
    • offset Integer. Offset in the buffer where the message starts.
    • length Integer. Number of bytes in the message.
    • port Integer. Destination port.
    • address String. Destination hostname or IP address.
    • callback Function. Called when the message has been sent. Optional.

    For UDP sockets, the destination port and address must be specified. A string may be supplied for the address parameter, and it will be resolved with DNS.

    If the address is omitted or is an empty string, '0.0.0.0' or '::0' is used instead. Depending on the network configuration, those defaults may or may not work; it's best to be explicit about the destination address.

    If the socket has not been previously bound with a call to bind, it gets assigned a random port number and is bound to the "all interfaces" address ('0.0.0.0' for udp4 sockets, '::0' for udp6 sockets.)

    An optional callback may be specified to detect DNS errors or for determining when it's safe to reuse the buf object. Note that DNS lookups delay the time to send for at least one tick. The only way to know for sure that the datagram has been sent is by using a callback.

    Example of sending a UDP packet to a random port on localhost;

    var dgram = require('dgram');
    var message = new Buffer("Some bytes");
    var client = dgram.createSocket("udp4");
    client.send(message, 0, message.length, 41234, "localhost", function(err, bytes) {
      client.close();
    });

    A Note about UDP datagram size

    The maximum size of an IPv4/v6 datagram depends on the MTU (Maximum Transmission Unit) and on the Payload Length field size.

    • The Payload Length field is 16 bits wide, which means that a normal payload cannot be larger than 64K octets including internet header and data (65,507 bytes = 65,535 − 8 bytes UDP header − 20 bytes IP header); this is generally true for loopback interfaces, but such long datagrams are impractical for most hosts and networks.

    • The MTU is the largest size a given link layer technology can support for datagrams. For any link, IPv4 mandates a minimum MTU of 68 octets, while the recommended MTU for IPv4 is 576 (typically recommended as the MTU for dial-up type applications), whether they arrive whole or in fragments.

      For IPv6, the minimum MTU is 1280 octets, however, the mandatory minimum fragment reassembly buffer size is 1500 octets. The value of 68 octets is very small, since most current link layer technologies have a minimum MTU of 1500 (like Ethernet).

    Note that it's impossible to know in advance the MTU of each link through which a packet might travel, and that generally sending a datagram greater than the (receiver) MTU won't work (the packet gets silently dropped, without informing the source that the data did not reach its intended recipient).

    socket.bind(port, [address], [callback])#

    • port Integer
    • address String, Optional
    • callback Function with no parameters, Optional. Callback when binding is done.

    For UDP sockets, listen for datagrams on a named port and optional address. If address is not specified, the OS will try to listen on all addresses. After binding is done, a "listening" event is emitted and the callback(if specified) is called. Specifying both a "listening" event listener and callback is not harmful but not very useful.

    A bound datagram socket keeps the node process running to receive datagrams.

    If binding fails, an "error" event is generated. In rare case (e.g. binding a closed socket), an Error may be thrown by this method.

    Example of a UDP server listening on port 41234:

    var dgram = require("dgram");
    
    var server = dgram.createSocket("udp4");
    
    server.on("error", function (err) {
      console.log("server error:\n" + err.stack);
      server.close();
    });
    
    server.on("message", function (msg, rinfo) {
      console.log("server got: " + msg + " from " +
        rinfo.address + ":" + rinfo.port);
    });
    
    server.on("listening", function () {
      var address = server.address();
      console.log("server listening " +
          address.address + ":" + address.port);
    });
    
    server.bind(41234);
    // server listening 0.0.0.0:41234

    socket.close()#

    Close the underlying socket and stop listening for data on it.

    socket.address()#

    Returns an object containing the address information for a socket. For UDP sockets, this object will contain address , family and port.

    socket.setBroadcast(flag)#

    • flag Boolean

    Sets or clears the SO_BROADCAST socket option. When this option is set, UDP packets may be sent to a local interface's broadcast address.

    socket.setTTL(ttl)#

    • ttl Integer

    Sets the IP_TTL socket option. TTL stands for "Time to Live," but in this context it specifies the number of IP hops that a packet is allowed to go through. Each router or gateway that forwards a packet decrements the TTL. If the TTL is decremented to 0 by a router, it will not be forwarded. Changing TTL values is typically done for network probes or when multicasting.

    The argument to setTTL() is a number of hops between 1 and 255. The default on most systems is 64.

    socket.setMulticastTTL(ttl)#

    • ttl Integer

    Sets the IP_MULTICAST_TTL socket option. TTL stands for "Time to Live," but in this context it specifies the number of IP hops that a packet is allowed to go through, specifically for multicast traffic. Each router or gateway that forwards a packet decrements the TTL. If the TTL is decremented to 0 by a router, it will not be forwarded.

    The argument to setMulticastTTL() is a number of hops between 0 and 255. The default on most systems is 1.

    socket.setMulticastLoopback(flag)#

    • flag Boolean

    Sets or clears the IP_MULTICAST_LOOP socket option. When this option is set, multicast packets will also be received on the local interface.

    socket.addMembership(multicastAddress, [multicastInterface])#

    • multicastAddress String
    • multicastInterface String, Optional

    Tells the kernel to join a multicast group with IP_ADD_MEMBERSHIP socket option.

    If multicastInterface is not specified, the OS will try to add membership to all valid interfaces.

    socket.dropMembership(multicastAddress, [multicastInterface])#

    • multicastAddress String
    • multicastInterface String, Optional

    Opposite of addMembership - tells the kernel to leave a multicast group with IP_DROP_MEMBERSHIP socket option. This is automatically called by the kernel when the socket is closed or process terminates, so most apps will never need to call this.

    If multicastInterface is not specified, the OS will try to drop membership to all valid interfaces.

    socket.unref()#

    Calling unref on a socket will allow the program to exit if this is the only active socket in the event system. If the socket is already unrefd calling unref again will have no effect.

    socket.ref()#

    Opposite of unref, calling ref on a previously unrefd socket will not let the program exit if it's the only socket left (the default behavior). If the socket is refd calling ref again will have no effect.

    DNS#

    Stability: 3 - Stable

    Use require('dns') to access this module. All methods in the dns module use C-Ares except for dns.lookup which uses getaddrinfo(3) in a thread pool. C-Ares is much faster than getaddrinfo but the system resolver is more consistent with how other programs operate. When a user does net.connect(80, 'google.com') or http.get({ host: 'google.com' }) the dns.lookup method is used. Users who need to do a large number of lookups quickly should use the methods that go through C-Ares.

    Here is an example which resolves 'www.google.com' then reverse resolves the IP addresses which are returned.

    var dns = require('dns');
    
    dns.resolve4('www.google.com', function (err, addresses) {
      if (err) throw err;
    
      console.log('addresses: ' + JSON.stringify(addresses));
    
      addresses.forEach(function (a) {
        dns.reverse(a, function (err, domains) {
          if (err) {
            throw err;
          }
    
          console.log('reverse for ' + a + ': ' + JSON.stringify(domains));
        });
      });
    });

    dns.lookup(domain, [family], callback)#

    Resolves a domain (e.g. 'google.com') into the first found A (IPv4) or AAAA (IPv6) record. The family can be the integer 4 or 6. Defaults to null that indicates both Ip v4 and v6 address family.

    The callback has arguments (err, address, family). The address argument is a string representation of a IP v4 or v6 address. The family argument is either the integer 4 or 6 and denotes the family of address (not necessarily the value initially passed to lookup).

    On error, err is an Error object, where err.code is the error code. Keep in mind that err.code will be set to 'ENOENT' not only when the domain does not exist but also when the lookup fails in other ways such as no available file descriptors.

    dns.resolve(domain, [rrtype], callback)#

    Resolves a domain (e.g. 'google.com') into an array of the record types specified by rrtype. Valid rrtypes are 'A' (IPV4 addresses, default), 'AAAA' (IPV6 addresses), 'MX' (mail exchange records), 'TXT' (text records), 'SRV' (SRV records), 'PTR' (used for reverse IP lookups), 'NS' (name server records) and 'CNAME' (canonical name records).

    The callback has arguments (err, addresses). The type of each item in addresses is determined by the record type, and described in the documentation for the corresponding lookup methods below.

    On error, err is an Error object, where err.code is one of the error codes listed below.

    dns.resolve4(domain, callback)#

    The same as dns.resolve(), but only for IPv4 queries (A records). addresses is an array of IPv4 addresses (e.g. ['74.125.79.104', '74.125.79.105', '74.125.79.106']).

    dns.resolve6(domain, callback)#

    The same as dns.resolve4() except for IPv6 queries (an AAAA query).

    dns.resolveMx(domain, callback)#

    The same as dns.resolve(), but only for mail exchange queries (MX records).

    addresses is an array of MX records, each with a priority and an exchange attribute (e.g. [{'priority': 10, 'exchange': 'mx.example.com'},...]).

    dns.resolveTxt(domain, callback)#

    The same as dns.resolve(), but only for text queries (TXT records). addresses is an array of the text records available for domain (e.g., ['v=spf1 ip4:0.0.0.0 ~all']).

    dns.resolveSrv(domain, callback)#

    The same as dns.resolve(), but only for service records (SRV records). addresses is an array of the SRV records available for domain. Properties of SRV records are priority, weight, port, and name (e.g., [{'priority': 10, {'weight': 5, 'port': 21223, 'name': 'service.example.com'}, ...]).

    dns.resolveNs(domain, callback)#

    The same as dns.resolve(), but only for name server records (NS records). addresses is an array of the name server records available for domain (e.g., ['ns1.example.com', 'ns2.example.com']).

    dns.resolveCname(domain, callback)#

    The same as dns.resolve(), but only for canonical name records (CNAME records). addresses is an array of the canonical name records available for domain (e.g., ['bar.example.com']).

    dns.reverse(ip, callback)#

    Reverse resolves an ip address to an array of domain names.

    The callback has arguments (err, domains).

    On error, err is an Error object, where err.code is one of the error codes listed below.

    Error codes#

    Each DNS query can return one of the following error codes:

    • dns.NODATA: DNS server returned answer with no data.
    • dns.FORMERR: DNS server claims query was misformatted.
    • dns.SERVFAIL: DNS server returned general failure.
    • dns.NOTFOUND: Domain name not found.
    • dns.NOTIMP: DNS server does not implement requested operation.
    • dns.REFUSED: DNS server refused query.
    • dns.BADQUERY: Misformatted DNS query.
    • dns.BADNAME: Misformatted domain name.
    • dns.BADFAMILY: Unsupported address family.
    • dns.BADRESP: Misformatted DNS reply.
    • dns.CONNREFUSED: Could not contact DNS servers.
    • dns.TIMEOUT: Timeout while contacting DNS servers.
    • dns.EOF: End of file.
    • dns.FILE: Error reading file.
    • dns.NOMEM: Out of memory.
    • dns.DESTRUCTION: Channel is being destroyed.
    • dns.BADSTR: Misformatted string.
    • dns.BADFLAGS: Illegal flags specified.
    • dns.NONAME: Given hostname is not numeric.
    • dns.BADHINTS: Illegal hints flags specified.
    • dns.NOTINITIALIZED: c-ares library initialization not yet performed.
    • dns.LOADIPHLPAPI: Error loading iphlpapi.dll.
    • dns.ADDRGETNETWORKPARAMS: Could not find GetNetworkParams function.
    • dns.CANCELLED: DNS query cancelled.

    HTTP#

    Stability: 3 - Stable

    To use the HTTP server and client one must require('http').

    The HTTP interfaces in Node are designed to support many features of the protocol which have been traditionally difficult to use. In particular, large, possibly chunk-encoded, messages. The interface is careful to never buffer entire requests or responses--the user is able to stream data.

    HTTP message headers are represented by an object like this:

    { 'content-length': '123',
      'content-type': 'text/plain',
      'connection': 'keep-alive',
      'accept': '*/*' }

    Keys are lowercased. Values are not modified.

    In order to support the full spectrum of possible HTTP applications, Node's HTTP API is very low-level. It deals with stream handling and message parsing only. It parses a message into headers and body but it does not parse the actual headers or the body.

    http.STATUS_CODES#

    • Object

    A collection of all the standard HTTP response status codes, and the short description of each. For example, http.STATUS_CODES[404] === 'Not Found'.

    http.createServer([requestListener])#

    Returns a new web server object.

    The requestListener is a function which is automatically added to the 'request' event.

    http.createClient([port], [host])#

    This function is deprecated; please use http.request() instead. Constructs a new HTTP client. port and host refer to the server to be connected to.

    Class: http.Server#

    This is an EventEmitter with the following events:

    Event: 'request'#

    function (request, response) { }

    Emitted each time there is a request. Note that there may be multiple requests per connection (in the case of keep-alive connections). request is an instance of http.IncomingMessage and response is an instance of http.ServerResponse.

    Event: 'connection'#

    function (socket) { }

    When a new TCP stream is established. socket is an object of type net.Socket. Usually users will not want to access this event. In particular, the socket will not emit readable events because of how the protocol parser attaches to the socket. The socket can also be accessed at request.connection.

    Event: 'close'#

    function () { }

    Emitted when the server closes.

    Event: 'checkContinue'#

    function (request, response) { }

    Emitted each time a request with an http Expect: 100-continue is received. If this event isn't listened for, the server will automatically respond with a 100 Continue as appropriate.

    Handling this event involves calling response.writeContinue() if the client should continue to send the request body, or generating an appropriate HTTP response (e.g., 400 Bad Request) if the client should not continue to send the request body.

    Note that when this event is emitted and handled, the request event will not be emitted.

    Event: 'connect'#

    function (request, socket, head) { }

    Emitted each time a client requests a http CONNECT method. If this event isn't listened for, then clients requesting a CONNECT method will have their connections closed.

    • request is the arguments for the http request, as it is in the request event.
    • socket is the network socket between the server and client.
    • head is an instance of Buffer, the first packet of the tunneling stream, this may be empty.

    After this event is emitted, the request's socket will not have a data event listener, meaning you will need to bind to it in order to handle data sent to the server on that socket.

    Event: 'upgrade'#

    function (request, socket, head) { }

    Emitted each time a client requests a http upgrade. If this event isn't listened for, then clients requesting an upgrade will have their connections closed.

    • request is the arguments for the http request, as it is in the request event.
    • socket is the network socket between the server and client.
    • head is an instance of Buffer, the first packet of the upgraded stream, this may be empty.

    After this event is emitted, the request's socket will not have a data event listener, meaning you will need to bind to it in order to handle data sent to the server on that socket.

    Event: 'clientError'#

    function (exception, socket) { }

    If a client connection emits an 'error' event - it will forwarded here.

    socket is the net.Socket object that the error originated from.

    server.listen(port, [hostname], [backlog], [callback])#

    Begin accepting connections on the specified port and hostname. If the hostname is omitted, the server will accept connections directed to any IPv4 address (INADDR_ANY).

    To listen to a unix socket, supply a filename instead of port and hostname.

    Backlog is the maximum length of the queue of pending connections. The actual length will be determined by your OS through sysctl settings such as tcp_max_syn_backlog and somaxconn on linux. The default value of this parameter is 511 (not 512).

    This function is asynchronous. The last parameter callback will be added as a listener for the 'listening' event. See also net.Server.listen(port).

    server.listen(path, [callback])#

    Start a UNIX socket server listening for connections on the given path.

    This function is asynchronous. The last parameter callback will be added as a listener for the 'listening' event. See also net.Server.listen(path).

    server.listen(handle, [callback])#

    • handle Object
    • callback Function

    The handle object can be set to either a server or socket (anything with an underlying _handle member), or a {fd: <n>} object.

    This will cause the server to accept connections on the specified handle, but it is presumed that the file descriptor or handle has already been bound to a port or domain socket.

    Listening on a file descriptor is not supported on Windows.

    This function is asynchronous. The last parameter callback will be added as a listener for the 'listening' event. See also net.Server.listen().

    server.close([callback])#

    Stops the server from accepting new connections. See net.Server.close().

    server.maxHeadersCount#

    Limits maximum incoming headers count, equal to 1000 by default. If set to 0 - no limit will be applied.

    server.setTimeout(msecs, callback)#

    • msecs Number
    • callback Function

    Sets the timeout value for sockets, and emits a 'timeout' event on the Server object, passing the socket as an argument, if a timeout occurs.

    If there is a 'timeout' event listener on the Server object, then it will be called with the timed-out socket as an argument.

    By default, the Server's timeout value is 2 minutes, and sockets are destroyed automatically if they time out. However, if you assign a callback to the Server's 'timeout' event, then you are responsible for handling socket timeouts.

    server.timeout#

    • Number Default = 120000 (2 minutes)

    The number of milliseconds of inactivity before a socket is presumed to have timed out.

    Note that the socket timeout logic is set up on connection, so changing this value only affects new connections to the server, not any existing connections.

    Set to 0 to disable any kind of automatic timeout behavior on incoming connections.

    Class: http.ServerResponse#

    This object is created internally by a HTTP server--not by the user. It is passed as the second parameter to the 'request' event.

    The response implements the Writable Stream interface. This is an EventEmitter with the following events:

    Event: 'close'#

    function () { }

    Indicates that the underlying connection was terminated before response.end() was called or able to flush.

    Event: 'finish'#

    function () { }

    Emitted when the response has been sent. More specifically, this event is emitted when the last segment of the response headers and body have been handed off to the operating system for transmission over the network. It does not imply that the client has received anything yet.

    After this event, no more events will be emitted on the response object.

    response.writeContinue()#

    Sends a HTTP/1.1 100 Continue message to the client, indicating that the request body should be sent. See the 'checkContinue' event on Server.

    response.writeHead(statusCode, [reasonPhrase], [headers])#

    Sends a response header to the request. The status code is a 3-digit HTTP status code, like 404. The last argument, headers, are the response headers. Optionally one can give a human-readable reasonPhrase as the second argument.

    Example:

    var body = 'hello world';
    response.writeHead(200, {
      'Content-Length': body.length,
      'Content-Type': 'text/plain' });

    This method must only be called once on a message and it must be called before response.end() is called.

    If you call response.write() or response.end() before calling this, the implicit/mutable headers will be calculated and call this function for you.

    Note: that Content-Length is given in bytes not characters. The above example works because the string 'hello world' contains only single byte characters. If the body contains higher coded characters then Buffer.byteLength() should be used to determine the number of bytes in a given encoding. And Node does not check whether Content-Length and the length of the body which has been transmitted are equal or not.

    response.setTimeout(msecs, callback)#

    • msecs Number
    • callback Function

    Sets the Socket's timeout value to msecs. If a callback is provided, then it is added as a listener on the 'timeout' event on the response object.

    If no 'timeout' listener is added to the request, the response, or the server, then sockets are destroyed when they time out. If you assign a handler on the request, the response, or the server's 'timeout' events, then it is your responsibility to handle timed out sockets.

    response.statusCode#

    When using implicit headers (not calling response.writeHead() explicitly), this property controls the status code that will be sent to the client when the headers get flushed.

    Example:

    response.statusCode = 404;

    After response header was sent to the client, this property indicates the status code which was sent out.

    response.setHeader(name, value)#

    Sets a single header value for implicit headers. If this header already exists in the to-be-sent headers, its value will be replaced. Use an array of strings here if you need to send multiple headers with the same name.

    Example:

    response.setHeader("Content-Type", "text/html");

    or

    response.setHeader("Set-Cookie", ["type=ninja", "language=javascript"]);

    response.headersSent#

    Boolean (read-only). True if headers were sent, false otherwise.

    response.sendDate#

    When true, the Date header will be automatically generated and sent in the response if it is not already present in the headers. Defaults to true.

    This should only be disabled for testing; HTTP requires the Date header in responses.

    response.getHeader(name)#

    Reads out a header that's already been queued but not sent to the client. Note that the name is case insensitive. This can only be called before headers get implicitly flushed.

    Example:

    var contentType = response.getHeader('content-type');

    response.removeHeader(name)#

    Removes a header that's queued for implicit sending.

    Example:

    response.removeHeader("Content-Encoding");

    response.write(chunk, [encoding])#

    If this method is called and response.writeHead() has not been called, it will switch to implicit header mode and flush the implicit headers.

    This sends a chunk of the response body. This method may be called multiple times to provide successive parts of the body.

    chunk can be a string or a buffer. If chunk is a string, the second parameter specifies how to encode it into a byte stream. By default the encoding is 'utf8'.

    Note: This is the raw HTTP body and has nothing to do with higher-level multi-part body encodings that may be used.

    The first time response.write() is called, it will send the buffered header information and the first body to the client. The second time response.write() is called, Node assumes you're going to be streaming data, and sends that separately. That is, the response is buffered up to the first chunk of body.

    Returns true if the entire data was flushed successfully to the kernel buffer. Returns false if all or part of the data was queued in user memory. 'drain' will be emitted when the buffer is again free.

    response.addTrailers(headers)#

    This method adds HTTP trailing headers (a header but at the end of the message) to the response.

    Trailers will only be emitted if chunked encoding is used for the response; if it is not (e.g., if the request was HTTP/1.0), they will be silently discarded.

    Note that HTTP requires the Trailer header to be sent if you intend to emit trailers, with a list of the header fields in its value. E.g.,

    response.writeHead(200, { 'Content-Type': 'text/plain',
                              'Trailer': 'Content-MD5' });
    response.write(fileData);
    response.addTrailers({'Content-MD5': "7895bf4b8828b55ceaf47747b4bca667"});
    response.end();

    response.end([data], [encoding])#

    This method signals to the server that all of the response headers and body have been sent; that server should consider this message complete. The method, response.end(), MUST be called on each response.

    If data is specified, it is equivalent to calling response.write(data, encoding) followed by response.end().

    http.request(options, [callback])#

    Node maintains several connections per server to make HTTP requests. This function allows one to transparently issue requests.

    options can be an object or a string. If options is a string, it is automatically parsed with url.parse().

    Options:

    • host: A domain name or IP address of the server to issue the request to. Defaults to 'localhost'.
    • hostname: To support url.parse() hostname is preferred over host
    • port: Port of remote server. Defaults to 80.
    • localAddress: Local interface to bind for network connections.
    • socketPath: Unix Domain Socket (use one of host:port or socketPath)
    • method: A string specifying the HTTP request method. Defaults to 'GET'.
    • path: Request path. Defaults to '/'. Should include query string if any. E.G. '/index.html?page=12'
    • headers: An object containing request headers.
    • auth: Basic authentication i.e. 'user:password' to compute an Authorization header.
    • agent: Controls Agent behavior. When an Agent is used request will default to Connection: keep-alive. Possible values:
      • undefined (default): use global Agent for this host and port.
      • Agent object: explicitly use the passed in Agent.
      • false: opts out of connection pooling with an Agent, defaults request to Connection: close.

    The optional callback parameter will be added as a one time listener for the 'response' event.

    http.request() returns an instance of the http.ClientRequest class. The ClientRequest instance is a writable stream. If one needs to upload a file with a POST request, then write to the ClientRequest object.

    Example:

    var options = {
      hostname: 'www.google.com',
      port: 80,
      path: '/upload',
      method: 'POST'
    };
    
    var req = http.request(options, function(res) {
      console.log('STATUS: ' + res.statusCode);
      console.log('HEADERS: ' + JSON.stringify(res.headers));
      res.setEncoding('utf8');
      res.on('data', function (chunk) {
        console.log('BODY: ' + chunk);
      });
    });
    
    req.on('error', function(e) {
      console.log('problem with request: ' + e.message);
    });
    
    // write data to request body
    req.write('data\n');
    req.write('data\n');
    req.end();

    Note that in the example req.end() was called. With http.request() one must always call req.end() to signify that you're done with the request - even if there is no data being written to the request body.

    If any error is encountered during the request (be that with DNS resolution, TCP level errors, or actual HTTP parse errors) an 'error' event is emitted on the returned request object.

    There are a few special headers that should be noted.

    • Sending a 'Connection: keep-alive' will notify Node that the connection to the server should be persisted until the next request.

    • Sending a 'Content-length' header will disable the default chunked encoding.

    • Sending an 'Expect' header will immediately send the request headers. Usually, when sending 'Expect: 100-continue', you should both set a timeout and listen for the continue event. See RFC2616 Section 8.2.3 for more information.

    • Sending an Authorization header will override using the auth option to compute basic authentication.

    http.get(options, [callback])#

    Since most requests are GET requests without bodies, Node provides this convenience method. The only difference between this method and http.request() is that it sets the method to GET and calls req.end() automatically.

    Example:

    http.get("http://www.google.com/index.html", function(res) {
      console.log("Got response: " + res.statusCode);
    }).on('error', function(e) {
      console.log("Got error: " + e.message);
    });

    Class: http.Agent#

    In node 0.5.3+ there is a new implementation of the HTTP Agent which is used for pooling sockets used in HTTP client requests.

    Previously, a single agent instance helped pool for a single host+port. The current implementation now holds sockets for any number of hosts.

    The current HTTP Agent also defaults client requests to using Connection:keep-alive. If no pending HTTP requests are waiting on a socket to become free the socket is closed. This means that node's pool has the benefit of keep-alive when under load but still does not require developers to manually close the HTTP clients using keep-alive.

    Sockets are removed from the agent's pool when the socket emits either a "close" event or a special "agentRemove" event. This means that if you intend to keep one HTTP request open for a long time and don't want it to stay in the pool you can do something along the lines of:

    http.get(options, function(res) {
      // Do stuff
    }).on("socket", function (socket) {
      socket.emit("agentRemove");
    });

    Alternatively, you could just opt out of pooling entirely using agent:false:

    http.get({hostname:'localhost', port:80, path:'/', agent:false}, function (res) {
      // Do stuff
    })

    agent.maxSockets#

    By default set to 5. Determines how many concurrent sockets the agent can have open per host.

    agent.sockets#

    An object which contains arrays of sockets currently in use by the Agent. Do not modify.

    agent.requests#

    An object which contains queues of requests that have not yet been assigned to sockets. Do not modify.

    http.globalAgent#

    Global instance of Agent which is used as the default for all http client requests.

    Class: http.ClientRequest#

    This object is created internally and returned from http.request(). It represents an in-progress request whose header has already been queued. The header is still mutable using the setHeader(name, value), getHeader(name), removeHeader(name) API. The actual header will be sent along with the first data chunk or when closing the connection.

    To get the response, add a listener for 'response' to the request object. 'response' will be emitted from the request object when the response headers have been received. The 'response' event is executed with one argument which is an instance of http.IncomingMessage.

    During the 'response' event, one can add listeners to the response object; particularly to listen for the 'data' event.

    If no 'response' handler is added, then the response will be entirely discarded. However, if you add a 'response' event handler, then you must consume the data from the response object, either by calling response.read() whenever there is a 'readable' event, or by adding a 'data' handler, or by calling the .resume() method. Until the data is consumed, the 'end' event will not fire. Also, until the data is read it will consume memory that can eventually lead to a 'process out of memory' error.

    Note: Node does not check whether Content-Length and the length of the body which has been transmitted are equal or not.

    The request implements the Writable Stream interface. This is an EventEmitter with the following events:

    Event 'response'#

    function (response) { }

    Emitted when a response is received to this request. This event is emitted only once. The response argument will be an instance of http.IncomingMessage.

    Options:

    • host: A domain name or IP address of the server to issue the request to.
    • port: Port of remote server.
    • socketPath: Unix Domain Socket (use one of host:port or socketPath)

    Event: 'socket'#

    function (socket) { }

    Emitted after a socket is assigned to this request.

    Event: 'connect'#

    function (response, socket, head) { }

    Emitted each time a server responds to a request with a CONNECT method. If this event isn't being listened for, clients receiving a CONNECT method will have their connections closed.

    A client server pair that show you how to listen for the connect event.

    var http = require('http');
    var net = require('net');
    var url = require('url');
    
    // Create an HTTP tunneling proxy
    var proxy = http.createServer(function (req, res) {
      res.writeHead(200, {'Content-Type': 'text/plain'});
      res.end('okay');
    });
    proxy.on('connect', function(req, cltSocket, head) {
      // connect to an origin server
      var srvUrl = url.parse('http://' + req.url);
      var srvSocket = net.connect(srvUrl.port, srvUrl.hostname, function() {
        cltSocket.write('HTTP/1.1 200 Connection Established\r\n' +
                        'Proxy-agent: Node-Proxy\r\n' +
                        '\r\n');
        srvSocket.write(head);
        srvSocket.pipe(cltSocket);
        cltSocket.pipe(srvSocket);
      });
    });
    
    // now that proxy is running
    proxy.listen(1337, '127.0.0.1', function() {
    
      // make a request to a tunneling proxy
      var options = {
        port: 1337,
        hostname: '127.0.0.1',
        method: 'CONNECT',
        path: 'www.google.com:80'
      };
    
      var req = http.request(options);
      req.end();
    
      req.on('connect', function(res, socket, head) {
        console.log('got connected!');
    
        // make a request over an HTTP tunnel
        socket.write('GET / HTTP/1.1\r\n' +
                     'Host: www.google.com:80\r\n' +
                     'Connection: close\r\n' +
                     '\r\n');
        socket.on('data', function(chunk) {
          console.log(chunk.toString());
        });
        socket.on('end', function() {
          proxy.close();
        });
      });
    });

    Event: 'upgrade'#

    function (response, socket, head) { }

    Emitted each time a server responds to a request with an upgrade. If this event isn't being listened for, clients receiving an upgrade header will have their connections closed.

    A client server pair that show you how to listen for the upgrade event.

    var http = require('http');
    
    // Create an HTTP server
    var srv = http.createServer(function (req, res) {
      res.writeHead(200, {'Content-Type': 'text/plain'});
      res.end('okay');
    });
    srv.on('upgrade', function(req, socket, head) {
      socket.write('HTTP/1.1 101 Web Socket Protocol Handshake\r\n' +
                   'Upgrade: WebSocket\r\n' +
                   'Connection: Upgrade\r\n' +
                   '\r\n');
    
      socket.pipe(socket); // echo back
    });
    
    // now that server is running
    srv.listen(1337, '127.0.0.1', function() {
    
      // make a request
      var options = {
        port: 1337,
        hostname: '127.0.0.1',
        headers: {
          'Connection': 'Upgrade',
          'Upgrade': 'websocket'
        }
      };
    
      var req = http.request(options);
      req.end();
    
      req.on('upgrade', function(res, socket, upgradeHead) {
        console.log('got upgraded!');
        socket.end();
        process.exit(0);
      });
    });

    Event: 'continue'#

    function () { }

    Emitted when the server sends a '100 Continue' HTTP response, usually because the request contained 'Expect: 100-continue'. This is an instruction that the client should send the request body.

    request.write(chunk, [encoding])#

    Sends a chunk of the body. By calling this method many times, the user can stream a request body to a server--in that case it is suggested to use the ['Transfer-Encoding', 'chunked'] header line when creating the request.

    The chunk argument should be a Buffer or a string.

    The encoding argument is optional and only applies when chunk is a string. Defaults to 'utf8'.

    request.end([data], [encoding])#

    Finishes sending the request. If any parts of the body are unsent, it will flush them to the stream. If the request is chunked, this will send the terminating '0\r\n\r\n'.

    If data is specified, it is equivalent to calling request.write(data, encoding) followed by request.end().

    request.abort()#

    Aborts a request. (New since v0.3.8.)

    request.setTimeout(timeout, [callback])#

    Once a socket is assigned to this request and is connected socket.setTimeout() will be called.

    request.setNoDelay([noDelay])#

    Once a socket is assigned to this request and is connected socket.setNoDelay() will be called.

    request.setSocketKeepAlive([enable], [initialDelay])#

    Once a socket is assigned to this request and is connected socket.setKeepAlive() will be called.

    http.IncomingMessage#

    An IncomingMessage object is created by http.Server or http.ClientRequest and passed as the first argument to the 'request' and 'response' event respectively. It may be used to access response status, headers and data.

    It implements the Readable Stream interface, as well as the following additional events, methods, and properties.

    Event: 'close'#

    function () { }

    Indicates that the underlaying connection was closed. Just like 'end', this event occurs only once per response.

    message.httpVersion#

    In case of server request, the HTTP version sent by the client. In the case of client response, the HTTP version of the connected-to server. Probably either '1.1' or '1.0'.

    Also response.httpVersionMajor is the first integer and response.httpVersionMinor is the second.

    message.headers#

    The request/response headers object.

    Read only map of header names and values. Header names are lower-cased. Example:

    // Prints something like:
    //
    // { 'user-agent': 'curl/7.22.0',
    //   host: '127.0.0.1:8000',
    //   accept: '*/*' }
    console.log(request.headers);

    message.trailers#

    The request/response trailers object. Only populated after the 'end' event.

    message.setTimeout(msecs, callback)#

    • msecs Number
    • callback Function

    Calls message.connection.setTimeout(msecs, callback).

    message.method#

    Only valid for request obtained from http.Server.

    The request method as a string. Read only. Example: 'GET', 'DELETE'.

    message.url#

    Only valid for request obtained from http.Server.

    Request URL string. This contains only the URL that is present in the actual HTTP request. If the request is:

    GET /status?name=ryan HTTP/1.1\r\n
    Accept: text/plain\r\n
    \r\n

    Then request.url will be:

    '/status?name=ryan'

    If you would like to parse the URL into its parts, you can use require('url').parse(request.url). Example:

    node> require('url').parse('/status?name=ryan')
    { href: '/status?name=ryan',
      search: '?name=ryan',
      query: 'name=ryan',
      pathname: '/status' }

    If you would like to extract the params from the query string, you can use the require('querystring').parse function, or pass true as the second argument to require('url').parse. Example:

    node> require('url').parse('/status?name=ryan', true)
    { href: '/status?name=ryan',
      search: '?name=ryan',
      query: { name: 'ryan' },
      pathname: '/status' }

    message.statusCode#

    Only valid for response obtained from http.ClientRequest.

    The 3-digit HTTP response status code. E.G. 404.

    message.socket#

    The net.Socket object associated with the connection.

    With HTTPS support, use request.connection.verifyPeer() and request.connection.getPeerCertificate() to obtain the client's authentication details.

    HTTPS#

    Stability: 3 - Stable

    HTTPS is the HTTP protocol over TLS/SSL. In Node this is implemented as a separate module.

    Class: https.Server#

    This class is a subclass of tls.Server and emits events same as http.Server. See http.Server for more information.

    https.createServer(options, [requestListener])#

    Returns a new HTTPS web server object. The options is similar to tls.createServer(). The requestListener is a function which is automatically added to the 'request' event.

    Example:

    // curl -k https://localhost:8000/
    var https = require('https');
    var fs = require('fs');
    
    var options = {
      key: fs.readFileSync('test/fixtures/keys/agent2-key.pem'),
      cert: fs.readFileSync('test/fixtures/keys/agent2-cert.pem')
    };
    
    https.createServer(options, function (req, res) {
      res.writeHead(200);
      res.end("hello world\n");
    }).listen(8000);

    Or

    var https = require('https');
    var fs = require('fs');
    
    var options = {
      pfx: fs.readFileSync('server.pfx')
    };
    
    https.createServer(options, function (req, res) {
      res.writeHead(200);
      res.end("hello world\n");
    }).listen(8000);

    server.listen(port, [host], [backlog], [callback])#

    server.listen(path, [callback])#

    server.listen(handle, [callback])#

    See http.listen() for details.

    server.close([callback])#

    See http.close() for details.

    https.request(options, callback)#

    Makes a request to a secure web server.

    options can be an object or a string. If options is a string, it is automatically parsed with url.parse().

    All options from http.request() are valid.

    Example:

    var https = require('https');
    
    var options = {
      hostname: 'encrypted.google.com',
      port: 443,
      path: '/',
      method: 'GET'
    };
    
    var req = https.request(options, function(res) {
      console.log("statusCode: ", res.statusCode);
      console.log("headers: ", res.headers);
    
      res.on('data', function(d) {
        process.stdout.write(d);
      });
    });
    req.end();
    
    req.on('error', function(e) {
      console.error(e);
    });

    The options argument has the following options

    • host: A domain name or IP address of the server to issue the request to. Defaults to 'localhost'.
    • hostname: To support url.parse() hostname is preferred over host
    • port: Port of remote server. Defaults to 443.
    • method: A string specifying the HTTP request method. Defaults to 'GET'.
    • path: Request path. Defaults to '/'. Should include query string if any. E.G. '/index.html?page=12'
    • headers: An object containing request headers.
    • auth: Basic authentication i.e. 'user:password' to compute an Authorization header.
    • agent: Controls Agent behavior. When an Agent is used request will default to Connection: keep-alive. Possible values:
      • undefined (default): use globalAgent for this host and port.
      • Agent object: explicitly use the passed in Agent.
      • false: opts out of connection pooling with an Agent, defaults request to Connection: close.

    The following options from tls.connect() can also be specified. However, a globalAgent silently ignores these.

    • pfx: Certificate, Private key and CA certificates to use for SSL. Default null.
    • key: Private key to use for SSL. Default null.
    • passphrase: A string of passphrase for the private key or pfx. Default null.
    • cert: Public x509 certificate to use. Default null.
    • ca: An authority certificate or array of authority certificates to check the remote host against.
    • ciphers: A string describing the ciphers to use or exclude. Consult http://www.openssl.org/docs/apps/ciphers.html#CIPHER_LIST_FORMAT for details on the format.
    • rejectUnauthorized: If true, the server certificate is verified against the list of supplied CAs. An 'error' event is emitted if verification fails. Verification happens at the connection level, before the HTTP request is sent. Default true.
    • secureProtocol: The SSL method to use, e.g. SSLv3_method to force SSL version 3. The possible values depend on your installation of OpenSSL and are defined in the constant SSL_METHODS.

    In order to specify these options, use a custom Agent.

    Example:

    var options = {
      hostname: 'encrypted.google.com',
      port: 443,
      path: '/',
      method: 'GET',
      key: fs.readFileSync('test/fixtures/keys/agent2-key.pem'),
      cert: fs.readFileSync('test/fixtures/keys/agent2-cert.pem')
    };
    options.agent = new https.Agent(options);
    
    var req = https.request(options, function(res) {
      ...
    }

    Or does not use an Agent.

    Example:

    var options = {
      hostname: 'encrypted.google.com',
      port: 443,
      path: '/',
      method: 'GET',
      key: fs.readFileSync('test/fixtures/keys/agent2-key.pem'),
      cert: fs.readFileSync('test/fixtures/keys/agent2-cert.pem'),
      agent: false
    };
    
    var req = https.request(options, function(res) {
      ...
    }

    https.get(options, callback)#

    Like http.get() but for HTTPS.

    options can be an object or a string. If options is a string, it is automatically parsed with url.parse().

    Example:

    var https = require('https');
    
    https.get('https://encrypted.google.com/', function(res) {
      console.log("statusCode: ", res.statusCode);
      console.log("headers: ", res.headers);
    
      res.on('data', function(d) {
        process.stdout.write(d);
      });
    
    }).on('error', function(e) {
      console.error(e);
    });

    Class: https.Agent#

    An Agent object for HTTPS similar to http.Agent. See https.request() for more information.

    https.globalAgent#

    Global instance of https.Agent for all HTTPS client requests.

    URL#

    Stability: 3 - Stable

    This module has utilities for URL resolution and parsing. Call require('url') to use it.

    Parsed URL objects have some or all of the following fields, depending on whether or not they exist in the URL string. Any parts that are not in the URL string will not be in the parsed object. Examples are shown for the URL

    'http://user:pass@host.com:8080/p/a/t/h?query=string#hash'

    • href: The full URL that was originally parsed. Both the protocol and host are lowercased.

      Example: 'http://user:pass@host.com:8080/p/a/t/h?query=string#hash'

    • protocol: The request protocol, lowercased.

      Example: 'http:'

    • host: The full lowercased host portion of the URL, including port information.

      Example: 'host.com:8080'

    • auth: The authentication information portion of a URL.

      Example: 'user:pass'

    • hostname: Just the lowercased hostname portion of the host.

      Example: 'host.com'

    • port: The port number portion of the host.

      Example: '8080'

    • pathname: The path section of the URL, that comes after the host and before the query, including the initial slash if present.

      Example: '/p/a/t/h'

    • search: The 'query string' portion of the URL, including the leading question mark.

      Example: '?query=string'

    • path: Concatenation of pathname and search.

      Example: '/p/a/t/h?query=string'

    • query: Either the 'params' portion of the query string, or a querystring-parsed object.

      Example: 'query=string' or {'query':'string'}

    • hash: The 'fragment' portion of the URL including the pound-sign.

      Example: '#hash'

    The following methods are provided by the URL module:

    url.parse(urlStr, [parseQueryString], [slashesDenoteHost])#

    Take a URL string, and return an object.

    Pass true as the second argument to also parse the query string using the querystring module. Defaults to false.

    Pass true as the third argument to treat //foo/bar as { host: 'foo', pathname: '/bar' } rather than { pathname: '//foo/bar' }. Defaults to false.

    url.format(urlObj)#

    Take a parsed URL object, and return a formatted URL string.

    • href will be ignored.
    • protocolis treated the same with or without the trailing : (colon).
      • The protocols http, https, ftp, gopher, file will be postfixed with :// (colon-slash-slash).
      • All other protocols mailto, xmpp, aim, sftp, foo, etc will be postfixed with : (colon)
    • auth will be used if present.
    • hostname will only be used if host is absent.
    • port will only be used if host is absent.
    • host will be used in place of hostname and port
    • pathname is treated the same with or without the leading / (slash)
    • search will be used in place of query
    • query (object; see querystring) will only be used if search is absent.
    • search is treated the same with or without the leading ? (question mark)
    • hash is treated the same with or without the leading # (pound sign, anchor)

    url.resolve(from, to)#

    Take a base URL, and a href URL, and resolve them as a browser would for an anchor tag. Examples:

    url.resolve('/one/two/three', 'four')         // '/one/two/four'
    url.resolve('http://example.com/', '/one')    // 'http://example.com/one'
    url.resolve('http://example.com/one', '/two') // 'http://example.com/two'

    Query String#

    Stability: 3 - Stable

    This module provides utilities for dealing with query strings. It provides the following methods:

    querystring.stringify(obj, [sep], [eq])#

    Serialize an object to a query string. Optionally override the default separator ('&') and assignment ('=') characters.

    Example:

    querystring.stringify({ foo: 'bar', baz: ['qux', 'quux'], corge: '' })
    // returns
    'foo=bar&baz=qux&baz=quux&corge='
    
    querystring.stringify({foo: 'bar', baz: 'qux'}, ';', ':')
    // returns
    'foo:bar;baz:qux'

    querystring.parse(str, [sep], [eq], [options])#

    Deserialize a query string to an object. Optionally override the default separator ('&') and assignment ('=') characters.

    Options object may contain maxKeys property (equal to 1000 by default), it'll be used to limit processed keys. Set it to 0 to remove key count limitation.

    Example:

    querystring.parse('foo=bar&baz=qux&baz=quux&corge')
    // returns
    { foo: 'bar', baz: ['qux', 'quux'], corge: '' }

    querystring.escape#

    The escape function used by querystring.stringify, provided so that it could be overridden if necessary.

    querystring.unescape#

    The unescape function used by querystring.parse, provided so that it could be overridden if necessary.

    punycode#

    Stability: 2 - Unstable

    Punycode.js is bundled with Node.js v0.6.2+. Use require('punycode') to access it. (To use it with other Node.js versions, use npm to install the punycode module first.)

    punycode.decode(string)#

    Converts a Punycode string of ASCII code points to a string of Unicode code points.

    // decode domain name parts
    punycode.decode('maana-pta'); // 'mañana'
    punycode.decode('--dqo34k'); // '☃-⌘'

    punycode.encode(string)#

    Converts a string of Unicode code points to a Punycode string of ASCII code points.

    // encode domain name parts
    punycode.encode('mañana'); // 'maana-pta'
    punycode.encode('☃-⌘'); // '--dqo34k'

    punycode.toUnicode(domain)#

    Converts a Punycode string representing a domain name to Unicode. Only the Punycoded parts of the domain name will be converted, i.e. it doesn't matter if you call it on a string that has already been converted to Unicode.

    // decode domain names
    punycode.toUnicode('xn--maana-pta.com'); // 'mañana.com'
    punycode.toUnicode('xn----dqo34k.com'); // '☃-⌘.com'

    punycode.toASCII(domain)#

    Converts a Unicode string representing a domain name to Punycode. Only the non-ASCII parts of the domain name will be converted, i.e. it doesn't matter if you call it with a domain that's already in ASCII.

    // encode domain names
    punycode.toASCII('mañana.com'); // 'xn--maana-pta.com'
    punycode.toASCII('☃-⌘.com'); // 'xn----dqo34k.com'

    punycode.ucs2#

    punycode.ucs2.decode(string)#

    Creates an array containing the decimal code points of each Unicode character in the string. While JavaScript uses UCS-2 internally, this function will convert a pair of surrogate halves (each of which UCS-2 exposes as separate characters) into a single code point, matching UTF-16.

    punycode.ucs2.decode('abc'); // [97, 98, 99]
    // surrogate pair for U+1D306 tetragram for centre:
    punycode.ucs2.decode('\uD834\uDF06'); // [0x1D306]

    punycode.ucs2.encode(codePoints)#

    Creates a string based on an array of decimal code points.

    punycode.ucs2.encode([97, 98, 99]); // 'abc'
    punycode.ucs2.encode([0x1D306]); // '\uD834\uDF06'

    punycode.version#

    A string representing the current Punycode.js version number.

    Readline#

    Stability: 2 - Unstable

    To use this module, do require('readline'). Readline allows reading of a stream (such as process.stdin) on a line-by-line basis.

    Note that once you've invoked this module, your node program will not terminate until you've closed the interface. Here's how to allow your program to gracefully exit:

    var readline = require('readline');
    
    var rl = readline.createInterface({
      input: process.stdin,
      output: process.stdout
    });
    
    rl.question("What do you think of node.js? ", function(answer) {
      // TODO: Log the answer in a database
      console.log("Thank you for your valuable feedback:", answer);
    
      rl.close();
    });

    readline.createInterface(options)#

    Creates a readline Interface instance. Accepts an "options" Object that takes the following values:

    • input - the readable stream to listen to (Required).

    • output - the writable stream to write readline data to (Required).

    • completer - an optional function that is used for Tab autocompletion. See below for an example of using this.

    • terminal - pass true if the input and output streams should be treated like a TTY, and have ANSI/VT100 escape codes written to it. Defaults to checking isTTY on the output stream upon instantiation.

    The completer function is given a the current line entered by the user, and is supposed to return an Array with 2 entries:

    1. An Array with matching entries for the completion.

    2. The substring that was used for the matching.

    Which ends up looking something like: [[substr1, substr2, ...], originalsubstring].

    Example:

    function completer(line) {
      var completions = '.help .error .exit .quit .q'.split(' ')
      var hits = completions.filter(function(c) { return c.indexOf(line) == 0 })
      // show all completions if none found
      return [hits.length ? hits : completions, line]
    }

    Also completer can be run in async mode if it accepts two arguments:

    function completer(linePartial, callback) {
      callback(null, [['123'], linePartial]);
    }

    createInterface is commonly used with process.stdin and process.stdout in order to accept user input:

    var readline = require('readline');
    var rl = readline.createInterface({
      input: process.stdin,
      output: process.stdout
    });

    Once you have a readline instance, you most commonly listen for the "line" event.

    If terminal is true for this instance then the output stream will get the best compatibility if it defines an output.columns property, and fires a "resize" event on the output if/when the columns ever change (process.stdout does this automatically when it is a TTY).

    Class: Interface#

    The class that represents a readline interface with an input and output stream.

    rl.setPrompt(prompt, length)#

    Sets the prompt, for example when you run node on the command line, you see > , which is node's prompt.

    rl.prompt([preserveCursor])#

    Readies readline for input from the user, putting the current setPrompt options on a new line, giving the user a new spot to write. Set preserveCursor to true to prevent the cursor placement being reset to 0.

    This will also resume the input stream used with createInterface if it has been paused.

    rl.question(query, callback)#

    Prepends the prompt with query and invokes callback with the user's response. Displays the query to the user, and then invokes callback with the user's response after it has been typed.

    This will also resume the input stream used with createInterface if it has been paused.

    Example usage:

    interface.question('What is your favorite food?', function(answer) {
      console.log('Oh, so your favorite food is ' + answer);
    });

    rl.pause()#

    Pauses the readline input stream, allowing it to be resumed later if needed.

    rl.resume()#

    Resumes the readline input stream.

    rl.close()#

    Closes the Interface instance, relinquishing control on the input and output streams. The "close" event will also be emitted.

    rl.write(data, [key])#

    Writes data to output stream. key is an object literal to represent a key sequence; available if the terminal is a TTY.

    This will also resume the input stream if it has been paused.

    Example:

    rl.write('Delete me!');
    // Simulate ctrl+u to delete the line written previously
    rl.write(null, {ctrl: true, name: 'u'});

    Events#

    Event: 'line'#

    function (line) {}

    Emitted whenever the input stream receives a \n, usually received when the user hits enter, or return. This is a good hook to listen for user input.

    Example of listening for line:

    rl.on('line', function (cmd) {
      console.log('You just typed: '+cmd);
    });

    Event: 'pause'#

    function () {}

    Emitted whenever the input stream is paused.

    Also emitted whenever the input stream is not paused and receives the SIGCONT event. (See events SIGTSTP and SIGCONT)

    Example of listening for pause:

    rl.on('pause', function() {
      console.log('Readline paused.');
    });

    Event: 'resume'#

    function () {}

    Emitted whenever the input stream is resumed.

    Example of listening for resume:

    rl.on('resume', function() {
      console.log('Readline resumed.');
    });

    Event: 'close'#

    function () {}

    Emitted when close() is called.

    Also emitted when the input stream receives its "end" event. The Interface instance should be considered "finished" once this is emitted. For example, when the input stream receives ^D, respectively known as EOT.

    This event is also called if there is no SIGINT event listener present when the input stream receives a ^C, respectively known as SIGINT.

    Event: 'SIGINT'#

    function () {}

    Emitted whenever the input stream receives a ^C, respectively known as SIGINT. If there is no SIGINT event listener present when the input stream receives a SIGINT, pause will be triggered.

    Example of listening for SIGINT:

    rl.on('SIGINT', function() {
      rl.question('Are you sure you want to exit?', function(answer) {
        if (answer.match(/^y(es)?$/i)) rl.pause();
      });
    });

    Event: 'SIGTSTP'#

    function () {}

    This does not work on Windows.

    Emitted whenever the input stream receives a ^Z, respectively known as SIGTSTP. If there is no SIGTSTP event listener present when the input stream receives a SIGTSTP, the program will be sent to the background.

    When the program is resumed with fg, the pause and SIGCONT events will be emitted. You can use either to resume the stream.

    The pause and SIGCONT events will not be triggered if the stream was paused before the program was sent to the background.

    Example of listening for SIGTSTP:

    rl.on('SIGTSTP', function() {
      // This will override SIGTSTP and prevent the program from going to the
      // background.
      console.log('Caught SIGTSTP.');
    });

    Event: 'SIGCONT'#

    function () {}

    This does not work on Windows.

    Emitted whenever the input stream is sent to the background with ^Z, respectively known as SIGTSTP, and then continued with fg(1). This event only emits if the stream was not paused before sending the program to the background.

    Example of listening for SIGCONT:

    rl.on('SIGCONT', function() {
      // `prompt` will automatically resume the stream
      rl.prompt();
    });

    Example: Tiny CLI#

    Here's an example of how to use all these together to craft a tiny command line interface:

    var readline = require('readline'),
        rl = readline.createInterface(process.stdin, process.stdout);
    
    rl.setPrompt('OHAI> ');
    rl.prompt();
    
    rl.on('line', function(line) {
      switch(line.trim()) {
        case 'hello':
          console.log('world!');
          break;
        default:
          console.log('Say what? I might have heard `' + line.trim() + '`');
          break;
      }
      rl.prompt();
    }).on('close', function() {
      console.log('Have a great day!');
      process.exit(0);
    });

    REPL#

    A Read-Eval-Print-Loop (REPL) is available both as a standalone program and easily includable in other programs. The REPL provides a way to interactively run JavaScript and see the results. It can be used for debugging, testing, or just trying things out.

    By executing node without any arguments from the command-line you will be dropped into the REPL. It has simplistic emacs line-editing.

    mjr:~$ node
    Type '.help' for options.
    > a = [ 1, 2, 3];
    [ 1, 2, 3 ]
    > a.forEach(function (v) {
    ...   console.log(v);
    ...   });
    1
    2
    3

    For advanced line-editors, start node with the environmental variable NODE_NO_READLINE=1. This will start the main and debugger REPL in canonical terminal settings which will allow you to use with rlwrap.

    For example, you could add this to your bashrc file:

    alias node="env NODE_NO_READLINE=1 rlwrap node"

    repl.start(options)#

    Returns and starts a REPLServer instance. Accepts an "options" Object that takes the following values:

    • prompt - the prompt and stream for all I/O. Defaults to > .

    • input - the readable stream to listen to. Defaults to process.stdin.

    • output - the writable stream to write readline data to. Defaults to process.stdout.

    • terminal - pass true if the stream should be treated like a TTY, and have ANSI/VT100 escape codes written to it. Defaults to checking isTTY on the output stream upon instantiation.

    • eval - function that will be used to eval each given line. Defaults to an async wrapper for eval(). See below for an example of a custom eval.

    • useColors - a boolean which specifies whether or not the writer function should output colors. If a different writer function is set then this does nothing. Defaults to the repl's terminal value.

    • useGlobal - if set to true, then the repl will use the global object, instead of running scripts in a separate context. Defaults to false.

    • ignoreUndefined - if set to true, then the repl will not output the return value of command if it's undefined. Defaults to false.

    • writer - the function to invoke for each command that gets evaluated which returns the formatting (including coloring) to display. Defaults to util.inspect.

    You can use your own eval function if it has following signature:

    function eval(cmd, context, filename, callback) {
      callback(null, result);
    }

    Multiple REPLs may be started against the same running instance of node. Each will share the same global object but will have unique I/O.

    Here is an example that starts a REPL on stdin, a Unix socket, and a TCP socket:

    var net = require("net"),
        repl = require("repl");
    
    connections = 0;
    
    repl.start({
      prompt: "node via stdin> ",
      input: process.stdin,
      output: process.stdout
    });
    
    net.createServer(function (socket) {
      connections += 1;
      repl.start({
        prompt: "node via Unix socket> ",
        input: socket,
        output: socket
      }).on('exit', function() {
        socket.end();
      })
    }).listen("/tmp/node-repl-sock");
    
    net.createServer(function (socket) {
      connections += 1;
      repl.start({
        prompt: "node via TCP socket> ",
        input: socket,
        output: socket
      }).on('exit', function() {
        socket.end();
      });
    }).listen(5001);

    Running this program from the command line will start a REPL on stdin. Other REPL clients may connect through the Unix socket or TCP socket. telnet is useful for connecting to TCP sockets, and socat can be used to connect to both Unix and TCP sockets.

    By starting a REPL from a Unix socket-based server instead of stdin, you can connect to a long-running node process without restarting it.

    For an example of running a "full-featured" (terminal) REPL over a net.Server and net.Socket instance, see: https://gist.github.com/2209310

    For an example of running a REPL instance over curl(1), see: https://gist.github.com/2053342

    Event: 'exit'#

    function () {}

    Emitted when the user exits the REPL in any of the defined ways. Namely, typing .exit at the repl, pressing Ctrl+C twice to signal SIGINT, or pressing Ctrl+D to signal "end" on the input stream.

    Example of listening for exit:

    r.on('exit', function () {
      console.log('Got "exit" event from repl!');
      process.exit();
    });

    REPL Features#

    Inside the REPL, Control+D will exit. Multi-line expressions can be input. Tab completion is supported for both global and local variables.

    The special variable _ (underscore) contains the result of the last expression.

    > [ "a", "b", "c" ]
    [ 'a', 'b', 'c' ]
    > _.length
    3
    > _ += 1
    4

    The REPL provides access to any variables in the global scope. You can expose a variable to the REPL explicitly by assigning it to the context object associated with each REPLServer. For example:

    // repl_test.js
    var repl = require("repl"),
        msg = "message";
    
    repl.start("> ").context.m = msg;

    Things in the context object appear as local within the REPL:

    mjr:~$ node repl_test.js
    > m
    'message'

    There are a few special REPL commands:

    • .break - While inputting a multi-line expression, sometimes you get lost or just don't care about completing it. .break will start over.
    • .clear - Resets the context object to an empty object and clears any multi-line expression.
    • .exit - Close the I/O stream, which will cause the REPL to exit.
    • .help - Show this list of special commands.
    • .save - Save the current REPL session to a file

      .save ./file/to/save.js

    • .load - Load a file into the current REPL session.

      .load ./file/to/load.js

    The following key combinations in the REPL have these special effects:

    • <ctrl>C - Similar to the .break keyword. Terminates the current command. Press twice on a blank line to forcibly exit.
    • <ctrl>D - Similar to the .exit keyword.

    Executing JavaScript#

    Stability: 2 - Unstable. See Caveats, below.

    You can access this module with:

    var vm = require('vm');

    JavaScript code can be compiled and run immediately or compiled, saved, and run later.

    Caveats#

    The vm module has many known issues and edge cases. If you run into issues or unexpected behavior, please consult the open issues on GitHub. Some of the biggest problems are described below.

    Sandboxes#

    The sandbox argument to vm.runInNewContext and vm.createContext, along with the initSandbox argument to vm.createContext, do not behave as one might normally expect and their behavior varies between different versions of Node.

    The key issue to be aware of is that V8 provides no way to directly control the global object used within a context. As a result, while properties of your sandbox object will be available in the context, any properties from the prototypes of the sandbox may not be available. Furthermore, the this expression within the global scope of the context evaluates to the empty object ({}) instead of to your sandbox.

    Your sandbox's properties are also not shared directly with the script. Instead, the properties of the sandbox are copied into the context at the beginning of execution, and then after execution, the properties are copied back out in an attempt to propagate any changes.

    Globals#

    Properties of the global object, like Array and String, have different values inside of a context. This means that common expressions like [] instanceof Array or Object.getPrototypeOf([]) === Array.prototype may not produce expected results when used inside of scripts evaluated via the vm module.

    Some of these problems have known workarounds listed in the issues for vm on GitHub. for example, Array.isArray works around the example problem with Array.

    vm.runInThisContext(code, [filename])#

    vm.runInThisContext() compiles code, runs it and returns the result. Running code does not have access to local scope. filename is optional, it's used only in stack traces.

    Example of using vm.runInThisContext and eval to run the same code:

    var localVar = 123,
        usingscript, evaled,
        vm = require('vm');
    
    usingscript = vm.runInThisContext('localVar = 1;',
      'myfile.vm');
    console.log('localVar: ' + localVar + ', usingscript: ' +
      usingscript);
    evaled = eval('localVar = 1;');
    console.log('localVar: ' + localVar + ', evaled: ' +
      evaled);
    
    // localVar: 123, usingscript: 1
    // localVar: 1, evaled: 1

    vm.runInThisContext does not have access to the local scope, so localVar is unchanged. eval does have access to the local scope, so localVar is changed.

    In case of syntax error in code, vm.runInThisContext emits the syntax error to stderr and throws an exception.

    vm.runInNewContext(code, [sandbox], [filename])#

    vm.runInNewContext compiles code, then runs it in sandbox and returns the result. Running code does not have access to local scope. The object sandbox will be used as the global object for code. sandbox and filename are optional, filename is only used in stack traces.

    Example: compile and execute code that increments a global variable and sets a new one. These globals are contained in the sandbox.

    var util = require('util'),
        vm = require('vm'),
        sandbox = {
          animal: 'cat',
          count: 2
        };
    
    vm.runInNewContext('count += 1; name = "kitty"', sandbox, 'myfile.vm');
    console.log(util.inspect(sandbox));
    
    // { animal: 'cat', count: 3, name: 'kitty' }

    Note that running untrusted code is a tricky business requiring great care. To prevent accidental global variable leakage, vm.runInNewContext is quite useful, but safely running untrusted code requires a separate process.

    In case of syntax error in code, vm.runInNewContext emits the syntax error to stderr and throws an exception.

    vm.runInContext(code, context, [filename])#

    vm.runInContext compiles code, then runs it in context and returns the result. A (V8) context comprises a global object, together with a set of built-in objects and functions. Running code does not have access to local scope and the global object held within context will be used as the global object for code. filename is optional, it's used only in stack traces.

    Example: compile and execute code in a existing context.

    var util = require('util'),
        vm = require('vm'),
        initSandbox = {
          animal: 'cat',
          count: 2
        },
        context = vm.createContext(initSandbox);
    
    vm.runInContext('count += 1; name = "CATT"', context, 'myfile.vm');
    console.log(util.inspect(context));
    
    // { animal: 'cat', count: 3, name: 'CATT' }

    Note that createContext will perform a shallow clone of the supplied sandbox object in order to initialize the global object of the freshly constructed context.

    Note that running untrusted code is a tricky business requiring great care. To prevent accidental global variable leakage, vm.runInContext is quite useful, but safely running untrusted code requires a separate process.

    In case of syntax error in code, vm.runInContext emits the syntax error to stderr and throws an exception.

    vm.createContext([initSandbox])#

    vm.createContext creates a new context which is suitable for use as the 2nd argument of a subsequent call to vm.runInContext. A (V8) context comprises a global object together with a set of build-in objects and functions. The optional argument initSandbox will be shallow-copied to seed the initial contents of the global object used by the context.

    vm.createScript(code, [filename])#

    createScript compiles code but does not run it. Instead, it returns a vm.Script object representing this compiled code. This script can be run later many times using methods below. The returned script is not bound to any global object. It is bound before each run, just for that run. filename is optional, it's only used in stack traces.

    In case of syntax error in code, createScript prints the syntax error to stderr and throws an exception.

    Class: Script#

    A class for running scripts. Returned by vm.createScript.

    script.runInThisContext()#

    Similar to vm.runInThisContext but a method of a precompiled Script object. script.runInThisContext runs the code of script and returns the result. Running code does not have access to local scope, but does have access to the global object (v8: in actual context).

    Example of using script.runInThisContext to compile code once and run it multiple times:

    var vm = require('vm');
    
    globalVar = 0;
    
    var script = vm.createScript('globalVar += 1', 'myfile.vm');
    
    for (var i = 0; i < 1000 ; i += 1) {
      script.runInThisContext();
    }
    
    console.log(globalVar);
    
    // 1000

    script.runInNewContext([sandbox])#

    Similar to vm.runInNewContext a method of a precompiled Script object. script.runInNewContext runs the code of script with sandbox as the global object and returns the result. Running code does not have access to local scope. sandbox is optional.

    Example: compile code that increments a global variable and sets one, then execute this code multiple times. These globals are contained in the sandbox.

    var util = require('util'),
        vm = require('vm'),
        sandbox = {
          animal: 'cat',
          count: 2
        };
    
    var script = vm.createScript('count += 1; name = "kitty"', 'myfile.vm');
    
    for (var i = 0; i < 10 ; i += 1) {
      script.runInNewContext(sandbox);
    }
    
    console.log(util.inspect(sandbox));
    
    // { animal: 'cat', count: 12, name: 'kitty' }

    Note that running untrusted code is a tricky business requiring great care. To prevent accidental global variable leakage, script.runInNewContext is quite useful, but safely running untrusted code requires a separate process.

    Child Process#

    Stability: 3 - Stable

    Node provides a tri-directional popen(3) facility through the child_process module.

    It is possible to stream data through a child's stdin, stdout, and stderr in a fully non-blocking way. (Note that some programs use line-buffered I/O internally. That doesn't affect node.js but it means data you send to the child process is not immediately consumed.)

    To create a child process use require('child_process').spawn() or require('child_process').fork(). The semantics of each are slightly different, and explained below.

    Class: ChildProcess#

    ChildProcess is an EventEmitter.

    Child processes always have three streams associated with them. child.stdin, child.stdout, and child.stderr. These may be shared with the stdio streams of the parent process, or they may be separate stream objects which can be piped to and from.

    The ChildProcess class is not intended to be used directly. Use the spawn() or fork() methods to create a Child Process instance.

    Event: 'error'#

    • err Error Object the error.

    Emitted when:

    1. The process could not be spawned, or
    2. The process could not be killed, or
    3. Sending a message to the child process failed for whatever reason.

    Note that the exit-event may or may not fire after an error has occured. If you are listening on both events to fire a function, remember to guard against calling your function twice.

    See also ChildProcess#kill() and ChildProcess#send().

    Event: 'exit'#

    • code Number the exit code, if it exited normally.
    • signal String the signal passed to kill the child process, if it was killed by the parent.

    This event is emitted after the child process ends. If the process terminated normally, code is the final exit code of the process, otherwise null. If the process terminated due to receipt of a signal, signal is the string name of the signal, otherwise null.

    Note that the child process stdio streams might still be open.

    Also, note that node establishes signal handlers for 'SIGINT' and 'SIGTERM', so it will not terminate due to receipt of those signals, it will exit.

    See waitpid(2).

    Event: 'close'#

    • code Number the exit code, if it exited normally.
    • signal String the signal passed to kill the child process, if it was killed by the parent.

    This event is emitted when the stdio streams of a child process have all terminated. This is distinct from 'exit', since multiple processes might share the same stdio streams.

    Event: 'disconnect'#

    This event is emitted after calling the .disconnect() method in the parent or in the child. After disconnecting it is no longer possible to send messages, and the .connected property is false.

    Event: 'message'#

    • message Object a parsed JSON object or primitive value
    • sendHandle Handle object a Socket or Server object

    Messages send by .send(message, [sendHandle]) are obtained using the message event.

    child.stdin#

    • Stream object

    A Writable Stream that represents the child process's stdin. Closing this stream via end() often causes the child process to terminate.

    If the child stdio streams are shared with the parent, then this will not be set.

    child.stdout#

    • Stream object

    A Readable Stream that represents the child process's stdout.

    If the child stdio streams are shared with the parent, then this will not be set.

    child.stderr#

    • Stream object

    A Readable Stream that represents the child process's stderr.

    If the child stdio streams are shared with the parent, then this will not be set.

    child.pid#

    • Integer

    The PID of the child process.

    Example:

    var spawn = require('child_process').spawn,
        grep  = spawn('grep', ['ssh']);
    
    console.log('Spawned child pid: ' + grep.pid);
    grep.stdin.end();

    child.connected#

    • Boolean Set to false after `.disconnect' is called

    If .connected is false, it is no longer possible to send messages.

    child.kill([signal])#

    • signal String

    Send a signal to the child process. If no argument is given, the process will be sent 'SIGTERM'. See signal(7) for a list of available signals.

    var spawn = require('child_process').spawn,
        grep  = spawn('grep', ['ssh']);
    
    grep.on('close', function (code, signal) {
      console.log('child process terminated due to receipt of signal '+signal);
    });
    
    // send SIGHUP to process
    grep.kill('SIGHUP');

    May emit an 'error' event when the signal cannot be delivered. Sending a signal to a child process that has already exited is not an error but may have unforeseen consequences: if the PID (the process ID) has been reassigned to another process, the signal will be delivered to that process instead. What happens next is anyone's guess.

    Note that while the function is called kill, the signal delivered to the child process may not actually kill it. kill really just sends a signal to a process.

    See kill(2)

    child.send(message, [sendHandle])#

    • message Object
    • sendHandle Handle object

    When using child_process.fork() you can write to the child using child.send(message, [sendHandle]) and messages are received by a 'message' event on the child.

    For example:

    var cp = require('child_process');
    
    var n = cp.fork(__dirname + '/sub.js');
    
    n.on('message', function(m) {
      console.log('PARENT got message:', m);
    });
    
    n.send({ hello: 'world' });

    And then the child script, 'sub.js' might look like this:

    process.on('message', function(m) {
      console.log('CHILD got message:', m);
    });
    
    process.send({ foo: 'bar' });

    In the child the process object will have a send() method, and process will emit objects each time it receives a message on its channel.

    Please note that the send() method on both the parent and child are synchronous - sending large chunks of data is not advised (pipes can be used instead, see child_process.spawn).

    There is a special case when sending a {cmd: 'NODE_foo'} message. All messages containing a NODE_ prefix in its cmd property will not be emitted in the message event, since they are internal messages used by node core. Messages containing the prefix are emitted in the internalMessage event, you should by all means avoid using this feature, it is subject to change without notice.

    The sendHandle option to child.send() is for sending a TCP server or socket object to another process. The child will receive the object as its second argument to the message event.

    Emits an 'error' event if the message cannot be sent, for example because the child process has already exited.

    Example: sending server object#

    Here is an example of sending a server:

    var child = require('child_process').fork('child.js');
    
    // Open up the server object and send the handle.
    var server = require('net').createServer();
    server.on('connection', function (socket) {
      socket.end('handled by parent');
    });
    server.listen(1337, function() {
      child.send('server', server);
    });

    And the child would the receive the server object as:

    process.on('message', function(m, server) {
      if (m === 'server') {
        server.on('connection', function (socket) {
          socket.end('handled by child');
        });
      }
    });

    Note that the server is now shared between the parent and child, this means that some connections will be handled by the parent and some by the child.

    For dgram servers the workflow is exactly the same. Here you listen on a message event instead of connection and use server.bind instead of server.listen. (Currently only supported on UNIX platforms.)

    Example: sending socket object#

    Here is an example of sending a socket. It will spawn two children and handle connections with the remote address 74.125.127.100 as VIP by sending the socket to a "special" child process. Other sockets will go to a "normal" process.

    var normal = require('child_process').fork('child.js', ['normal']);
    var special = require('child_process').fork('child.js', ['special']);
    
    // Open up the server and send sockets to child
    var server = require('net').createServer();
    server.on('connection', function (socket) {
    
      // if this is a VIP
      if (socket.remoteAddress === '74.125.127.100') {
        special.send('socket', socket);
        return;
      }
      // just the usual dudes
      normal.send('socket', socket);
    });
    server.listen(1337);

    The child.js could look like this:

    process.on('message', function(m, socket) {
      if (m === 'socket') {
        socket.end('You were handled as a ' + process.argv[2] + ' person');
      }
    });

    Note that once a single socket has been sent to a child the parent can no longer keep track of when the socket is destroyed. To indicate this condition the .connections property becomes null. It is also recommended not to use .maxConnections in this condition.

    child.disconnect()#

    Close the IPC channel between parent and child, allowing the child to exit gracefully once there are no other connections keeping it alive. After calling this method the .connected flag will be set to false in both the parent and child, and it is no longer possible to send messages.

    The 'disconnect' event will be emitted when there are no messages in the process of being received, most likely immediately.

    Note that you can also call process.disconnect() in the child process.

    child_process.spawn(command, [args], [options])#

    • command String The command to run
    • args Array List of string arguments
    • options Object
      • cwd String Current working directory of the child process
      • stdio Array|String Child's stdio configuration. (See below)
      • customFds Array Deprecated File descriptors for the child to use for stdio. (See below)
      • env Object Environment key-value pairs
      • detached Boolean The child will be a process group leader. (See below)
      • uid Number Sets the user identity of the process. (See setuid(2).)
      • gid Number Sets the group identity of the process. (See setgid(2).)
    • return: ChildProcess object

    Launches a new process with the given command, with command line arguments in args. If omitted, args defaults to an empty Array.

    The third argument is used to specify additional options, which defaults to:

    { cwd: undefined,
      env: process.env
    }

    cwd allows you to specify the working directory from which the process is spawned. Use env to specify environment variables that will be visible to the new process.

    Example of running ls -lh /usr, capturing stdout, stderr, and the exit code:

    var spawn = require('child_process').spawn,
        ls    = spawn('ls', ['-lh', '/usr']);
    
    ls.stdout.on('data', function (data) {
      console.log('stdout: ' + data);
    });
    
    ls.stderr.on('data', function (data) {
      console.log('stderr: ' + data);
    });
    
    ls.on('close', function (code) {
      console.log('child process exited with code ' + code);
    });

    Example: A very elaborate way to run 'ps ax | grep ssh'

    var spawn = require('child_process').spawn,
        ps    = spawn('ps', ['ax']),
        grep  = spawn('grep', ['ssh']);
    
    ps.stdout.on('data', function (data) {
      grep.stdin.write(data);
    });
    
    ps.stderr.on('data', function (data) {
      console.log('ps stderr: ' + data);
    });
    
    ps.on('close', function (code) {
      if (code !== 0) {
        console.log('ps process exited with code ' + code);
      }
      grep.stdin.end();
    });
    
    grep.stdout.on('data', function (data) {
      console.log('' + data);
    });
    
    grep.stderr.on('data', function (data) {
      console.log('grep stderr: ' + data);
    });
    
    grep.on('close', function (code) {
      if (code !== 0) {
        console.log('grep process exited with code ' + code);
      }
    });

    Example of checking for failed exec:

    var spawn = require('child_process').spawn,
        child = spawn('bad_command');
    
    child.stderr.setEncoding('utf8');
    child.stderr.on('data', function (data) {
      if (/^execvp\(\)/.test(data)) {
        console.log('Failed to start child process.');
      }
    });

    Note that if spawn receives an empty options object, it will result in spawning the process with an empty environment rather than using process.env. This due to backwards compatibility issues with a deprecated API.

    The 'stdio' option to child_process.spawn() is an array where each index corresponds to a fd in the child. The value is one of the following:

    1. 'pipe' - Create a pipe between the child process and the parent process. The parent end of the pipe is exposed to the parent as a property on the child_process object as ChildProcess.stdio[fd]. Pipes created for fds 0 - 2 are also available as ChildProcess.stdin, ChildProcess.stdout and ChildProcess.stderr, respectively.
    2. 'ipc' - Create an IPC channel for passing messages/file descriptors between parent and child. A ChildProcess may have at most one IPC stdio file descriptor. Setting this option enables the ChildProcess.send() method. If the child writes JSON messages to this file descriptor, then this will trigger ChildProcess.on('message'). If the child is a Node.js program, then the presence of an IPC channel will enable process.send() and process.on('message').
    3. 'ignore' - Do not set this file descriptor in the child. Note that Node will always open fd 0 - 2 for the processes it spawns. When any of these is ignored node will open /dev/null and attach it to the child's fd.
    4. Stream object - Share a readable or writable stream that refers to a tty, file, socket, or a pipe with the child process. The stream's underlying file descriptor is duplicated in the child process to the fd that corresponds to the index in the stdio array. Note that the stream must have an underlying descriptor (file streams do not until the 'open' event has occurred).
    5. Positive integer - The integer value is interpreted as a file descriptor that is is currently open in the parent process. It is shared with the child process, similar to how Stream objects can be shared.
    6. null, undefined - Use default value. For stdio fds 0, 1 and 2 (in other words, stdin, stdout, and stderr) a pipe is created. For fd 3 and up, the default is 'ignore'.

    As a shorthand, the stdio argument may also be one of the following strings, rather than an array:

    • ignore - ['ignore', 'ignore', 'ignore']
    • pipe - ['pipe', 'pipe', 'pipe']
    • inherit - [process.stdin, process.stdout, process.stderr] or [0,1,2]

    Example:

    var spawn = require('child_process').spawn;
    
    // Child will use parent's stdios
    spawn('prg', [], { stdio: 'inherit' });
    
    // Spawn child sharing only stderr
    spawn('prg', [], { stdio: ['pipe', 'pipe', process.stderr] });
    
    // Open an extra fd=4, to interact with programs present a
    // startd-style interface.
    spawn('prg', [], { stdio: ['pipe', null, null, null, 'pipe'] });

    If the detached option is set, the child process will be made the leader of a new process group. This makes it possible for the child to continue running after the parent exits.

    By default, the parent will wait for the detached child to exit. To prevent the parent from waiting for a given child, use the child.unref() method, and the parent's event loop will not include the child in its reference count.

    Example of detaching a long-running process and redirecting its output to a file:

     var fs = require('fs'),
         spawn = require('child_process').spawn,
         out = fs.openSync('./out.log', 'a'),
         err = fs.openSync('./out.log', 'a');
    
     var child = spawn('prg', [], {
       detached: true,
       stdio: [ 'ignore', out, err ]
     });
    
     child.unref();

    When using the detached option to start a long-running process, the process will not stay running in the background unless it is provided with a stdio configuration that is not connected to the parent. If the parent's stdio is inherited, the child will remain attached to the controlling terminal.

    There is a deprecated option called customFds which allows one to specify specific file descriptors for the stdio of the child process. This API was not portable to all platforms and therefore removed. With customFds it was possible to hook up the new process' [stdin, stdout, stderr] to existing streams; -1 meant that a new stream should be created. Use at your own risk.

    See also: child_process.exec() and child_process.fork()

    child_process.exec(command, [options], callback)#

    • command String The command to run, with space-separated arguments
    • options Object
      • cwd String Current working directory of the child process
      • env Object Environment key-value pairs
      • encoding String (Default: 'utf8')
      • timeout Number (Default: 0)
      • maxBuffer Number (Default: 200*1024)
      • killSignal String (Default: 'SIGTERM')
    • callback Function called with the output when process terminates
      • error Error
      • stdout Buffer
      • stderr Buffer
    • Return: ChildProcess object

    Runs a command in a shell and buffers the output.

    var exec = require('child_process').exec,
        child;
    
    child = exec('cat *.js bad_file | wc -l',
      function (error, stdout, stderr) {
        console.log('stdout: ' + stdout);
        console.log('stderr: ' + stderr);
        if (error !== null) {
          console.log('exec error: ' + error);
        }
    });

    The callback gets the arguments (error, stdout, stderr). On success, error will be null. On error, error will be an instance of Error and err.code will be the exit code of the child process, and err.signal will be set to the signal that terminated the process.

    There is a second optional argument to specify several options. The default options are

    { encoding: 'utf8',
      timeout: 0,
      maxBuffer: 200*1024,
      killSignal: 'SIGTERM',
      cwd: null,
      env: null }

    If timeout is greater than 0, then it will kill the child process if it runs longer than timeout milliseconds. The child process is killed with killSignal (default: 'SIGTERM'). maxBuffer specifies the largest amount of data allowed on stdout or stderr - if this value is exceeded then the child process is killed.

    child_process.execFile(file, [args], [options], [callback])#

    • file String The filename of the program to run
    • args Array List of string arguments
    • options Object
      • cwd String Current working directory of the child process
      • env Object Environment key-value pairs
      • encoding String (Default: 'utf8')
      • timeout Number (Default: 0)
      • maxBuffer Number (Default: 200*1024)
      • killSignal String (Default: 'SIGTERM')
    • callback Function called with the output when process terminates
      • error Error
      • stdout Buffer
      • stderr Buffer
    • Return: ChildProcess object

    This is similar to child_process.exec() except it does not execute a subshell but rather the specified file directly. This makes it slightly leaner than child_process.exec. It has the same options.

    child_process.fork(modulePath, [args], [options])#

    • modulePath String The module to run in the child
    • args Array List of string arguments
    • options Object
      • cwd String Current working directory of the child process
      • env Object Environment key-value pairs
      • encoding String (Default: 'utf8')
      • execPath String Executable used to create the child process
      • execArgv Array List of string arguments passed to the executable (Default: process.execArgv)
      • silent Boolean If true, stdin, stdout, and stderr of the child will be piped to the parent, otherwise they will be inherited from the parent, see the "pipe" and "inherit" options for spawn()'s stdio for more details (default is false)
    • Return: ChildProcess object

    This is a special case of the spawn() functionality for spawning Node processes. In addition to having all the methods in a normal ChildProcess instance, the returned object has a communication channel built-in. See child.send(message, [sendHandle]) for details.

    These child Nodes are still whole new instances of V8. Assume at least 30ms startup and 10mb memory for each new Node. That is, you cannot create many thousands of them.

    The execPath property in the options object allows for a process to be created for the child rather than the current node executable. This should be done with care and by default will talk over the fd represented an environmental variable NODE_CHANNEL_FD on the child process. The input and output on this fd is expected to be line delimited JSON objects.

    Assert#

    Stability: 5 - Locked

    This module is used for writing unit tests for your applications, you can access it with require('assert').

    assert.fail(actual, expected, message, operator)#

    Throws an exception that displays the values for actual and expected separated by the provided operator.

    assert(value, message), assert.ok(value, [message])#

    Tests if value is truthy, it is equivalent to assert.equal(true, !!value, message);

    assert.equal(actual, expected, [message])#

    Tests shallow, coercive equality with the equal comparison operator ( == ).

    assert.notEqual(actual, expected, [message])#

    Tests shallow, coercive non-equality with the not equal comparison operator ( != ).

    assert.deepEqual(actual, expected, [message])#

    Tests for deep equality.

    assert.notDeepEqual(actual, expected, [message])#

    Tests for any deep inequality.

    assert.strictEqual(actual, expected, [message])#

    Tests strict equality, as determined by the strict equality operator ( === )

    assert.notStrictEqual(actual, expected, [message])#

    Tests strict non-equality, as determined by the strict not equal operator ( !== )

    assert.throws(block, [error], [message])#

    Expects block to throw an error. error can be constructor, regexp or validation function.

    Validate instanceof using constructor:

    assert.throws(
      function() {
        throw new Error("Wrong value");
      },
      Error
    );

    Validate error message using RegExp:

    assert.throws(
      function() {
        throw new Error("Wrong value");
      },
      /value/
    );

    Custom error validation:

    assert.throws(
      function() {
        throw new Error("Wrong value");
      },
      function(err) {
        if ( (err instanceof Error) && /value/.test(err) ) {
          return true;
        }
      },
      "unexpected error"
    );

    assert.doesNotThrow(block, [message])#

    Expects block not to throw an error, see assert.throws for details.

    assert.ifError(value)#

    Tests if value is not a false value, throws if it is a true value. Useful when testing the first argument, error in callbacks.

    TTY#

    Stability: 2 - Unstable

    The tty module houses the tty.ReadStream and tty.WriteStream classes. In most cases, you will not need to use this module directly.

    When node detects that it is being run inside a TTY context, then process.stdin will be a tty.ReadStream instance and process.stdout will be a tty.WriteStream instance. The preferred way to check if node is being run in a TTY context is to check process.stdout.isTTY:

    $ node -p -e "Boolean(process.stdout.isTTY)"
    true
    $ node -p -e "Boolean(process.stdout.isTTY)" | cat
    false

    tty.isatty(fd)#

    Returns true or false depending on if the fd is associated with a terminal.

    tty.setRawMode(mode)#

    Deprecated. Use tty.ReadStream#setRawMode() (i.e. process.stdin.setRawMode()) instead.

    Class: ReadStream#

    A net.Socket subclass that represents the readable portion of a tty. In normal circumstances, process.stdin will be the only tty.ReadStream instance in any node program (only when isatty(0) is true).

    rs.isRaw#

    A Boolean that is initialized to false. It represents the current "raw" state of the tty.ReadStream instance.

    rs.setRawMode(mode)#

    mode should be true or false. This sets the properties of the tty.ReadStream to act either as a raw device or default. isRaw will be set to the resulting mode.

    Class: WriteStream#

    A net.Socket subclass that represents the writable portion of a tty. In normal circumstances, process.stdout will be the only tty.WriteStream instance ever created (and only when isatty(1) is true).

    ws.columns#

    A Number that gives the number of columns the TTY currently has. This property gets updated on "resize" events.

    ws.rows#

    A Number that gives the number of rows the TTY currently has. This property gets updated on "resize" events.

    Event: 'resize'#

    function () {}

    Emitted by refreshSize() when either of the columns or rows properties has changed.

    process.stdout.on('resize', function() {
      console.log('screen size has changed!');
      console.log(process.stdout.columns + 'x' + process.stdout.rows);
    });

    Zlib#

    Stability: 3 - Stable

    You can access this module with:

    var zlib = require('zlib');

    This provides bindings to Gzip/Gunzip, Deflate/Inflate, and DeflateRaw/InflateRaw classes. Each class takes the same options, and is a readable/writable Stream.

    Examples#

    Compressing or decompressing a file can be done by piping an fs.ReadStream into a zlib stream, then into an fs.WriteStream.

    var gzip = zlib.createGzip();
    var fs = require('fs');
    var inp = fs.createReadStream('input.txt');
    var out = fs.createWriteStream('input.txt.gz');
    
    inp.pipe(gzip).pipe(out);

    Compressing or decompressing data in one step can be done by using the convenience methods.

    var input = '.................................';
    zlib.deflate(input, function(err, buffer) {
      if (!err) {
        console.log(buffer.toString('base64'));
      }
    });
    
    var buffer = new Buffer('eJzT0yMAAGTvBe8=', 'base64');
    zlib.unzip(buffer, function(err, buffer) {
      if (!err) {
        console.log(buffer.toString());
      }
    });

    To use this module in an HTTP client or server, use the accept-encoding on requests, and the content-encoding header on responses.

    Note: these examples are drastically simplified to show the basic concept. Zlib encoding can be expensive, and the results ought to be cached. See Memory Usage Tuning below for more information on the speed/memory/compression tradeoffs involved in zlib usage.

    // client request example
    var zlib = require('zlib');
    var http = require('http');
    var fs = require('fs');
    var request = http.get({ host: 'izs.me',
                             path: '/',
                             port: 80,
                             headers: { 'accept-encoding': 'gzip,deflate' } });
    request.on('response', function(response) {
      var output = fs.createWriteStream('izs.me_index.html');
    
      switch (response.headers['content-encoding']) {
        // or, just use zlib.createUnzip() to handle both cases
        case 'gzip':
          response.pipe(zlib.createGunzip()).pipe(output);
          break;
        case 'deflate':
          response.pipe(zlib.createInflate()).pipe(output);
          break;
        default:
          response.pipe(output);
          break;
      }
    });
    
    // server example
    // Running a gzip operation on every request is quite expensive.
    // It would be much more efficient to cache the compressed buffer.
    var zlib = require('zlib');
    var http = require('http');
    var fs = require('fs');
    http.createServer(function(request, response) {
      var raw = fs.createReadStream('index.html');
      var acceptEncoding = request.headers['accept-encoding'];
      if (!acceptEncoding) {
        acceptEncoding = '';
      }
    
      // Note: this is not a conformant accept-encoding parser.
      // See http://www.w3.org/Protocols/rfc2616/rfc2616-sec14.html#sec14.3
      if (acceptEncoding.match(/\bdeflate\b/)) {
        response.writeHead(200, { 'content-encoding': 'deflate' });
        raw.pipe(zlib.createDeflate()).pipe(response);
      } else if (acceptEncoding.match(/\bgzip\b/)) {
        response.writeHead(200, { 'content-encoding': 'gzip' });
        raw.pipe(zlib.createGzip()).pipe(response);
      } else {
        response.writeHead(200, {});
        raw.pipe(response);
      }
    }).listen(1337);

    zlib.createGzip([options])#

    Returns a new Gzip object with an options.

    zlib.createGunzip([options])#

    Returns a new Gunzip object with an options.

    zlib.createDeflate([options])#

    Returns a new Deflate object with an options.

    zlib.createInflate([options])#

    Returns a new Inflate object with an options.

    zlib.createDeflateRaw([options])#

    Returns a new DeflateRaw object with an options.

    zlib.createInflateRaw([options])#

    Returns a new InflateRaw object with an options.

    zlib.createUnzip([options])#

    Returns a new Unzip object with an options.

    Class: zlib.Zlib#

    Not exported by the zlib module. It is documented here because it is the base class of the compressor/decompressor classes.

    zlib.flush(callback)#

    Flush pending data. Don't call this frivolously, premature flushes negatively impact the effectiveness of the compression algorithm.

    zlib.reset()#

    Reset the compressor/decompressor to factory defaults. Only applicable to the inflate and deflate algorithms.

    Class: zlib.Gzip#

    Compress data using gzip.

    Class: zlib.Gunzip#

    Decompress a gzip stream.

    Class: zlib.Deflate#

    Compress data using deflate.

    Class: zlib.Inflate#

    Decompress a deflate stream.

    Class: zlib.DeflateRaw#

    Compress data using deflate, and do not append a zlib header.

    Class: zlib.InflateRaw#

    Decompress a raw deflate stream.

    Class: zlib.Unzip#

    Decompress either a Gzip- or Deflate-compressed stream by auto-detecting the header.

    Convenience Methods#

    All of these take a string or buffer as the first argument, and call the supplied callback with callback(error, result). The compression/decompression engine is created using the default settings in all convenience methods. To supply different options, use the zlib classes directly.

    zlib.deflate(buf, callback)#

    Compress a string with Deflate.

    zlib.deflateRaw(buf, callback)#

    Compress a string with DeflateRaw.

    zlib.gzip(buf, callback)#

    Compress a string with Gzip.

    zlib.gunzip(buf, callback)#

    Decompress a raw Buffer with Gunzip.

    zlib.inflate(buf, callback)#

    Decompress a raw Buffer with Inflate.

    zlib.inflateRaw(buf, callback)#

    Decompress a raw Buffer with InflateRaw.

    zlib.unzip(buf, callback)#

    Decompress a raw Buffer with Unzip.

    Options#

    Each class takes an options object. All options are optional. (The convenience methods use the default settings for all options.)

    Note that some options are only relevant when compressing, and are ignored by the decompression classes.

    • flush (default: zlib.Z_NO_FLUSH)
    • chunkSize (default: 16*1024)
    • windowBits
    • level (compression only)
    • memLevel (compression only)
    • strategy (compression only)
    • dictionary (deflate/inflate only, empty dictionary by default)

    See the description of deflateInit2 and inflateInit2 at

    http://zlib.net/manual.html#Advanced for more information on these.

    Memory Usage Tuning#

    From zlib/zconf.h, modified to node's usage:

    The memory requirements for deflate are (in bytes):

    (1 << (windowBits+2)) +  (1 << (memLevel+9))

    that is: 128K for windowBits=15 + 128K for memLevel = 8 (default values) plus a few kilobytes for small objects.

    For example, if you want to reduce the default memory requirements from 256K to 128K, set the options to:

    { windowBits: 14, memLevel: 7 }

    Of course this will generally degrade compression (there's no free lunch).

    The memory requirements for inflate are (in bytes)

    1 << windowBits

    that is, 32K for windowBits=15 (default value) plus a few kilobytes for small objects.

    This is in addition to a single internal output slab buffer of size chunkSize, which defaults to 16K.

    The speed of zlib compression is affected most dramatically by the level setting. A higher level will result in better compression, but will take longer to complete. A lower level will result in less compression, but will be much faster.

    In general, greater memory usage options will mean that node has to make fewer calls to zlib, since it'll be able to process more data in a single write operation. So, this is another factor that affects the speed, at the cost of memory usage.

    Constants#

    All of the constants defined in zlib.h are also defined on require('zlib'). In the normal course of operations, you will not need to ever set any of these. They are documented here so that their presence is not surprising. This section is taken almost directly from the zlib documentation. See

    http://zlib.net/manual.html#Constants for more details.

    Allowed flush values.

    • zlib.Z_NO_FLUSH
    • zlib.Z_PARTIAL_FLUSH
    • zlib.Z_SYNC_FLUSH
    • zlib.Z_FULL_FLUSH
    • zlib.Z_FINISH
    • zlib.Z_BLOCK
    • zlib.Z_TREES

    Return codes for the compression/decompression functions. Negative values are errors, positive values are used for special but normal events.

    • zlib.Z_OK
    • zlib.Z_STREAM_END
    • zlib.Z_NEED_DICT
    • zlib.Z_ERRNO
    • zlib.Z_STREAM_ERROR
    • zlib.Z_DATA_ERROR
    • zlib.Z_MEM_ERROR
    • zlib.Z_BUF_ERROR
    • zlib.Z_VERSION_ERROR

    Compression levels.

    • zlib.Z_NO_COMPRESSION
    • zlib.Z_BEST_SPEED
    • zlib.Z_BEST_COMPRESSION
    • zlib.Z_DEFAULT_COMPRESSION

    Compression strategy.

    • zlib.Z_FILTERED
    • zlib.Z_HUFFMAN_ONLY
    • zlib.Z_RLE
    • zlib.Z_FIXED
    • zlib.Z_DEFAULT_STRATEGY

    Possible values of the data_type field.

    • zlib.Z_BINARY
    • zlib.Z_TEXT
    • zlib.Z_ASCII
    • zlib.Z_UNKNOWN

    The deflate compression method (the only one supported in this version).

    • zlib.Z_DEFLATED

    For initializing zalloc, zfree, opaque.

    • zlib.Z_NULL

    os#

    Stability: 4 - API Frozen

    Provides a few basic operating-system related utility functions.

    Use require('os') to access this module.

    os.tmpdir()#

    Returns the operating system's default directory for temp files.

    os.endianness()#

    Returns the endianness of the CPU. Possible values are "BE" or "LE".

    os.hostname()#

    Returns the hostname of the operating system.

    os.type()#

    Returns the operating system name.

    os.platform()#

    Returns the operating system platform.

    os.arch()#

    Returns the operating system CPU architecture.

    os.release()#

    Returns the operating system release.

    os.uptime()#

    Returns the system uptime in seconds.

    os.loadavg()#

    Returns an array containing the 1, 5, and 15 minute load averages.

    The load average is a measure of system activity, calculated by the operating system and expressed as a fractional number. As a rule of thumb, the load average should ideally be less than the number of logical CPUs in the system.

    The load average is a very UNIX-y concept; there is no real equivalent on Windows platforms. That is why this function always returns [0, 0, 0] on Windows.

    os.totalmem()#

    Returns the total amount of system memory in bytes.

    os.freemem()#

    Returns the amount of free system memory in bytes.

    os.cpus()#

    Returns an array of objects containing information about each CPU/core installed: model, speed (in MHz), and times (an object containing the number of milliseconds the CPU/core spent in: user, nice, sys, idle, and irq).

    Example inspection of os.cpus:

    [ { model: 'Intel(R) Core(TM) i7 CPU         860  @ 2.80GHz',
        speed: 2926,
        times:
         { user: 252020,
           nice: 0,
           sys: 30340,
           idle: 1070356870,
           irq: 0 } },
      { model: 'Intel(R) Core(TM) i7 CPU         860  @ 2.80GHz',
        speed: 2926,
        times:
         { user: 306960,
           nice: 0,
           sys: 26980,
           idle: 1071569080,
           irq: 0 } },
      { model: 'Intel(R) Core(TM) i7 CPU         860  @ 2.80GHz',
        speed: 2926,
        times:
         { user: 248450,
           nice: 0,
           sys: 21750,
           idle: 1070919370,
           irq: 0 } },
      { model: 'Intel(R) Core(TM) i7 CPU         860  @ 2.80GHz',
        speed: 2926,
        times:
         { user: 256880,
           nice: 0,
           sys: 19430,
           idle: 1070905480,
           irq: 20 } },
      { model: 'Intel(R) Core(TM) i7 CPU         860  @ 2.80GHz',
        speed: 2926,
        times:
         { user: 511580,
           nice: 20,
           sys: 40900,
           idle: 1070842510,
           irq: 0 } },
      { model: 'Intel(R) Core(TM) i7 CPU         860  @ 2.80GHz',
        speed: 2926,
        times:
         { user: 291660,
           nice: 0,
           sys: 34360,
           idle: 1070888000,
           irq: 10 } },
      { model: 'Intel(R) Core(TM) i7 CPU         860  @ 2.80GHz',
        speed: 2926,
        times:
         { user: 308260,
           nice: 0,
           sys: 55410,
           idle: 1071129970,
           irq: 880 } },
      { model: 'Intel(R) Core(TM) i7 CPU         860  @ 2.80GHz',
        speed: 2926,
        times:
         { user: 266450,
           nice: 1480,
           sys: 34920,
           idle: 1072572010,
           irq: 30 } } ]

    os.networkInterfaces()#

    Get a list of network interfaces:

    { lo0: 
       [ { address: '::1', family: 'IPv6', internal: true },
         { address: 'fe80::1', family: 'IPv6', internal: true },
         { address: '127.0.0.1', family: 'IPv4', internal: true } ],
      en1: 
       [ { address: 'fe80::cabc:c8ff:feef:f996', family: 'IPv6',
           internal: false },
         { address: '10.0.1.123', family: 'IPv4', internal: false } ],
      vmnet1: [ { address: '10.99.99.254', family: 'IPv4', internal: false } ],
      vmnet8: [ { address: '10.88.88.1', family: 'IPv4', internal: false } ],
      ppp0: [ { address: '10.2.0.231', family: 'IPv4', internal: false } ] }

    os.EOL#

    A constant defining the appropriate End-of-line marker for the operating system.

    Debugger#

    Stability: 3 - Stable

    V8 comes with an extensive debugger which is accessible out-of-process via a simple TCP protocol. Node has a built-in client for this debugger. To use this, start Node with the debug argument; a prompt will appear:

    % node debug myscript.js
    < debugger listening on port 5858
    connecting... ok
    break in /home/indutny/Code/git/indutny/myscript.js:1
      1 x = 5;
      2 setTimeout(function () {
      3   debugger;
    debug>

    Node's debugger client doesn't support the full range of commands, but simple step and inspection is possible. By putting the statement debugger; into the source code of your script, you will enable a breakpoint.

    For example, suppose myscript.js looked like this:

    // myscript.js
    x = 5;
    setTimeout(function () {
      debugger;
      console.log("world");
    }, 1000);
    console.log("hello");

    Then once the debugger is run, it will break on line 4.

    % node debug myscript.js
    < debugger listening on port 5858
    connecting... ok
    break in /home/indutny/Code/git/indutny/myscript.js:1
      1 x = 5;
      2 setTimeout(function () {
      3   debugger;
    debug> cont
    < hello
    break in /home/indutny/Code/git/indutny/myscript.js:3
      1 x = 5;
      2 setTimeout(function () {
      3   debugger;
      4   console.log("world");
      5 }, 1000);
    debug> next
    break in /home/indutny/Code/git/indutny/myscript.js:4
      2 setTimeout(function () {
      3   debugger;
      4   console.log("world");
      5 }, 1000);
      6 console.log("hello");
    debug> repl
    Press Ctrl + C to leave debug repl
    > x
    5
    > 2+2
    4
    debug> next
    < world
    break in /home/indutny/Code/git/indutny/myscript.js:5
      3   debugger;
      4   console.log("world");
      5 }, 1000);
      6 console.log("hello");
      7
    debug> quit
    %

    The repl command allows you to evaluate code remotely. The next command steps over to the next line. There are a few other commands available and more to come. Type help to see others.

    Watchers#

    You can watch expression and variable values while debugging your code. On every breakpoint each expression from the watchers list will be evaluated in the current context and displayed just before the breakpoint's source code listing.

    To start watching an expression, type watch("my_expression"). watchers prints the active watchers. To remove a watcher, type unwatch("my_expression").

    Commands reference#

    Stepping#

    • cont, c - Continue execution
    • next, n - Step next
    • step, s - Step in
    • out, o - Step out
    • pause - Pause running code (like pause button in Developer Tools)

    Breakpoints#

    • setBreakpoint(), sb() - Set breakpoint on current line
    • setBreakpoint(line), sb(line) - Set breakpoint on specific line
    • setBreakpoint('fn()'), sb(...) - Set breakpoint on a first statement in functions body
    • setBreakpoint('script.js', 1), sb(...) - Set breakpoint on first line of script.js
    • clearBreakpoint, cb(...) - Clear breakpoint

    It is also possible to set a breakpoint in a file (module) that isn't loaded yet:

    % ./node debug test/fixtures/break-in-module/main.js
    < debugger listening on port 5858
    connecting to port 5858... ok
    break in test/fixtures/break-in-module/main.js:1
      1 var mod = require('./mod.js');
      2 mod.hello();
      3 mod.hello();
    debug> setBreakpoint('mod.js', 23)
    Warning: script 'mod.js' was not loaded yet.
      1 var mod = require('./mod.js');
      2 mod.hello();
      3 mod.hello();
    debug> c
    break in test/fixtures/break-in-module/mod.js:23
     21
     22 exports.hello = function() {
     23   return 'hello from module';
     24 };
     25
    debug>

    Info#

    • backtrace, bt - Print backtrace of current execution frame
    • list(5) - List scripts source code with 5 line context (5 lines before and after)
    • watch(expr) - Add expression to watch list
    • unwatch(expr) - Remove expression from watch list
    • watchers - List all watchers and their values (automatically listed on each breakpoint)
    • repl - Open debugger's repl for evaluation in debugging script's context

    Execution control#

    • run - Run script (automatically runs on debugger's start)
    • restart - Restart script
    • kill - Kill script

    Various#

    • scripts - List all loaded scripts
    • version - Display v8's version

    Advanced Usage#

    The V8 debugger can be enabled and accessed either by starting Node with the --debug command-line flag or by signaling an existing Node process with SIGUSR1.

    Once a process has been set in debug mode with this it can be connected to with the node debugger. Either connect to the pid or the URI to the debugger. The syntax is:

    • node debug -p <pid> - Connects to the process via the pid
    • node debug <URI> - Connects to the process via the URI such as localhost:5858

    Cluster#

    Stability: 1 - Experimental

    A single instance of Node runs in a single thread. To take advantage of multi-core systems the user will sometimes want to launch a cluster of Node processes to handle the load.

    The cluster module allows you to easily create child processes that all share server ports.

    var cluster = require('cluster');
    var http = require('http');
    var numCPUs = require('os').cpus().length;
    
    if (cluster.isMaster) {
      // Fork workers.
      for (var i = 0; i < numCPUs; i++) {
        cluster.fork();
      }
    
      cluster.on('exit', function(worker, code, signal) {
        console.log('worker ' + worker.process.pid + ' died');
      });
    } else {
      // Workers can share any TCP connection
      // In this case its a HTTP server
      http.createServer(function(req, res) {
        res.writeHead(200);
        res.end("hello world\n");
      }).listen(8000);
    }

    Running node will now share port 8000 between the workers:

    % NODE_DEBUG=cluster node server.js
    23521,Master Worker 23524 online
    23521,Master Worker 23526 online
    23521,Master Worker 23523 online
    23521,Master Worker 23528 online

    This feature was introduced recently, and may change in future versions. Please try it out and provide feedback.

    Also note that, on Windows, it is not yet possible to set up a named pipe server in a worker.

    How It Works#

    The worker processes are spawned using the child_process.fork method, so that they can communicate with the parent via IPC and pass server handles back and forth.

    When you call server.listen(...) in a worker, it serializes the arguments and passes the request to the master process. If the master process already has a listening server matching the worker's requirements, then it passes the handle to the worker. If it does not already have a listening server matching that requirement, then it will create one, and pass the handle to the worker.

    This causes potentially surprising behavior in three edge cases:

    1. server.listen({fd: 7}) Because the message is passed to the master, file descriptor 7 in the parent will be listened on, and the handle passed to the worker, rather than listening to the worker's idea of what the number 7 file descriptor references.
    2. server.listen(handle) Listening on handles explicitly will cause the worker to use the supplied handle, rather than talk to the master process. If the worker already has the handle, then it's presumed that you know what you are doing.
    3. server.listen(0) Normally, this will cause servers to listen on a random port. However, in a cluster, each worker will receive the same "random" port each time they do listen(0). In essence, the port is random the first time, but predictable thereafter. If you want to listen on a unique port, generate a port number based on the cluster worker ID.

    When multiple processes are all accept()ing on the same underlying resource, the operating system load-balances across them very efficiently. There is no routing logic in Node.js, or in your program, and no shared state between the workers. Therefore, it is important to design your program such that it does not rely too heavily on in-memory data objects for things like sessions and login.

    Because workers are all separate processes, they can be killed or re-spawned depending on your program's needs, without affecting other workers. As long as there are some workers still alive, the server will continue to accept connections. Node does not automatically manage the number of workers for you, however. It is your responsibility to manage the worker pool for your application's needs.

    cluster.settings#

    • Object
      • execArgv Array list of string arguments passed to the node executable. (Default=process.execArgv)
      • exec String file path to worker file. (Default=process.argv[1])
      • args Array string arguments passed to worker. (Default=process.argv.slice(2))
      • silent Boolean whether or not to send output to parent's stdio. (Default=false)

    After calling .setupMaster() (or .fork()) this settings object will contain the settings, including the default values.

    It is effectively frozen after being set, because .setupMaster() can only be called once.

    This object is not supposed to be changed or set manually, by you.

    cluster.isMaster#

    • Boolean

    True if the process is a master. This is determined by the process.env.NODE_UNIQUE_ID. If process.env.NODE_UNIQUE_ID is undefined, then isMaster is true.

    cluster.isWorker#

    • Boolean

    True if the process is not a master (it is the negation of cluster.isMaster).

    Event: 'fork'#

    • worker Worker object

    When a new worker is forked the cluster module will emit a 'fork' event. This can be used to log worker activity, and create your own timeout.

    var timeouts = [];
    function errorMsg() {
      console.error("Something must be wrong with the connection ...");
    }
    
    cluster.on('fork', function(worker) {
      timeouts[worker.id] = setTimeout(errorMsg, 2000);
    });
    cluster.on('listening', function(worker, address) {
      clearTimeout(timeouts[worker.id]);
    });
    cluster.on('exit', function(worker, code, signal) {
      clearTimeout(timeouts[worker.id]);
      errorMsg();
    });

    Event: 'online'#

    • worker Worker object

    After forking a new worker, the worker should respond with an online message. When the master receives an online message it will emit this event. The difference between 'fork' and 'online' is that fork is emitted when the master forks a worker, and 'online' is emitted when the worker is running.

    cluster.on('online', function(worker) {
      console.log("Yay, the worker responded after it was forked");
    });

    Event: 'listening'#

    • worker Worker object
    • address Object

    After calling listen() from a worker, when the 'listening' event is emitted on the server, a listening event will also be emitted on cluster in the master.

    The event handler is executed with two arguments, the worker contains the worker object and the address object contains the following connection properties: address, port and addressType. This is very useful if the worker is listening on more than one address.

    cluster.on('listening', function(worker, address) {
      console.log("A worker is now connected to " + address.address + ":" + address.port);
    });

    The addressType is one of:

    • 4 (TCPv4)
    • 6 (TCPv6)
    • -1 (unix domain socket)
    • "udp4" or "udp6" (UDP v4 or v6)

    Event: 'disconnect'#

    • worker Worker object

    Emitted after the worker IPC channel has disconnected. This can occur when a worker exits gracefully, is killed, or is disconnected manually (such as with worker.disconnect()).

    There may be a delay between the disconnect and exit events. These events can be used to detect if the process is stuck in a cleanup or if there are long-living connections.

    cluster.on('disconnect', function(worker) {
      console.log('The worker #' + worker.id + ' has disconnected');
    });

    Event: 'exit'#

    • worker Worker object
    • code Number the exit code, if it exited normally.
    • signal String the name of the signal (eg. 'SIGHUP') that caused the process to be killed.

    When any of the workers die the cluster module will emit the 'exit' event.

    This can be used to restart the worker by calling .fork() again.

    cluster.on('exit', function(worker, code, signal) {
      console.log('worker %d died (%s). restarting...',
        worker.process.pid, signal || code);
      cluster.fork();
    });

    See child_process event: 'exit'.

    Event: 'setup'#

    Emitted the first time that .setupMaster() is called.

    cluster.setupMaster([settings])#

    • settings Object
      • exec String file path to worker file. (Default=process.argv[1])
      • args Array string arguments passed to worker. (Default=process.argv.slice(2))
      • silent Boolean whether or not to send output to parent's stdio. (Default=false)

    setupMaster is used to change the default 'fork' behavior. Once called, the settings will be present in cluster.settings.

    Note that:

    • Only the first call to .setupMaster() has any effect, subsequent calls are ignored
    • That because of the above, the only attribute of a worker that may be customized per-worker is the env passed to .fork()
    • .fork() calls .setupMaster() internally to establish the defaults, so to have any effect, .setupMaster() must be called before any calls to .fork()

    Example:

    var cluster = require("cluster");
    cluster.setupMaster({
      exec : "worker.js",
      args : ["--use", "https"],
      silent : true
    });
    cluster.fork();

    This can only be called from the master process.

    cluster.fork([env])#

    • env Object Key/value pairs to add to worker process environment.
    • return Worker object

    Spawn a new worker process.

    This can only be called from the master process.

    cluster.disconnect([callback])#

    • callback Function called when all workers are disconnected and handles are closed

    Calls .disconnect() on each worker in cluster.workers.

    When they are disconnected all internal handles will be closed, allowing the master process to die gracefully if no other event is waiting.

    The method takes an optional callback argument which will be called when finished.

    This can only be called from the master process.

    cluster.worker#

    • Object

    A reference to the current worker object. Not available in the master process.

    var cluster = require('cluster');
    
    if (cluster.isMaster) {
      console.log('I am master');
      cluster.fork();
      cluster.fork();
    } else if (cluster.isWorker) {
      console.log('I am worker #' + cluster.worker.id);
    }

    cluster.workers#

    • Object

    A hash that stores the active worker objects, keyed by id field. Makes it easy to loop through all the workers. It is only available in the master process.

    A worker is removed from cluster.workers just before the 'disconnect' or 'exit' event is emitted.

    // Go through all workers
    function eachWorker(callback) {
      for (var id in cluster.workers) {
        callback(cluster.workers[id]);
      }
    }
    eachWorker(function(worker) {
      worker.send('big announcement to all workers');
    });

    Should you wish to reference a worker over a communication channel, using the worker's unique id is the easiest way to find the worker.

    socket.on('data', function(id) {
      var worker = cluster.workers[id];
    });

    Class: Worker#

    A Worker object contains all public information and method about a worker. In the master it can be obtained using cluster.workers. In a worker it can be obtained using cluster.worker.

    worker.id#

    • String

    Each new worker is given its own unique id, this id is stored in the id.

    While a worker is alive, this is the key that indexes it in cluster.workers

    worker.process#

    • ChildProcess object

    All workers are created using child_process.fork(), the returned object from this function is stored as .process. In a worker, the global process is stored.

    See: Child Process module

    Note that workers will call process.exit(0) if the 'disconnect' event occurs on process and .suicide is not true. This protects against accidental disconnection.

    worker.suicide#

    • Boolean

    Set by calling .kill() or .disconnect(), until then it is undefined.

    The boolean worker.suicide lets you distinguish between voluntary and accidental exit, the master may choose not to respawn a worker based on this value.

    cluster.on('exit', function(worker, code, signal) {
      if (worker.suicide === true) {
        console.log('Oh, it was just suicide\' – no need to worry').
      }
    });
    
    // kill worker
    worker.kill();

    worker.send(message, [sendHandle])#

    • message Object
    • sendHandle Handle object

    This function is equal to the send methods provided by child_process.fork(). In the master you should use this function to send a message to a specific worker.

    In a worker you can also use process.send(message), it is the same function.

    This example will echo back all messages from the master:

    if (cluster.isMaster) {
      var worker = cluster.fork();
      worker.send('hi there');
    
    } else if (cluster.isWorker) {
      process.on('message', function(msg) {
        process.send(msg);
      });
    }

    worker.kill([signal='SIGTERM'])#

    • signal String Name of the kill signal to send to the worker process.

    This function will kill the worker. In the master, it does this by disconnecting the worker.process, and once disconnected, killing with signal. In the worker, it does it by disconnecting the channel, and then exiting with code 0.

    Causes .suicide to be set.

    This method is aliased as worker.destroy() for backwards compatibility.

    Note that in a worker, process.kill() exists, but it is not this function, it is kill.

    worker.disconnect()#

    In a worker, this function will close all servers, wait for the 'close' event on those servers, and then disconnect the IPC channel.

    In the master, an internal message is sent to the worker causing it to call .disconnect() on itself.

    Causes .suicide to be set.

    Note that after a server is closed, it will no longer accept new connections, but connections may be accepted by any other listening worker. Existing connections will be allowed to close as usual. When no more connections exist, see server.close(), the IPC channel to the worker will close allowing it to die gracefully.

    The above applies only to server connections, client connections are not automatically closed by workers, and disconnect does not wait for them to close before exiting.

    Note that in a worker, process.disconnect exists, but it is not this function, it is disconnect.

    Because long living server connections may block workers from disconnecting, it may be useful to send a message, so application specific actions may be taken to close them. It also may be useful to implement a timeout, killing a worker if the disconnect event has not been emitted after some time.

    if (cluster.isMaster) {
      var worker = cluster.fork();
      var timeout;
    
      worker.on('listening', function(address) {
        worker.send('shutdown');
        worker.disconnect();
        timeout = setTimeout(function() {
          worker.kill();
        }, 2000);
      });
    
      worker.on('disconnect', function() {
        clearTimeout(timeout);
      });
    
    } else if (cluster.isWorker) {
      var net = require('net');
      var server = net.createServer(function(socket) {
        // connections never end
      });
    
      server.listen(8000);
    
      process.on('message', function(msg) {
        if(msg === 'shutdown') {
          // initiate graceful close of any connections to server
        }
      });
    }

    Event: 'message'#

    • message Object

    This event is the same as the one provided by child_process.fork().

    In a worker you can also use process.on('message').

    As an example, here is a cluster that keeps count of the number of requests in the master process using the message system:

    var cluster = require('cluster');
    var http = require('http');
    
    if (cluster.isMaster) {
    
      // Keep track of http requests
      var numReqs = 0;
      setInterval(function() {
        console.log("numReqs =", numReqs);
      }, 1000);
    
      // Count requestes
      function messageHandler(msg) {
        if (msg.cmd && msg.cmd == 'notifyRequest') {
          numReqs += 1;
        }
      }
    
      // Start workers and listen for messages containing notifyRequest
      var numCPUs = require('os').cpus().length;
      for (var i = 0; i < numCPUs; i++) {
        cluster.fork();
      }
    
      Object.keys(cluster.workers).forEach(function(id) {
        cluster.workers[id].on('message', messageHandler);
      });
    
    } else {
    
      // Worker processes have a http server.
      http.Server(function(req, res) {
        res.writeHead(200);
        res.end("hello world\n");
    
        // notify master about the request
        process.send({ cmd: 'notifyRequest' });
      }).listen(8000);
    }

    Event: 'online'#

    Similar to the cluster.on('online') event, but specific to this worker.

    cluster.fork().on('online', function() {
      // Worker is online
    });

    It is not emitted in the worker.

    Event: 'listening'#

    • address Object

    Similar to the cluster.on('listening') event, but specific to this worker.

    cluster.fork().on('listening', function(address) {
      // Worker is listening
    });

    It is not emitted in the worker.

    Event: 'disconnect'#

    Similar to the cluster.on('disconnect') event, but specfic to this worker.

    cluster.fork().on('disconnect', function() {
      // Worker has disconnected
    });

    Event: 'exit'#

    • code Number the exit code, if it exited normally.
    • signal String the name of the signal (eg. 'SIGHUP') that caused the process to be killed.

    Similar to the cluster.on('exit') event, but specific to this worker.

    var worker = cluster.fork();
    worker.on('exit', function(code, signal) {
      if( signal ) {
        console.log("worker was killed by signal: "+signal);
      } else if( code !== 0 ) {
        console.log("worker exited with error code: "+code);
      } else {
        console.log("worker success!");
      }
    });

    Event: 'error'#

    This event is the same as the one provided by child_process.fork().

    In a worker you can also use process.on('error').

    node-v0.10.25~dfsg2/doc/api/index.html0000644000000000000000000001172512270264601016135 0ustar rootroot Node.js v0.10.25 Manual & Documentation node-v0.10.25~dfsg2/doc/api/net.markdown0000644000000000000000000004223512270121457016473 0ustar rootroot# net Stability: 3 - Stable The `net` module provides you with an asynchronous network wrapper. It contains methods for creating both servers and clients (called streams). You can include this module with `require('net');` ## net.createServer([options], [connectionListener]) Creates a new TCP server. The `connectionListener` argument is automatically set as a listener for the ['connection'][] event. `options` is an object with the following defaults: { allowHalfOpen: false } If `allowHalfOpen` is `true`, then the socket won't automatically send a FIN packet when the other end of the socket sends a FIN packet. The socket becomes non-readable, but still writable. You should call the `end()` method explicitly. See ['end'][] event for more information. Here is an example of an echo server which listens for connections on port 8124: var net = require('net'); var server = net.createServer(function(c) { //'connection' listener console.log('server connected'); c.on('end', function() { console.log('server disconnected'); }); c.write('hello\r\n'); c.pipe(c); }); server.listen(8124, function() { //'listening' listener console.log('server bound'); }); Test this by using `telnet`: telnet localhost 8124 To listen on the socket `/tmp/echo.sock` the third line from the last would just be changed to server.listen('/tmp/echo.sock', function() { //'listening' listener Use `nc` to connect to a UNIX domain socket server: nc -U /tmp/echo.sock ## net.connect(options, [connectionListener]) ## net.createConnection(options, [connectionListener]) Constructs a new socket object and opens the socket to the given location. When the socket is established, the ['connect'][] event will be emitted. For TCP sockets, `options` argument should be an object which specifies: - `port`: Port the client should connect to (Required). - `host`: Host the client should connect to. Defaults to `'localhost'`. - `localAddress`: Local interface to bind to for network connections. For UNIX domain sockets, `options` argument should be an object which specifies: - `path`: Path the client should connect to (Required). Common options are: - `allowHalfOpen`: if `true`, the socket won't automatically send a FIN packet when the other end of the socket sends a FIN packet. Defaults to `false`. See ['end'][] event for more information. The `connectListener` parameter will be added as an listener for the ['connect'][] event. Here is an example of a client of echo server as described previously: var net = require('net'); var client = net.connect({port: 8124}, function() { //'connect' listener console.log('client connected'); client.write('world!\r\n'); }); client.on('data', function(data) { console.log(data.toString()); client.end(); }); client.on('end', function() { console.log('client disconnected'); }); To connect on the socket `/tmp/echo.sock` the second line would just be changed to var client = net.connect({path: '/tmp/echo.sock'}); ## net.connect(port, [host], [connectListener]) ## net.createConnection(port, [host], [connectListener]) Creates a TCP connection to `port` on `host`. If `host` is omitted, `'localhost'` will be assumed. The `connectListener` parameter will be added as an listener for the ['connect'][] event. ## net.connect(path, [connectListener]) ## net.createConnection(path, [connectListener]) Creates unix socket connection to `path`. The `connectListener` parameter will be added as an listener for the ['connect'][] event. ## Class: net.Server This class is used to create a TCP or UNIX server. ### server.listen(port, [host], [backlog], [callback]) Begin accepting connections on the specified `port` and `host`. If the `host` is omitted, the server will accept connections directed to any IPv4 address (`INADDR_ANY`). A port value of zero will assign a random port. Backlog is the maximum length of the queue of pending connections. The actual length will be determined by your OS through sysctl settings such as `tcp_max_syn_backlog` and `somaxconn` on linux. The default value of this parameter is 511 (not 512). This function is asynchronous. When the server has been bound, ['listening'][] event will be emitted. The last parameter `callback` will be added as an listener for the ['listening'][] event. One issue some users run into is getting `EADDRINUSE` errors. This means that another server is already running on the requested port. One way of handling this would be to wait a second and then try again. This can be done with server.on('error', function (e) { if (e.code == 'EADDRINUSE') { console.log('Address in use, retrying...'); setTimeout(function () { server.close(); server.listen(PORT, HOST); }, 1000); } }); (Note: All sockets in Node set `SO_REUSEADDR` already) ### server.listen(path, [callback]) Start a UNIX socket server listening for connections on the given `path`. This function is asynchronous. When the server has been bound, ['listening'][] event will be emitted. The last parameter `callback` will be added as an listener for the ['listening'][] event. ### server.listen(handle, [callback]) * `handle` {Object} * `callback` {Function} The `handle` object can be set to either a server or socket (anything with an underlying `_handle` member), or a `{fd: }` object. This will cause the server to accept connections on the specified handle, but it is presumed that the file descriptor or handle has already been bound to a port or domain socket. Listening on a file descriptor is not supported on Windows. This function is asynchronous. When the server has been bound, ['listening'](#event_listening_) event will be emitted. the last parameter `callback` will be added as an listener for the ['listening'](#event_listening_) event. ### server.close([callback]) Stops the server from accepting new connections and keeps existing connections. This function is asynchronous, the server is finally closed when all connections are ended and the server emits a `'close'` event. Optionally, you can pass a callback to listen for the `'close'` event. ### server.address() Returns the bound address, the address family name and port of the server as reported by the operating system. Useful to find which port was assigned when giving getting an OS-assigned address. Returns an object with three properties, e.g. `{ port: 12346, family: 'IPv4', address: '127.0.0.1' }` Example: var server = net.createServer(function (socket) { socket.end("goodbye\n"); }); // grab a random port. server.listen(function() { address = server.address(); console.log("opened server on %j", address); }); Don't call `server.address()` until the `'listening'` event has been emitted. ### server.unref() Calling `unref` on a server will allow the program to exit if this is the only active server in the event system. If the server is already `unref`d calling `unref` again will have no effect. ### server.ref() Opposite of `unref`, calling `ref` on a previously `unref`d server will *not* let the program exit if it's the only server left (the default behavior). If the server is `ref`d calling `ref` again will have no effect. ### server.maxConnections Set this property to reject connections when the server's connection count gets high. It is not recommended to use this option once a socket has been sent to a child with `child_process.fork()`. ### server.connections This function is **deprecated**; please use [server.getConnections()][] instead. The number of concurrent connections on the server. This becomes `null` when sending a socket to a child with `child_process.fork()`. To poll forks and get current number of active connections use asynchronous `server.getConnections` instead. `net.Server` is an [EventEmitter][] with the following events: ### server.getConnections(callback) Asynchronously get the number of concurrent connections on the server. Works when sockets were sent to forks. Callback should take two arguments `err` and `count`. ### Event: 'listening' Emitted when the server has been bound after calling `server.listen`. ### Event: 'connection' * {Socket object} The connection object Emitted when a new connection is made. `socket` is an instance of `net.Socket`. ### Event: 'close' Emitted when the server closes. Note that if connections exist, this event is not emitted until all connections are ended. ### Event: 'error' * {Error Object} Emitted when an error occurs. The `'close'` event will be called directly following this event. See example in discussion of `server.listen`. ## Class: net.Socket This object is an abstraction of a TCP or UNIX socket. `net.Socket` instances implement a duplex Stream interface. They can be created by the user and used as a client (with `connect()`) or they can be created by Node and passed to the user through the `'connection'` event of a server. ### new net.Socket([options]) Construct a new socket object. `options` is an object with the following defaults: { fd: null allowHalfOpen: false, readable: false, writable: false } `fd` allows you to specify the existing file descriptor of socket. Set `readable` and/or `writable` to `true` to allow reads and/or writes on this socket (NOTE: Works only when `fd` is passed). About `allowHalfOpen`, refer to `createServer()` and `'end'` event. ### socket.connect(port, [host], [connectListener]) ### socket.connect(path, [connectListener]) Opens the connection for a given socket. If `port` and `host` are given, then the socket will be opened as a TCP socket, if `host` is omitted, `localhost` will be assumed. If a `path` is given, the socket will be opened as a unix socket to that path. Normally this method is not needed, as `net.createConnection` opens the socket. Use this only if you are implementing a custom Socket. This function is asynchronous. When the ['connect'][] event is emitted the socket is established. If there is a problem connecting, the `'connect'` event will not be emitted, the `'error'` event will be emitted with the exception. The `connectListener` parameter will be added as an listener for the ['connect'][] event. ### socket.bufferSize `net.Socket` has the property that `socket.write()` always works. This is to help users get up and running quickly. The computer cannot always keep up with the amount of data that is written to a socket - the network connection simply might be too slow. Node will internally queue up the data written to a socket and send it out over the wire when it is possible. (Internally it is polling on the socket's file descriptor for being writable). The consequence of this internal buffering is that memory may grow. This property shows the number of characters currently buffered to be written. (Number of characters is approximately equal to the number of bytes to be written, but the buffer may contain strings, and the strings are lazily encoded, so the exact number of bytes is not known.) Users who experience large or growing `bufferSize` should attempt to "throttle" the data flows in their program with `pause()` and `resume()`. ### socket.setEncoding([encoding]) Set the encoding for the socket as a Readable Stream. See [stream.setEncoding()][] for more information. ### socket.write(data, [encoding], [callback]) Sends data on the socket. The second parameter specifies the encoding in the case of a string--it defaults to UTF8 encoding. Returns `true` if the entire data was flushed successfully to the kernel buffer. Returns `false` if all or part of the data was queued in user memory. `'drain'` will be emitted when the buffer is again free. The optional `callback` parameter will be executed when the data is finally written out - this may not be immediately. ### socket.end([data], [encoding]) Half-closes the socket. i.e., it sends a FIN packet. It is possible the server will still send some data. If `data` is specified, it is equivalent to calling `socket.write(data, encoding)` followed by `socket.end()`. ### socket.destroy() Ensures that no more I/O activity happens on this socket. Only necessary in case of errors (parse error or so). ### socket.pause() Pauses the reading of data. That is, `'data'` events will not be emitted. Useful to throttle back an upload. ### socket.resume() Resumes reading after a call to `pause()`. ### socket.setTimeout(timeout, [callback]) Sets the socket to timeout after `timeout` milliseconds of inactivity on the socket. By default `net.Socket` do not have a timeout. When an idle timeout is triggered the socket will receive a `'timeout'` event but the connection will not be severed. The user must manually `end()` or `destroy()` the socket. If `timeout` is 0, then the existing idle timeout is disabled. The optional `callback` parameter will be added as a one time listener for the `'timeout'` event. ### socket.setNoDelay([noDelay]) Disables the Nagle algorithm. By default TCP connections use the Nagle algorithm, they buffer data before sending it off. Setting `true` for `noDelay` will immediately fire off data each time `socket.write()` is called. `noDelay` defaults to `true`. ### socket.setKeepAlive([enable], [initialDelay]) Enable/disable keep-alive functionality, and optionally set the initial delay before the first keepalive probe is sent on an idle socket. `enable` defaults to `false`. Set `initialDelay` (in milliseconds) to set the delay between the last data packet received and the first keepalive probe. Setting 0 for initialDelay will leave the value unchanged from the default (or previous) setting. Defaults to `0`. ### socket.address() Returns the bound address, the address family name and port of the socket as reported by the operating system. Returns an object with three properties, e.g. `{ port: 12346, family: 'IPv4', address: '127.0.0.1' }` ### socket.unref() Calling `unref` on a socket will allow the program to exit if this is the only active socket in the event system. If the socket is already `unref`d calling `unref` again will have no effect. ### socket.ref() Opposite of `unref`, calling `ref` on a previously `unref`d socket will *not* let the program exit if it's the only socket left (the default behavior). If the socket is `ref`d calling `ref` again will have no effect. ### socket.remoteAddress The string representation of the remote IP address. For example, `'74.125.127.100'` or `'2001:4860:a005::68'`. ### socket.remotePort The numeric representation of the remote port. For example, `80` or `21`. ### socket.localAddress The string representation of the local IP address the remote client is connecting on. For example, if you are listening on `'0.0.0.0'` and the client connects on `'192.168.1.1'`, the value would be `'192.168.1.1'`. ### socket.localPort The numeric representation of the local port. For example, `80` or `21`. ### socket.bytesRead The amount of received bytes. ### socket.bytesWritten The amount of bytes sent. `net.Socket` instances are [EventEmitter][] with the following events: ### Event: 'connect' Emitted when a socket connection is successfully established. See `connect()`. ### Event: 'data' * {Buffer object} Emitted when data is received. The argument `data` will be a `Buffer` or `String`. Encoding of data is set by `socket.setEncoding()`. (See the [Readable Stream][] section for more information.) Note that the __data will be lost__ if there is no listener when a `Socket` emits a `'data'` event. ### Event: 'end' Emitted when the other end of the socket sends a FIN packet. By default (`allowHalfOpen == false`) the socket will destroy its file descriptor once it has written out its pending write queue. However, by setting `allowHalfOpen == true` the socket will not automatically `end()` its side allowing the user to write arbitrary amounts of data, with the caveat that the user is required to `end()` their side now. ### Event: 'timeout' Emitted if the socket times out from inactivity. This is only to notify that the socket has been idle. The user must manually close the connection. See also: `socket.setTimeout()` ### Event: 'drain' Emitted when the write buffer becomes empty. Can be used to throttle uploads. See also: the return values of `socket.write()` ### Event: 'error' * {Error object} Emitted when an error occurs. The `'close'` event will be called directly following this event. ### Event: 'close' * `had_error` {Boolean} true if the socket had a transmission error Emitted once the socket is fully closed. The argument `had_error` is a boolean which says if the socket was closed due to a transmission error. ## net.isIP(input) Tests if input is an IP address. Returns 0 for invalid strings, returns 4 for IP version 4 addresses, and returns 6 for IP version 6 addresses. ## net.isIPv4(input) Returns true if input is a version 4 IP address, otherwise returns false. ## net.isIPv6(input) Returns true if input is a version 6 IP address, otherwise returns false. ['connect']: #net_event_connect ['connection']: #net_event_connection ['end']: #net_event_end [EventEmitter]: events.html#events_class_events_eventemitter ['listening']: #net_event_listening [Readable Stream]: stream.html#stream_readable_stream [stream.setEncoding()]: stream.html#stream_stream_setencoding_encoding node-v0.10.25~dfsg2/doc/api/vm.html0000644000000000000000000003545112270264601015452 0ustar rootroot Executing JavaScript Node.js v0.10.25 Manual & Documentation

    Node.js v0.10.25 Manual & Documentation


    Executing JavaScript#

    Stability: 2 - Unstable. See Caveats, below.

    You can access this module with:

    var vm = require('vm');

    JavaScript code can be compiled and run immediately or compiled, saved, and run later.

    Caveats#

    The vm module has many known issues and edge cases. If you run into issues or unexpected behavior, please consult the open issues on GitHub. Some of the biggest problems are described below.

    Sandboxes#

    The sandbox argument to vm.runInNewContext and vm.createContext, along with the initSandbox argument to vm.createContext, do not behave as one might normally expect and their behavior varies between different versions of Node.

    The key issue to be aware of is that V8 provides no way to directly control the global object used within a context. As a result, while properties of your sandbox object will be available in the context, any properties from the prototypes of the sandbox may not be available. Furthermore, the this expression within the global scope of the context evaluates to the empty object ({}) instead of to your sandbox.

    Your sandbox's properties are also not shared directly with the script. Instead, the properties of the sandbox are copied into the context at the beginning of execution, and then after execution, the properties are copied back out in an attempt to propagate any changes.

    Globals#

    Properties of the global object, like Array and String, have different values inside of a context. This means that common expressions like [] instanceof Array or Object.getPrototypeOf([]) === Array.prototype may not produce expected results when used inside of scripts evaluated via the vm module.

    Some of these problems have known workarounds listed in the issues for vm on GitHub. for example, Array.isArray works around the example problem with Array.

    vm.runInThisContext(code, [filename])#

    vm.runInThisContext() compiles code, runs it and returns the result. Running code does not have access to local scope. filename is optional, it's used only in stack traces.

    Example of using vm.runInThisContext and eval to run the same code:

    var localVar = 123,
        usingscript, evaled,
        vm = require('vm');
    
    usingscript = vm.runInThisContext('localVar = 1;',
      'myfile.vm');
    console.log('localVar: ' + localVar + ', usingscript: ' +
      usingscript);
    evaled = eval('localVar = 1;');
    console.log('localVar: ' + localVar + ', evaled: ' +
      evaled);
    
    // localVar: 123, usingscript: 1
    // localVar: 1, evaled: 1

    vm.runInThisContext does not have access to the local scope, so localVar is unchanged. eval does have access to the local scope, so localVar is changed.

    In case of syntax error in code, vm.runInThisContext emits the syntax error to stderr and throws an exception.

    vm.runInNewContext(code, [sandbox], [filename])#

    vm.runInNewContext compiles code, then runs it in sandbox and returns the result. Running code does not have access to local scope. The object sandbox will be used as the global object for code. sandbox and filename are optional, filename is only used in stack traces.

    Example: compile and execute code that increments a global variable and sets a new one. These globals are contained in the sandbox.

    var util = require('util'),
        vm = require('vm'),
        sandbox = {
          animal: 'cat',
          count: 2
        };
    
    vm.runInNewContext('count += 1; name = "kitty"', sandbox, 'myfile.vm');
    console.log(util.inspect(sandbox));
    
    // { animal: 'cat', count: 3, name: 'kitty' }

    Note that running untrusted code is a tricky business requiring great care. To prevent accidental global variable leakage, vm.runInNewContext is quite useful, but safely running untrusted code requires a separate process.

    In case of syntax error in code, vm.runInNewContext emits the syntax error to stderr and throws an exception.

    vm.runInContext(code, context, [filename])#

    vm.runInContext compiles code, then runs it in context and returns the result. A (V8) context comprises a global object, together with a set of built-in objects and functions. Running code does not have access to local scope and the global object held within context will be used as the global object for code. filename is optional, it's used only in stack traces.

    Example: compile and execute code in a existing context.

    var util = require('util'),
        vm = require('vm'),
        initSandbox = {
          animal: 'cat',
          count: 2
        },
        context = vm.createContext(initSandbox);
    
    vm.runInContext('count += 1; name = "CATT"', context, 'myfile.vm');
    console.log(util.inspect(context));
    
    // { animal: 'cat', count: 3, name: 'CATT' }

    Note that createContext will perform a shallow clone of the supplied sandbox object in order to initialize the global object of the freshly constructed context.

    Note that running untrusted code is a tricky business requiring great care. To prevent accidental global variable leakage, vm.runInContext is quite useful, but safely running untrusted code requires a separate process.

    In case of syntax error in code, vm.runInContext emits the syntax error to stderr and throws an exception.

    vm.createContext([initSandbox])#

    vm.createContext creates a new context which is suitable for use as the 2nd argument of a subsequent call to vm.runInContext. A (V8) context comprises a global object together with a set of build-in objects and functions. The optional argument initSandbox will be shallow-copied to seed the initial contents of the global object used by the context.

    vm.createScript(code, [filename])#

    createScript compiles code but does not run it. Instead, it returns a vm.Script object representing this compiled code. This script can be run later many times using methods below. The returned script is not bound to any global object. It is bound before each run, just for that run. filename is optional, it's only used in stack traces.

    In case of syntax error in code, createScript prints the syntax error to stderr and throws an exception.

    Class: Script#

    A class for running scripts. Returned by vm.createScript.

    script.runInThisContext()#

    Similar to vm.runInThisContext but a method of a precompiled Script object. script.runInThisContext runs the code of script and returns the result. Running code does not have access to local scope, but does have access to the global object (v8: in actual context).

    Example of using script.runInThisContext to compile code once and run it multiple times:

    var vm = require('vm');
    
    globalVar = 0;
    
    var script = vm.createScript('globalVar += 1', 'myfile.vm');
    
    for (var i = 0; i < 1000 ; i += 1) {
      script.runInThisContext();
    }
    
    console.log(globalVar);
    
    // 1000

    script.runInNewContext([sandbox])#

    Similar to vm.runInNewContext a method of a precompiled Script object. script.runInNewContext runs the code of script with sandbox as the global object and returns the result. Running code does not have access to local scope. sandbox is optional.

    Example: compile code that increments a global variable and sets one, then execute this code multiple times. These globals are contained in the sandbox.

    var util = require('util'),
        vm = require('vm'),
        sandbox = {
          animal: 'cat',
          count: 2
        };
    
    var script = vm.createScript('count += 1; name = "kitty"', 'myfile.vm');
    
    for (var i = 0; i < 10 ; i += 1) {
      script.runInNewContext(sandbox);
    }
    
    console.log(util.inspect(sandbox));
    
    // { animal: 'cat', count: 12, name: 'kitty' }

    Note that running untrusted code is a tricky business requiring great care. To prevent accidental global variable leakage, script.runInNewContext is quite useful, but safely running untrusted code requires a separate process.

    node-v0.10.25~dfsg2/doc/api/crypto.json0000644000000000000000000012076512270264601016360 0ustar rootroot{ "source": "doc/api/crypto.markdown", "modules": [ { "textRaw": "Crypto", "name": "crypto", "desc": "
    Stability: 2 - Unstable; API changes are being discussed for\nfuture versions.  Breaking changes will be minimized.  See below.
    \n

    Use require('crypto') to access this module.\n\n

    \n

    The crypto module offers a way of encapsulating secure credentials to be\nused as part of a secure HTTPS net or http connection.\n\n

    \n

    It also offers a set of wrappers for OpenSSL's hash, hmac, cipher,\ndecipher, sign and verify methods.\n\n\n

    \n", "methods": [ { "textRaw": "crypto.getCiphers()", "type": "method", "name": "getCiphers", "desc": "

    Returns an array with the names of the supported ciphers.\n\n

    \n

    Example:\n\n

    \n
    var ciphers = crypto.getCiphers();\nconsole.log(ciphers); // ['AES-128-CBC', 'AES-128-CBC-HMAC-SHA1', ...]
    \n", "signatures": [ { "params": [] } ] }, { "textRaw": "crypto.getHashes()", "type": "method", "name": "getHashes", "desc": "

    Returns an array with the names of the supported hash algorithms.\n\n

    \n

    Example:\n\n

    \n
    var hashes = crypto.getHashes();\nconsole.log(hashes); // ['sha', 'sha1', 'sha1WithRSAEncryption', ...]
    \n", "signatures": [ { "params": [] } ] }, { "textRaw": "crypto.createCredentials(details)", "type": "method", "name": "createCredentials", "desc": "

    Creates a credentials object, with the optional details being a\ndictionary with keys:\n\n

    \n
      \n
    • pfx : A string or buffer holding the PFX or PKCS12 encoded private\nkey, certificate and CA certificates
    • \n
    • key : A string holding the PEM encoded private key
    • \n
    • passphrase : A string of passphrase for the private key or pfx
    • \n
    • cert : A string holding the PEM encoded certificate
    • \n
    • ca : Either a string or list of strings of PEM encoded CA\ncertificates to trust.
    • \n
    • crl : Either a string or list of strings of PEM encoded CRLs\n(Certificate Revocation List)
    • \n
    • ciphers: A string describing the ciphers to use or exclude.\nConsult\nhttp://www.openssl.org/docs/apps/ciphers.html#CIPHER_LIST_FORMAT\nfor details on the format.
    • \n
    \n

    If no 'ca' details are given, then node.js will use the default\npublicly trusted list of CAs as given in\n

    \n

    http://mxr.mozilla.org/mozilla/source/security/nss/lib/ckfw/builtins/certdata.txt.\n\n\n

    \n", "signatures": [ { "params": [ { "name": "details" } ] } ] }, { "textRaw": "crypto.createHash(algorithm)", "type": "method", "name": "createHash", "desc": "

    Creates and returns a hash object, a cryptographic hash with the given\nalgorithm which can be used to generate hash digests.\n\n

    \n

    algorithm is dependent on the available algorithms supported by the\nversion of OpenSSL on the platform. Examples are 'sha1', 'md5',\n'sha256', 'sha512', etc. On recent releases, openssl\nlist-message-digest-algorithms will display the available digest\nalgorithms.\n\n

    \n

    Example: this program that takes the sha1 sum of a file\n\n

    \n
    var filename = process.argv[2];\nvar crypto = require('crypto');\nvar fs = require('fs');\n\nvar shasum = crypto.createHash('sha1');\n\nvar s = fs.ReadStream(filename);\ns.on('data', function(d) {\n  shasum.update(d);\n});\n\ns.on('end', function() {\n  var d = shasum.digest('hex');\n  console.log(d + '  ' + filename);\n});
    \n", "signatures": [ { "params": [ { "name": "algorithm" } ] } ] }, { "textRaw": "crypto.createHmac(algorithm, key)", "type": "method", "name": "createHmac", "desc": "

    Creates and returns a hmac object, a cryptographic hmac with the given\nalgorithm and key.\n\n

    \n

    It is a stream that is both readable and writable. The\nwritten data is used to compute the hmac. Once the writable side of\nthe stream is ended, use the read() method to get the computed\ndigest. The legacy update and digest methods are also supported.\n\n

    \n

    algorithm is dependent on the available algorithms supported by\nOpenSSL - see createHash above. key is the hmac key to be used.\n\n

    \n", "signatures": [ { "params": [ { "name": "algorithm" }, { "name": "key" } ] } ] }, { "textRaw": "crypto.createCipher(algorithm, password)", "type": "method", "name": "createCipher", "desc": "

    Creates and returns a cipher object, with the given algorithm and\npassword.\n\n

    \n

    algorithm is dependent on OpenSSL, examples are 'aes192', etc. On\nrecent releases, openssl list-cipher-algorithms will display the\navailable cipher algorithms. password is used to derive key and IV,\nwhich must be a 'binary' encoded string or a buffer.\n\n

    \n

    It is a stream that is both readable and writable. The\nwritten data is used to compute the hash. Once the writable side of\nthe stream is ended, use the read() method to get the computed hash\ndigest. The legacy update and digest methods are also supported.\n\n

    \n", "signatures": [ { "params": [ { "name": "algorithm" }, { "name": "password" } ] } ] }, { "textRaw": "crypto.createCipheriv(algorithm, key, iv)", "type": "method", "name": "createCipheriv", "desc": "

    Creates and returns a cipher object, with the given algorithm, key and\niv.\n\n

    \n

    algorithm is the same as the argument to createCipher(). key is\nthe raw key used by the algorithm. iv is an initialization\nvector.\n\n

    \n

    key and iv must be 'binary' encoded strings or\nbuffers.\n\n

    \n", "signatures": [ { "params": [ { "name": "algorithm" }, { "name": "key" }, { "name": "iv" } ] } ] }, { "textRaw": "crypto.createDecipher(algorithm, password)", "type": "method", "name": "createDecipher", "desc": "

    Creates and returns a decipher object, with the given algorithm and\nkey. This is the mirror of the [createCipher()][] above.\n\n

    \n", "signatures": [ { "params": [ { "name": "algorithm" }, { "name": "password" } ] } ] }, { "textRaw": "crypto.createDecipheriv(algorithm, key, iv)", "type": "method", "name": "createDecipheriv", "desc": "

    Creates and returns a decipher object, with the given algorithm, key\nand iv. This is the mirror of the [createCipheriv()][] above.\n\n

    \n", "signatures": [ { "params": [ { "name": "algorithm" }, { "name": "key" }, { "name": "iv" } ] } ] }, { "textRaw": "crypto.createSign(algorithm)", "type": "method", "name": "createSign", "desc": "

    Creates and returns a signing object, with the given algorithm. On\nrecent OpenSSL releases, openssl list-public-key-algorithms will\ndisplay the available signing algorithms. Examples are 'RSA-SHA256'.\n\n

    \n", "signatures": [ { "params": [ { "name": "algorithm" } ] } ] }, { "textRaw": "crypto.createVerify(algorithm)", "type": "method", "name": "createVerify", "desc": "

    Creates and returns a verification object, with the given algorithm.\nThis is the mirror of the signing object above.\n\n

    \n", "signatures": [ { "params": [ { "name": "algorithm" } ] } ] }, { "textRaw": "crypto.createDiffieHellman(prime_length)", "type": "method", "name": "createDiffieHellman", "desc": "

    Creates a Diffie-Hellman key exchange object and generates a prime of\nthe given bit length. The generator used is 2.\n\n

    \n", "signatures": [ { "params": [ { "name": "prime_length" } ] } ] }, { "textRaw": "crypto.createDiffieHellman(prime, [encoding])", "type": "method", "name": "createDiffieHellman", "desc": "

    Creates a Diffie-Hellman key exchange object using the supplied prime.\nThe generator used is 2. Encoding can be 'binary', 'hex', or\n'base64'. If no encoding is specified, then a buffer is expected.\n\n

    \n", "signatures": [ { "params": [ { "name": "prime" }, { "name": "encoding", "optional": true } ] } ] }, { "textRaw": "crypto.getDiffieHellman(group_name)", "type": "method", "name": "getDiffieHellman", "desc": "

    Creates a predefined Diffie-Hellman key exchange object. The\nsupported groups are: 'modp1', 'modp2', 'modp5' (defined in [RFC\n2412][]) and 'modp14', 'modp15', 'modp16', 'modp17',\n'modp18' (defined in [RFC 3526][]). The returned object mimics the\ninterface of objects created by [crypto.createDiffieHellman()][]\nabove, but will not allow to change the keys (with\n[diffieHellman.setPublicKey()][] for example). The advantage of using\nthis routine is that the parties don't have to generate nor exchange\ngroup modulus beforehand, saving both processor and communication\ntime.\n\n

    \n

    Example (obtaining a shared secret):\n\n

    \n
    var crypto = require('crypto');\nvar alice = crypto.getDiffieHellman('modp5');\nvar bob = crypto.getDiffieHellman('modp5');\n\nalice.generateKeys();\nbob.generateKeys();\n\nvar alice_secret = alice.computeSecret(bob.getPublicKey(), null, 'hex');\nvar bob_secret = bob.computeSecret(alice.getPublicKey(), null, 'hex');\n\n/* alice_secret and bob_secret should be the same */\nconsole.log(alice_secret == bob_secret);
    \n", "signatures": [ { "params": [ { "name": "group_name" } ] } ] }, { "textRaw": "crypto.pbkdf2(password, salt, iterations, keylen, callback)", "type": "method", "name": "pbkdf2", "desc": "

    Asynchronous PBKDF2 applies pseudorandom function HMAC-SHA1 to derive\na key of given length from the given password, salt and iterations.\nThe callback gets two arguments (err, derivedKey).\n\n

    \n", "signatures": [ { "params": [ { "name": "password" }, { "name": "salt" }, { "name": "iterations" }, { "name": "keylen" }, { "name": "callback" } ] } ] }, { "textRaw": "crypto.pbkdf2Sync(password, salt, iterations, keylen)", "type": "method", "name": "pbkdf2Sync", "desc": "

    Synchronous PBKDF2 function. Returns derivedKey or throws error.\n\n

    \n", "signatures": [ { "params": [ { "name": "password" }, { "name": "salt" }, { "name": "iterations" }, { "name": "keylen" } ] } ] }, { "textRaw": "crypto.randomBytes(size, [callback])", "type": "method", "name": "randomBytes", "desc": "

    Generates cryptographically strong pseudo-random data. Usage:\n\n

    \n
    // async\ncrypto.randomBytes(256, function(ex, buf) {\n  if (ex) throw ex;\n  console.log('Have %d bytes of random data: %s', buf.length, buf);\n});\n\n// sync\ntry {\n  var buf = crypto.randomBytes(256);\n  console.log('Have %d bytes of random data: %s', buf.length, buf);\n} catch (ex) {\n  // handle error\n  // most likely, entropy sources are drained\n}
    \n

    NOTE: Will throw error or invoke callback with error, if there is not enough\naccumulated entropy to generate cryptographically strong data. In other words,\ncrypto.randomBytes without callback will not block even if all entropy sources\nare drained.\n\n

    \n", "signatures": [ { "params": [ { "name": "size" }, { "name": "callback", "optional": true } ] } ] }, { "textRaw": "crypto.pseudoRandomBytes(size, [callback])", "type": "method", "name": "pseudoRandomBytes", "desc": "

    Generates non-cryptographically strong pseudo-random data. The data\nreturned will be unique if it is sufficiently long, but is not\nnecessarily unpredictable. For this reason, the output of this\nfunction should never be used where unpredictability is important,\nsuch as in the generation of encryption keys.\n\n

    \n

    Usage is otherwise identical to crypto.randomBytes.\n\n

    \n", "signatures": [ { "params": [ { "name": "size" }, { "name": "callback", "optional": true } ] } ] } ], "classes": [ { "textRaw": "Class: Hash", "type": "class", "name": "Hash", "desc": "

    The class for creating hash digests of data.\n\n

    \n

    It is a stream that is both readable and writable. The\nwritten data is used to compute the hash. Once the writable side of\nthe stream is ended, use the read() method to get the computed hash\ndigest. The legacy update and digest methods are also supported.\n\n

    \n

    Returned by crypto.createHash.\n\n

    \n", "methods": [ { "textRaw": "hash.update(data, [input_encoding])", "type": "method", "name": "update", "desc": "

    Updates the hash content with the given data, the encoding of which\nis given in input_encoding and can be 'utf8', 'ascii' or\n'binary'. If no encoding is provided and the input is a string an\nencoding of 'binary' is enforced. If data is a Buffer then\ninput_encoding is ignored.\n\n

    \n

    This can be called many times with new data as it is streamed.\n\n

    \n", "signatures": [ { "params": [ { "name": "data" }, { "name": "input_encoding", "optional": true } ] } ] }, { "textRaw": "hash.digest([encoding])", "type": "method", "name": "digest", "desc": "

    Calculates the digest of all of the passed data to be hashed. The\nencoding can be 'hex', 'binary' or 'base64'. If no encoding\nis provided, then a buffer is returned.\n\n

    \n

    Note: hash object can not be used after digest() method has been\ncalled.\n\n\n

    \n", "signatures": [ { "params": [ { "name": "encoding", "optional": true } ] } ] } ] }, { "textRaw": "Class: Hmac", "type": "class", "name": "Hmac", "desc": "

    Class for creating cryptographic hmac content.\n\n

    \n

    Returned by crypto.createHmac.\n\n

    \n", "methods": [ { "textRaw": "hmac.update(data)", "type": "method", "name": "update", "desc": "

    Update the hmac content with the given data. This can be called\nmany times with new data as it is streamed.\n\n

    \n", "signatures": [ { "params": [ { "name": "data" } ] } ] }, { "textRaw": "hmac.digest([encoding])", "type": "method", "name": "digest", "desc": "

    Calculates the digest of all of the passed data to the hmac. The\nencoding can be 'hex', 'binary' or 'base64'. If no encoding\nis provided, then a buffer is returned.\n\n

    \n

    Note: hmac object can not be used after digest() method has been\ncalled.\n\n\n

    \n", "signatures": [ { "params": [ { "name": "encoding", "optional": true } ] } ] } ] }, { "textRaw": "Class: Cipher", "type": "class", "name": "Cipher", "desc": "

    Class for encrypting data.\n\n

    \n

    Returned by crypto.createCipher and crypto.createCipheriv.\n\n

    \n

    Cipher objects are streams that are both readable and\nwritable. The written plain text data is used to produce the\nencrypted data on the readable side. The legacy update and final\nmethods are also supported.\n\n

    \n", "methods": [ { "textRaw": "cipher.update(data, [input_encoding], [output_encoding])", "type": "method", "name": "update", "desc": "

    Updates the cipher with data, the encoding of which is given in\ninput_encoding and can be 'utf8', 'ascii' or 'binary'. If no\nencoding is provided, then a buffer is expected.\nIf data is a Buffer then input_encoding is ignored.\n\n

    \n

    The output_encoding specifies the output format of the enciphered\ndata, and can be 'binary', 'base64' or 'hex'. If no encoding is\nprovided, then a buffer is returned.\n\n

    \n

    Returns the enciphered contents, and can be called many times with new\ndata as it is streamed.\n\n

    \n", "signatures": [ { "params": [ { "name": "data" }, { "name": "input_encoding", "optional": true }, { "name": "output_encoding", "optional": true } ] } ] }, { "textRaw": "cipher.final([output_encoding])", "type": "method", "name": "final", "desc": "

    Returns any remaining enciphered contents, with output_encoding\nbeing one of: 'binary', 'base64' or 'hex'. If no encoding is\nprovided, then a buffer is returned.\n\n

    \n

    Note: cipher object can not be used after final() method has been\ncalled.\n\n

    \n", "signatures": [ { "params": [ { "name": "output_encoding", "optional": true } ] } ] }, { "textRaw": "cipher.setAutoPadding(auto_padding=true)", "type": "method", "name": "setAutoPadding", "desc": "

    You can disable automatic padding of the input data to block size. If\nauto_padding is false, the length of the entire input data must be a\nmultiple of the cipher's block size or final will fail. Useful for\nnon-standard padding, e.g. using 0x0 instead of PKCS padding. You\nmust call this before cipher.final.\n\n\n

    \n", "signatures": [ { "params": [ { "name": "auto_padding", "default": "true" } ] } ] } ] }, { "textRaw": "Class: Decipher", "type": "class", "name": "Decipher", "desc": "

    Class for decrypting data.\n\n

    \n

    Returned by crypto.createDecipher and crypto.createDecipheriv.\n\n

    \n

    Decipher objects are streams that are both readable and\nwritable. The written enciphered data is used to produce the\nplain-text data on the the readable side. The legacy update and\nfinal methods are also supported.\n\n

    \n", "methods": [ { "textRaw": "decipher.update(data, [input_encoding], [output_encoding])", "type": "method", "name": "update", "desc": "

    Updates the decipher with data, which is encoded in 'binary',\n'base64' or 'hex'. If no encoding is provided, then a buffer is\nexpected.\nIf data is a Buffer then input_encoding is ignored.\n\n

    \n

    The output_decoding specifies in what format to return the\ndeciphered plaintext: 'binary', 'ascii' or 'utf8'. If no\nencoding is provided, then a buffer is returned.\n\n

    \n", "signatures": [ { "params": [ { "name": "data" }, { "name": "input_encoding", "optional": true }, { "name": "output_encoding", "optional": true } ] } ] }, { "textRaw": "decipher.final([output_encoding])", "type": "method", "name": "final", "desc": "

    Returns any remaining plaintext which is deciphered, with\noutput_encoding being one of: 'binary', 'ascii' or 'utf8'. If\nno encoding is provided, then a buffer is returned.\n\n

    \n

    Note: decipher object can not be used after final() method has been\ncalled.\n\n

    \n", "signatures": [ { "params": [ { "name": "output_encoding", "optional": true } ] } ] }, { "textRaw": "decipher.setAutoPadding(auto_padding=true)", "type": "method", "name": "setAutoPadding", "desc": "

    You can disable auto padding if the data has been encrypted without\nstandard block padding to prevent decipher.final from checking and\nremoving it. Can only work if the input data's length is a multiple of\nthe ciphers block size. You must call this before streaming data to\ndecipher.update.\n\n

    \n", "signatures": [ { "params": [ { "name": "auto_padding", "default": "true" } ] } ] } ] }, { "textRaw": "Class: Sign", "type": "class", "name": "Sign", "desc": "

    Class for generating signatures.\n\n

    \n

    Returned by crypto.createSign.\n\n

    \n

    Sign objects are writable streams. The written data is\nused to generate the signature. Once all of the data has been\nwritten, the sign method will return the signature. The legacy\nupdate method is also supported.\n\n

    \n", "methods": [ { "textRaw": "sign.update(data)", "type": "method", "name": "update", "desc": "

    Updates the sign object with data. This can be called many times\nwith new data as it is streamed.\n\n

    \n", "signatures": [ { "params": [ { "name": "data" } ] } ] }, { "textRaw": "sign.sign(private_key, [output_format])", "type": "method", "name": "sign", "desc": "

    Calculates the signature on all the updated data passed through the\nsign. private_key is a string containing the PEM encoded private\nkey for signing.\n\n

    \n

    Returns the signature in output_format which can be 'binary',\n'hex' or 'base64'. If no encoding is provided, then a buffer is\nreturned.\n\n

    \n

    Note: sign object can not be used after sign() method has been\ncalled.\n\n

    \n", "signatures": [ { "params": [ { "name": "private_key" }, { "name": "output_format", "optional": true } ] } ] } ] }, { "textRaw": "Class: Verify", "type": "class", "name": "Verify", "desc": "

    Class for verifying signatures.\n\n

    \n

    Returned by crypto.createVerify.\n\n

    \n

    Verify objects are writable streams. The written data\nis used to validate against the supplied signature. Once all of the\ndata has been written, the verify method will return true if the\nsupplied signature is valid. The legacy update method is also\nsupported.\n\n

    \n", "methods": [ { "textRaw": "verifier.update(data)", "type": "method", "name": "update", "desc": "

    Updates the verifier object with data. This can be called many times\nwith new data as it is streamed.\n\n

    \n", "signatures": [ { "params": [ { "name": "data" } ] } ] }, { "textRaw": "verifier.verify(object, signature, [signature_format])", "type": "method", "name": "verify", "desc": "

    Verifies the signed data by using the object and signature.\nobject is a string containing a PEM encoded object, which can be\none of RSA public key, DSA public key, or X.509 certificate.\nsignature is the previously calculated signature for the data, in\nthe signature_format which can be 'binary', 'hex' or 'base64'.\nIf no encoding is specified, then a buffer is expected.\n\n

    \n

    Returns true or false depending on the validity of the signature for\nthe data and public key.\n\n

    \n

    Note: verifier object can not be used after verify() method has been\ncalled.\n\n

    \n", "signatures": [ { "params": [ { "name": "object" }, { "name": "signature" }, { "name": "signature_format", "optional": true } ] } ] } ] }, { "textRaw": "Class: DiffieHellman", "type": "class", "name": "DiffieHellman", "desc": "

    The class for creating Diffie-Hellman key exchanges.\n\n

    \n

    Returned by crypto.createDiffieHellman.\n\n

    \n", "methods": [ { "textRaw": "diffieHellman.generateKeys([encoding])", "type": "method", "name": "generateKeys", "desc": "

    Generates private and public Diffie-Hellman key values, and returns\nthe public key in the specified encoding. This key should be\ntransferred to the other party. Encoding can be 'binary', 'hex',\nor 'base64'. If no encoding is provided, then a buffer is returned.\n\n

    \n", "signatures": [ { "params": [ { "name": "encoding", "optional": true } ] } ] }, { "textRaw": "diffieHellman.computeSecret(other_public_key, [input_encoding], [output_encoding])", "type": "method", "name": "computeSecret", "desc": "

    Computes the shared secret using other_public_key as the other\nparty's public key and returns the computed shared secret. Supplied\nkey is interpreted using specified input_encoding, and secret is\nencoded using specified output_encoding. Encodings can be\n'binary', 'hex', or 'base64'. If the input encoding is not\nprovided, then a buffer is expected.\n\n

    \n

    If no output encoding is given, then a buffer is returned.\n\n

    \n", "signatures": [ { "params": [ { "name": "other_public_key" }, { "name": "input_encoding", "optional": true }, { "name": "output_encoding", "optional": true } ] } ] }, { "textRaw": "diffieHellman.getPrime([encoding])", "type": "method", "name": "getPrime", "desc": "

    Returns the Diffie-Hellman prime in the specified encoding, which can\nbe 'binary', 'hex', or 'base64'. If no encoding is provided,\nthen a buffer is returned.\n\n

    \n", "signatures": [ { "params": [ { "name": "encoding", "optional": true } ] } ] }, { "textRaw": "diffieHellman.getGenerator([encoding])", "type": "method", "name": "getGenerator", "desc": "

    Returns the Diffie-Hellman prime in the specified encoding, which can\nbe 'binary', 'hex', or 'base64'. If no encoding is provided,\nthen a buffer is returned.\n\n

    \n", "signatures": [ { "params": [ { "name": "encoding", "optional": true } ] } ] }, { "textRaw": "diffieHellman.getPublicKey([encoding])", "type": "method", "name": "getPublicKey", "desc": "

    Returns the Diffie-Hellman public key in the specified encoding, which\ncan be 'binary', 'hex', or 'base64'. If no encoding is provided,\nthen a buffer is returned.\n\n

    \n", "signatures": [ { "params": [ { "name": "encoding", "optional": true } ] } ] }, { "textRaw": "diffieHellman.getPrivateKey([encoding])", "type": "method", "name": "getPrivateKey", "desc": "

    Returns the Diffie-Hellman private key in the specified encoding,\nwhich can be 'binary', 'hex', or 'base64'. If no encoding is\nprovided, then a buffer is returned.\n\n

    \n", "signatures": [ { "params": [ { "name": "encoding", "optional": true } ] } ] }, { "textRaw": "diffieHellman.setPublicKey(public_key, [encoding])", "type": "method", "name": "setPublicKey", "desc": "

    Sets the Diffie-Hellman public key. Key encoding can be 'binary',\n'hex' or 'base64'. If no encoding is provided, then a buffer is\nexpected.\n\n

    \n", "signatures": [ { "params": [ { "name": "public_key" }, { "name": "encoding", "optional": true } ] } ] }, { "textRaw": "diffieHellman.setPrivateKey(private_key, [encoding])", "type": "method", "name": "setPrivateKey", "desc": "

    Sets the Diffie-Hellman private key. Key encoding can be 'binary',\n'hex' or 'base64'. If no encoding is provided, then a buffer is\nexpected.\n\n

    \n", "signatures": [ { "params": [ { "name": "private_key" }, { "name": "encoding", "optional": true } ] } ] } ] } ], "properties": [ { "textRaw": "crypto.DEFAULT_ENCODING", "name": "DEFAULT_ENCODING", "desc": "

    The default encoding to use for functions that can take either strings\nor buffers. The default value is 'buffer', which makes it default\nto using Buffer objects. This is here to make the crypto module more\neasily compatible with legacy programs that expected 'binary' to be\nthe default encoding.\n\n

    \n

    Note that new programs will probably expect buffers, so only use this\nas a temporary measure.\n\n

    \n" } ], "modules": [ { "textRaw": "Recent API Changes", "name": "recent_api_changes", "desc": "

    The Crypto module was added to Node before there was the concept of a\nunified Stream API, and before there were Buffer objects for handling\nbinary data.\n\n

    \n

    As such, the streaming classes don't have the typical methods found on\nother Node classes, and many methods accepted and returned\nBinary-encoded strings by default rather than Buffers. This was\nchanged to use Buffers by default instead.\n\n

    \n

    This is a breaking change for some use cases, but not all.\n\n

    \n

    For example, if you currently use the default arguments to the Sign\nclass, and then pass the results to the Verify class, without ever\ninspecting the data, then it will continue to work as before. Where\nyou once got a binary string and then presented the binary string to\nthe Verify object, you'll now get a Buffer, and present the Buffer to\nthe Verify object.\n\n

    \n

    However, if you were doing things with the string data that will not\nwork properly on Buffers (such as, concatenating them, storing in\ndatabases, etc.), or you are passing binary strings to the crypto\nfunctions without an encoding argument, then you will need to start\nproviding encoding arguments to specify which encoding you'd like to\nuse. To switch to the previous style of using binary strings by\ndefault, set the crypto.DEFAULT_ENCODING field to 'binary'. Note\nthat new programs will probably expect buffers, so only use this as a\ntemporary measure.\n\n\n

    \n", "type": "module", "displayName": "Recent API Changes" } ], "type": "module", "displayName": "Crypto" } ] } node-v0.10.25~dfsg2/doc/api/util.html0000644000000000000000000003435712270264601016011 0ustar rootroot util Node.js v0.10.25 Manual & Documentation

    Node.js v0.10.25 Manual & Documentation


    util#

    Stability: 4 - API Frozen

    These functions are in the module 'util'. Use require('util') to access them.

    util.format(format, [...])#

    Returns a formatted string using the first argument as a printf-like format.

    The first argument is a string that contains zero or more placeholders. Each placeholder is replaced with the converted value from its corresponding argument. Supported placeholders are:

    • %s - String.
    • %d - Number (both integer and float).
    • %j - JSON.
    • % - single percent sign ('%'). This does not consume an argument.

    If the placeholder does not have a corresponding argument, the placeholder is not replaced.

    util.format('%s:%s', 'foo'); // 'foo:%s'

    If there are more arguments than placeholders, the extra arguments are converted to strings with util.inspect() and these strings are concatenated, delimited by a space.

    util.format('%s:%s', 'foo', 'bar', 'baz'); // 'foo:bar baz'

    If the first argument is not a format string then util.format() returns a string that is the concatenation of all its arguments separated by spaces. Each argument is converted to a string with util.inspect().

    util.format(1, 2, 3); // '1 2 3'

    util.debug(string)#

    A synchronous output function. Will block the process and output string immediately to stderr.

    require('util').debug('message on stderr');

    util.error([...])#

    Same as util.debug() except this will output all arguments immediately to stderr.

    util.puts([...])#

    A synchronous output function. Will block the process and output all arguments to stdout with newlines after each argument.

    util.print([...])#

    A synchronous output function. Will block the process, cast each argument to a string then output to stdout. Does not place newlines after each argument.

    util.log(string)#

    Output with timestamp on stdout.

    require('util').log('Timestamped message.');

    util.inspect(object, [options])#

    Return a string representation of object, which is useful for debugging.

    An optional options object may be passed that alters certain aspects of the formatted string:

    • showHidden - if true then the object's non-enumerable properties will be shown too. Defaults to false.

    • depth - tells inspect how many times to recurse while formatting the object. This is useful for inspecting large complicated objects. Defaults to 2. To make it recurse indefinitely pass null.

    • colors - if true, then the output will be styled with ANSI color codes. Defaults to false. Colors are customizable, see below.

    • customInspect - if false, then custom inspect() functions defined on the objects being inspected won't be called. Defaults to true.

    Example of inspecting all properties of the util object:

    var util = require('util');
    
    console.log(util.inspect(util, { showHidden: true, depth: null }));

    Customizing util.inspect colors#

    Color output (if enabled) of util.inspect is customizable globally via util.inspect.styles and util.inspect.colors objects.

    util.inspect.styles is a map assigning each style a color from util.inspect.colors. Highlighted styles and their default values are: number (yellow) boolean (yellow) string (green) date (magenta) regexp (red) null (bold) undefined (grey) special - only function at this time (cyan) * name (intentionally no styling)

    Predefined color codes are: white, grey, black, blue, cyan, green, magenta, red and yellow. There are also bold, italic, underline and inverse codes.

    Objects also may define their own inspect(depth) function which util.inspect() will invoke and use the result of when inspecting the object:

    var util = require('util');
    
    var obj = { name: 'nate' };
    obj.inspect = function(depth) {
      return '{' + this.name + '}';
    };
    
    util.inspect(obj);
      // "{nate}"

    util.isArray(object)#

    Returns true if the given "object" is an Array. false otherwise.

    var util = require('util');
    
    util.isArray([])
      // true
    util.isArray(new Array)
      // true
    util.isArray({})
      // false

    util.isRegExp(object)#

    Returns true if the given "object" is a RegExp. false otherwise.

    var util = require('util');
    
    util.isRegExp(/some regexp/)
      // true
    util.isRegExp(new RegExp('another regexp'))
      // true
    util.isRegExp({})
      // false

    util.isDate(object)#

    Returns true if the given "object" is a Date. false otherwise.

    var util = require('util');
    
    util.isDate(new Date())
      // true
    util.isDate(Date())
      // false (without 'new' returns a String)
    util.isDate({})
      // false

    util.isError(object)#

    Returns true if the given "object" is an Error. false otherwise.

    var util = require('util');
    
    util.isError(new Error())
      // true
    util.isError(new TypeError())
      // true
    util.isError({ name: 'Error', message: 'an error occurred' })
      // false

    util.pump(readableStream, writableStream, [callback])#

    Stability: 0 - Deprecated: Use readableStream.pipe(writableStream)

    Read the data from readableStream and send it to the writableStream. When writableStream.write(data) returns false readableStream will be paused until the drain event occurs on the writableStream. callback gets an error as its only argument and is called when writableStream is closed or when an error occurs.

    util.inherits(constructor, superConstructor)#

    Inherit the prototype methods from one constructor into another. The prototype of constructor will be set to a new object created from superConstructor.

    As an additional convenience, superConstructor will be accessible through the constructor.super_ property.

    var util = require("util");
    var events = require("events");
    
    function MyStream() {
        events.EventEmitter.call(this);
    }
    
    util.inherits(MyStream, events.EventEmitter);
    
    MyStream.prototype.write = function(data) {
        this.emit("data", data);
    }
    
    var stream = new MyStream();
    
    console.log(stream instanceof events.EventEmitter); // true
    console.log(MyStream.super_ === events.EventEmitter); // true
    
    stream.on("data", function(data) {
        console.log('Received data: "' + data + '"');
    })
    stream.write("It works!"); // Received data: "It works!"
    node-v0.10.25~dfsg2/doc/api/http.json0000644000000000000000000014732712270264601016022 0ustar rootroot{ "source": "doc/api/http.markdown", "modules": [ { "textRaw": "HTTP", "name": "http", "stability": 3, "stabilityText": "Stable", "desc": "

    To use the HTTP server and client one must require('http').\n\n

    \n

    The HTTP interfaces in Node are designed to support many features\nof the protocol which have been traditionally difficult to use.\nIn particular, large, possibly chunk-encoded, messages. The interface is\ncareful to never buffer entire requests or responses--the\nuser is able to stream data.\n\n

    \n

    HTTP message headers are represented by an object like this:\n\n

    \n
    { 'content-length': '123',\n  'content-type': 'text/plain',\n  'connection': 'keep-alive',\n  'accept': '*/*' }
    \n

    Keys are lowercased. Values are not modified.\n\n

    \n

    In order to support the full spectrum of possible HTTP applications, Node's\nHTTP API is very low-level. It deals with stream handling and message\nparsing only. It parses a message into headers and body but it does not\nparse the actual headers or the body.\n\n\n

    \n", "properties": [ { "textRaw": "`STATUS_CODES` {Object} ", "name": "STATUS_CODES", "desc": "

    A collection of all the standard HTTP response status codes, and the\nshort description of each. For example, http.STATUS_CODES[404] === 'Not\nFound'.\n\n

    \n" }, { "textRaw": "http.globalAgent", "name": "globalAgent", "desc": "

    Global instance of Agent which is used as the default for all http client\nrequests.\n\n\n

    \n" }, { "textRaw": "http.IncomingMessage", "name": "IncomingMessage", "desc": "

    An IncomingMessage object is created by [http.Server][] or\n[http.ClientRequest][] and passed as the first argument to the 'request'\nand 'response' event respectively. It may be used to access response status,\nheaders and data.\n\n

    \n

    It implements the [Readable Stream][] interface, as well as the\nfollowing additional events, methods, and properties.\n\n

    \n", "events": [ { "textRaw": "Event: 'close'", "type": "event", "name": "close", "desc": "

    function () { }\n\n

    \n

    Indicates that the underlaying connection was closed.\nJust like 'end', this event occurs only once per response.\n\n

    \n", "params": [] } ], "properties": [ { "textRaw": "message.httpVersion", "name": "httpVersion", "desc": "

    In case of server request, the HTTP version sent by the client. In the case of\nclient response, the HTTP version of the connected-to server.\nProbably either '1.1' or '1.0'.\n\n

    \n

    Also response.httpVersionMajor is the first integer and\nresponse.httpVersionMinor is the second.\n\n

    \n" }, { "textRaw": "message.headers", "name": "headers", "desc": "

    The request/response headers object.\n\n

    \n

    Read only map of header names and values. Header names are lower-cased.\nExample:\n\n

    \n
    // Prints something like:\n//\n// { 'user-agent': 'curl/7.22.0',\n//   host: '127.0.0.1:8000',\n//   accept: '*/*' }\nconsole.log(request.headers);
    \n" }, { "textRaw": "message.trailers", "name": "trailers", "desc": "

    The request/response trailers object. Only populated after the 'end' event.\n\n

    \n" }, { "textRaw": "message.method", "name": "method", "desc": "

    Only valid for request obtained from [http.Server][].\n\n

    \n

    The request method as a string. Read only. Example:\n'GET', 'DELETE'.\n\n

    \n" }, { "textRaw": "message.url", "name": "url", "desc": "

    Only valid for request obtained from [http.Server][].\n\n

    \n

    Request URL string. This contains only the URL that is\npresent in the actual HTTP request. If the request is:\n\n

    \n
    GET /status?name=ryan HTTP/1.1\\r\\n\nAccept: text/plain\\r\\n\n\\r\\n
    \n

    Then request.url will be:\n\n

    \n
    '/status?name=ryan'
    \n

    If you would like to parse the URL into its parts, you can use\nrequire('url').parse(request.url). Example:\n\n

    \n
    node> require('url').parse('/status?name=ryan')\n{ href: '/status?name=ryan',\n  search: '?name=ryan',\n  query: 'name=ryan',\n  pathname: '/status' }
    \n

    If you would like to extract the params from the query string,\nyou can use the require('querystring').parse function, or pass\ntrue as the second argument to require('url').parse. Example:\n\n

    \n
    node> require('url').parse('/status?name=ryan', true)\n{ href: '/status?name=ryan',\n  search: '?name=ryan',\n  query: { name: 'ryan' },\n  pathname: '/status' }
    \n" }, { "textRaw": "message.statusCode", "name": "statusCode", "desc": "

    Only valid for response obtained from http.ClientRequest.\n\n

    \n

    The 3-digit HTTP response status code. E.G. 404.\n\n

    \n" }, { "textRaw": "message.socket", "name": "socket", "desc": "

    The net.Socket object associated with the connection.\n\n

    \n

    With HTTPS support, use request.connection.verifyPeer() and\nrequest.connection.getPeerCertificate() to obtain the client's\nauthentication details.\n\n\n

    \n" } ], "methods": [ { "textRaw": "message.setTimeout(msecs, callback)", "type": "method", "name": "setTimeout", "signatures": [ { "params": [ { "textRaw": "`msecs` {Number} ", "name": "msecs", "type": "Number" }, { "textRaw": "`callback` {Function} ", "name": "callback", "type": "Function" } ] }, { "params": [ { "name": "msecs" }, { "name": "callback" } ] } ], "desc": "

    Calls message.connection.setTimeout(msecs, callback).\n\n

    \n" } ] } ], "methods": [ { "textRaw": "http.createServer([requestListener])", "type": "method", "name": "createServer", "desc": "

    Returns a new web server object.\n\n

    \n

    The requestListener is a function which is automatically\nadded to the 'request' event.\n\n

    \n", "signatures": [ { "params": [ { "name": "requestListener", "optional": true } ] } ] }, { "textRaw": "http.createClient([port], [host])", "type": "method", "name": "createClient", "desc": "

    This function is deprecated; please use [http.request()][] instead.\nConstructs a new HTTP client. port and host refer to the server to be\nconnected to.\n\n

    \n", "signatures": [ { "params": [ { "name": "port", "optional": true }, { "name": "host", "optional": true } ] } ] }, { "textRaw": "http.request(options, [callback])", "type": "method", "name": "request", "desc": "

    Node maintains several connections per server to make HTTP requests.\nThis function allows one to transparently issue requests.\n\n

    \n

    options can be an object or a string. If options is a string, it is\nautomatically parsed with [url.parse()][].\n\n

    \n

    Options:\n\n

    \n
      \n
    • host: A domain name or IP address of the server to issue the request to.\nDefaults to 'localhost'.
    • \n
    • hostname: To support url.parse() hostname is preferred over host
    • \n
    • port: Port of remote server. Defaults to 80.
    • \n
    • localAddress: Local interface to bind for network connections.
    • \n
    • socketPath: Unix Domain Socket (use one of host:port or socketPath)
    • \n
    • method: A string specifying the HTTP request method. Defaults to 'GET'.
    • \n
    • path: Request path. Defaults to '/'. Should include query string if any.\nE.G. '/index.html?page=12'
    • \n
    • headers: An object containing request headers.
    • \n
    • auth: Basic authentication i.e. 'user:password' to compute an\nAuthorization header.
    • \n
    • agent: Controls [Agent][] behavior. When an Agent is used request will\ndefault to Connection: keep-alive. Possible values:
        \n
      • undefined (default): use [global Agent][] for this host and port.
      • \n
      • Agent object: explicitly use the passed in Agent.
      • \n
      • false: opts out of connection pooling with an Agent, defaults request to\nConnection: close.
      • \n
      \n
    • \n
    \n

    The optional callback parameter will be added as a one time listener for\nthe ['response'][] event.\n\n

    \n

    http.request() returns an instance of the [http.ClientRequest][]\nclass. The ClientRequest instance is a writable stream. If one needs to\nupload a file with a POST request, then write to the ClientRequest object.\n\n

    \n

    Example:\n\n

    \n
    var options = {\n  hostname: 'www.google.com',\n  port: 80,\n  path: '/upload',\n  method: 'POST'\n};\n\nvar req = http.request(options, function(res) {\n  console.log('STATUS: ' + res.statusCode);\n  console.log('HEADERS: ' + JSON.stringify(res.headers));\n  res.setEncoding('utf8');\n  res.on('data', function (chunk) {\n    console.log('BODY: ' + chunk);\n  });\n});\n\nreq.on('error', function(e) {\n  console.log('problem with request: ' + e.message);\n});\n\n// write data to request body\nreq.write('data\\n');\nreq.write('data\\n');\nreq.end();
    \n

    Note that in the example req.end() was called. With http.request() one\nmust always call req.end() to signify that you're done with the request -\neven if there is no data being written to the request body.\n\n

    \n

    If any error is encountered during the request (be that with DNS resolution,\nTCP level errors, or actual HTTP parse errors) an 'error' event is emitted\non the returned request object.\n\n

    \n

    There are a few special headers that should be noted.\n\n

    \n
      \n
    • Sending a 'Connection: keep-alive' will notify Node that the connection to\nthe server should be persisted until the next request.

      \n
    • \n
    • Sending a 'Content-length' header will disable the default chunked encoding.

      \n
    • \n
    • Sending an 'Expect' header will immediately send the request headers.\nUsually, when sending 'Expect: 100-continue', you should both set a timeout\nand listen for the continue event. See RFC2616 Section 8.2.3 for more\ninformation.

      \n
    • \n
    • Sending an Authorization header will override using the auth option\nto compute basic authentication.

      \n
    • \n
    \n", "signatures": [ { "params": [ { "name": "options" }, { "name": "callback", "optional": true } ] } ] }, { "textRaw": "http.get(options, [callback])", "type": "method", "name": "get", "desc": "

    Since most requests are GET requests without bodies, Node provides this\nconvenience method. The only difference between this method and http.request()\nis that it sets the method to GET and calls req.end() automatically.\n\n

    \n

    Example:\n\n

    \n
    http.get("http://www.google.com/index.html", function(res) {\n  console.log("Got response: " + res.statusCode);\n}).on('error', function(e) {\n  console.log("Got error: " + e.message);\n});
    \n", "signatures": [ { "params": [ { "name": "options" }, { "name": "callback", "optional": true } ] } ] } ], "classes": [ { "textRaw": "Class: http.Server", "type": "class", "name": "http.Server", "desc": "

    This is an [EventEmitter][] with the following events:\n\n

    \n", "events": [ { "textRaw": "Event: 'request'", "type": "event", "name": "request", "desc": "

    function (request, response) { }\n\n

    \n

    Emitted each time there is a request. Note that there may be multiple requests\nper connection (in the case of keep-alive connections).\n request is an instance of [http.IncomingMessage][] and response is\nan instance of [http.ServerResponse][].\n\n

    \n", "params": [] }, { "textRaw": "Event: 'connection'", "type": "event", "name": "connection", "desc": "

    function (socket) { }\n\n

    \n

    When a new TCP stream is established. socket is an object of type\n net.Socket. Usually users will not want to access this event. In\n particular, the socket will not emit readable events because of how\n the protocol parser attaches to the socket. The socket can also be\n accessed at request.connection.\n\n

    \n", "params": [] }, { "textRaw": "Event: 'close'", "type": "event", "name": "close", "desc": "

    function () { }\n\n

    \n

    Emitted when the server closes.\n\n

    \n", "params": [] }, { "textRaw": "Event: 'checkContinue'", "type": "event", "name": "checkContinue", "desc": "

    function (request, response) { }\n\n

    \n

    Emitted each time a request with an http Expect: 100-continue is received.\nIf this event isn't listened for, the server will automatically respond\nwith a 100 Continue as appropriate.\n\n

    \n

    Handling this event involves calling [response.writeContinue()][] if the client\nshould continue to send the request body, or generating an appropriate HTTP\nresponse (e.g., 400 Bad Request) if the client should not continue to send the\nrequest body.\n\n

    \n

    Note that when this event is emitted and handled, the request event will\nnot be emitted.\n\n

    \n", "params": [] }, { "textRaw": "Event: 'connect'", "type": "event", "name": "connect", "desc": "

    function (request, socket, head) { }\n\n

    \n

    Emitted each time a client requests a http CONNECT method. If this event isn't\nlistened for, then clients requesting a CONNECT method will have their\nconnections closed.\n\n

    \n
      \n
    • request is the arguments for the http request, as it is in the request\nevent.
    • \n
    • socket is the network socket between the server and client.
    • \n
    • head is an instance of Buffer, the first packet of the tunneling stream,\nthis may be empty.
    • \n
    \n

    After this event is emitted, the request's socket will not have a data\nevent listener, meaning you will need to bind to it in order to handle data\nsent to the server on that socket.\n\n

    \n", "params": [] }, { "textRaw": "Event: 'upgrade'", "type": "event", "name": "upgrade", "desc": "

    function (request, socket, head) { }\n\n

    \n

    Emitted each time a client requests a http upgrade. If this event isn't\nlistened for, then clients requesting an upgrade will have their connections\nclosed.\n\n

    \n
      \n
    • request is the arguments for the http request, as it is in the request\nevent.
    • \n
    • socket is the network socket between the server and client.
    • \n
    • head is an instance of Buffer, the first packet of the upgraded stream,\nthis may be empty.
    • \n
    \n

    After this event is emitted, the request's socket will not have a data\nevent listener, meaning you will need to bind to it in order to handle data\nsent to the server on that socket.\n\n

    \n", "params": [] }, { "textRaw": "Event: 'clientError'", "type": "event", "name": "clientError", "desc": "

    function (exception, socket) { }\n\n

    \n

    If a client connection emits an 'error' event - it will forwarded here.\n\n

    \n

    socket is the net.Socket object that the error originated from.\n\n\n

    \n", "params": [] } ], "methods": [ { "textRaw": "server.listen(port, [hostname], [backlog], [callback])", "type": "method", "name": "listen", "desc": "

    Begin accepting connections on the specified port and hostname. If the\nhostname is omitted, the server will accept connections directed to any\nIPv4 address (INADDR_ANY).\n\n

    \n

    To listen to a unix socket, supply a filename instead of port and hostname.\n\n

    \n

    Backlog is the maximum length of the queue of pending connections.\nThe actual length will be determined by your OS through sysctl settings such as\ntcp_max_syn_backlog and somaxconn on linux. The default value of this\nparameter is 511 (not 512).\n\n

    \n

    This function is asynchronous. The last parameter callback will be added as\na listener for the ['listening'][] event. See also [net.Server.listen(port)][].\n\n\n

    \n", "signatures": [ { "params": [ { "name": "port" }, { "name": "hostname", "optional": true }, { "name": "backlog", "optional": true }, { "name": "callback", "optional": true } ] } ] }, { "textRaw": "server.listen(path, [callback])", "type": "method", "name": "listen", "desc": "

    Start a UNIX socket server listening for connections on the given path.\n\n

    \n

    This function is asynchronous. The last parameter callback will be added as\na listener for the ['listening'][] event. See also [net.Server.listen(path)][].\n\n\n

    \n", "signatures": [ { "params": [ { "name": "path" }, { "name": "callback", "optional": true } ] } ] }, { "textRaw": "server.listen(handle, [callback])", "type": "method", "name": "listen", "signatures": [ { "params": [ { "textRaw": "`handle` {Object} ", "name": "handle", "type": "Object" }, { "textRaw": "`callback` {Function} ", "name": "callback", "type": "Function", "optional": true } ] }, { "params": [ { "name": "handle" }, { "name": "callback", "optional": true } ] } ], "desc": "

    The handle object can be set to either a server or socket (anything\nwith an underlying _handle member), or a {fd: <n>} object.\n\n

    \n

    This will cause the server to accept connections on the specified\nhandle, but it is presumed that the file descriptor or handle has\nalready been bound to a port or domain socket.\n\n

    \n

    Listening on a file descriptor is not supported on Windows.\n\n

    \n

    This function is asynchronous. The last parameter callback will be added as\na listener for the 'listening' event.\nSee also net.Server.listen().\n\n

    \n" }, { "textRaw": "server.close([callback])", "type": "method", "name": "close", "desc": "

    Stops the server from accepting new connections. See [net.Server.close()][].\n\n\n

    \n", "signatures": [ { "params": [ { "name": "callback", "optional": true } ] } ] }, { "textRaw": "server.setTimeout(msecs, callback)", "type": "method", "name": "setTimeout", "signatures": [ { "params": [ { "textRaw": "`msecs` {Number} ", "name": "msecs", "type": "Number" }, { "textRaw": "`callback` {Function} ", "name": "callback", "type": "Function" } ] }, { "params": [ { "name": "msecs" }, { "name": "callback" } ] } ], "desc": "

    Sets the timeout value for sockets, and emits a 'timeout' event on\nthe Server object, passing the socket as an argument, if a timeout\noccurs.\n\n

    \n

    If there is a 'timeout' event listener on the Server object, then it\nwill be called with the timed-out socket as an argument.\n\n

    \n

    By default, the Server's timeout value is 2 minutes, and sockets are\ndestroyed automatically if they time out. However, if you assign a\ncallback to the Server's 'timeout' event, then you are responsible\nfor handling socket timeouts.\n\n

    \n" } ], "properties": [ { "textRaw": "server.maxHeadersCount", "name": "maxHeadersCount", "desc": "

    Limits maximum incoming headers count, equal to 1000 by default. If set to 0 -\nno limit will be applied.\n\n

    \n" }, { "textRaw": "`timeout` {Number} Default = 120000 (2 minutes) ", "name": "timeout", "desc": "

    The number of milliseconds of inactivity before a socket is presumed\nto have timed out.\n\n

    \n

    Note that the socket timeout logic is set up on connection, so\nchanging this value only affects new connections to the server, not\nany existing connections.\n\n

    \n

    Set to 0 to disable any kind of automatic timeout behavior on incoming\nconnections.\n\n

    \n", "shortDesc": "Default = 120000 (2 minutes)" } ] }, { "textRaw": "Class: http.ServerResponse", "type": "class", "name": "http.ServerResponse", "desc": "

    This object is created internally by a HTTP server--not by the user. It is\npassed as the second parameter to the 'request' event.\n\n

    \n

    The response implements the [Writable Stream][] interface. This is an\n[EventEmitter][] with the following events:\n\n

    \n", "events": [ { "textRaw": "Event: 'close'", "type": "event", "name": "close", "desc": "

    function () { }\n\n

    \n

    Indicates that the underlying connection was terminated before\n[response.end()][] was called or able to flush.\n\n

    \n", "params": [] }, { "textRaw": "Event: 'finish'", "type": "event", "name": "finish", "desc": "

    function () { }\n\n

    \n

    Emitted when the response has been sent. More specifically, this event is\nemitted when the last segment of the response headers and body have been\nhanded off to the operating system for transmission over the network. It\ndoes not imply that the client has received anything yet.\n\n

    \n

    After this event, no more events will be emitted on the response object.\n\n

    \n", "params": [] } ], "methods": [ { "textRaw": "response.writeContinue()", "type": "method", "name": "writeContinue", "desc": "

    Sends a HTTP/1.1 100 Continue message to the client, indicating that\nthe request body should be sent. See the ['checkContinue'][] event on Server.\n\n

    \n", "signatures": [ { "params": [] } ] }, { "textRaw": "response.writeHead(statusCode, [reasonPhrase], [headers])", "type": "method", "name": "writeHead", "desc": "

    Sends a response header to the request. The status code is a 3-digit HTTP\nstatus code, like 404. The last argument, headers, are the response headers.\nOptionally one can give a human-readable reasonPhrase as the second\nargument.\n\n

    \n

    Example:\n\n

    \n
    var body = 'hello world';\nresponse.writeHead(200, {\n  'Content-Length': body.length,\n  'Content-Type': 'text/plain' });
    \n

    This method must only be called once on a message and it must\nbe called before [response.end()][] is called.\n\n

    \n

    If you call [response.write()][] or [response.end()][] before calling this, the\nimplicit/mutable headers will be calculated and call this function for you.\n\n

    \n

    Note: that Content-Length is given in bytes not characters. The above example\nworks because the string 'hello world' contains only single byte characters.\nIf the body contains higher coded characters then Buffer.byteLength()\nshould be used to determine the number of bytes in a given encoding.\nAnd Node does not check whether Content-Length and the length of the body\nwhich has been transmitted are equal or not.\n\n

    \n", "signatures": [ { "params": [ { "name": "statusCode" }, { "name": "reasonPhrase", "optional": true }, { "name": "headers", "optional": true } ] } ] }, { "textRaw": "response.setTimeout(msecs, callback)", "type": "method", "name": "setTimeout", "signatures": [ { "params": [ { "textRaw": "`msecs` {Number} ", "name": "msecs", "type": "Number" }, { "textRaw": "`callback` {Function} ", "name": "callback", "type": "Function" } ] }, { "params": [ { "name": "msecs" }, { "name": "callback" } ] } ], "desc": "

    Sets the Socket's timeout value to msecs. If a callback is\nprovided, then it is added as a listener on the 'timeout' event on\nthe response object.\n\n

    \n

    If no 'timeout' listener is added to the request, the response, or\nthe server, then sockets are destroyed when they time out. If you\nassign a handler on the request, the response, or the server's\n'timeout' events, then it is your responsibility to handle timed out\nsockets.\n\n

    \n" }, { "textRaw": "response.setHeader(name, value)", "type": "method", "name": "setHeader", "desc": "

    Sets a single header value for implicit headers. If this header already exists\nin the to-be-sent headers, its value will be replaced. Use an array of strings\nhere if you need to send multiple headers with the same name.\n\n

    \n

    Example:\n\n

    \n
    response.setHeader("Content-Type", "text/html");
    \n

    or\n\n

    \n
    response.setHeader("Set-Cookie", ["type=ninja", "language=javascript"]);
    \n", "signatures": [ { "params": [ { "name": "name" }, { "name": "value" } ] } ] }, { "textRaw": "response.getHeader(name)", "type": "method", "name": "getHeader", "desc": "

    Reads out a header that's already been queued but not sent to the client. Note\nthat the name is case insensitive. This can only be called before headers get\nimplicitly flushed.\n\n

    \n

    Example:\n\n

    \n
    var contentType = response.getHeader('content-type');
    \n", "signatures": [ { "params": [ { "name": "name" } ] } ] }, { "textRaw": "response.removeHeader(name)", "type": "method", "name": "removeHeader", "desc": "

    Removes a header that's queued for implicit sending.\n\n

    \n

    Example:\n\n

    \n
    response.removeHeader("Content-Encoding");
    \n", "signatures": [ { "params": [ { "name": "name" } ] } ] }, { "textRaw": "response.write(chunk, [encoding])", "type": "method", "name": "write", "desc": "

    If this method is called and [response.writeHead()][] has not been called,\nit will switch to implicit header mode and flush the implicit headers.\n\n

    \n

    This sends a chunk of the response body. This method may\nbe called multiple times to provide successive parts of the body.\n\n

    \n

    chunk can be a string or a buffer. If chunk is a string,\nthe second parameter specifies how to encode it into a byte stream.\nBy default the encoding is 'utf8'.\n\n

    \n

    Note: This is the raw HTTP body and has nothing to do with\nhigher-level multi-part body encodings that may be used.\n\n

    \n

    The first time response.write() is called, it will send the buffered\nheader information and the first body to the client. The second time\nresponse.write() is called, Node assumes you're going to be streaming\ndata, and sends that separately. That is, the response is buffered up to the\nfirst chunk of body.\n\n

    \n

    Returns true if the entire data was flushed successfully to the kernel\nbuffer. Returns false if all or part of the data was queued in user memory.\n'drain' will be emitted when the buffer is again free.\n\n

    \n", "signatures": [ { "params": [ { "name": "chunk" }, { "name": "encoding", "optional": true } ] } ] }, { "textRaw": "response.addTrailers(headers)", "type": "method", "name": "addTrailers", "desc": "

    This method adds HTTP trailing headers (a header but at the end of the\nmessage) to the response.\n\n

    \n

    Trailers will only be emitted if chunked encoding is used for the\nresponse; if it is not (e.g., if the request was HTTP/1.0), they will\nbe silently discarded.\n\n

    \n

    Note that HTTP requires the Trailer header to be sent if you intend to\nemit trailers, with a list of the header fields in its value. E.g.,\n\n

    \n
    response.writeHead(200, { 'Content-Type': 'text/plain',\n                          'Trailer': 'Content-MD5' });\nresponse.write(fileData);\nresponse.addTrailers({'Content-MD5': "7895bf4b8828b55ceaf47747b4bca667"});\nresponse.end();
    \n", "signatures": [ { "params": [ { "name": "headers" } ] } ] }, { "textRaw": "response.end([data], [encoding])", "type": "method", "name": "end", "desc": "

    This method signals to the server that all of the response headers and body\nhave been sent; that server should consider this message complete.\nThe method, response.end(), MUST be called on each\nresponse.\n\n

    \n

    If data is specified, it is equivalent to calling response.write(data, encoding)\nfollowed by response.end().\n\n\n

    \n", "signatures": [ { "params": [ { "name": "data", "optional": true }, { "name": "encoding", "optional": true } ] } ] } ], "properties": [ { "textRaw": "response.statusCode", "name": "statusCode", "desc": "

    When using implicit headers (not calling [response.writeHead()][] explicitly),\nthis property controls the status code that will be sent to the client when\nthe headers get flushed.\n\n

    \n

    Example:\n\n

    \n
    response.statusCode = 404;
    \n

    After response header was sent to the client, this property indicates the\nstatus code which was sent out.\n\n

    \n" }, { "textRaw": "response.headersSent", "name": "headersSent", "desc": "

    Boolean (read-only). True if headers were sent, false otherwise.\n\n

    \n" }, { "textRaw": "response.sendDate", "name": "sendDate", "desc": "

    When true, the Date header will be automatically generated and sent in\nthe response if it is not already present in the headers. Defaults to true.\n\n

    \n

    This should only be disabled for testing; HTTP requires the Date header\nin responses.\n\n

    \n" } ] }, { "textRaw": "Class: http.Agent", "type": "class", "name": "http.Agent", "desc": "

    In node 0.5.3+ there is a new implementation of the HTTP Agent which is used\nfor pooling sockets used in HTTP client requests.\n\n

    \n

    Previously, a single agent instance helped pool for a single host+port. The\ncurrent implementation now holds sockets for any number of hosts.\n\n

    \n

    The current HTTP Agent also defaults client requests to using\nConnection:keep-alive. If no pending HTTP requests are waiting on a socket\nto become free the socket is closed. This means that node's pool has the\nbenefit of keep-alive when under load but still does not require developers\nto manually close the HTTP clients using keep-alive.\n\n

    \n

    Sockets are removed from the agent's pool when the socket emits either a\n"close" event or a special "agentRemove" event. This means that if you intend\nto keep one HTTP request open for a long time and don't want it to stay in the\npool you can do something along the lines of:\n\n

    \n
    http.get(options, function(res) {\n  // Do stuff\n}).on("socket", function (socket) {\n  socket.emit("agentRemove");\n});
    \n

    Alternatively, you could just opt out of pooling entirely using agent:false:\n\n

    \n
    http.get({hostname:'localhost', port:80, path:'/', agent:false}, function (res) {\n  // Do stuff\n})
    \n", "properties": [ { "textRaw": "agent.maxSockets", "name": "maxSockets", "desc": "

    By default set to 5. Determines how many concurrent sockets the agent can have\nopen per host.\n\n

    \n" }, { "textRaw": "agent.sockets", "name": "sockets", "desc": "

    An object which contains arrays of sockets currently in use by the Agent. Do not\nmodify.\n\n

    \n" }, { "textRaw": "agent.requests", "name": "requests", "desc": "

    An object which contains queues of requests that have not yet been assigned to\nsockets. Do not modify.\n\n

    \n" } ] }, { "textRaw": "Class: http.ClientRequest", "type": "class", "name": "http.ClientRequest", "desc": "

    This object is created internally and returned from http.request(). It\nrepresents an in-progress request whose header has already been queued. The\nheader is still mutable using the setHeader(name, value), getHeader(name),\nremoveHeader(name) API. The actual header will be sent along with the first\ndata chunk or when closing the connection.\n\n

    \n

    To get the response, add a listener for 'response' to the request object.\n'response' will be emitted from the request object when the response\nheaders have been received. The 'response' event is executed with one\nargument which is an instance of [http.IncomingMessage][].\n\n

    \n

    During the 'response' event, one can add listeners to the\nresponse object; particularly to listen for the 'data' event.\n\n

    \n

    If no 'response' handler is added, then the response will be\nentirely discarded. However, if you add a 'response' event handler,\nthen you must consume the data from the response object, either by\ncalling response.read() whenever there is a 'readable' event, or\nby adding a 'data' handler, or by calling the .resume() method.\nUntil the data is consumed, the 'end' event will not fire. Also, until\nthe data is read it will consume memory that can eventually lead to a\n'process out of memory' error.\n\n

    \n

    Note: Node does not check whether Content-Length and the length of the body\nwhich has been transmitted are equal or not.\n\n

    \n

    The request implements the [Writable Stream][] interface. This is an\n[EventEmitter][] with the following events:\n\n

    \n", "events": [ { "textRaw": "Event 'response'", "type": "event", "name": "response", "desc": "

    function (response) { }\n\n

    \n

    Emitted when a response is received to this request. This event is emitted only\nonce. The response argument will be an instance of [http.IncomingMessage][].\n\n

    \n

    Options:\n\n

    \n
      \n
    • host: A domain name or IP address of the server to issue the request to.
    • \n
    • port: Port of remote server.
    • \n
    • socketPath: Unix Domain Socket (use one of host:port or socketPath)
    • \n
    \n", "params": [] }, { "textRaw": "Event: 'socket'", "type": "event", "name": "socket", "desc": "

    function (socket) { }\n\n

    \n

    Emitted after a socket is assigned to this request.\n\n

    \n", "params": [] }, { "textRaw": "Event: 'connect'", "type": "event", "name": "connect", "desc": "

    function (response, socket, head) { }\n\n

    \n

    Emitted each time a server responds to a request with a CONNECT method. If this\nevent isn't being listened for, clients receiving a CONNECT method will have\ntheir connections closed.\n\n

    \n

    A client server pair that show you how to listen for the connect event.\n\n

    \n
    var http = require('http');\nvar net = require('net');\nvar url = require('url');\n\n// Create an HTTP tunneling proxy\nvar proxy = http.createServer(function (req, res) {\n  res.writeHead(200, {'Content-Type': 'text/plain'});\n  res.end('okay');\n});\nproxy.on('connect', function(req, cltSocket, head) {\n  // connect to an origin server\n  var srvUrl = url.parse('http://' + req.url);\n  var srvSocket = net.connect(srvUrl.port, srvUrl.hostname, function() {\n    cltSocket.write('HTTP/1.1 200 Connection Established\\r\\n' +\n                    'Proxy-agent: Node-Proxy\\r\\n' +\n                    '\\r\\n');\n    srvSocket.write(head);\n    srvSocket.pipe(cltSocket);\n    cltSocket.pipe(srvSocket);\n  });\n});\n\n// now that proxy is running\nproxy.listen(1337, '127.0.0.1', function() {\n\n  // make a request to a tunneling proxy\n  var options = {\n    port: 1337,\n    hostname: '127.0.0.1',\n    method: 'CONNECT',\n    path: 'www.google.com:80'\n  };\n\n  var req = http.request(options);\n  req.end();\n\n  req.on('connect', function(res, socket, head) {\n    console.log('got connected!');\n\n    // make a request over an HTTP tunnel\n    socket.write('GET / HTTP/1.1\\r\\n' +\n                 'Host: www.google.com:80\\r\\n' +\n                 'Connection: close\\r\\n' +\n                 '\\r\\n');\n    socket.on('data', function(chunk) {\n      console.log(chunk.toString());\n    });\n    socket.on('end', function() {\n      proxy.close();\n    });\n  });\n});
    \n", "params": [] }, { "textRaw": "Event: 'upgrade'", "type": "event", "name": "upgrade", "desc": "

    function (response, socket, head) { }\n\n

    \n

    Emitted each time a server responds to a request with an upgrade. If this\nevent isn't being listened for, clients receiving an upgrade header will have\ntheir connections closed.\n\n

    \n

    A client server pair that show you how to listen for the upgrade event.\n\n

    \n
    var http = require('http');\n\n// Create an HTTP server\nvar srv = http.createServer(function (req, res) {\n  res.writeHead(200, {'Content-Type': 'text/plain'});\n  res.end('okay');\n});\nsrv.on('upgrade', function(req, socket, head) {\n  socket.write('HTTP/1.1 101 Web Socket Protocol Handshake\\r\\n' +\n               'Upgrade: WebSocket\\r\\n' +\n               'Connection: Upgrade\\r\\n' +\n               '\\r\\n');\n\n  socket.pipe(socket); // echo back\n});\n\n// now that server is running\nsrv.listen(1337, '127.0.0.1', function() {\n\n  // make a request\n  var options = {\n    port: 1337,\n    hostname: '127.0.0.1',\n    headers: {\n      'Connection': 'Upgrade',\n      'Upgrade': 'websocket'\n    }\n  };\n\n  var req = http.request(options);\n  req.end();\n\n  req.on('upgrade', function(res, socket, upgradeHead) {\n    console.log('got upgraded!');\n    socket.end();\n    process.exit(0);\n  });\n});
    \n", "params": [] }, { "textRaw": "Event: 'continue'", "type": "event", "name": "continue", "desc": "

    function () { }\n\n

    \n

    Emitted when the server sends a '100 Continue' HTTP response, usually because\nthe request contained 'Expect: 100-continue'. This is an instruction that\nthe client should send the request body.\n\n

    \n", "params": [] } ], "methods": [ { "textRaw": "request.write(chunk, [encoding])", "type": "method", "name": "write", "desc": "

    Sends a chunk of the body. By calling this method\nmany times, the user can stream a request body to a\nserver--in that case it is suggested to use the\n['Transfer-Encoding', 'chunked'] header line when\ncreating the request.\n\n

    \n

    The chunk argument should be a [Buffer][] or a string.\n\n

    \n

    The encoding argument is optional and only applies when chunk is a string.\nDefaults to 'utf8'.\n\n\n

    \n", "signatures": [ { "params": [ { "name": "chunk" }, { "name": "encoding", "optional": true } ] } ] }, { "textRaw": "request.end([data], [encoding])", "type": "method", "name": "end", "desc": "

    Finishes sending the request. If any parts of the body are\nunsent, it will flush them to the stream. If the request is\nchunked, this will send the terminating '0\\r\\n\\r\\n'.\n\n

    \n

    If data is specified, it is equivalent to calling\nrequest.write(data, encoding) followed by request.end().\n\n

    \n", "signatures": [ { "params": [ { "name": "data", "optional": true }, { "name": "encoding", "optional": true } ] } ] }, { "textRaw": "request.abort()", "type": "method", "name": "abort", "desc": "

    Aborts a request. (New since v0.3.8.)\n\n

    \n", "signatures": [ { "params": [] } ] }, { "textRaw": "request.setTimeout(timeout, [callback])", "type": "method", "name": "setTimeout", "desc": "

    Once a socket is assigned to this request and is connected\n[socket.setTimeout()][] will be called.\n\n

    \n", "signatures": [ { "params": [ { "name": "timeout" }, { "name": "callback", "optional": true } ] } ] }, { "textRaw": "request.setNoDelay([noDelay])", "type": "method", "name": "setNoDelay", "desc": "

    Once a socket is assigned to this request and is connected\n[socket.setNoDelay()][] will be called.\n\n

    \n", "signatures": [ { "params": [ { "name": "noDelay", "optional": true } ] } ] }, { "textRaw": "request.setSocketKeepAlive([enable], [initialDelay])", "type": "method", "name": "setSocketKeepAlive", "desc": "

    Once a socket is assigned to this request and is connected\n[socket.setKeepAlive()][] will be called.\n\n\n

    \n", "signatures": [ { "params": [ { "name": "enable", "optional": true }, { "name": "initialDelay", "optional": true } ] } ] } ] } ], "type": "module", "displayName": "HTTP" } ] } node-v0.10.25~dfsg2/doc/api/dns.html0000644000000000000000000003160512270264601015611 0ustar rootroot DNS Node.js v0.10.25 Manual & Documentation

    Node.js v0.10.25 Manual & Documentation


    DNS#

    Stability: 3 - Stable

    Use require('dns') to access this module. All methods in the dns module use C-Ares except for dns.lookup which uses getaddrinfo(3) in a thread pool. C-Ares is much faster than getaddrinfo but the system resolver is more consistent with how other programs operate. When a user does net.connect(80, 'google.com') or http.get({ host: 'google.com' }) the dns.lookup method is used. Users who need to do a large number of lookups quickly should use the methods that go through C-Ares.

    Here is an example which resolves 'www.google.com' then reverse resolves the IP addresses which are returned.

    var dns = require('dns');
    
    dns.resolve4('www.google.com', function (err, addresses) {
      if (err) throw err;
    
      console.log('addresses: ' + JSON.stringify(addresses));
    
      addresses.forEach(function (a) {
        dns.reverse(a, function (err, domains) {
          if (err) {
            throw err;
          }
    
          console.log('reverse for ' + a + ': ' + JSON.stringify(domains));
        });
      });
    });

    dns.lookup(domain, [family], callback)#

    Resolves a domain (e.g. 'google.com') into the first found A (IPv4) or AAAA (IPv6) record. The family can be the integer 4 or 6. Defaults to null that indicates both Ip v4 and v6 address family.

    The callback has arguments (err, address, family). The address argument is a string representation of a IP v4 or v6 address. The family argument is either the integer 4 or 6 and denotes the family of address (not necessarily the value initially passed to lookup).

    On error, err is an Error object, where err.code is the error code. Keep in mind that err.code will be set to 'ENOENT' not only when the domain does not exist but also when the lookup fails in other ways such as no available file descriptors.

    dns.resolve(domain, [rrtype], callback)#

    Resolves a domain (e.g. 'google.com') into an array of the record types specified by rrtype. Valid rrtypes are 'A' (IPV4 addresses, default), 'AAAA' (IPV6 addresses), 'MX' (mail exchange records), 'TXT' (text records), 'SRV' (SRV records), 'PTR' (used for reverse IP lookups), 'NS' (name server records) and 'CNAME' (canonical name records).

    The callback has arguments (err, addresses). The type of each item in addresses is determined by the record type, and described in the documentation for the corresponding lookup methods below.

    On error, err is an Error object, where err.code is one of the error codes listed below.

    dns.resolve4(domain, callback)#

    The same as dns.resolve(), but only for IPv4 queries (A records). addresses is an array of IPv4 addresses (e.g. ['74.125.79.104', '74.125.79.105', '74.125.79.106']).

    dns.resolve6(domain, callback)#

    The same as dns.resolve4() except for IPv6 queries (an AAAA query).

    dns.resolveMx(domain, callback)#

    The same as dns.resolve(), but only for mail exchange queries (MX records).

    addresses is an array of MX records, each with a priority and an exchange attribute (e.g. [{'priority': 10, 'exchange': 'mx.example.com'},...]).

    dns.resolveTxt(domain, callback)#

    The same as dns.resolve(), but only for text queries (TXT records). addresses is an array of the text records available for domain (e.g., ['v=spf1 ip4:0.0.0.0 ~all']).

    dns.resolveSrv(domain, callback)#

    The same as dns.resolve(), but only for service records (SRV records). addresses is an array of the SRV records available for domain. Properties of SRV records are priority, weight, port, and name (e.g., [{'priority': 10, {'weight': 5, 'port': 21223, 'name': 'service.example.com'}, ...]).

    dns.resolveNs(domain, callback)#

    The same as dns.resolve(), but only for name server records (NS records). addresses is an array of the name server records available for domain (e.g., ['ns1.example.com', 'ns2.example.com']).

    dns.resolveCname(domain, callback)#

    The same as dns.resolve(), but only for canonical name records (CNAME records). addresses is an array of the canonical name records available for domain (e.g., ['bar.example.com']).

    dns.reverse(ip, callback)#

    Reverse resolves an ip address to an array of domain names.

    The callback has arguments (err, domains).

    On error, err is an Error object, where err.code is one of the error codes listed below.

    Error codes#

    Each DNS query can return one of the following error codes:

    • dns.NODATA: DNS server returned answer with no data.
    • dns.FORMERR: DNS server claims query was misformatted.
    • dns.SERVFAIL: DNS server returned general failure.
    • dns.NOTFOUND: Domain name not found.
    • dns.NOTIMP: DNS server does not implement requested operation.
    • dns.REFUSED: DNS server refused query.
    • dns.BADQUERY: Misformatted DNS query.
    • dns.BADNAME: Misformatted domain name.
    • dns.BADFAMILY: Unsupported address family.
    • dns.BADRESP: Misformatted DNS reply.
    • dns.CONNREFUSED: Could not contact DNS servers.
    • dns.TIMEOUT: Timeout while contacting DNS servers.
    • dns.EOF: End of file.
    • dns.FILE: Error reading file.
    • dns.NOMEM: Out of memory.
    • dns.DESTRUCTION: Channel is being destroyed.
    • dns.BADSTR: Misformatted string.
    • dns.BADFLAGS: Illegal flags specified.
    • dns.NONAME: Given hostname is not numeric.
    • dns.BADHINTS: Illegal hints flags specified.
    • dns.NOTINITIALIZED: c-ares library initialization not yet performed.
    • dns.LOADIPHLPAPI: Error loading iphlpapi.dll.
    • dns.ADDRGETNETWORKPARAMS: Could not find GetNetworkParams function.
    • dns.CANCELLED: DNS query cancelled.
    node-v0.10.25~dfsg2/doc/api/assets/0000755000000000000000000000000012270264601015434 5ustar rootrootnode-v0.10.25~dfsg2/doc/api/assets/sh.css0000644000000000000000000000055512270264601016565 0ustar rootroot.sh_sourceCode { font-weight: normal; font-style: normal; } .sh_sourceCode .sh_symbol, .sh_sourceCode .sh_cbracket { color: #333; } .sh_sourceCode .sh_keyword { color: #c96; } .sh_sourceCode .sh_string, .sh_sourceCode .sh_regexp, .sh_sourceCode .sh_number, .sh_sourceCode .sh_specialchar { color: #690; } .sh_sourceCode .sh_comment { color: #666; } node-v0.10.25~dfsg2/doc/api/assets/style.css0000644000000000000000000002517112270264601017314 0ustar rootroot/*--------------------- Layout and Typography ----------------------------*/ html { -webkit-font-smoothing: antialiased; } body { font-family: "Lucida Grande", "Lucida Sans Unicode", "Lucida Sans", Verdana, Tahoma, sans-serif; font-size: 14px; line-height: 180%; color: black; background-color: white; margin: 0; padding: 49px 0 0 0; border-top: 6px #8CC84B solid; } a { color: #480; text-decoration: underline; } a:visited { color: #46483e; text-decoration: underline; } a:hover, a:focus { text-decoration: none; } code a:hover { background: none; color: #b950b7; } #changelog #gtoc { display: none; } #gtoc p { margin: 0; font-size: 18px; line-height: 30px; } #gtoc a { font-family: Georgia, FreeSerif, Times, serif; text-decoration: none; color: #46483e; } #gtoc a:hover { color: #669900; text-decoration: underline; } .notice { display: block; padding: 1em; margin: 1.4667em 0 2.9334em; background: #FFF6BF; color: #514721; border: 1px solid #FFD324; } .notice p { margin: 0; } .api_stability_0 { border-color: #D60027; } .api_stability_1 { border-color: #EC5315; } .api_stability_2 { border-color: #FFD700; } .api_stability_3 { border-color: #AEC516; } .api_stability_4 { border-color: #009431; } .api_stability_5 { border-color: #0084B6; } ul.plain { list-style: none; } abbr { border-bottom: 1px dotted #454545; } p { margin: 0 0 1.4667em 0; position: relative; text-rendering: optimizeLegibility; } table { border-collapse: collapse; margin: 0 0 1.4667em 0; } th, td { border: 1px solid #aaa; } table p { margin: 0 1ex; } th { text-align:left; } .apidoc #apicontent p, .apidoc #apicontent li { font-size: 15px; line-height: 22px; color: #000; font-family: Georgia, FreeSerif, Times, serif; } ol, ul, dl { margin: 0 0 1em 0; padding: 0; } ol ul, ol ol, ol dl, ul ul, ul ol, ul dl, dl ul, dl ol, dl dl { margin-bottom: 0; } ol p:first-child, ul p:first-child, dl p:first-child { margin-bottom: 0; } ul, ol { margin-left: 2em; } dl dt { position: relative; margin: 1.5em 0 0; } dl dd { position: relative; margin: 0 1em 0; } dd + dt.pre { margin-top: 1.6em; } h1, h2, h3, h4, h5, h6 { font-family: Helvetica, Arial, sans-serif; color: #000; text-rendering: optimizeLegibility; position: relative; } header h1 { font-family: Georgia, FreeSerif, Times, serif; font-size: 30px; font-weight: normal; line-height: 36px; color: #480; margin: 15px 0 11px; } h1 { font-size: 29px; line-height: 33px; margin: 2em 0 15px; } #toc + h1 { margin-top: 1em; padding-top: 0; } h2 { font-size: 1.4em; line-height: 1.0909em; margin: 1.5em 0 0.5em; } h2 + h2 { margin: 0 0 0.5em; } h3 { font-size: 1.3em; line-height: 1.1282em; margin: 2.2em 0 0.5em; } h3 + h3 { margin: 0 0 0.5em; } h2, h3, h4 { position: relative; padding-right: 40px; } h1 span, h2 span, h3 span, h4 span { font-size: 25px; position: absolute; display: block; top: 0; right: 0; opacity: 0.3; } h1 span:hover, h2 span:hover, h3 span:hover, h4 span:hover { opacity: 1; } h1 span a, h2 span a, h3 span a, h4 span a { font-size: 0.8em; color: #000; text-decoration: none; font-family: Helvetica, Arial, sans-serif; font-weight: bold; } h1 span a.top, h2 span a.top, h3 span a.top, h4 span a.top { /* XXX Get an image and clean up these two links * so that they look nice next to one another. * http://www.chrisglass.com/work/nodejs/website/v05/docs.html * -isaacs */ display: none; } h5 { font-size: 1.125em; line-height: 1.4em; } h6 { font-size: 1em; line-height: 1.4667em; } pre, tt, code { font-size: 14px; line-height: 1.5438em; font-family: Monaco, Consolas, "Lucida Console", monospace; margin: 0; padding: 0; } .pre { font-family: Monaco, Consolas, "Lucida Console", monospace; line-height: 1.5438em; font-size: 0.95em; } pre { padding: 1em 1.6em 1em 1.2em; vertical-align: top; background: #f8f8f8; border: 1px solid #e8e8e8; border-width: 1px 1px 1px 6px; margin: -0.5em 0 1.1em; overflow-x: auto; } pre + h3 { margin-top: 2.225em; } code.pre { white-space: pre; } #intro { width: 775px; margin: 0 auto; text-align: center; color: #d2d8ba; /* preload platform-icons.png */ background-image: url(http://nodejs.org/images/platform-icons.png); background-repeat: no-repeat; background-position: -999em -999em; } #intro.interior #logo { margin-left: -298px; border: 0; } hr { background: none; border: medium none; border-bottom: 1px solid #ccc; margin: 1em 0; } #toc { font-size: 15px; line-height: 1.5em; line-height: 22px; padding-top: 4px; } #toc h2 { font-size: 15px; line-height: 21px; margin: 0 0 0.5em; } #toc h2 a { float: right; } #toc hr { margin: 1em 0 2em; } #toc ul, #api-section-index #apicontent ul li, #api-section-index #apicontent ul { font-family: Georgia, FreeSerif, Times, serif; color: #666 !important; } #toc ul a { text-decoration: none; border-bottom: 1px dotted #480; } #toc ul a:hover, #toc ul a:focus { border-bottom: 1px dotted #fff; color: #000; } p tt, p code, span.type { background: #f8f8ff; border: 1px solid #dedede; padding: 0 0.2em; } #content { width: 953px; margin: 0 auto; overflow: visible; clear: both; display: block; } #column1.interior { width: 749px; float: right; padding-top: 7px; padding-top: 11px; font-size: 18px; } #column2.interior { width: 140px; float: left; margin-top: -55px; overflow: visible; } #column2.interior ul { margin-left: 0; } #column2.interior li { list-style-type: none; } #column2.interior li a { display: block; padding: 0 0 0 35px; color: #878b78; text-transform: uppercase; text-decoration: none; font-size: 11px; line-height: 23px; } #column2.interior li a.home { background: url(http://nodejs.org/images/icons-interior.png) no-repeat -156px 3px; } #column2.interior li a.download { background: url(http://nodejs.org/images/icons-interior.png) no-repeat -156px -21px; } #column2.interior li a.about { background: url(http://nodejs.org/images/icons-interior.png) no-repeat -156px -45px; } #column2.interior li a.npm { background: url(http://nodejs.org/images/icons-interior.png) no-repeat -156px -69px; } #column2.interior li a.docs { background: url(http://nodejs.org/images/icons-interior.png) no-repeat -156px -93px; } #column2.interior li a.blog { background: url(http://nodejs.org/images/icons-interior.png) no-repeat -156px -117px; } #column2.interior li a.community { background: url(http://nodejs.org/images/icons-interior.png) no-repeat -156px -141px; } #column2.interior li a.logos { background: url(http://nodejs.org/images/icons-interior.png) no-repeat -156px -165px; } #column2.interior li a.jobs { background: url(http://nodejs.org/images/icons-interior.png) no-repeat -156px -189px; } #column2.interior li a.home.current { background-position: 2px 3px; } #column2.interior li a.download.current { background-position: 2px -21px; } #column2.interior li a.about.current { background-position: 2px -45px; } #column2.interior li a.npm.current { background-position: 2px -69px; } #column2.interior li a.docs.current { background-position: 2px -93px; } #column2.interior li a.blog.current { background-position: 2px -117px; } #column2.interior li a.community.current { background-position: 2px -141px; } #column2.interior li a.logos.current { background-position: 2px -165px; } #column2.interior li a.jobs.current { background-position: 2px -189px; } #column2.interior li a.home:hover { background-position: -331px 3px; } #column2.interior li a.download:hover { background-position: -331px -21px; } #column2.interior li a.about:hover { background-position: -331px -45px; } #column2.interior li a.npm:hover { background-position: -331px -69px; } #column2.interior li a.docs:hover { background-position: -331px -93px; } #column2.interior li a.blog:hover { background-position: -331px -117px; } #column2.interior li a.community:hover { background-position: -331px -141px; } #column2.interior li a.logos:hover { background-position: -331px -165px; } #column2.interior li a.jobs:hover { background-position: -331px -189px; } #column2.interior li a.current { color: #8cc84b; font-weight: bold; } #column2.interior li a:hover { color: #000000; text-decoration: none; } #column2.interior li + li { border-top: 1px solid #c1c7ac; } #column2.interior p.twitter { padding-top: 20px; } #column2.interior p.twitter a { background: url(http://nodejs.org/images/twitter-bird.png) no-repeat 0 4px; padding-left: 37px; text-decoration: none; } #column2.interior p.twitter a:hover { text-decoration: underline; } a.totop { font-family: "Lucida Grande", "Lucida Sans Unicode", "Lucida Sans", Verdana, Tahoma, sans-serif; font-weight: bold; text-indent: -9999999px; background: url(http://nodejs.org/images/anchor.png) no-repeat top left; margin-right: 7px; display: block; width: 13px; border-bottom: 1px solid #cccccc; } a.anchor { font-family: "Lucida Grande", "Lucida Sans Unicode", "Lucida Sans", Verdana, Tahoma, sans-serif; font-weight: bold; text-indent: -9999999px; background: url(http://nodejs.org/images/anchor.png) no-repeat top right; display: block; width: 13px; border-bottom: 1px solid #cccccc; } #footer { width: 942px; margin: 150px auto 55px auto; padding: 0; } #footer .joyent-logo { display:block; position:absolute; overflow:hidden; text-indent:-999em; height:100px; width:190px; z-index:999; } #footer p { font-size: 11px; line-height: 1em; padding: 0 0 0 195px; color: #666; } #footer p, #footer li { font-family: "Lucida Grande", "Lucida Sans Unicode", "Lucida Sans", Verdana, Tahoma, sans-serif; } #footer a { text-decoration: none; border: none; color: #480; } #footer a:hover { color: #000; } #footer p a { border-bottom: 1px dotted #480; color: #878b78; } #footer ul { background: url(http://nodejs.org/images/footer-logo-alt.png) left 17px no-repeat; padding: 23px 0 0 195px; height: 26px; margin-left: -1px; border-top: 1px solid #626557; } #footer ul li { list-style-type: none; float: left; font-size: 12px; margin: 0 !important; padding: 0; height: 12px; } #footer ul li a { margin: 0; padding: 0 6px 0 0; display: block; height: 12px; line-height: 12px; } #footer ul li + li { margin-left: 3px; } #footer ul li + li a { padding: 0 6px 0 6px; border-left: 1px solid #878b78; } #footer ul li a.twitter { background: url(http://nodejs.org/images/twitter-bird.png) no-repeat 5px 0px; padding-left: 25px; } /* simpler clearfix */ .clearfix:after { content: "."; display: block; height: 0; clear: both; visibility: hidden; } node-v0.10.25~dfsg2/doc/api/events.html0000644000000000000000000002526712270264601016340 0ustar rootroot Events Node.js v0.10.25 Manual & Documentation

    Node.js v0.10.25 Manual & Documentation


    Events#

    Stability: 4 - API Frozen

    Many objects in Node emit events: a net.Server emits an event each time a peer connects to it, a fs.readStream emits an event when the file is opened. All objects which emit events are instances of events.EventEmitter. You can access this module by doing: require("events");

    Typically, event names are represented by a camel-cased string, however, there aren't any strict restrictions on that, as any string will be accepted.

    Functions can then be attached to objects, to be executed when an event is emitted. These functions are called listeners. Inside a listener function, this refers to the EventEmitter that the listener was attached to.

    Class: events.EventEmitter#

    To access the EventEmitter class, require('events').EventEmitter.

    When an EventEmitter instance experiences an error, the typical action is to emit an 'error' event. Error events are treated as a special case in node. If there is no listener for it, then the default action is to print a stack trace and exit the program.

    All EventEmitters emit the event 'newListener' when new listeners are added and 'removeListener' when a listener is removed.

    emitter.addListener(event, listener)#

    emitter.on(event, listener)#

    Adds a listener to the end of the listeners array for the specified event.

    server.on('connection', function (stream) {
      console.log('someone connected!');
    });

    Returns emitter, so calls can be chained.

    emitter.once(event, listener)#

    Adds a one time listener for the event. This listener is invoked only the next time the event is fired, after which it is removed.

    server.once('connection', function (stream) {
      console.log('Ah, we have our first user!');
    });

    Returns emitter, so calls can be chained.

    emitter.removeListener(event, listener)#

    Remove a listener from the listener array for the specified event. Caution: changes array indices in the listener array behind the listener.

    var callback = function(stream) {
      console.log('someone connected!');
    };
    server.on('connection', callback);
    // ...
    server.removeListener('connection', callback);

    Returns emitter, so calls can be chained.

    emitter.removeAllListeners([event])#

    Removes all listeners, or those of the specified event.

    Returns emitter, so calls can be chained.

    emitter.setMaxListeners(n)#

    By default EventEmitters will print a warning if more than 10 listeners are added for a particular event. This is a useful default which helps finding memory leaks. Obviously not all Emitters should be limited to 10. This function allows that to be increased. Set to zero for unlimited.

    emitter.listeners(event)#

    Returns an array of listeners for the specified event.

    server.on('connection', function (stream) {
      console.log('someone connected!');
    });
    console.log(util.inspect(server.listeners('connection'))); // [ [Function] ]

    emitter.emit(event, [arg1], [arg2], [...])#

    Execute each of the listeners in order with the supplied arguments.

    Returns true if event had listeners, false otherwise.

    Class Method: EventEmitter.listenerCount(emitter, event)#

    Return the number of listeners for a given event.

    Event: 'newListener'#

    • event String The event name
    • listener Function The event handler function

    This event is emitted any time someone adds a new listener. It is unspecified if listener is in the list returned by emitter.listeners(event).

    Event: 'removeListener'#

    • event String The event name
    • listener Function The event handler function

    This event is emitted any time someone removes a listener. It is unspecified if listener is in the list returned by emitter.listeners(event).

    node-v0.10.25~dfsg2/doc/api/timers.json0000644000000000000000000001430012270264601016326 0ustar rootroot{ "source": "doc/api/timers.markdown", "modules": [ { "textRaw": "Timers", "name": "timers", "stability": 5, "stabilityText": "Locked", "desc": "

    All of the timer functions are globals. You do not need to require()\nthis module in order to use them.\n\n

    \n", "methods": [ { "textRaw": "setTimeout(callback, delay, [arg], [...])", "type": "method", "name": "setTimeout", "desc": "

    To schedule execution of a one-time callback after delay milliseconds. Returns a\ntimeoutId for possible use with clearTimeout(). Optionally you can\nalso pass arguments to the callback.\n\n

    \n

    It is important to note that your callback will probably not be called in exactly\ndelay milliseconds - Node.js makes no guarantees about the exact timing of when\nthe callback will fire, nor of the ordering things will fire in. The callback will\nbe called as close as possible to the time specified.\n\n

    \n", "signatures": [ { "params": [ { "name": "callback" }, { "name": "delay" }, { "name": "arg", "optional": true }, { "name": "...", "optional": true } ] } ] }, { "textRaw": "clearTimeout(timeoutId)", "type": "method", "name": "clearTimeout", "desc": "

    Prevents a timeout from triggering.\n\n

    \n", "signatures": [ { "params": [ { "name": "timeoutId" } ] } ] }, { "textRaw": "setInterval(callback, delay, [arg], [...])", "type": "method", "name": "setInterval", "desc": "

    To schedule the repeated execution of callback every delay milliseconds.\nReturns a intervalId for possible use with clearInterval(). Optionally\nyou can also pass arguments to the callback.\n\n

    \n", "signatures": [ { "params": [ { "name": "callback" }, { "name": "delay" }, { "name": "arg", "optional": true }, { "name": "...", "optional": true } ] } ] }, { "textRaw": "clearInterval(intervalId)", "type": "method", "name": "clearInterval", "desc": "

    Stops a interval from triggering.\n\n

    \n", "signatures": [ { "params": [ { "name": "intervalId" } ] } ] }, { "textRaw": "unref()", "type": "method", "name": "unref", "desc": "

    The opaque value returned by setTimeout and setInterval also has the method\ntimer.unref() which will allow you to create a timer that is active but if\nit is the only item left in the event loop won't keep the program running.\nIf the timer is already unrefd calling unref again will have no effect.\n\n

    \n

    In the case of setTimeout when you unref you create a separate timer that\nwill wakeup the event loop, creating too many of these may adversely effect\nevent loop performance -- use wisely.\n\n

    \n", "signatures": [ { "params": [] } ] }, { "textRaw": "ref()", "type": "method", "name": "ref", "desc": "

    If you had previously unref()d a timer you can call ref() to explicitly\nrequest the timer hold the program open. If the timer is already refd calling\nref again will have no effect.\n\n

    \n", "signatures": [ { "params": [] } ] }, { "textRaw": "setImmediate(callback, [arg], [...])", "type": "method", "name": "setImmediate", "desc": "

    To schedule the "immediate" execution of callback after I/O events\ncallbacks and before setTimeout and setInterval . Returns an\nimmediateId for possible use with clearImmediate(). Optionally you\ncan also pass arguments to the callback.\n\n

    \n

    Immediates are queued in the order created, and are popped off the queue once\nper loop iteration. This is different from process.nextTick which will\nexecute process.maxTickDepth queued callbacks per iteration. setImmediate\nwill yield to the event loop after firing a queued callback to make sure I/O is\nnot being starved. While order is preserved for execution, other I/O events may\nfire between any two scheduled immediate callbacks.\n\n

    \n", "signatures": [ { "params": [ { "name": "callback" }, { "name": "arg", "optional": true }, { "name": "...", "optional": true } ] } ] }, { "textRaw": "clearImmediate(immediateId)", "type": "method", "name": "clearImmediate", "desc": "

    Stops an immediate from triggering.\n

    \n", "signatures": [ { "params": [ { "name": "immediateId" } ] } ] } ], "type": "module", "displayName": "Timers" } ] } node-v0.10.25~dfsg2/doc/api/globals.html0000644000000000000000000002751012270264601016450 0ustar rootroot Global Objects Node.js v0.10.25 Manual & Documentation

    Node.js v0.10.25 Manual & Documentation


    Global Objects#

    These objects are available in all modules. Some of these objects aren't actually in the global scope but in the module scope - this will be noted.

    global#

    • {Object} The global namespace object.

    In browsers, the top-level scope is the global scope. That means that in browsers if you're in the global scope var something will define a global variable. In Node this is different. The top-level scope is not the global scope; var something inside a Node module will be local to that module.

    process#

    • {Object}

    The process object. See the process object section.

    console#

    • {Object}

    Used to print to stdout and stderr. See the console section.

    Class: Buffer#

    • {Function}

    Used to handle binary data. See the buffer section

    require()#

    • {Function}

    To require modules. See the Modules section. require isn't actually a global but rather local to each module.

    require.resolve()#

    Use the internal require() machinery to look up the location of a module, but rather than loading the module, just return the resolved filename.

    require.cache#

    • Object

    Modules are cached in this object when they are required. By deleting a key value from this object, the next require will reload the module.

    require.extensions#

    Stability: 0 - Deprecated
    • Object

    Instruct require on how to handle certain file extensions.

    Process files with the extension .sjs as .js:

    require.extensions['.sjs'] = require.extensions['.js'];

    Deprecated In the past, this list has been used to load non-JavaScript modules into Node by compiling them on-demand. However, in practice, there are much better ways to do this, such as loading modules via some other Node program, or compiling them to JavaScript ahead of time.

    Since the Module system is locked, this feature will probably never go away. However, it may have subtle bugs and complexities that are best left untouched.

    __filename#

    • {String}

    The filename of the code being executed. This is the resolved absolute path of this code file. For a main program this is not necessarily the same filename used in the command line. The value inside a module is the path to that module file.

    Example: running node example.js from /Users/mjr

    console.log(__filename);
    // /Users/mjr/example.js

    __filename isn't actually a global but rather local to each module.

    __dirname#

    • {String}

    The name of the directory that the currently executing script resides in.

    Example: running node example.js from /Users/mjr

    console.log(__dirname);
    // /Users/mjr

    __dirname isn't actually a global but rather local to each module.

    module#

    • {Object}

    A reference to the current module. In particular module.exports is used for defining what a module exports and makes available through require().

    module isn't actually a global but rather local to each module.

    See the module system documentation for more information.

    exports#

    A reference to the module.exports that is shorter to type. See module system documentation for details on when to use exports and when to use module.exports.

    exports isn't actually a global but rather local to each module.

    See the module system documentation for more information.

    See the module section for more information.

    setTimeout(cb, ms)#

    Run callback cb after at least ms milliseconds. The actual delay depends on external factors like OS timer granularity and system load.

    The timeout must be in the range of 1-2,147,483,647 inclusive. If the value is outside that range, it's changed to 1 millisecond. Broadly speaking, a timer cannot span more than 24.8 days.

    Returns an opaque value that represents the timer.

    clearTimeout(t)#

    Stop a timer that was previously created with setTimeout(). The callback will not execute.

    setInterval(cb, ms)#

    Run callback cb repeatedly every ms milliseconds. Note that the actual interval may vary, depending on external factors like OS timer granularity and system load. It's never less than ms but it may be longer.

    The interval must be in the range of 1-2,147,483,647 inclusive. If the value is outside that range, it's changed to 1 millisecond. Broadly speaking, a timer cannot span more than 24.8 days.

    Returns an opaque value that represents the timer.

    clearInterval(t)#

    Stop a timer that was previously created with setInterval(). The callback will not execute.

    The timer functions are global variables. See the timers section.

    node-v0.10.25~dfsg2/doc/api/crypto.html0000644000000000000000000011206312270264601016343 0ustar rootroot Crypto Node.js v0.10.25 Manual & Documentation

    Node.js v0.10.25 Manual & Documentation


    Table of Contents

    Crypto#

    Stability: 2 - Unstable; API changes are being discussed for
    future versions.  Breaking changes will be minimized.  See below.

    Use require('crypto') to access this module.

    The crypto module offers a way of encapsulating secure credentials to be used as part of a secure HTTPS net or http connection.

    It also offers a set of wrappers for OpenSSL's hash, hmac, cipher, decipher, sign and verify methods.

    crypto.getCiphers()#

    Returns an array with the names of the supported ciphers.

    Example:

    var ciphers = crypto.getCiphers();
    console.log(ciphers); // ['AES-128-CBC', 'AES-128-CBC-HMAC-SHA1', ...]

    crypto.getHashes()#

    Returns an array with the names of the supported hash algorithms.

    Example:

    var hashes = crypto.getHashes();
    console.log(hashes); // ['sha', 'sha1', 'sha1WithRSAEncryption', ...]

    crypto.createCredentials(details)#

    Creates a credentials object, with the optional details being a dictionary with keys:

    • pfx : A string or buffer holding the PFX or PKCS12 encoded private key, certificate and CA certificates
    • key : A string holding the PEM encoded private key
    • passphrase : A string of passphrase for the private key or pfx
    • cert : A string holding the PEM encoded certificate
    • ca : Either a string or list of strings of PEM encoded CA certificates to trust.
    • crl : Either a string or list of strings of PEM encoded CRLs (Certificate Revocation List)
    • ciphers: A string describing the ciphers to use or exclude. Consult http://www.openssl.org/docs/apps/ciphers.html#CIPHER_LIST_FORMAT for details on the format.

    If no 'ca' details are given, then node.js will use the default publicly trusted list of CAs as given in

    http://mxr.mozilla.org/mozilla/source/security/nss/lib/ckfw/builtins/certdata.txt.

    crypto.createHash(algorithm)#

    Creates and returns a hash object, a cryptographic hash with the given algorithm which can be used to generate hash digests.

    algorithm is dependent on the available algorithms supported by the version of OpenSSL on the platform. Examples are 'sha1', 'md5', 'sha256', 'sha512', etc. On recent releases, openssl list-message-digest-algorithms will display the available digest algorithms.

    Example: this program that takes the sha1 sum of a file

    var filename = process.argv[2];
    var crypto = require('crypto');
    var fs = require('fs');
    
    var shasum = crypto.createHash('sha1');
    
    var s = fs.ReadStream(filename);
    s.on('data', function(d) {
      shasum.update(d);
    });
    
    s.on('end', function() {
      var d = shasum.digest('hex');
      console.log(d + '  ' + filename);
    });

    Class: Hash#

    The class for creating hash digests of data.

    It is a stream that is both readable and writable. The written data is used to compute the hash. Once the writable side of the stream is ended, use the read() method to get the computed hash digest. The legacy update and digest methods are also supported.

    Returned by crypto.createHash.

    hash.update(data, [input_encoding])#

    Updates the hash content with the given data, the encoding of which is given in input_encoding and can be 'utf8', 'ascii' or 'binary'. If no encoding is provided and the input is a string an encoding of 'binary' is enforced. If data is a Buffer then input_encoding is ignored.

    This can be called many times with new data as it is streamed.

    hash.digest([encoding])#

    Calculates the digest of all of the passed data to be hashed. The encoding can be 'hex', 'binary' or 'base64'. If no encoding is provided, then a buffer is returned.

    Note: hash object can not be used after digest() method has been called.

    crypto.createHmac(algorithm, key)#

    Creates and returns a hmac object, a cryptographic hmac with the given algorithm and key.

    It is a stream that is both readable and writable. The written data is used to compute the hmac. Once the writable side of the stream is ended, use the read() method to get the computed digest. The legacy update and digest methods are also supported.

    algorithm is dependent on the available algorithms supported by OpenSSL - see createHash above. key is the hmac key to be used.

    Class: Hmac#

    Class for creating cryptographic hmac content.

    Returned by crypto.createHmac.

    hmac.update(data)#

    Update the hmac content with the given data. This can be called many times with new data as it is streamed.

    hmac.digest([encoding])#

    Calculates the digest of all of the passed data to the hmac. The encoding can be 'hex', 'binary' or 'base64'. If no encoding is provided, then a buffer is returned.

    Note: hmac object can not be used after digest() method has been called.

    crypto.createCipher(algorithm, password)#

    Creates and returns a cipher object, with the given algorithm and password.

    algorithm is dependent on OpenSSL, examples are 'aes192', etc. On recent releases, openssl list-cipher-algorithms will display the available cipher algorithms. password is used to derive key and IV, which must be a 'binary' encoded string or a buffer.

    It is a stream that is both readable and writable. The written data is used to compute the hash. Once the writable side of the stream is ended, use the read() method to get the computed hash digest. The legacy update and digest methods are also supported.

    crypto.createCipheriv(algorithm, key, iv)#

    Creates and returns a cipher object, with the given algorithm, key and iv.

    algorithm is the same as the argument to createCipher(). key is the raw key used by the algorithm. iv is an initialization vector.

    key and iv must be 'binary' encoded strings or buffers.

    Class: Cipher#

    Class for encrypting data.

    Returned by crypto.createCipher and crypto.createCipheriv.

    Cipher objects are streams that are both readable and writable. The written plain text data is used to produce the encrypted data on the readable side. The legacy update and final methods are also supported.

    cipher.update(data, [input_encoding], [output_encoding])#

    Updates the cipher with data, the encoding of which is given in input_encoding and can be 'utf8', 'ascii' or 'binary'. If no encoding is provided, then a buffer is expected. If data is a Buffer then input_encoding is ignored.

    The output_encoding specifies the output format of the enciphered data, and can be 'binary', 'base64' or 'hex'. If no encoding is provided, then a buffer is returned.

    Returns the enciphered contents, and can be called many times with new data as it is streamed.

    cipher.final([output_encoding])#

    Returns any remaining enciphered contents, with output_encoding being one of: 'binary', 'base64' or 'hex'. If no encoding is provided, then a buffer is returned.

    Note: cipher object can not be used after final() method has been called.

    cipher.setAutoPadding(auto_padding=true)#

    You can disable automatic padding of the input data to block size. If auto_padding is false, the length of the entire input data must be a multiple of the cipher's block size or final will fail. Useful for non-standard padding, e.g. using 0x0 instead of PKCS padding. You must call this before cipher.final.

    crypto.createDecipher(algorithm, password)#

    Creates and returns a decipher object, with the given algorithm and key. This is the mirror of the createCipher() above.

    crypto.createDecipheriv(algorithm, key, iv)#

    Creates and returns a decipher object, with the given algorithm, key and iv. This is the mirror of the createCipheriv() above.

    Class: Decipher#

    Class for decrypting data.

    Returned by crypto.createDecipher and crypto.createDecipheriv.

    Decipher objects are streams that are both readable and writable. The written enciphered data is used to produce the plain-text data on the the readable side. The legacy update and final methods are also supported.

    decipher.update(data, [input_encoding], [output_encoding])#

    Updates the decipher with data, which is encoded in 'binary', 'base64' or 'hex'. If no encoding is provided, then a buffer is expected. If data is a Buffer then input_encoding is ignored.

    The output_decoding specifies in what format to return the deciphered plaintext: 'binary', 'ascii' or 'utf8'. If no encoding is provided, then a buffer is returned.

    decipher.final([output_encoding])#

    Returns any remaining plaintext which is deciphered, with output_encoding being one of: 'binary', 'ascii' or 'utf8'. If no encoding is provided, then a buffer is returned.

    Note: decipher object can not be used after final() method has been called.

    decipher.setAutoPadding(auto_padding=true)#

    You can disable auto padding if the data has been encrypted without standard block padding to prevent decipher.final from checking and removing it. Can only work if the input data's length is a multiple of the ciphers block size. You must call this before streaming data to decipher.update.

    crypto.createSign(algorithm)#

    Creates and returns a signing object, with the given algorithm. On recent OpenSSL releases, openssl list-public-key-algorithms will display the available signing algorithms. Examples are 'RSA-SHA256'.

    Class: Sign#

    Class for generating signatures.

    Returned by crypto.createSign.

    Sign objects are writable streams. The written data is used to generate the signature. Once all of the data has been written, the sign method will return the signature. The legacy update method is also supported.

    sign.update(data)#

    Updates the sign object with data. This can be called many times with new data as it is streamed.

    sign.sign(private_key, [output_format])#

    Calculates the signature on all the updated data passed through the sign. private_key is a string containing the PEM encoded private key for signing.

    Returns the signature in output_format which can be 'binary', 'hex' or 'base64'. If no encoding is provided, then a buffer is returned.

    Note: sign object can not be used after sign() method has been called.

    crypto.createVerify(algorithm)#

    Creates and returns a verification object, with the given algorithm. This is the mirror of the signing object above.

    Class: Verify#

    Class for verifying signatures.

    Returned by crypto.createVerify.

    Verify objects are writable streams. The written data is used to validate against the supplied signature. Once all of the data has been written, the verify method will return true if the supplied signature is valid. The legacy update method is also supported.

    verifier.update(data)#

    Updates the verifier object with data. This can be called many times with new data as it is streamed.

    verifier.verify(object, signature, [signature_format])#

    Verifies the signed data by using the object and signature. object is a string containing a PEM encoded object, which can be one of RSA public key, DSA public key, or X.509 certificate. signature is the previously calculated signature for the data, in the signature_format which can be 'binary', 'hex' or 'base64'. If no encoding is specified, then a buffer is expected.

    Returns true or false depending on the validity of the signature for the data and public key.

    Note: verifier object can not be used after verify() method has been called.

    crypto.createDiffieHellman(prime_length)#

    Creates a Diffie-Hellman key exchange object and generates a prime of the given bit length. The generator used is 2.

    crypto.createDiffieHellman(prime, [encoding])#

    Creates a Diffie-Hellman key exchange object using the supplied prime. The generator used is 2. Encoding can be 'binary', 'hex', or 'base64'. If no encoding is specified, then a buffer is expected.

    Class: DiffieHellman#

    The class for creating Diffie-Hellman key exchanges.

    Returned by crypto.createDiffieHellman.

    diffieHellman.generateKeys([encoding])#

    Generates private and public Diffie-Hellman key values, and returns the public key in the specified encoding. This key should be transferred to the other party. Encoding can be 'binary', 'hex', or 'base64'. If no encoding is provided, then a buffer is returned.

    diffieHellman.computeSecret(other_public_key, [input_encoding], [output_encoding])#

    Computes the shared secret using other_public_key as the other party's public key and returns the computed shared secret. Supplied key is interpreted using specified input_encoding, and secret is encoded using specified output_encoding. Encodings can be 'binary', 'hex', or 'base64'. If the input encoding is not provided, then a buffer is expected.

    If no output encoding is given, then a buffer is returned.

    diffieHellman.getPrime([encoding])#

    Returns the Diffie-Hellman prime in the specified encoding, which can be 'binary', 'hex', or 'base64'. If no encoding is provided, then a buffer is returned.

    diffieHellman.getGenerator([encoding])#

    Returns the Diffie-Hellman prime in the specified encoding, which can be 'binary', 'hex', or 'base64'. If no encoding is provided, then a buffer is returned.

    diffieHellman.getPublicKey([encoding])#

    Returns the Diffie-Hellman public key in the specified encoding, which can be 'binary', 'hex', or 'base64'. If no encoding is provided, then a buffer is returned.

    diffieHellman.getPrivateKey([encoding])#

    Returns the Diffie-Hellman private key in the specified encoding, which can be 'binary', 'hex', or 'base64'. If no encoding is provided, then a buffer is returned.

    diffieHellman.setPublicKey(public_key, [encoding])#

    Sets the Diffie-Hellman public key. Key encoding can be 'binary', 'hex' or 'base64'. If no encoding is provided, then a buffer is expected.

    diffieHellman.setPrivateKey(private_key, [encoding])#

    Sets the Diffie-Hellman private key. Key encoding can be 'binary', 'hex' or 'base64'. If no encoding is provided, then a buffer is expected.

    crypto.getDiffieHellman(group_name)#

    Creates a predefined Diffie-Hellman key exchange object. The supported groups are: 'modp1', 'modp2', 'modp5' (defined in RFC 2412) and 'modp14', 'modp15', 'modp16', 'modp17', 'modp18' (defined in RFC 3526). The returned object mimics the interface of objects created by crypto.createDiffieHellman() above, but will not allow to change the keys (with diffieHellman.setPublicKey() for example). The advantage of using this routine is that the parties don't have to generate nor exchange group modulus beforehand, saving both processor and communication time.

    Example (obtaining a shared secret):

    var crypto = require('crypto');
    var alice = crypto.getDiffieHellman('modp5');
    var bob = crypto.getDiffieHellman('modp5');
    
    alice.generateKeys();
    bob.generateKeys();
    
    var alice_secret = alice.computeSecret(bob.getPublicKey(), null, 'hex');
    var bob_secret = bob.computeSecret(alice.getPublicKey(), null, 'hex');
    
    /* alice_secret and bob_secret should be the same */
    console.log(alice_secret == bob_secret);

    crypto.pbkdf2(password, salt, iterations, keylen, callback)#

    Asynchronous PBKDF2 applies pseudorandom function HMAC-SHA1 to derive a key of given length from the given password, salt and iterations. The callback gets two arguments (err, derivedKey).

    crypto.pbkdf2Sync(password, salt, iterations, keylen)#

    Synchronous PBKDF2 function. Returns derivedKey or throws error.

    crypto.randomBytes(size, [callback])#

    Generates cryptographically strong pseudo-random data. Usage:

    // async
    crypto.randomBytes(256, function(ex, buf) {
      if (ex) throw ex;
      console.log('Have %d bytes of random data: %s', buf.length, buf);
    });
    
    // sync
    try {
      var buf = crypto.randomBytes(256);
      console.log('Have %d bytes of random data: %s', buf.length, buf);
    } catch (ex) {
      // handle error
      // most likely, entropy sources are drained
    }

    NOTE: Will throw error or invoke callback with error, if there is not enough accumulated entropy to generate cryptographically strong data. In other words, crypto.randomBytes without callback will not block even if all entropy sources are drained.

    crypto.pseudoRandomBytes(size, [callback])#

    Generates non-cryptographically strong pseudo-random data. The data returned will be unique if it is sufficiently long, but is not necessarily unpredictable. For this reason, the output of this function should never be used where unpredictability is important, such as in the generation of encryption keys.

    Usage is otherwise identical to crypto.randomBytes.

    crypto.DEFAULT_ENCODING#

    The default encoding to use for functions that can take either strings or buffers. The default value is 'buffer', which makes it default to using Buffer objects. This is here to make the crypto module more easily compatible with legacy programs that expected 'binary' to be the default encoding.

    Note that new programs will probably expect buffers, so only use this as a temporary measure.

    Recent API Changes#

    The Crypto module was added to Node before there was the concept of a unified Stream API, and before there were Buffer objects for handling binary data.

    As such, the streaming classes don't have the typical methods found on other Node classes, and many methods accepted and returned Binary-encoded strings by default rather than Buffers. This was changed to use Buffers by default instead.

    This is a breaking change for some use cases, but not all.

    For example, if you currently use the default arguments to the Sign class, and then pass the results to the Verify class, without ever inspecting the data, then it will continue to work as before. Where you once got a binary string and then presented the binary string to the Verify object, you'll now get a Buffer, and present the Buffer to the Verify object.

    However, if you were doing things with the string data that will not work properly on Buffers (such as, concatenating them, storing in databases, etc.), or you are passing binary strings to the crypto functions without an encoding argument, then you will need to start providing encoding arguments to specify which encoding you'd like to use. To switch to the previous style of using binary strings by default, set the crypto.DEFAULT_ENCODING field to 'binary'. Note that new programs will probably expect buffers, so only use this as a temporary measure.

    node-v0.10.25~dfsg2/doc/api/console.json0000644000000000000000000001301412270264601016466 0ustar rootroot{ "source": "doc/api/console.markdown", "globals": [ { "textRaw": "console", "name": "console", "stability": 4, "stabilityText": "API Frozen", "type": "global", "desc": "

    For printing to stdout and stderr. Similar to the console object functions\nprovided by most web browsers, here the output is sent to stdout or stderr.\n\n

    \n

    The console functions are synchronous when the destination is a terminal or\na file (to avoid lost messages in case of premature exit) and asynchronous\nwhen it's a pipe (to avoid blocking for long periods of time).\n\n

    \n

    That is, in the following example, stdout is non-blocking while stderr\nis blocking:\n\n

    \n
    $ node script.js 2> error.log | tee info.log
    \n

    In daily use, the blocking/non-blocking dichotomy is not something you\nshould worry about unless you log huge amounts of data.\n\n\n

    \n", "methods": [ { "textRaw": "console.log([data], [...])", "type": "method", "name": "log", "desc": "

    Prints to stdout with newline. This function can take multiple arguments in a\nprintf()-like way. Example:\n\n

    \n
    console.log('count: %d', count);
    \n

    If formatting elements are not found in the first string then util.inspect\nis used on each argument. See [util.format()][] for more information.\n\n

    \n", "signatures": [ { "params": [ { "name": "data", "optional": true }, { "name": "...", "optional": true } ] } ] }, { "textRaw": "console.info([data], [...])", "type": "method", "name": "info", "desc": "

    Same as console.log.\n\n

    \n", "signatures": [ { "params": [ { "name": "data", "optional": true }, { "name": "...", "optional": true } ] } ] }, { "textRaw": "console.error([data], [...])", "type": "method", "name": "error", "desc": "

    Same as console.log but prints to stderr.\n\n

    \n", "signatures": [ { "params": [ { "name": "data", "optional": true }, { "name": "...", "optional": true } ] } ] }, { "textRaw": "console.warn([data], [...])", "type": "method", "name": "warn", "desc": "

    Same as console.error.\n\n

    \n", "signatures": [ { "params": [ { "name": "data", "optional": true }, { "name": "...", "optional": true } ] } ] }, { "textRaw": "console.dir(obj)", "type": "method", "name": "dir", "desc": "

    Uses util.inspect on obj and prints resulting string to stdout.\n\n

    \n", "signatures": [ { "params": [ { "name": "obj" } ] } ] }, { "textRaw": "console.time(label)", "type": "method", "name": "time", "desc": "

    Mark a time.\n\n

    \n", "signatures": [ { "params": [ { "name": "label" } ] } ] }, { "textRaw": "console.timeEnd(label)", "type": "method", "name": "timeEnd", "desc": "

    Finish timer, record output. Example:\n\n

    \n
    console.time('100-elements');\nfor (var i = 0; i < 100; i++) {\n  ;\n}\nconsole.timeEnd('100-elements');
    \n", "signatures": [ { "params": [ { "name": "label" } ] } ] }, { "textRaw": "console.trace(label)", "type": "method", "name": "trace", "desc": "

    Print a stack trace to stderr of the current position.\n\n

    \n", "signatures": [ { "params": [ { "name": "label" } ] } ] }, { "textRaw": "console.assert(expression, [message])", "type": "method", "name": "assert", "desc": "

    Same as [assert.ok()][] where if the expression evaluates as false throw an\nAssertionError with message.\n\n

    \n", "signatures": [ { "params": [ { "name": "expression" }, { "name": "message", "optional": true } ] } ] } ] } ] } node-v0.10.25~dfsg2/doc/api/os.markdown0000644000000000000000000001002312270121457016314 0ustar rootroot# os Stability: 4 - API Frozen Provides a few basic operating-system related utility functions. Use `require('os')` to access this module. ## os.tmpdir() Returns the operating system's default directory for temp files. ## os.endianness() Returns the endianness of the CPU. Possible values are `"BE"` or `"LE"`. ## os.hostname() Returns the hostname of the operating system. ## os.type() Returns the operating system name. ## os.platform() Returns the operating system platform. ## os.arch() Returns the operating system CPU architecture. ## os.release() Returns the operating system release. ## os.uptime() Returns the system uptime in seconds. ## os.loadavg() Returns an array containing the 1, 5, and 15 minute load averages. The load average is a measure of system activity, calculated by the operating system and expressed as a fractional number. As a rule of thumb, the load average should ideally be less than the number of logical CPUs in the system. The load average is a very UNIX-y concept; there is no real equivalent on Windows platforms. That is why this function always returns `[0, 0, 0]` on Windows. ## os.totalmem() Returns the total amount of system memory in bytes. ## os.freemem() Returns the amount of free system memory in bytes. ## os.cpus() Returns an array of objects containing information about each CPU/core installed: model, speed (in MHz), and times (an object containing the number of milliseconds the CPU/core spent in: user, nice, sys, idle, and irq). Example inspection of os.cpus: [ { model: 'Intel(R) Core(TM) i7 CPU 860 @ 2.80GHz', speed: 2926, times: { user: 252020, nice: 0, sys: 30340, idle: 1070356870, irq: 0 } }, { model: 'Intel(R) Core(TM) i7 CPU 860 @ 2.80GHz', speed: 2926, times: { user: 306960, nice: 0, sys: 26980, idle: 1071569080, irq: 0 } }, { model: 'Intel(R) Core(TM) i7 CPU 860 @ 2.80GHz', speed: 2926, times: { user: 248450, nice: 0, sys: 21750, idle: 1070919370, irq: 0 } }, { model: 'Intel(R) Core(TM) i7 CPU 860 @ 2.80GHz', speed: 2926, times: { user: 256880, nice: 0, sys: 19430, idle: 1070905480, irq: 20 } }, { model: 'Intel(R) Core(TM) i7 CPU 860 @ 2.80GHz', speed: 2926, times: { user: 511580, nice: 20, sys: 40900, idle: 1070842510, irq: 0 } }, { model: 'Intel(R) Core(TM) i7 CPU 860 @ 2.80GHz', speed: 2926, times: { user: 291660, nice: 0, sys: 34360, idle: 1070888000, irq: 10 } }, { model: 'Intel(R) Core(TM) i7 CPU 860 @ 2.80GHz', speed: 2926, times: { user: 308260, nice: 0, sys: 55410, idle: 1071129970, irq: 880 } }, { model: 'Intel(R) Core(TM) i7 CPU 860 @ 2.80GHz', speed: 2926, times: { user: 266450, nice: 1480, sys: 34920, idle: 1072572010, irq: 30 } } ] ## os.networkInterfaces() Get a list of network interfaces: { lo0: [ { address: '::1', family: 'IPv6', internal: true }, { address: 'fe80::1', family: 'IPv6', internal: true }, { address: '127.0.0.1', family: 'IPv4', internal: true } ], en1: [ { address: 'fe80::cabc:c8ff:feef:f996', family: 'IPv6', internal: false }, { address: '10.0.1.123', family: 'IPv4', internal: false } ], vmnet1: [ { address: '10.99.99.254', family: 'IPv4', internal: false } ], vmnet8: [ { address: '10.88.88.1', family: 'IPv4', internal: false } ], ppp0: [ { address: '10.2.0.231', family: 'IPv4', internal: false } ] } ## os.EOL A constant defining the appropriate End-of-line marker for the operating system. node-v0.10.25~dfsg2/doc/api/synopsis.markdown0000644000000000000000000000116312270121457017567 0ustar rootroot# Synopsis An example of a [web server](http.html) written with Node which responds with 'Hello World': var http = require('http'); http.createServer(function (request, response) { response.writeHead(200, {'Content-Type': 'text/plain'}); response.end('Hello World\n'); }).listen(8124); console.log('Server running at http://127.0.0.1:8124/'); To run the server, put the code into a file called `example.js` and execute it with the node program > node example.js Server running at http://127.0.0.1:8124/ All of the examples in the documentation can be run similarly. node-v0.10.25~dfsg2/doc/api/stream.json0000644000000000000000000035501612270264601016332 0ustar rootroot{ "source": "doc/api/stream.markdown", "modules": [ { "textRaw": "Stream", "name": "stream", "stability": 2, "stabilityText": "Unstable", "desc": "

    A stream is an abstract interface implemented by various objects in\nNode. For example a request to an HTTP\nserver is a stream, as is\n[stdout][]. Streams are readable, writable, or both. All streams are\ninstances of [EventEmitter][]\n\n

    \n

    You can load the Stream base classes by doing require('stream').\nThere are base classes provided for [Readable][] streams, [Writable][]\nstreams, [Duplex][] streams, and [Transform][] streams.\n\n

    \n

    This document is split up into 3 sections. The first explains the\nparts of the API that you need to be aware of to use streams in your\nprograms. If you never implement a streaming API yourself, you can\nstop there.\n\n

    \n

    The second section explains the parts of the API that you need to use\nif you implement your own custom streams yourself. The API is\ndesigned to make this easy for you to do.\n\n

    \n

    The third section goes into more depth about how streams work,\nincluding some of the internal mechanisms and functions that you\nshould probably not modify unless you definitely know what you are\ndoing.\n\n\n

    \n", "classes": [ { "textRaw": "Class: stream.Readable", "type": "class", "name": "stream.Readable", "desc": "

    The Readable stream interface is the abstraction for a source of\ndata that you are reading from. In other words, data comes out of a\nReadable stream.\n\n

    \n

    A Readable stream will not start emitting data until you indicate that\nyou are ready to receive it.\n\n

    \n

    Readable streams have two "modes": a flowing mode and a non-flowing\nmode. When in flowing mode, data is read from the underlying system\nand provided to your program as fast as possible. In non-flowing\nmode, you must explicitly call stream.read() to get chunks of data\nout.\n\n

    \n

    Examples of readable streams include:\n\n

    \n\n", "events": [ { "textRaw": "Event: 'readable'", "type": "event", "name": "readable", "desc": "

    When a chunk of data can be read from the stream, it will emit a\n'readable' event.\n\n

    \n

    In some cases, listening for a 'readable' event will cause some data\nto be read into the internal buffer from the underlying system, if it\nhadn't already.\n\n

    \n
    var readable = getReadableStreamSomehow();\nreadable.on('readable', function() {\n  // there is some data to read now\n})
    \n

    Once the internal buffer is drained, a readable event will fire\nagain when more data is available.\n\n

    \n", "params": [] }, { "textRaw": "Event: 'data'", "type": "event", "name": "data", "params": [], "desc": "

    If you attach a data event listener, then it will switch the stream\ninto flowing mode, and data will be passed to your handler as soon as\nit is available.\n\n

    \n

    If you just want to get all the data out of the stream as fast as\npossible, this is the best way to do so.\n\n

    \n
    var readable = getReadableStreamSomehow();\nreadable.on('data', function(chunk) {\n  console.log('got %d bytes of data', chunk.length);\n})
    \n" }, { "textRaw": "Event: 'end'", "type": "event", "name": "end", "desc": "

    This event fires when no more data will be provided.\n\n

    \n

    Note that the end event will not fire unless the data is\ncompletely consumed. This can be done by switching into flowing mode,\nor by calling read() repeatedly until you get to the end.\n\n

    \n
    var readable = getReadableStreamSomehow();\nreadable.on('data', function(chunk) {\n  console.log('got %d bytes of data', chunk.length);\n})\nreadable.on('end', function() {\n  console.log('there will be no more data.');\n});
    \n", "params": [] }, { "textRaw": "Event: 'close'", "type": "event", "name": "close", "desc": "

    Emitted when the underlying resource (for example, the backing file\ndescriptor) has been closed. Not all streams will emit this.\n\n

    \n", "params": [] }, { "textRaw": "Event: 'error'", "type": "event", "name": "error", "desc": "

    Emitted if there was an error receiving data.\n\n

    \n", "params": [] } ], "methods": [ { "textRaw": "readable.read([size])", "type": "method", "name": "read", "signatures": [ { "return": { "textRaw": "Return {String | Buffer | null} ", "name": "return", "type": "String | Buffer | null" }, "params": [ { "textRaw": "`size` {Number} Optional argument to specify how much data to read. ", "name": "size", "type": "Number", "desc": "Optional argument to specify how much data to read.", "optional": true } ] }, { "params": [ { "name": "size", "optional": true } ] } ], "desc": "

    The read() method pulls some data out of the internal buffer and\nreturns it. If there is no data available, then it will return\nnull.\n\n

    \n

    If you pass in a size argument, then it will return that many\nbytes. If size bytes are not available, then it will return null.\n\n

    \n

    If you do not specify a size argument, then it will return all the\ndata in the internal buffer.\n\n

    \n

    This method should only be called in non-flowing mode. In\nflowing-mode, this method is called automatically until the internal\nbuffer is drained.\n\n

    \n
    var readable = getReadableStreamSomehow();\nreadable.on('readable', function() {\n  var chunk;\n  while (null !== (chunk = readable.read())) {\n    console.log('got %d bytes of data', chunk.length);\n  }\n});
    \n" }, { "textRaw": "readable.setEncoding(encoding)", "type": "method", "name": "setEncoding", "signatures": [ { "params": [ { "textRaw": "`encoding` {String} The encoding to use. ", "name": "encoding", "type": "String", "desc": "The encoding to use." } ] }, { "params": [ { "name": "encoding" } ] } ], "desc": "

    Call this function to cause the stream to return strings of the\nspecified encoding instead of Buffer objects. For example, if you do\nreadable.setEncoding('utf8'), then the output data will be\ninterpreted as UTF-8 data, and returned as strings. If you do\nreadable.setEncoding('hex'), then the data will be encoded in\nhexadecimal string format.\n\n

    \n

    This properly handles multi-byte characters that would otherwise be\npotentially mangled if you simply pulled the Buffers directly and\ncalled buf.toString(encoding) on them. If you want to read the data\nas strings, always use this method.\n\n

    \n
    var readable = getReadableStreamSomehow();\nreadable.setEncoding('utf8');\nreadable.on('data', function(chunk) {\n  assert.equal(typeof chunk, 'string');\n  console.log('got %d characters of string data', chunk.length);\n})
    \n" }, { "textRaw": "readable.resume()", "type": "method", "name": "resume", "desc": "

    This method will cause the readable stream to resume emitting data\nevents.\n\n

    \n

    This method will switch the stream into flowing-mode. If you do not\nwant to consume the data from a stream, but you do want to get to\nits end event, you can call readable.resume() to open the flow of\ndata.\n\n

    \n
    var readable = getReadableStreamSomehow();\nreadable.resume();\nreadable.on('end', function(chunk) {\n  console.log('got to the end, but did not read anything');\n})
    \n", "signatures": [ { "params": [] } ] }, { "textRaw": "readable.pause()", "type": "method", "name": "pause", "desc": "

    This method will cause a stream in flowing-mode to stop emitting\ndata events. Any data that becomes available will remain in the\ninternal buffer.\n\n

    \n

    This method is only relevant in flowing mode. When called on a\nnon-flowing stream, it will switch into flowing mode, but remain\npaused.\n\n

    \n
    var readable = getReadableStreamSomehow();\nreadable.on('data', function(chunk) {\n  console.log('got %d bytes of data', chunk.length);\n  readable.pause();\n  console.log('there will be no more data for 1 second');\n  setTimeout(function() {\n    console.log('now data will start flowing again');\n    readable.resume();\n  }, 1000);\n})
    \n", "signatures": [ { "params": [] } ] }, { "textRaw": "readable.pipe(destination, [options])", "type": "method", "name": "pipe", "signatures": [ { "params": [ { "textRaw": "`destination` {[Writable][] Stream} The destination for writing data ", "name": "destination", "type": "[Writable][] Stream", "desc": "The destination for writing data" }, { "textRaw": "`options` {Object} Pipe options ", "options": [ { "textRaw": "`end` {Boolean} End the writer when the reader ends. Default = `true` ", "name": "end", "type": "Boolean", "desc": "End the writer when the reader ends. Default = `true`" } ], "name": "options", "type": "Object", "desc": "Pipe options", "optional": true } ] }, { "params": [ { "name": "destination" }, { "name": "options", "optional": true } ] } ], "desc": "

    This method pulls all the data out of a readable stream, and writes it\nto the supplied destination, automatically managing the flow so that\nthe destination is not overwhelmed by a fast readable stream.\n\n

    \n

    Multiple destinations can be piped to safely.\n\n

    \n
    var readable = getReadableStreamSomehow();\nvar writable = fs.createWriteStream('file.txt');\n// All the data from readable goes into 'file.txt'\nreadable.pipe(writable);
    \n

    This function returns the destination stream, so you can set up pipe\nchains like so:\n\n

    \n
    var r = fs.createReadStream('file.txt');\nvar z = zlib.createGzip();\nvar w = fs.createWriteStream('file.txt.gz');\nr.pipe(z).pipe(w);
    \n

    For example, emulating the Unix cat command:\n\n

    \n
    process.stdin.pipe(process.stdout);
    \n

    By default [end()][] is called on the destination when the source stream\nemits end, so that destination is no longer writable. Pass { end:\nfalse } as options to keep the destination stream open.\n\n

    \n

    This keeps writer open so that "Goodbye" can be written at the\nend.\n\n

    \n
    reader.pipe(writer, { end: false });\nreader.on('end', function() {\n  writer.end('Goodbye\\n');\n});
    \n

    Note that process.stderr and process.stdout are never closed until\nthe process exits, regardless of the specified options.\n\n

    \n" }, { "textRaw": "readable.unpipe([destination])", "type": "method", "name": "unpipe", "signatures": [ { "params": [ { "textRaw": "`destination` {[Writable][] Stream} Optional specific stream to unpipe ", "name": "destination", "type": "[Writable][] Stream", "desc": "Optional specific stream to unpipe", "optional": true } ] }, { "params": [ { "name": "destination", "optional": true } ] } ], "desc": "

    This method will remove the hooks set up for a previous pipe() call.\n\n

    \n

    If the destination is not specified, then all pipes are removed.\n\n

    \n

    If the destination is specified, but no pipe is set up for it, then\nthis is a no-op.\n\n

    \n
    var readable = getReadableStreamSomehow();\nvar writable = fs.createWriteStream('file.txt');\n// All the data from readable goes into 'file.txt',\n// but only for the first second\nreadable.pipe(writable);\nsetTimeout(function() {\n  console.log('stop writing to file.txt');\n  readable.unpipe(writable);\n  console.log('manually close the file stream');\n  writable.end();\n}, 1000);
    \n" }, { "textRaw": "readable.unshift(chunk)", "type": "method", "name": "unshift", "signatures": [ { "params": [ { "textRaw": "`chunk` {Buffer | String} Chunk of data to unshift onto the read queue ", "name": "chunk", "type": "Buffer | String", "desc": "Chunk of data to unshift onto the read queue" } ] }, { "params": [ { "name": "chunk" } ] } ], "desc": "

    This is useful in certain cases where a stream is being consumed by a\nparser, which needs to "un-consume" some data that it has\noptimistically pulled out of the source, so that the stream can be\npassed on to some other party.\n\n

    \n

    If you find that you must often call stream.unshift(chunk) in your\nprograms, consider implementing a [Transform][] stream instead. (See API\nfor Stream Implementors, below.)\n\n

    \n
    // Pull off a header delimited by \\n\\n\n// use unshift() if we get too much\n// Call the callback with (error, header, stream)\nvar StringDecoder = require('string_decoder').StringDecoder;\nfunction parseHeader(stream, callback) {\n  stream.on('error', callback);\n  stream.on('readable', onReadable);\n  var decoder = new StringDecoder('utf8');\n  var header = '';\n  function onReadable() {\n    var chunk;\n    while (null !== (chunk = stream.read())) {\n      var str = decoder.write(chunk);\n      if (str.match(/\\n\\n/)) {\n        // found the header boundary\n        var split = str.split(/\\n\\n/);\n        header += split.shift();\n        var remaining = split.join('\\n\\n');\n        var buf = new Buffer(remaining, 'utf8');\n        if (buf.length)\n          stream.unshift(buf);\n        stream.removeListener('error', callback);\n        stream.removeListener('readable', onReadable);\n        // now the body of the message can be read from the stream.\n        callback(null, header, stream);\n      } else {\n        // still reading the header.\n        header += str;\n      }\n    }\n  }\n}
    \n" }, { "textRaw": "readable.wrap(stream)", "type": "method", "name": "wrap", "signatures": [ { "params": [ { "textRaw": "`stream` {Stream} An \"old style\" readable stream ", "name": "stream", "type": "Stream", "desc": "An \"old style\" readable stream" } ] }, { "params": [ { "name": "stream" } ] } ], "desc": "

    Versions of Node prior to v0.10 had streams that did not implement the\nentire Streams API as it is today. (See "Compatibility" below for\nmore information.)\n\n

    \n

    If you are using an older Node library that emits 'data' events and\nhas a pause() method that is advisory only, then you can use the\nwrap() method to create a [Readable][] stream that uses the old stream\nas its data source.\n\n

    \n

    You will very rarely ever need to call this function, but it exists\nas a convenience for interacting with old Node programs and libraries.\n\n

    \n

    For example:\n\n

    \n
    var OldReader = require('./old-api-module.js').OldReader;\nvar oreader = new OldReader;\nvar Readable = require('stream').Readable;\nvar myReader = new Readable().wrap(oreader);\n\nmyReader.on('readable', function() {\n  myReader.read(); // etc.\n});
    \n" } ] }, { "textRaw": "Class: stream.Writable", "type": "class", "name": "stream.Writable", "desc": "

    The Writable stream interface is an abstraction for a destination\nthat you are writing data to.\n\n

    \n

    Examples of writable streams include:\n\n

    \n\n", "methods": [ { "textRaw": "writable.write(chunk, [encoding], [callback])", "type": "method", "name": "write", "signatures": [ { "return": { "textRaw": "Returns: {Boolean} True if the data was handled completely. ", "name": "return", "type": "Boolean", "desc": "True if the data was handled completely." }, "params": [ { "textRaw": "`chunk` {String | Buffer} The data to write ", "name": "chunk", "type": "String | Buffer", "desc": "The data to write" }, { "textRaw": "`encoding` {String} The encoding, if `chunk` is a String ", "name": "encoding", "type": "String", "desc": "The encoding, if `chunk` is a String", "optional": true }, { "textRaw": "`callback` {Function} Callback for when this chunk of data is flushed ", "name": "callback", "type": "Function", "desc": "Callback for when this chunk of data is flushed", "optional": true } ] }, { "params": [ { "name": "chunk" }, { "name": "encoding", "optional": true }, { "name": "callback", "optional": true } ] } ], "desc": "

    This method writes some data to the underlying system, and calls the\nsupplied callback once the data has been fully handled.\n\n

    \n

    The return value indicates if you should continue writing right now.\nIf the data had to be buffered internally, then it will return\nfalse. Otherwise, it will return true.\n\n

    \n

    This return value is strictly advisory. You MAY continue to write,\neven if it returns false. However, writes will be buffered in\nmemory, so it is best not to do this excessively. Instead, wait for\nthe drain event before writing more data.\n\n

    \n" }, { "textRaw": "writable.end([chunk], [encoding], [callback])", "type": "method", "name": "end", "signatures": [ { "params": [ { "textRaw": "`chunk` {String | Buffer} Optional data to write ", "name": "chunk", "type": "String | Buffer", "desc": "Optional data to write", "optional": true }, { "textRaw": "`encoding` {String} The encoding, if `chunk` is a String ", "name": "encoding", "type": "String", "desc": "The encoding, if `chunk` is a String", "optional": true }, { "textRaw": "`callback` {Function} Optional callback for when the stream is finished ", "name": "callback", "type": "Function", "desc": "Optional callback for when the stream is finished", "optional": true } ] }, { "params": [ { "name": "chunk", "optional": true }, { "name": "encoding", "optional": true }, { "name": "callback", "optional": true } ] } ], "desc": "

    Call this method when no more data will be written to the stream. If\nsupplied, the callback is attached as a listener on the finish event.\n\n

    \n

    Calling [write()][] after calling [end()][] will raise an error.\n\n

    \n
    // write 'hello, ' and then end with 'world!'\nhttp.createServer(function (req, res) {\n  res.write('hello, ');\n  res.end('world!');\n  // writing more now is not allowed!\n});
    \n" } ], "events": [ { "textRaw": "Event: 'drain'", "type": "event", "name": "drain", "desc": "

    If a [writable.write(chunk)][] call returns false, then the drain\nevent will indicate when it is appropriate to begin writing more data\nto the stream.\n\n

    \n
    // Write the data to the supplied writable stream 1MM times.\n// Be attentive to back-pressure.\nfunction writeOneMillionTimes(writer, data, encoding, callback) {\n  var i = 1000000;\n  write();\n  function write() {\n    var ok = true;\n    do {\n      i -= 1;\n      if (i === 0) {\n        // last time!\n        writer.write(data, encoding, callback);\n      } else {\n        // see if we should continue, or wait\n        // don't pass the callback, because we're not done yet.\n        ok = writer.write(data, encoding);\n      }\n    } while (i > 0 && ok);\n    if (i > 0) {\n      // had to stop early!\n      // write some more once it drains\n      writer.once('drain', write);\n    }\n  }\n}
    \n", "params": [] }, { "textRaw": "Event: 'finish'", "type": "event", "name": "finish", "desc": "

    When the [end()][] method has been called, and all data has been flushed\nto the underlying system, this event is emitted.\n\n

    \n
    var writer = getWritableStreamSomehow();\nfor (var i = 0; i < 100; i ++) {\n  writer.write('hello, #' + i + '!\\n');\n}\nwriter.end('this is the end\\n');\nwriter.on('finish', function() {\n  console.error('all writes are now complete.');\n});
    \n", "params": [] }, { "textRaw": "Event: 'pipe'", "type": "event", "name": "pipe", "params": [], "desc": "

    This is emitted whenever the pipe() method is called on a readable\nstream, adding this writable to its set of destinations.\n\n

    \n
    var writer = getWritableStreamSomehow();\nvar reader = getReadableStreamSomehow();\nwriter.on('pipe', function(src) {\n  console.error('something is piping into the writer');\n  assert.equal(src, reader);\n});\nreader.pipe(writer);
    \n" }, { "textRaw": "Event: 'unpipe'", "type": "event", "name": "unpipe", "params": [], "desc": "

    This is emitted whenever the [unpipe()][] method is called on a\nreadable stream, removing this writable from its set of destinations.\n\n

    \n
    var writer = getWritableStreamSomehow();\nvar reader = getReadableStreamSomehow();\nwriter.on('unpipe', function(src) {\n  console.error('something has stopped piping into the writer');\n  assert.equal(src, reader);\n});\nreader.pipe(writer);\nreader.unpipe(writer);
    \n" }, { "textRaw": "Event: 'error'", "type": "event", "name": "error", "desc": "

    Emitted if there was an error when writing or piping data.\n\n

    \n", "params": [] } ] }, { "textRaw": "Class: stream.Duplex", "type": "class", "name": "stream.Duplex", "desc": "

    Duplex streams are streams that implement both the [Readable][] and\n[Writable][] interfaces. See above for usage.\n\n

    \n

    Examples of Duplex streams include:\n\n

    \n
      \n
    • [tcp sockets][]
    • \n
    • [zlib streams][]
    • \n
    • [crypto streams][]
    • \n
    \n" }, { "textRaw": "Class: stream.Transform", "type": "class", "name": "stream.Transform", "desc": "

    Transform streams are [Duplex][] streams where the output is in some way\ncomputed from the input. They implement both the [Readable][] and\n[Writable][] interfaces. See above for usage.\n\n

    \n

    Examples of Transform streams include:\n\n

    \n
      \n
    • [zlib streams][]
    • \n
    • [crypto streams][]
    • \n
    \n" } ], "miscs": [ { "textRaw": "API for Stream Consumers", "name": "API for Stream Consumers", "type": "misc", "desc": "

    Streams can be either [Readable][], [Writable][], or both ([Duplex][]).\n\n

    \n

    All streams are EventEmitters, but they also have other custom methods\nand properties depending on whether they are Readable, Writable, or\nDuplex.\n\n

    \n

    If a stream is both Readable and Writable, then it implements all of\nthe methods and events below. So, a [Duplex][] or [Transform][] stream is\nfully described by this API, though their implementation may be\nsomewhat different.\n\n

    \n

    It is not necessary to implement Stream interfaces in order to consume\nstreams in your programs. If you are implementing streaming\ninterfaces in your own program, please also refer to\n[API for Stream Implementors][] below.\n\n

    \n

    Almost all Node programs, no matter how simple, use Streams in some\nway. Here is an example of using Streams in a Node program:\n\n

    \n
    var http = require('http');\n\nvar server = http.createServer(function (req, res) {\n  // req is an http.IncomingMessage, which is a Readable Stream\n  // res is an http.ServerResponse, which is a Writable Stream\n\n  var body = '';\n  // we want to get the data as utf8 strings\n  // If you don't set an encoding, then you'll get Buffer objects\n  req.setEncoding('utf8');\n\n  // Readable streams emit 'data' events once a listener is added\n  req.on('data', function (chunk) {\n    body += chunk;\n  })\n\n  // the end event tells you that you have entire body\n  req.on('end', function () {\n    try {\n      var data = JSON.parse(body);\n    } catch (er) {\n      // uh oh!  bad json!\n      res.statusCode = 400;\n      return res.end('error: ' + er.message);\n    }\n\n    // write back something interesting to the user:\n    res.write(typeof data);\n    res.end();\n  })\n})\n\nserver.listen(1337);\n\n// $ curl localhost:1337 -d '{}'\n// object\n// $ curl localhost:1337 -d '"foo"'\n// string\n// $ curl localhost:1337 -d 'not json'\n// error: Unexpected token o
    \n", "classes": [ { "textRaw": "Class: stream.Readable", "type": "class", "name": "stream.Readable", "desc": "

    The Readable stream interface is the abstraction for a source of\ndata that you are reading from. In other words, data comes out of a\nReadable stream.\n\n

    \n

    A Readable stream will not start emitting data until you indicate that\nyou are ready to receive it.\n\n

    \n

    Readable streams have two "modes": a flowing mode and a non-flowing\nmode. When in flowing mode, data is read from the underlying system\nand provided to your program as fast as possible. In non-flowing\nmode, you must explicitly call stream.read() to get chunks of data\nout.\n\n

    \n

    Examples of readable streams include:\n\n

    \n\n", "events": [ { "textRaw": "Event: 'readable'", "type": "event", "name": "readable", "desc": "

    When a chunk of data can be read from the stream, it will emit a\n'readable' event.\n\n

    \n

    In some cases, listening for a 'readable' event will cause some data\nto be read into the internal buffer from the underlying system, if it\nhadn't already.\n\n

    \n
    var readable = getReadableStreamSomehow();\nreadable.on('readable', function() {\n  // there is some data to read now\n})
    \n

    Once the internal buffer is drained, a readable event will fire\nagain when more data is available.\n\n

    \n", "params": [] }, { "textRaw": "Event: 'data'", "type": "event", "name": "data", "params": [], "desc": "

    If you attach a data event listener, then it will switch the stream\ninto flowing mode, and data will be passed to your handler as soon as\nit is available.\n\n

    \n

    If you just want to get all the data out of the stream as fast as\npossible, this is the best way to do so.\n\n

    \n
    var readable = getReadableStreamSomehow();\nreadable.on('data', function(chunk) {\n  console.log('got %d bytes of data', chunk.length);\n})
    \n" }, { "textRaw": "Event: 'end'", "type": "event", "name": "end", "desc": "

    This event fires when no more data will be provided.\n\n

    \n

    Note that the end event will not fire unless the data is\ncompletely consumed. This can be done by switching into flowing mode,\nor by calling read() repeatedly until you get to the end.\n\n

    \n
    var readable = getReadableStreamSomehow();\nreadable.on('data', function(chunk) {\n  console.log('got %d bytes of data', chunk.length);\n})\nreadable.on('end', function() {\n  console.log('there will be no more data.');\n});
    \n", "params": [] }, { "textRaw": "Event: 'close'", "type": "event", "name": "close", "desc": "

    Emitted when the underlying resource (for example, the backing file\ndescriptor) has been closed. Not all streams will emit this.\n\n

    \n", "params": [] }, { "textRaw": "Event: 'error'", "type": "event", "name": "error", "desc": "

    Emitted if there was an error receiving data.\n\n

    \n", "params": [] } ], "methods": [ { "textRaw": "readable.read([size])", "type": "method", "name": "read", "signatures": [ { "return": { "textRaw": "Return {String | Buffer | null} ", "name": "return", "type": "String | Buffer | null" }, "params": [ { "textRaw": "`size` {Number} Optional argument to specify how much data to read. ", "name": "size", "type": "Number", "desc": "Optional argument to specify how much data to read.", "optional": true } ] }, { "params": [ { "name": "size", "optional": true } ] } ], "desc": "

    The read() method pulls some data out of the internal buffer and\nreturns it. If there is no data available, then it will return\nnull.\n\n

    \n

    If you pass in a size argument, then it will return that many\nbytes. If size bytes are not available, then it will return null.\n\n

    \n

    If you do not specify a size argument, then it will return all the\ndata in the internal buffer.\n\n

    \n

    This method should only be called in non-flowing mode. In\nflowing-mode, this method is called automatically until the internal\nbuffer is drained.\n\n

    \n
    var readable = getReadableStreamSomehow();\nreadable.on('readable', function() {\n  var chunk;\n  while (null !== (chunk = readable.read())) {\n    console.log('got %d bytes of data', chunk.length);\n  }\n});
    \n" }, { "textRaw": "readable.setEncoding(encoding)", "type": "method", "name": "setEncoding", "signatures": [ { "params": [ { "textRaw": "`encoding` {String} The encoding to use. ", "name": "encoding", "type": "String", "desc": "The encoding to use." } ] }, { "params": [ { "name": "encoding" } ] } ], "desc": "

    Call this function to cause the stream to return strings of the\nspecified encoding instead of Buffer objects. For example, if you do\nreadable.setEncoding('utf8'), then the output data will be\ninterpreted as UTF-8 data, and returned as strings. If you do\nreadable.setEncoding('hex'), then the data will be encoded in\nhexadecimal string format.\n\n

    \n

    This properly handles multi-byte characters that would otherwise be\npotentially mangled if you simply pulled the Buffers directly and\ncalled buf.toString(encoding) on them. If you want to read the data\nas strings, always use this method.\n\n

    \n
    var readable = getReadableStreamSomehow();\nreadable.setEncoding('utf8');\nreadable.on('data', function(chunk) {\n  assert.equal(typeof chunk, 'string');\n  console.log('got %d characters of string data', chunk.length);\n})
    \n" }, { "textRaw": "readable.resume()", "type": "method", "name": "resume", "desc": "

    This method will cause the readable stream to resume emitting data\nevents.\n\n

    \n

    This method will switch the stream into flowing-mode. If you do not\nwant to consume the data from a stream, but you do want to get to\nits end event, you can call readable.resume() to open the flow of\ndata.\n\n

    \n
    var readable = getReadableStreamSomehow();\nreadable.resume();\nreadable.on('end', function(chunk) {\n  console.log('got to the end, but did not read anything');\n})
    \n", "signatures": [ { "params": [] } ] }, { "textRaw": "readable.pause()", "type": "method", "name": "pause", "desc": "

    This method will cause a stream in flowing-mode to stop emitting\ndata events. Any data that becomes available will remain in the\ninternal buffer.\n\n

    \n

    This method is only relevant in flowing mode. When called on a\nnon-flowing stream, it will switch into flowing mode, but remain\npaused.\n\n

    \n
    var readable = getReadableStreamSomehow();\nreadable.on('data', function(chunk) {\n  console.log('got %d bytes of data', chunk.length);\n  readable.pause();\n  console.log('there will be no more data for 1 second');\n  setTimeout(function() {\n    console.log('now data will start flowing again');\n    readable.resume();\n  }, 1000);\n})
    \n", "signatures": [ { "params": [] } ] }, { "textRaw": "readable.pipe(destination, [options])", "type": "method", "name": "pipe", "signatures": [ { "params": [ { "textRaw": "`destination` {[Writable][] Stream} The destination for writing data ", "name": "destination", "type": "[Writable][] Stream", "desc": "The destination for writing data" }, { "textRaw": "`options` {Object} Pipe options ", "options": [ { "textRaw": "`end` {Boolean} End the writer when the reader ends. Default = `true` ", "name": "end", "type": "Boolean", "desc": "End the writer when the reader ends. Default = `true`" } ], "name": "options", "type": "Object", "desc": "Pipe options", "optional": true } ] }, { "params": [ { "name": "destination" }, { "name": "options", "optional": true } ] } ], "desc": "

    This method pulls all the data out of a readable stream, and writes it\nto the supplied destination, automatically managing the flow so that\nthe destination is not overwhelmed by a fast readable stream.\n\n

    \n

    Multiple destinations can be piped to safely.\n\n

    \n
    var readable = getReadableStreamSomehow();\nvar writable = fs.createWriteStream('file.txt');\n// All the data from readable goes into 'file.txt'\nreadable.pipe(writable);
    \n

    This function returns the destination stream, so you can set up pipe\nchains like so:\n\n

    \n
    var r = fs.createReadStream('file.txt');\nvar z = zlib.createGzip();\nvar w = fs.createWriteStream('file.txt.gz');\nr.pipe(z).pipe(w);
    \n

    For example, emulating the Unix cat command:\n\n

    \n
    process.stdin.pipe(process.stdout);
    \n

    By default [end()][] is called on the destination when the source stream\nemits end, so that destination is no longer writable. Pass { end:\nfalse } as options to keep the destination stream open.\n\n

    \n

    This keeps writer open so that "Goodbye" can be written at the\nend.\n\n

    \n
    reader.pipe(writer, { end: false });\nreader.on('end', function() {\n  writer.end('Goodbye\\n');\n});
    \n

    Note that process.stderr and process.stdout are never closed until\nthe process exits, regardless of the specified options.\n\n

    \n" }, { "textRaw": "readable.unpipe([destination])", "type": "method", "name": "unpipe", "signatures": [ { "params": [ { "textRaw": "`destination` {[Writable][] Stream} Optional specific stream to unpipe ", "name": "destination", "type": "[Writable][] Stream", "desc": "Optional specific stream to unpipe", "optional": true } ] }, { "params": [ { "name": "destination", "optional": true } ] } ], "desc": "

    This method will remove the hooks set up for a previous pipe() call.\n\n

    \n

    If the destination is not specified, then all pipes are removed.\n\n

    \n

    If the destination is specified, but no pipe is set up for it, then\nthis is a no-op.\n\n

    \n
    var readable = getReadableStreamSomehow();\nvar writable = fs.createWriteStream('file.txt');\n// All the data from readable goes into 'file.txt',\n// but only for the first second\nreadable.pipe(writable);\nsetTimeout(function() {\n  console.log('stop writing to file.txt');\n  readable.unpipe(writable);\n  console.log('manually close the file stream');\n  writable.end();\n}, 1000);
    \n" }, { "textRaw": "readable.unshift(chunk)", "type": "method", "name": "unshift", "signatures": [ { "params": [ { "textRaw": "`chunk` {Buffer | String} Chunk of data to unshift onto the read queue ", "name": "chunk", "type": "Buffer | String", "desc": "Chunk of data to unshift onto the read queue" } ] }, { "params": [ { "name": "chunk" } ] } ], "desc": "

    This is useful in certain cases where a stream is being consumed by a\nparser, which needs to "un-consume" some data that it has\noptimistically pulled out of the source, so that the stream can be\npassed on to some other party.\n\n

    \n

    If you find that you must often call stream.unshift(chunk) in your\nprograms, consider implementing a [Transform][] stream instead. (See API\nfor Stream Implementors, below.)\n\n

    \n
    // Pull off a header delimited by \\n\\n\n// use unshift() if we get too much\n// Call the callback with (error, header, stream)\nvar StringDecoder = require('string_decoder').StringDecoder;\nfunction parseHeader(stream, callback) {\n  stream.on('error', callback);\n  stream.on('readable', onReadable);\n  var decoder = new StringDecoder('utf8');\n  var header = '';\n  function onReadable() {\n    var chunk;\n    while (null !== (chunk = stream.read())) {\n      var str = decoder.write(chunk);\n      if (str.match(/\\n\\n/)) {\n        // found the header boundary\n        var split = str.split(/\\n\\n/);\n        header += split.shift();\n        var remaining = split.join('\\n\\n');\n        var buf = new Buffer(remaining, 'utf8');\n        if (buf.length)\n          stream.unshift(buf);\n        stream.removeListener('error', callback);\n        stream.removeListener('readable', onReadable);\n        // now the body of the message can be read from the stream.\n        callback(null, header, stream);\n      } else {\n        // still reading the header.\n        header += str;\n      }\n    }\n  }\n}
    \n" }, { "textRaw": "readable.wrap(stream)", "type": "method", "name": "wrap", "signatures": [ { "params": [ { "textRaw": "`stream` {Stream} An \"old style\" readable stream ", "name": "stream", "type": "Stream", "desc": "An \"old style\" readable stream" } ] }, { "params": [ { "name": "stream" } ] } ], "desc": "

    Versions of Node prior to v0.10 had streams that did not implement the\nentire Streams API as it is today. (See "Compatibility" below for\nmore information.)\n\n

    \n

    If you are using an older Node library that emits 'data' events and\nhas a pause() method that is advisory only, then you can use the\nwrap() method to create a [Readable][] stream that uses the old stream\nas its data source.\n\n

    \n

    You will very rarely ever need to call this function, but it exists\nas a convenience for interacting with old Node programs and libraries.\n\n

    \n

    For example:\n\n

    \n
    var OldReader = require('./old-api-module.js').OldReader;\nvar oreader = new OldReader;\nvar Readable = require('stream').Readable;\nvar myReader = new Readable().wrap(oreader);\n\nmyReader.on('readable', function() {\n  myReader.read(); // etc.\n});
    \n" } ] }, { "textRaw": "Class: stream.Writable", "type": "class", "name": "stream.Writable", "desc": "

    The Writable stream interface is an abstraction for a destination\nthat you are writing data to.\n\n

    \n

    Examples of writable streams include:\n\n

    \n\n", "methods": [ { "textRaw": "writable.write(chunk, [encoding], [callback])", "type": "method", "name": "write", "signatures": [ { "return": { "textRaw": "Returns: {Boolean} True if the data was handled completely. ", "name": "return", "type": "Boolean", "desc": "True if the data was handled completely." }, "params": [ { "textRaw": "`chunk` {String | Buffer} The data to write ", "name": "chunk", "type": "String | Buffer", "desc": "The data to write" }, { "textRaw": "`encoding` {String} The encoding, if `chunk` is a String ", "name": "encoding", "type": "String", "desc": "The encoding, if `chunk` is a String", "optional": true }, { "textRaw": "`callback` {Function} Callback for when this chunk of data is flushed ", "name": "callback", "type": "Function", "desc": "Callback for when this chunk of data is flushed", "optional": true } ] }, { "params": [ { "name": "chunk" }, { "name": "encoding", "optional": true }, { "name": "callback", "optional": true } ] } ], "desc": "

    This method writes some data to the underlying system, and calls the\nsupplied callback once the data has been fully handled.\n\n

    \n

    The return value indicates if you should continue writing right now.\nIf the data had to be buffered internally, then it will return\nfalse. Otherwise, it will return true.\n\n

    \n

    This return value is strictly advisory. You MAY continue to write,\neven if it returns false. However, writes will be buffered in\nmemory, so it is best not to do this excessively. Instead, wait for\nthe drain event before writing more data.\n\n

    \n" }, { "textRaw": "writable.end([chunk], [encoding], [callback])", "type": "method", "name": "end", "signatures": [ { "params": [ { "textRaw": "`chunk` {String | Buffer} Optional data to write ", "name": "chunk", "type": "String | Buffer", "desc": "Optional data to write", "optional": true }, { "textRaw": "`encoding` {String} The encoding, if `chunk` is a String ", "name": "encoding", "type": "String", "desc": "The encoding, if `chunk` is a String", "optional": true }, { "textRaw": "`callback` {Function} Optional callback for when the stream is finished ", "name": "callback", "type": "Function", "desc": "Optional callback for when the stream is finished", "optional": true } ] }, { "params": [ { "name": "chunk", "optional": true }, { "name": "encoding", "optional": true }, { "name": "callback", "optional": true } ] } ], "desc": "

    Call this method when no more data will be written to the stream. If\nsupplied, the callback is attached as a listener on the finish event.\n\n

    \n

    Calling [write()][] after calling [end()][] will raise an error.\n\n

    \n
    // write 'hello, ' and then end with 'world!'\nhttp.createServer(function (req, res) {\n  res.write('hello, ');\n  res.end('world!');\n  // writing more now is not allowed!\n});
    \n" } ], "events": [ { "textRaw": "Event: 'drain'", "type": "event", "name": "drain", "desc": "

    If a [writable.write(chunk)][] call returns false, then the drain\nevent will indicate when it is appropriate to begin writing more data\nto the stream.\n\n

    \n
    // Write the data to the supplied writable stream 1MM times.\n// Be attentive to back-pressure.\nfunction writeOneMillionTimes(writer, data, encoding, callback) {\n  var i = 1000000;\n  write();\n  function write() {\n    var ok = true;\n    do {\n      i -= 1;\n      if (i === 0) {\n        // last time!\n        writer.write(data, encoding, callback);\n      } else {\n        // see if we should continue, or wait\n        // don't pass the callback, because we're not done yet.\n        ok = writer.write(data, encoding);\n      }\n    } while (i > 0 && ok);\n    if (i > 0) {\n      // had to stop early!\n      // write some more once it drains\n      writer.once('drain', write);\n    }\n  }\n}
    \n", "params": [] }, { "textRaw": "Event: 'finish'", "type": "event", "name": "finish", "desc": "

    When the [end()][] method has been called, and all data has been flushed\nto the underlying system, this event is emitted.\n\n

    \n
    var writer = getWritableStreamSomehow();\nfor (var i = 0; i < 100; i ++) {\n  writer.write('hello, #' + i + '!\\n');\n}\nwriter.end('this is the end\\n');\nwriter.on('finish', function() {\n  console.error('all writes are now complete.');\n});
    \n", "params": [] }, { "textRaw": "Event: 'pipe'", "type": "event", "name": "pipe", "params": [], "desc": "

    This is emitted whenever the pipe() method is called on a readable\nstream, adding this writable to its set of destinations.\n\n

    \n
    var writer = getWritableStreamSomehow();\nvar reader = getReadableStreamSomehow();\nwriter.on('pipe', function(src) {\n  console.error('something is piping into the writer');\n  assert.equal(src, reader);\n});\nreader.pipe(writer);
    \n" }, { "textRaw": "Event: 'unpipe'", "type": "event", "name": "unpipe", "params": [], "desc": "

    This is emitted whenever the [unpipe()][] method is called on a\nreadable stream, removing this writable from its set of destinations.\n\n

    \n
    var writer = getWritableStreamSomehow();\nvar reader = getReadableStreamSomehow();\nwriter.on('unpipe', function(src) {\n  console.error('something has stopped piping into the writer');\n  assert.equal(src, reader);\n});\nreader.pipe(writer);\nreader.unpipe(writer);
    \n" }, { "textRaw": "Event: 'error'", "type": "event", "name": "error", "desc": "

    Emitted if there was an error when writing or piping data.\n\n

    \n", "params": [] } ] }, { "textRaw": "Class: stream.Duplex", "type": "class", "name": "stream.Duplex", "desc": "

    Duplex streams are streams that implement both the [Readable][] and\n[Writable][] interfaces. See above for usage.\n\n

    \n

    Examples of Duplex streams include:\n\n

    \n
      \n
    • [tcp sockets][]
    • \n
    • [zlib streams][]
    • \n
    • [crypto streams][]
    • \n
    \n" }, { "textRaw": "Class: stream.Transform", "type": "class", "name": "stream.Transform", "desc": "

    Transform streams are [Duplex][] streams where the output is in some way\ncomputed from the input. They implement both the [Readable][] and\n[Writable][] interfaces. See above for usage.\n\n

    \n

    Examples of Transform streams include:\n\n

    \n
      \n
    • [zlib streams][]
    • \n
    • [crypto streams][]
    • \n
    \n" } ] }, { "textRaw": "API for Stream Implementors", "name": "API for Stream Implementors", "type": "misc", "desc": "

    To implement any sort of stream, the pattern is the same:\n\n

    \n
      \n
    1. Extend the appropriate parent class in your own subclass. (The\n[util.inherits][] method is particularly helpful for this.)
    2. \n
    3. Call the appropriate parent class constructor in your constructor,\nto be sure that the internal mechanisms are set up properly.
    4. \n
    5. Implement one or more specific methods, as detailed below.
    6. \n
    \n

    The class to extend and the method(s) to implement depend on the sort\nof stream class you are writing:\n\n

    \n\n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n
    \n

    Use-case

    \n
    \n

    Class

    \n
    \n

    Method(s) to implement

    \n
    \n

    Reading only

    \n
    \n

    Readable

    \n
    \n

    [_read][]

    \n
    \n

    Writing only

    \n
    \n

    Writable

    \n
    \n

    [_write][]

    \n
    \n

    Reading and writing

    \n
    \n

    Duplex

    \n
    \n

    [_read][], [_write][]

    \n
    \n

    Operate on written data, then read the result

    \n
    \n

    Transform

    \n
    \n

    _transform, _flush

    \n
    \n\n

    In your implementation code, it is very important to never call the\nmethods described in [API for Stream Consumers][] above. Otherwise, you\ncan potentially cause adverse side effects in programs that consume\nyour streaming interfaces.\n\n

    \n", "examples": [ { "textRaw": "Class: stream.Readable", "type": "example", "name": "stream.Readable", "desc": "

    stream.Readable is an abstract class designed to be extended with an\nunderlying implementation of the [_read(size)][] method.\n\n

    \n

    Please see above under [API for Stream Consumers][] for how to consume\nstreams in your programs. What follows is an explanation of how to\nimplement Readable streams in your programs.\n\n

    \n

    Example: A Counting Stream

    \n

    This is a basic example of a Readable stream. It emits the numerals\nfrom 1 to 1,000,000 in ascending order, and then ends.\n\n

    \n
    var Readable = require('stream').Readable;\nvar util = require('util');\nutil.inherits(Counter, Readable);\n\nfunction Counter(opt) {\n  Readable.call(this, opt);\n  this._max = 1000000;\n  this._index = 1;\n}\n\nCounter.prototype._read = function() {\n  var i = this._index++;\n  if (i > this._max)\n    this.push(null);\n  else {\n    var str = '' + i;\n    var buf = new Buffer(str, 'ascii');\n    this.push(buf);\n  }\n};
    \n

    Example: SimpleProtocol v1 (Sub-optimal)

    \n

    This is similar to the parseHeader function described above, but\nimplemented as a custom stream. Also, note that this implementation\ndoes not convert the incoming data to a string.\n\n

    \n

    However, this would be better implemented as a [Transform][] stream. See\nbelow for a better implementation.\n\n

    \n
    // A parser for a simple data protocol.\n// The "header" is a JSON object, followed by 2 \\n characters, and\n// then a message body.\n//\n// NOTE: This can be done more simply as a Transform stream!\n// Using Readable directly for this is sub-optimal.  See the\n// alternative example below under the Transform section.\n\nvar Readable = require('stream').Readable;\nvar util = require('util');\n\nutil.inherits(SimpleProtocol, Readable);\n\nfunction SimpleProtocol(source, options) {\n  if (!(this instanceof SimpleProtocol))\n    return new SimpleProtocol(source, options);\n\n  Readable.call(this, options);\n  this._inBody = false;\n  this._sawFirstCr = false;\n\n  // source is a readable stream, such as a socket or file\n  this._source = source;\n\n  var self = this;\n  source.on('end', function() {\n    self.push(null);\n  });\n\n  // give it a kick whenever the source is readable\n  // read(0) will not consume any bytes\n  source.on('readable', function() {\n    self.read(0);\n  });\n\n  this._rawHeader = [];\n  this.header = null;\n}\n\nSimpleProtocol.prototype._read = function(n) {\n  if (!this._inBody) {\n    var chunk = this._source.read();\n\n    // if the source doesn't have data, we don't have data yet.\n    if (chunk === null)\n      return this.push('');\n\n    // check if the chunk has a \\n\\n\n    var split = -1;\n    for (var i = 0; i < chunk.length; i++) {\n      if (chunk[i] === 10) { // '\\n'\n        if (this._sawFirstCr) {\n          split = i;\n          break;\n        } else {\n          this._sawFirstCr = true;\n        }\n      } else {\n        this._sawFirstCr = false;\n      }\n    }\n\n    if (split === -1) {\n      // still waiting for the \\n\\n\n      // stash the chunk, and try again.\n      this._rawHeader.push(chunk);\n      this.push('');\n    } else {\n      this._inBody = true;\n      var h = chunk.slice(0, split);\n      this._rawHeader.push(h);\n      var header = Buffer.concat(this._rawHeader).toString();\n      try {\n        this.header = JSON.parse(header);\n      } catch (er) {\n        this.emit('error', new Error('invalid simple protocol data'));\n        return;\n      }\n      // now, because we got some extra data, unshift the rest\n      // back into the read queue so that our consumer will see it.\n      var b = chunk.slice(split);\n      this.unshift(b);\n\n      // and let them know that we are done parsing the header.\n      this.emit('header', this.header);\n    }\n  } else {\n    // from there on, just provide the data to our consumer.\n    // careful not to push(null), since that would indicate EOF.\n    var chunk = this._source.read();\n    if (chunk) this.push(chunk);\n  }\n};\n\n// Usage:\n// var parser = new SimpleProtocol(source);\n// Now parser is a readable stream that will emit 'header'\n// with the parsed header data.
    \n", "methods": [ { "textRaw": "new stream.Readable([options])", "type": "method", "name": "Readable", "signatures": [ { "params": [ { "textRaw": "`options` {Object} ", "options": [ { "textRaw": "`highWaterMark` {Number} The maximum number of bytes to store in the internal buffer before ceasing to read from the underlying resource. Default=16kb ", "name": "highWaterMark", "type": "Number", "desc": "The maximum number of bytes to store in the internal buffer before ceasing to read from the underlying resource. Default=16kb" }, { "textRaw": "`encoding` {String} If specified, then buffers will be decoded to strings using the specified encoding. Default=null ", "name": "encoding", "type": "String", "desc": "If specified, then buffers will be decoded to strings using the specified encoding. Default=null" }, { "textRaw": "`objectMode` {Boolean} Whether this stream should behave as a stream of objects. Meaning that stream.read(n) returns a single value instead of a Buffer of size n. Default=false ", "name": "objectMode", "type": "Boolean", "desc": "Whether this stream should behave as a stream of objects. Meaning that stream.read(n) returns a single value instead of a Buffer of size n. Default=false" } ], "name": "options", "type": "Object", "optional": true } ] }, { "params": [ { "name": "options", "optional": true } ] } ], "desc": "

    In classes that extend the Readable class, make sure to call the\nReadable constructor so that the buffering settings can be properly\ninitialized.\n\n

    \n" }, { "textRaw": "readable.\\_read(size)", "type": "method", "name": "\\_read", "signatures": [ { "params": [ { "textRaw": "`size` {Number} Number of bytes to read asynchronously ", "name": "size", "type": "Number", "desc": "Number of bytes to read asynchronously" } ] }, { "params": [ { "name": "size" } ] } ], "desc": "

    Note: Implement this function, but do NOT call it directly.\n\n

    \n

    This function should NOT be called directly. It should be implemented\nby child classes, and only called by the internal Readable class\nmethods.\n\n

    \n

    All Readable stream implementations must provide a _read method to\nfetch data from the underlying resource.\n\n

    \n

    This method is prefixed with an underscore because it is internal to\nthe class that defines it, and should not be called directly by user\nprograms. However, you are expected to override this method in\nyour own extension classes.\n\n

    \n

    When data is available, put it into the read queue by calling\nreadable.push(chunk). If push returns false, then you should stop\nreading. When _read is called again, you should start pushing more\ndata.\n\n

    \n

    The size argument is advisory. Implementations where a "read" is a\nsingle call that returns data can use this to know how much data to\nfetch. Implementations where that is not relevant, such as TCP or\nTLS, may ignore this argument, and simply provide data whenever it\nbecomes available. There is no need, for example to "wait" until\nsize bytes are available before calling [stream.push(chunk)][].\n\n

    \n" }, { "textRaw": "readable.push(chunk, [encoding])", "type": "method", "name": "push", "signatures": [ { "return": { "textRaw": "return {Boolean} Whether or not more pushes should be performed ", "name": "return", "type": "Boolean", "desc": "Whether or not more pushes should be performed" }, "params": [ { "textRaw": "`chunk` {Buffer | null | String} Chunk of data to push into the read queue ", "name": "chunk", "type": "Buffer | null | String", "desc": "Chunk of data to push into the read queue" }, { "textRaw": "`encoding` {String} Encoding of String chunks. Must be a valid Buffer encoding, such as `'utf8'` or `'ascii'` ", "name": "encoding", "type": "String", "desc": "Encoding of String chunks. Must be a valid Buffer encoding, such as `'utf8'` or `'ascii'`", "optional": true } ] }, { "params": [ { "name": "chunk" }, { "name": "encoding", "optional": true } ] } ], "desc": "

    Note: This function should be called by Readable implementors, NOT\nby consumers of Readable streams.\n\n

    \n

    The _read() function will not be called again until at least one\npush(chunk) call is made.\n\n

    \n

    The Readable class works by putting data into a read queue to be\npulled out later by calling the read() method when the 'readable'\nevent fires.\n\n

    \n

    The push() method will explicitly insert some data into the read\nqueue. If it is called with null then it will signal the end of the\ndata (EOF).\n\n

    \n

    This API is designed to be as flexible as possible. For example,\nyou may be wrapping a lower-level source which has some sort of\npause/resume mechanism, and a data callback. In those cases, you\ncould wrap the low-level source object by doing something like this:\n\n

    \n
    // source is an object with readStop() and readStart() methods,\n// and an `ondata` member that gets called when it has data, and\n// an `onend` member that gets called when the data is over.\n\nutil.inherits(SourceWrapper, Readable);\n\nfunction SourceWrapper(options) {\n  Readable.call(this, options);\n\n  this._source = getLowlevelSourceObject();\n  var self = this;\n\n  // Every time there's data, we push it into the internal buffer.\n  this._source.ondata = function(chunk) {\n    // if push() returns false, then we need to stop reading from source\n    if (!self.push(chunk))\n      self._source.readStop();\n  };\n\n  // When the source ends, we push the EOF-signalling `null` chunk\n  this._source.onend = function() {\n    self.push(null);\n  };\n}\n\n// _read will be called when the stream wants to pull more data in\n// the advisory size argument is ignored in this case.\nSourceWrapper.prototype._read = function(size) {\n  this._source.readStart();\n};
    \n" } ] } ], "classes": [ { "textRaw": "Class: stream.Writable", "type": "class", "name": "stream.Writable", "desc": "

    stream.Writable is an abstract class designed to be extended with an\nunderlying implementation of the [_write(chunk, encoding, callback)][] method.\n\n

    \n

    Please see above under [API for Stream Consumers][] for how to consume\nwritable streams in your programs. What follows is an explanation of\nhow to implement Writable streams in your programs.\n\n

    \n", "methods": [ { "textRaw": "new stream.Writable([options])", "type": "method", "name": "Writable", "signatures": [ { "params": [ { "textRaw": "`options` {Object} ", "options": [ { "textRaw": "`highWaterMark` {Number} Buffer level when [`write()`][] starts returning false. Default=16kb ", "name": "highWaterMark", "type": "Number", "desc": "Buffer level when [`write()`][] starts returning false. Default=16kb" }, { "textRaw": "`decodeStrings` {Boolean} Whether or not to decode strings into Buffers before passing them to [`_write()`][]. Default=true ", "name": "decodeStrings", "type": "Boolean", "desc": "Whether or not to decode strings into Buffers before passing them to [`_write()`][]. Default=true" } ], "name": "options", "type": "Object", "optional": true } ] }, { "params": [ { "name": "options", "optional": true } ] } ], "desc": "

    In classes that extend the Writable class, make sure to call the\nconstructor so that the buffering settings can be properly\ninitialized.\n\n

    \n" }, { "textRaw": "writable.\\_write(chunk, encoding, callback)", "type": "method", "name": "\\_write", "signatures": [ { "params": [ { "textRaw": "`chunk` {Buffer | String} The chunk to be written. Will always be a buffer unless the `decodeStrings` option was set to `false`. ", "name": "chunk", "type": "Buffer | String", "desc": "The chunk to be written. Will always be a buffer unless the `decodeStrings` option was set to `false`." }, { "textRaw": "`encoding` {String} If the chunk is a string, then this is the encoding type. Ignore chunk is a buffer. Note that chunk will **always** be a buffer unless the `decodeStrings` option is explicitly set to `false`. ", "name": "encoding", "type": "String", "desc": "If the chunk is a string, then this is the encoding type. Ignore chunk is a buffer. Note that chunk will **always** be a buffer unless the `decodeStrings` option is explicitly set to `false`." }, { "textRaw": "`callback` {Function} Call this function (optionally with an error argument) when you are done processing the supplied chunk. ", "name": "callback", "type": "Function", "desc": "Call this function (optionally with an error argument) when you are done processing the supplied chunk." } ] }, { "params": [ { "name": "chunk" }, { "name": "encoding" }, { "name": "callback" } ] } ], "desc": "

    All Writable stream implementations must provide a [_write()][]\nmethod to send data to the underlying resource.\n\n

    \n

    Note: This function MUST NOT be called directly. It should be\nimplemented by child classes, and called by the internal Writable\nclass methods only.\n\n

    \n

    Call the callback using the standard callback(error) pattern to\nsignal that the write completed successfully or with an error.\n\n

    \n

    If the decodeStrings flag is set in the constructor options, then\nchunk may be a string rather than a Buffer, and encoding will\nindicate the sort of string that it is. This is to support\nimplementations that have an optimized handling for certain string\ndata encodings. If you do not explicitly set the decodeStrings\noption to false, then you can safely ignore the encoding argument,\nand assume that chunk will always be a Buffer.\n\n

    \n

    This method is prefixed with an underscore because it is internal to\nthe class that defines it, and should not be called directly by user\nprograms. However, you are expected to override this method in\nyour own extension classes.\n\n\n

    \n" } ] }, { "textRaw": "Class: stream.Duplex", "type": "class", "name": "stream.Duplex", "desc": "

    A "duplex" stream is one that is both Readable and Writable, such as a\nTCP socket connection.\n\n

    \n

    Note that stream.Duplex is an abstract class designed to be extended\nwith an underlying implementation of the _read(size) and\n[_write(chunk, encoding, callback)][] methods as you would with a\nReadable or Writable stream class.\n\n

    \n

    Since JavaScript doesn't have multiple prototypal inheritance, this\nclass prototypally inherits from Readable, and then parasitically from\nWritable. It is thus up to the user to implement both the lowlevel\n_read(n) method as well as the lowlevel\n[_write(chunk, encoding, callback)][] method on extension duplex classes.\n\n

    \n", "methods": [ { "textRaw": "new stream.Duplex(options)", "type": "method", "name": "Duplex", "signatures": [ { "params": [ { "textRaw": "`options` {Object} Passed to both Writable and Readable constructors. Also has the following fields: ", "options": [ { "textRaw": "`allowHalfOpen` {Boolean} Default=true. If set to `false`, then the stream will automatically end the readable side when the writable side ends and vice versa. ", "name": "allowHalfOpen", "type": "Boolean", "desc": "Default=true. If set to `false`, then the stream will automatically end the readable side when the writable side ends and vice versa." } ], "name": "options", "type": "Object", "desc": "Passed to both Writable and Readable constructors. Also has the following fields:" } ] }, { "params": [ { "name": "options" } ] } ], "desc": "

    In classes that extend the Duplex class, make sure to call the\nconstructor so that the buffering settings can be properly\ninitialized.\n\n\n

    \n" } ] }, { "textRaw": "Class: stream.Transform", "type": "class", "name": "stream.Transform", "desc": "

    A "transform" stream is a duplex stream where the output is causally\nconnected in some way to the input, such as a [zlib][] stream or a\n[crypto][] stream.\n\n

    \n

    There is no requirement that the output be the same size as the input,\nthe same number of chunks, or arrive at the same time. For example, a\nHash stream will only ever have a single chunk of output which is\nprovided when the input is ended. A zlib stream will produce output\nthat is either much smaller or much larger than its input.\n\n

    \n

    Rather than implement the [_read()][] and [_write()][] methods, Transform\nclasses must implement the _transform() method, and may optionally\nalso implement the _flush() method. (See below.)\n\n

    \n", "methods": [ { "textRaw": "new stream.Transform([options])", "type": "method", "name": "Transform", "signatures": [ { "params": [ { "textRaw": "`options` {Object} Passed to both Writable and Readable constructors. ", "name": "options", "type": "Object", "desc": "Passed to both Writable and Readable constructors.", "optional": true } ] }, { "params": [ { "name": "options", "optional": true } ] } ], "desc": "

    In classes that extend the Transform class, make sure to call the\nconstructor so that the buffering settings can be properly\ninitialized.\n\n

    \n" }, { "textRaw": "transform.\\_transform(chunk, encoding, callback)", "type": "method", "name": "\\_transform", "signatures": [ { "params": [ { "textRaw": "`chunk` {Buffer | String} The chunk to be transformed. Will always be a buffer unless the `decodeStrings` option was set to `false`. ", "name": "chunk", "type": "Buffer | String", "desc": "The chunk to be transformed. Will always be a buffer unless the `decodeStrings` option was set to `false`." }, { "textRaw": "`encoding` {String} If the chunk is a string, then this is the encoding type. (Ignore if `decodeStrings` chunk is a buffer.) ", "name": "encoding", "type": "String", "desc": "If the chunk is a string, then this is the encoding type. (Ignore if `decodeStrings` chunk is a buffer.)" }, { "textRaw": "`callback` {Function} Call this function (optionally with an error argument) when you are done processing the supplied chunk. ", "name": "callback", "type": "Function", "desc": "Call this function (optionally with an error argument) when you are done processing the supplied chunk." } ] }, { "params": [ { "name": "chunk" }, { "name": "encoding" }, { "name": "callback" } ] } ], "desc": "

    Note: This function MUST NOT be called directly. It should be\nimplemented by child classes, and called by the internal Transform\nclass methods only.\n\n

    \n

    All Transform stream implementations must provide a _transform\nmethod to accept input and produce output.\n\n

    \n

    _transform should do whatever has to be done in this specific\nTransform class, to handle the bytes being written, and pass them off\nto the readable portion of the interface. Do asynchronous I/O,\nprocess things, and so on.\n\n

    \n

    Call transform.push(outputChunk) 0 or more times to generate output\nfrom this input chunk, depending on how much data you want to output\nas a result of this chunk.\n\n

    \n

    Call the callback function only when the current chunk is completely\nconsumed. Note that there may or may not be output as a result of any\nparticular input chunk.\n\n

    \n

    This method is prefixed with an underscore because it is internal to\nthe class that defines it, and should not be called directly by user\nprograms. However, you are expected to override this method in\nyour own extension classes.\n\n

    \n" }, { "textRaw": "transform.\\_flush(callback)", "type": "method", "name": "\\_flush", "signatures": [ { "params": [ { "textRaw": "`callback` {Function} Call this function (optionally with an error argument) when you are done flushing any remaining data. ", "name": "callback", "type": "Function", "desc": "Call this function (optionally with an error argument) when you are done flushing any remaining data." } ] }, { "params": [ { "name": "callback" } ] } ], "desc": "

    Note: This function MUST NOT be called directly. It MAY be implemented\nby child classes, and if so, will be called by the internal Transform\nclass methods only.\n\n

    \n

    In some cases, your transform operation may need to emit a bit more\ndata at the end of the stream. For example, a Zlib compression\nstream will store up some internal state so that it can optimally\ncompress the output. At the end, however, it needs to do the best it\ncan with what is left, so that the data will be complete.\n\n

    \n

    In those cases, you can implement a _flush method, which will be\ncalled at the very end, after all the written data is consumed, but\nbefore emitting end to signal the end of the readable side. Just\nlike with _transform, call transform.push(chunk) zero or more\ntimes, as appropriate, and call callback when the flush operation is\ncomplete.\n\n

    \n

    This method is prefixed with an underscore because it is internal to\nthe class that defines it, and should not be called directly by user\nprograms. However, you are expected to override this method in\nyour own extension classes.\n\n

    \n

    Example: SimpleProtocol parser v2

    \n

    The example above of a simple protocol parser can be implemented\nsimply by using the higher level [Transform][] stream class, similar to\nthe parseHeader and SimpleProtocol v1 examples above.\n\n

    \n

    In this example, rather than providing the input as an argument, it\nwould be piped into the parser, which is a more idiomatic Node stream\napproach.\n\n

    \n
    var util = require('util');\nvar Transform = require('stream').Transform;\nutil.inherits(SimpleProtocol, Transform);\n\nfunction SimpleProtocol(options) {\n  if (!(this instanceof SimpleProtocol))\n    return new SimpleProtocol(options);\n\n  Transform.call(this, options);\n  this._inBody = false;\n  this._sawFirstCr = false;\n  this._rawHeader = [];\n  this.header = null;\n}\n\nSimpleProtocol.prototype._transform = function(chunk, encoding, done) {\n  if (!this._inBody) {\n    // check if the chunk has a \\n\\n\n    var split = -1;\n    for (var i = 0; i < chunk.length; i++) {\n      if (chunk[i] === 10) { // '\\n'\n        if (this._sawFirstCr) {\n          split = i;\n          break;\n        } else {\n          this._sawFirstCr = true;\n        }\n      } else {\n        this._sawFirstCr = false;\n      }\n    }\n\n    if (split === -1) {\n      // still waiting for the \\n\\n\n      // stash the chunk, and try again.\n      this._rawHeader.push(chunk);\n    } else {\n      this._inBody = true;\n      var h = chunk.slice(0, split);\n      this._rawHeader.push(h);\n      var header = Buffer.concat(this._rawHeader).toString();\n      try {\n        this.header = JSON.parse(header);\n      } catch (er) {\n        this.emit('error', new Error('invalid simple protocol data'));\n        return;\n      }\n      // and let them know that we are done parsing the header.\n      this.emit('header', this.header);\n\n      // now, because we got some extra data, emit this first.\n      this.push(chunk.slice(split));\n    }\n  } else {\n    // from there on, just provide the data to our consumer as-is.\n    this.push(chunk);\n  }\n  done();\n};\n\n// Usage:\n// var parser = new SimpleProtocol();\n// source.pipe(parser)\n// Now parser is a readable stream that will emit 'header'\n// with the parsed header data.
    \n" } ] }, { "textRaw": "Class: stream.PassThrough", "type": "class", "name": "stream.PassThrough", "desc": "

    This is a trivial implementation of a [Transform][] stream that simply\npasses the input bytes across to the output. Its purpose is mainly\nfor examples and testing, but there are occasionally use cases where\nit can come in handy as a building block for novel sorts of streams.\n\n\n

    \n" } ] }, { "textRaw": "Streams: Under the Hood", "name": "Streams: Under the Hood", "type": "misc", "miscs": [ { "textRaw": "Buffering", "name": "Buffering", "type": "misc", "desc": "

    Both Writable and Readable streams will buffer data on an internal\nobject called _writableState.buffer or _readableState.buffer,\nrespectively.\n\n

    \n

    The amount of data that will potentially be buffered depends on the\nhighWaterMark option which is passed into the constructor.\n\n

    \n

    Buffering in Readable streams happens when the implementation calls\n[stream.push(chunk)][]. If the consumer of the Stream does not call\nstream.read(), then the data will sit in the internal queue until it\nis consumed.\n\n

    \n

    Buffering in Writable streams happens when the user calls\n[stream.write(chunk)][] repeatedly, even when write() returns false.\n\n

    \n

    The purpose of streams, especially with the pipe() method, is to\nlimit the buffering of data to acceptable levels, so that sources and\ndestinations of varying speed will not overwhelm the available memory.\n\n

    \n" }, { "textRaw": "`stream.read(0)`", "name": "`stream.read(0)`", "desc": "

    There are some cases where you want to trigger a refresh of the\nunderlying readable stream mechanisms, without actually consuming any\ndata. In that case, you can call stream.read(0), which will always\nreturn null.\n\n

    \n

    If the internal read buffer is below the highWaterMark, and the\nstream is not currently reading, then calling read(0) will trigger\na low-level _read call.\n\n

    \n

    There is almost never a need to do this. However, you will see some\ncases in Node's internals where this is done, particularly in the\nReadable stream class internals.\n\n

    \n", "type": "misc", "displayName": "`stream.read(0)`" }, { "textRaw": "`stream.push('')`", "name": "`stream.push('')`", "desc": "

    Pushing a zero-byte string or Buffer (when not in [Object mode][]) has an\ninteresting side effect. Because it is a call to\n[stream.push()][], it will end the reading process. However, it\ndoes not add any data to the readable buffer, so there's nothing for\na user to consume.\n\n

    \n

    Very rarely, there are cases where you have no data to provide now,\nbut the consumer of your stream (or, perhaps, another bit of your own\ncode) will know when to check again, by calling stream.read(0). In\nthose cases, you may call stream.push('').\n\n

    \n

    So far, the only use case for this functionality is in the\n[tls.CryptoStream][] class, which is deprecated in Node v0.12. If you\nfind that you have to use stream.push(''), please consider another\napproach, because it almost certainly indicates that something is\nhorribly wrong.\n\n

    \n", "type": "misc", "displayName": "`stream.push('')`" }, { "textRaw": "Compatibility with Older Node Versions", "name": "Compatibility with Older Node Versions", "type": "misc", "desc": "

    In versions of Node prior to v0.10, the Readable stream interface was\nsimpler, but also less powerful and less useful.\n\n

    \n
      \n
    • Rather than waiting for you to call the read() method, 'data'\nevents would start emitting immediately. If you needed to do some\nI/O to decide how to handle data, then you had to store the chunks\nin some kind of buffer so that they would not be lost.
    • \n
    • The pause() method was advisory, rather than guaranteed. This\nmeant that you still had to be prepared to receive 'data' events\neven when the stream was in a paused state.
    • \n
    \n

    In Node v0.10, the Readable class described below was added. For\nbackwards compatibility with older Node programs, Readable streams\nswitch into "flowing mode" when a 'data' event handler is added, or\nwhen the pause() or resume() methods are called. The effect is\nthat, even if you are not using the new read() method and\n'readable' event, you no longer have to worry about losing 'data'\nchunks.\n\n

    \n

    Most programs will continue to function normally. However, this\nintroduces an edge case in the following conditions:\n\n

    \n
      \n
    • No 'data' event handler is added.
    • \n
    • The pause() and resume() methods are never called.
    • \n
    \n

    For example, consider the following code:\n\n

    \n
    // WARNING!  BROKEN!\nnet.createServer(function(socket) {\n\n  // we add an 'end' method, but never consume the data\n  socket.on('end', function() {\n    // It will never get here.\n    socket.end('I got your message (but didnt read it)\\n');\n  });\n\n}).listen(1337);
    \n

    In versions of node prior to v0.10, the incoming message data would be\nsimply discarded. However, in Node v0.10 and beyond, the socket will\nremain paused forever.\n\n

    \n

    The workaround in this situation is to call the resume() method to\ntrigger "old mode" behavior:\n\n

    \n
    // Workaround\nnet.createServer(function(socket) {\n\n  socket.on('end', function() {\n    socket.end('I got your message (but didnt read it)\\n');\n  });\n\n  // start the flow of data, discarding it.\n  socket.resume();\n\n}).listen(1337);
    \n

    In addition to new Readable streams switching into flowing-mode, pre-v0.10\nstyle streams can be wrapped in a Readable class using the wrap()\nmethod.\n\n\n

    \n" }, { "textRaw": "Object Mode", "name": "Object Mode", "type": "misc", "desc": "

    Normally, Streams operate on Strings and Buffers exclusively.\n\n

    \n

    Streams that are in object mode can emit generic JavaScript values\nother than Buffers and Strings.\n\n

    \n

    A Readable stream in object mode will always return a single item from\na call to stream.read(size), regardless of what the size argument\nis.\n\n

    \n

    A Writable stream in object mode will always ignore the encoding\nargument to stream.write(data, encoding).\n\n

    \n

    The special value null still retains its special value for object\nmode streams. That is, for object mode readable streams, null as a\nreturn value from stream.read() indicates that there is no more\ndata, and [stream.push(null)][] will signal the end of stream data\n(EOF).\n\n

    \n

    No streams in Node core are object mode streams. This pattern is only\nused by userland streaming libraries.\n\n

    \n

    You should set objectMode in your stream child class constructor on\nthe options object. Setting objectMode mid-stream is not safe.\n\n

    \n" }, { "textRaw": "State Objects", "name": "state_objects", "desc": "

    [Readable][] streams have a member object called _readableState.\n[Writable][] streams have a member object called _writableState.\n[Duplex][] streams have both.\n\n

    \n

    These objects should generally not be modified in child classes.\nHowever, if you have a Duplex or Transform stream that should be in\nobjectMode on the readable side, and not in objectMode on the\nwritable side, then you may do this in the constructor by setting the\nflag explicitly on the appropriate state object.\n\n

    \n
    var util = require('util');\nvar StringDecoder = require('string_decoder').StringDecoder;\nvar Transform = require('stream').Transform;\nutil.inherits(JSONParseStream, Transform);\n\n// Gets \\n-delimited JSON string data, and emits the parsed objects\nfunction JSONParseStream(options) {\n  if (!(this instanceof JSONParseStream))\n    return new JSONParseStream(options);\n\n  Transform.call(this, options);\n  this._writableState.objectMode = false;\n  this._readableState.objectMode = true;\n  this._buffer = '';\n  this._decoder = new StringDecoder('utf8');\n}\n\nJSONParseStream.prototype._transform = function(chunk, encoding, cb) {\n  this._buffer += this._decoder.write(chunk);\n  // split on newlines\n  var lines = this._buffer.split(/\\r?\\n/);\n  // keep the last partial line buffered\n  this._buffer = lines.pop();\n  for (var l = 0; l < lines.length; l++) {\n    var line = lines[l];\n    try {\n      var obj = JSON.parse(line);\n    } catch (er) {\n      this.emit('error', er);\n      return;\n    }\n    // push the parsed object out to the readable consumer\n    this.push(obj);\n  }\n  cb();\n};\n\nJSONParseStream.prototype._flush = function(cb) {\n  // Just handle any leftover\n  var rem = this._buffer.trim();\n  if (rem) {\n    try {\n      var obj = JSON.parse(rem);\n    } catch (er) {\n      this.emit('error', er);\n      return;\n    }\n    // push the parsed object out to the readable consumer\n    this.push(obj);\n  }\n  cb();\n};
    \n

    The state objects contain other useful information for debugging the\nstate of streams in your programs. It is safe to look at them, but\nbeyond setting option flags in the constructor, it is not safe to\nmodify them.\n\n\n

    \n", "type": "misc", "displayName": "State Objects" } ] } ], "examples": [ { "textRaw": "Class: stream.Readable", "type": "example", "name": "stream.Readable", "desc": "

    stream.Readable is an abstract class designed to be extended with an\nunderlying implementation of the [_read(size)][] method.\n\n

    \n

    Please see above under [API for Stream Consumers][] for how to consume\nstreams in your programs. What follows is an explanation of how to\nimplement Readable streams in your programs.\n\n

    \n

    Example: A Counting Stream

    \n

    This is a basic example of a Readable stream. It emits the numerals\nfrom 1 to 1,000,000 in ascending order, and then ends.\n\n

    \n
    var Readable = require('stream').Readable;\nvar util = require('util');\nutil.inherits(Counter, Readable);\n\nfunction Counter(opt) {\n  Readable.call(this, opt);\n  this._max = 1000000;\n  this._index = 1;\n}\n\nCounter.prototype._read = function() {\n  var i = this._index++;\n  if (i > this._max)\n    this.push(null);\n  else {\n    var str = '' + i;\n    var buf = new Buffer(str, 'ascii');\n    this.push(buf);\n  }\n};
    \n

    Example: SimpleProtocol v1 (Sub-optimal)

    \n

    This is similar to the parseHeader function described above, but\nimplemented as a custom stream. Also, note that this implementation\ndoes not convert the incoming data to a string.\n\n

    \n

    However, this would be better implemented as a [Transform][] stream. See\nbelow for a better implementation.\n\n

    \n
    // A parser for a simple data protocol.\n// The "header" is a JSON object, followed by 2 \\n characters, and\n// then a message body.\n//\n// NOTE: This can be done more simply as a Transform stream!\n// Using Readable directly for this is sub-optimal.  See the\n// alternative example below under the Transform section.\n\nvar Readable = require('stream').Readable;\nvar util = require('util');\n\nutil.inherits(SimpleProtocol, Readable);\n\nfunction SimpleProtocol(source, options) {\n  if (!(this instanceof SimpleProtocol))\n    return new SimpleProtocol(source, options);\n\n  Readable.call(this, options);\n  this._inBody = false;\n  this._sawFirstCr = false;\n\n  // source is a readable stream, such as a socket or file\n  this._source = source;\n\n  var self = this;\n  source.on('end', function() {\n    self.push(null);\n  });\n\n  // give it a kick whenever the source is readable\n  // read(0) will not consume any bytes\n  source.on('readable', function() {\n    self.read(0);\n  });\n\n  this._rawHeader = [];\n  this.header = null;\n}\n\nSimpleProtocol.prototype._read = function(n) {\n  if (!this._inBody) {\n    var chunk = this._source.read();\n\n    // if the source doesn't have data, we don't have data yet.\n    if (chunk === null)\n      return this.push('');\n\n    // check if the chunk has a \\n\\n\n    var split = -1;\n    for (var i = 0; i < chunk.length; i++) {\n      if (chunk[i] === 10) { // '\\n'\n        if (this._sawFirstCr) {\n          split = i;\n          break;\n        } else {\n          this._sawFirstCr = true;\n        }\n      } else {\n        this._sawFirstCr = false;\n      }\n    }\n\n    if (split === -1) {\n      // still waiting for the \\n\\n\n      // stash the chunk, and try again.\n      this._rawHeader.push(chunk);\n      this.push('');\n    } else {\n      this._inBody = true;\n      var h = chunk.slice(0, split);\n      this._rawHeader.push(h);\n      var header = Buffer.concat(this._rawHeader).toString();\n      try {\n        this.header = JSON.parse(header);\n      } catch (er) {\n        this.emit('error', new Error('invalid simple protocol data'));\n        return;\n      }\n      // now, because we got some extra data, unshift the rest\n      // back into the read queue so that our consumer will see it.\n      var b = chunk.slice(split);\n      this.unshift(b);\n\n      // and let them know that we are done parsing the header.\n      this.emit('header', this.header);\n    }\n  } else {\n    // from there on, just provide the data to our consumer.\n    // careful not to push(null), since that would indicate EOF.\n    var chunk = this._source.read();\n    if (chunk) this.push(chunk);\n  }\n};\n\n// Usage:\n// var parser = new SimpleProtocol(source);\n// Now parser is a readable stream that will emit 'header'\n// with the parsed header data.
    \n", "methods": [ { "textRaw": "new stream.Readable([options])", "type": "method", "name": "Readable", "signatures": [ { "params": [ { "textRaw": "`options` {Object} ", "options": [ { "textRaw": "`highWaterMark` {Number} The maximum number of bytes to store in the internal buffer before ceasing to read from the underlying resource. Default=16kb ", "name": "highWaterMark", "type": "Number", "desc": "The maximum number of bytes to store in the internal buffer before ceasing to read from the underlying resource. Default=16kb" }, { "textRaw": "`encoding` {String} If specified, then buffers will be decoded to strings using the specified encoding. Default=null ", "name": "encoding", "type": "String", "desc": "If specified, then buffers will be decoded to strings using the specified encoding. Default=null" }, { "textRaw": "`objectMode` {Boolean} Whether this stream should behave as a stream of objects. Meaning that stream.read(n) returns a single value instead of a Buffer of size n. Default=false ", "name": "objectMode", "type": "Boolean", "desc": "Whether this stream should behave as a stream of objects. Meaning that stream.read(n) returns a single value instead of a Buffer of size n. Default=false" } ], "name": "options", "type": "Object", "optional": true } ] }, { "params": [ { "name": "options", "optional": true } ] } ], "desc": "

    In classes that extend the Readable class, make sure to call the\nReadable constructor so that the buffering settings can be properly\ninitialized.\n\n

    \n" }, { "textRaw": "readable.\\_read(size)", "type": "method", "name": "\\_read", "signatures": [ { "params": [ { "textRaw": "`size` {Number} Number of bytes to read asynchronously ", "name": "size", "type": "Number", "desc": "Number of bytes to read asynchronously" } ] }, { "params": [ { "name": "size" } ] } ], "desc": "

    Note: Implement this function, but do NOT call it directly.\n\n

    \n

    This function should NOT be called directly. It should be implemented\nby child classes, and only called by the internal Readable class\nmethods.\n\n

    \n

    All Readable stream implementations must provide a _read method to\nfetch data from the underlying resource.\n\n

    \n

    This method is prefixed with an underscore because it is internal to\nthe class that defines it, and should not be called directly by user\nprograms. However, you are expected to override this method in\nyour own extension classes.\n\n

    \n

    When data is available, put it into the read queue by calling\nreadable.push(chunk). If push returns false, then you should stop\nreading. When _read is called again, you should start pushing more\ndata.\n\n

    \n

    The size argument is advisory. Implementations where a "read" is a\nsingle call that returns data can use this to know how much data to\nfetch. Implementations where that is not relevant, such as TCP or\nTLS, may ignore this argument, and simply provide data whenever it\nbecomes available. There is no need, for example to "wait" until\nsize bytes are available before calling [stream.push(chunk)][].\n\n

    \n" }, { "textRaw": "readable.push(chunk, [encoding])", "type": "method", "name": "push", "signatures": [ { "return": { "textRaw": "return {Boolean} Whether or not more pushes should be performed ", "name": "return", "type": "Boolean", "desc": "Whether or not more pushes should be performed" }, "params": [ { "textRaw": "`chunk` {Buffer | null | String} Chunk of data to push into the read queue ", "name": "chunk", "type": "Buffer | null | String", "desc": "Chunk of data to push into the read queue" }, { "textRaw": "`encoding` {String} Encoding of String chunks. Must be a valid Buffer encoding, such as `'utf8'` or `'ascii'` ", "name": "encoding", "type": "String", "desc": "Encoding of String chunks. Must be a valid Buffer encoding, such as `'utf8'` or `'ascii'`", "optional": true } ] }, { "params": [ { "name": "chunk" }, { "name": "encoding", "optional": true } ] } ], "desc": "

    Note: This function should be called by Readable implementors, NOT\nby consumers of Readable streams.\n\n

    \n

    The _read() function will not be called again until at least one\npush(chunk) call is made.\n\n

    \n

    The Readable class works by putting data into a read queue to be\npulled out later by calling the read() method when the 'readable'\nevent fires.\n\n

    \n

    The push() method will explicitly insert some data into the read\nqueue. If it is called with null then it will signal the end of the\ndata (EOF).\n\n

    \n

    This API is designed to be as flexible as possible. For example,\nyou may be wrapping a lower-level source which has some sort of\npause/resume mechanism, and a data callback. In those cases, you\ncould wrap the low-level source object by doing something like this:\n\n

    \n
    // source is an object with readStop() and readStart() methods,\n// and an `ondata` member that gets called when it has data, and\n// an `onend` member that gets called when the data is over.\n\nutil.inherits(SourceWrapper, Readable);\n\nfunction SourceWrapper(options) {\n  Readable.call(this, options);\n\n  this._source = getLowlevelSourceObject();\n  var self = this;\n\n  // Every time there's data, we push it into the internal buffer.\n  this._source.ondata = function(chunk) {\n    // if push() returns false, then we need to stop reading from source\n    if (!self.push(chunk))\n      self._source.readStop();\n  };\n\n  // When the source ends, we push the EOF-signalling `null` chunk\n  this._source.onend = function() {\n    self.push(null);\n  };\n}\n\n// _read will be called when the stream wants to pull more data in\n// the advisory size argument is ignored in this case.\nSourceWrapper.prototype._read = function(size) {\n  this._source.readStart();\n};
    \n" } ] } ], "type": "module", "displayName": "Stream" } ] } node-v0.10.25~dfsg2/doc/api/repl.html0000644000000000000000000002645112270264601015772 0ustar rootroot REPL Node.js v0.10.25 Manual & Documentation

    Node.js v0.10.25 Manual & Documentation


    REPL#

    A Read-Eval-Print-Loop (REPL) is available both as a standalone program and easily includable in other programs. The REPL provides a way to interactively run JavaScript and see the results. It can be used for debugging, testing, or just trying things out.

    By executing node without any arguments from the command-line you will be dropped into the REPL. It has simplistic emacs line-editing.

    mjr:~$ node
    Type '.help' for options.
    > a = [ 1, 2, 3];
    [ 1, 2, 3 ]
    > a.forEach(function (v) {
    ...   console.log(v);
    ...   });
    1
    2
    3

    For advanced line-editors, start node with the environmental variable NODE_NO_READLINE=1. This will start the main and debugger REPL in canonical terminal settings which will allow you to use with rlwrap.

    For example, you could add this to your bashrc file:

    alias node="env NODE_NO_READLINE=1 rlwrap node"

    repl.start(options)#

    Returns and starts a REPLServer instance. Accepts an "options" Object that takes the following values:

    • prompt - the prompt and stream for all I/O. Defaults to > .

    • input - the readable stream to listen to. Defaults to process.stdin.

    • output - the writable stream to write readline data to. Defaults to process.stdout.

    • terminal - pass true if the stream should be treated like a TTY, and have ANSI/VT100 escape codes written to it. Defaults to checking isTTY on the output stream upon instantiation.

    • eval - function that will be used to eval each given line. Defaults to an async wrapper for eval(). See below for an example of a custom eval.

    • useColors - a boolean which specifies whether or not the writer function should output colors. If a different writer function is set then this does nothing. Defaults to the repl's terminal value.

    • useGlobal - if set to true, then the repl will use the global object, instead of running scripts in a separate context. Defaults to false.

    • ignoreUndefined - if set to true, then the repl will not output the return value of command if it's undefined. Defaults to false.

    • writer - the function to invoke for each command that gets evaluated which returns the formatting (including coloring) to display. Defaults to util.inspect.

    You can use your own eval function if it has following signature:

    function eval(cmd, context, filename, callback) {
      callback(null, result);
    }

    Multiple REPLs may be started against the same running instance of node. Each will share the same global object but will have unique I/O.

    Here is an example that starts a REPL on stdin, a Unix socket, and a TCP socket:

    var net = require("net"),
        repl = require("repl");
    
    connections = 0;
    
    repl.start({
      prompt: "node via stdin> ",
      input: process.stdin,
      output: process.stdout
    });
    
    net.createServer(function (socket) {
      connections += 1;
      repl.start({
        prompt: "node via Unix socket> ",
        input: socket,
        output: socket
      }).on('exit', function() {
        socket.end();
      })
    }).listen("/tmp/node-repl-sock");
    
    net.createServer(function (socket) {
      connections += 1;
      repl.start({
        prompt: "node via TCP socket> ",
        input: socket,
        output: socket
      }).on('exit', function() {
        socket.end();
      });
    }).listen(5001);

    Running this program from the command line will start a REPL on stdin. Other REPL clients may connect through the Unix socket or TCP socket. telnet is useful for connecting to TCP sockets, and socat can be used to connect to both Unix and TCP sockets.

    By starting a REPL from a Unix socket-based server instead of stdin, you can connect to a long-running node process without restarting it.

    For an example of running a "full-featured" (terminal) REPL over a net.Server and net.Socket instance, see: https://gist.github.com/2209310

    For an example of running a REPL instance over curl(1), see: https://gist.github.com/2053342

    Event: 'exit'#

    function () {}

    Emitted when the user exits the REPL in any of the defined ways. Namely, typing .exit at the repl, pressing Ctrl+C twice to signal SIGINT, or pressing Ctrl+D to signal "end" on the input stream.

    Example of listening for exit:

    r.on('exit', function () {
      console.log('Got "exit" event from repl!');
      process.exit();
    });

    REPL Features#

    Inside the REPL, Control+D will exit. Multi-line expressions can be input. Tab completion is supported for both global and local variables.

    The special variable _ (underscore) contains the result of the last expression.

    > [ "a", "b", "c" ]
    [ 'a', 'b', 'c' ]
    > _.length
    3
    > _ += 1
    4

    The REPL provides access to any variables in the global scope. You can expose a variable to the REPL explicitly by assigning it to the context object associated with each REPLServer. For example:

    // repl_test.js
    var repl = require("repl"),
        msg = "message";
    
    repl.start("> ").context.m = msg;

    Things in the context object appear as local within the REPL:

    mjr:~$ node repl_test.js
    > m
    'message'

    There are a few special REPL commands:

    • .break - While inputting a multi-line expression, sometimes you get lost or just don't care about completing it. .break will start over.
    • .clear - Resets the context object to an empty object and clears any multi-line expression.
    • .exit - Close the I/O stream, which will cause the REPL to exit.
    • .help - Show this list of special commands.
    • .save - Save the current REPL session to a file

      .save ./file/to/save.js

    • .load - Load a file into the current REPL session.

      .load ./file/to/load.js

    The following key combinations in the REPL have these special effects:

    • <ctrl>C - Similar to the .break keyword. Terminates the current command. Press twice on a blank line to forcibly exit.
    • <ctrl>D - Similar to the .exit keyword.
    node-v0.10.25~dfsg2/doc/api/os.html0000644000000000000000000002304212270264601015442 0ustar rootroot os Node.js v0.10.25 Manual & Documentation

    Node.js v0.10.25 Manual & Documentation


    os#

    Stability: 4 - API Frozen

    Provides a few basic operating-system related utility functions.

    Use require('os') to access this module.

    os.tmpdir()#

    Returns the operating system's default directory for temp files.

    os.endianness()#

    Returns the endianness of the CPU. Possible values are "BE" or "LE".

    os.hostname()#

    Returns the hostname of the operating system.

    os.type()#

    Returns the operating system name.

    os.platform()#

    Returns the operating system platform.

    os.arch()#

    Returns the operating system CPU architecture.

    os.release()#

    Returns the operating system release.

    os.uptime()#

    Returns the system uptime in seconds.

    os.loadavg()#

    Returns an array containing the 1, 5, and 15 minute load averages.

    The load average is a measure of system activity, calculated by the operating system and expressed as a fractional number. As a rule of thumb, the load average should ideally be less than the number of logical CPUs in the system.

    The load average is a very UNIX-y concept; there is no real equivalent on Windows platforms. That is why this function always returns [0, 0, 0] on Windows.

    os.totalmem()#

    Returns the total amount of system memory in bytes.

    os.freemem()#

    Returns the amount of free system memory in bytes.

    os.cpus()#

    Returns an array of objects containing information about each CPU/core installed: model, speed (in MHz), and times (an object containing the number of milliseconds the CPU/core spent in: user, nice, sys, idle, and irq).

    Example inspection of os.cpus:

    [ { model: 'Intel(R) Core(TM) i7 CPU         860  @ 2.80GHz',
        speed: 2926,
        times:
         { user: 252020,
           nice: 0,
           sys: 30340,
           idle: 1070356870,
           irq: 0 } },
      { model: 'Intel(R) Core(TM) i7 CPU         860  @ 2.80GHz',
        speed: 2926,
        times:
         { user: 306960,
           nice: 0,
           sys: 26980,
           idle: 1071569080,
           irq: 0 } },
      { model: 'Intel(R) Core(TM) i7 CPU         860  @ 2.80GHz',
        speed: 2926,
        times:
         { user: 248450,
           nice: 0,
           sys: 21750,
           idle: 1070919370,
           irq: 0 } },
      { model: 'Intel(R) Core(TM) i7 CPU         860  @ 2.80GHz',
        speed: 2926,
        times:
         { user: 256880,
           nice: 0,
           sys: 19430,
           idle: 1070905480,
           irq: 20 } },
      { model: 'Intel(R) Core(TM) i7 CPU         860  @ 2.80GHz',
        speed: 2926,
        times:
         { user: 511580,
           nice: 20,
           sys: 40900,
           idle: 1070842510,
           irq: 0 } },
      { model: 'Intel(R) Core(TM) i7 CPU         860  @ 2.80GHz',
        speed: 2926,
        times:
         { user: 291660,
           nice: 0,
           sys: 34360,
           idle: 1070888000,
           irq: 10 } },
      { model: 'Intel(R) Core(TM) i7 CPU         860  @ 2.80GHz',
        speed: 2926,
        times:
         { user: 308260,
           nice: 0,
           sys: 55410,
           idle: 1071129970,
           irq: 880 } },
      { model: 'Intel(R) Core(TM) i7 CPU         860  @ 2.80GHz',
        speed: 2926,
        times:
         { user: 266450,
           nice: 1480,
           sys: 34920,
           idle: 1072572010,
           irq: 30 } } ]

    os.networkInterfaces()#

    Get a list of network interfaces:

    { lo0: 
       [ { address: '::1', family: 'IPv6', internal: true },
         { address: 'fe80::1', family: 'IPv6', internal: true },
         { address: '127.0.0.1', family: 'IPv4', internal: true } ],
      en1: 
       [ { address: 'fe80::cabc:c8ff:feef:f996', family: 'IPv6',
           internal: false },
         { address: '10.0.1.123', family: 'IPv4', internal: false } ],
      vmnet1: [ { address: '10.99.99.254', family: 'IPv4', internal: false } ],
      vmnet8: [ { address: '10.88.88.1', family: 'IPv4', internal: false } ],
      ppp0: [ { address: '10.2.0.231', family: 'IPv4', internal: false } ] }

    os.EOL#

    A constant defining the appropriate End-of-line marker for the operating system.

    node-v0.10.25~dfsg2/doc/api/tls.json0000644000000000000000000010552112270264601015633 0ustar rootroot{ "source": "doc/api/tls.markdown", "modules": [ { "textRaw": "TLS (SSL)", "name": "tls_(ssl)", "stability": 3, "stabilityText": "Stable", "desc": "

    Use require('tls') to access this module.\n\n

    \n

    The tls module uses OpenSSL to provide Transport Layer Security and/or\nSecure Socket Layer: encrypted stream communication.\n\n

    \n

    TLS/SSL is a public/private key infrastructure. Each client and each\nserver must have a private key. A private key is created like this\n\n

    \n
    openssl genrsa -out ryans-key.pem 1024
    \n

    All severs and some clients need to have a certificate. Certificates are public\nkeys signed by a Certificate Authority or self-signed. The first step to\ngetting a certificate is to create a "Certificate Signing Request" (CSR)\nfile. This is done with:\n\n

    \n
    openssl req -new -key ryans-key.pem -out ryans-csr.pem
    \n

    To create a self-signed certificate with the CSR, do this:\n\n

    \n
    openssl x509 -req -in ryans-csr.pem -signkey ryans-key.pem -out ryans-cert.pem
    \n

    Alternatively you can send the CSR to a Certificate Authority for signing.\n\n

    \n

    (TODO: docs on creating a CA, for now interested users should just look at\ntest/fixtures/keys/Makefile in the Node source code)\n\n

    \n

    To create .pfx or .p12, do this:\n\n

    \n
    openssl pkcs12 -export -in agent5-cert.pem -inkey agent5-key.pem \\\n    -certfile ca-cert.pem -out agent5.pfx
    \n
      \n
    • in: certificate
    • \n
    • inkey: private key
    • \n
    • certfile: all CA certs concatenated in one file like\ncat ca1-cert.pem ca2-cert.pem > ca-cert.pem
    • \n
    \n", "miscs": [ { "textRaw": "Client-initiated renegotiation attack mitigation", "name": "Client-initiated renegotiation attack mitigation", "type": "misc", "desc": "

    The TLS protocol lets the client renegotiate certain aspects of the TLS session.\nUnfortunately, session renegotiation requires a disproportional amount of\nserver-side resources, which makes it a potential vector for denial-of-service\nattacks.\n\n

    \n

    To mitigate this, renegotiations are limited to three times every 10 minutes. An\nerror is emitted on the [CleartextStream][] instance when the threshold is\nexceeded. The limits are configurable:\n\n

    \n
      \n
    • tls.CLIENT_RENEG_LIMIT: renegotiation limit, default is 3.

      \n
    • \n
    • tls.CLIENT_RENEG_WINDOW: renegotiation window in seconds, default is\n10 minutes.

      \n
    • \n
    \n

    Don't change the defaults unless you know what you are doing.\n\n

    \n

    To test your server, connect to it with openssl s_client -connect address:port\nand tap R<CR> (that's the letter R followed by a carriage return) a few\ntimes.\n\n\n

    \n" }, { "textRaw": "NPN and SNI", "name": "NPN and SNI", "type": "misc", "desc": "

    NPN (Next Protocol Negotiation) and SNI (Server Name Indication) are TLS\nhandshake extensions allowing you:\n\n

    \n
      \n
    • NPN - to use one TLS server for multiple protocols (HTTP, SPDY)
    • \n
    • SNI - to use one TLS server for multiple hostnames with different SSL\ncertificates.
    • \n
    \n" } ], "methods": [ { "textRaw": "tls.getCiphers()", "type": "method", "name": "getCiphers", "desc": "

    Returns an array with the names of the supported SSL ciphers.\n\n

    \n

    Example:\n\n

    \n
    var ciphers = tls.getCiphers();\nconsole.log(ciphers); // ['AES128-SHA', 'AES256-SHA', ...]
    \n", "signatures": [ { "params": [] } ] }, { "textRaw": "tls.createServer(options, [secureConnectionListener])", "type": "method", "name": "createServer", "desc": "

    Creates a new [tls.Server][]. The connectionListener argument is\nautomatically set as a listener for the [secureConnection][] event. The\noptions object has these possibilities:\n\n

    \n
      \n
    • pfx: A string or Buffer containing the private key, certificate and\nCA certs of the server in PFX or PKCS12 format. (Mutually exclusive with\nthe key, cert and ca options.)

      \n
    • \n
    • key: A string or Buffer containing the private key of the server in\nPEM format. (Required)

      \n
    • \n
    • passphrase: A string of passphrase for the private key or pfx.

      \n
    • \n
    • cert: A string or Buffer containing the certificate key of the server in\nPEM format. (Required)

      \n
    • \n
    • ca: An array of strings or Buffers of trusted certificates in PEM\nformat. If this is omitted several well known "root" CAs will be used,\nlike VeriSign. These are used to authorize connections.

      \n
    • \n
    • crl : Either a string or list of strings of PEM encoded CRLs (Certificate\nRevocation List)

      \n
    • \n
    • ciphers: A string describing the ciphers to use or exclude.

      \n

      To mitigate [BEAST attacks] it is recommended that you use this option in\nconjunction with the honorCipherOrder option described below to\nprioritize the non-CBC cipher.

      \n

      Defaults to AES128-GCM-SHA256:RC4:HIGH:!MD5:!aNULL:!EDH.\nConsult the [OpenSSL cipher list format documentation] for details on the\nformat. ECDH (Elliptic Curve Diffie-Hellman) ciphers are not yet supported.

      \n
    • \n
    \n
    `AES128-GCM-SHA256` is used when node.js is linked against OpenSSL 1.0.1\nor newer and the client speaks TLS 1.2, RC4 is used as a secure fallback.\n\n**NOTE**: Previous revisions of this section suggested `AES256-SHA` as an\nacceptable cipher. Unfortunately, `AES256-SHA` is a CBC cipher and therefore\nsusceptible to BEAST attacks. Do *not* use it.
    \n
      \n
    • handshakeTimeout: Abort the connection if the SSL/TLS handshake does not\nfinish in this many milliseconds. The default is 120 seconds.

      \n

      A 'clientError' is emitted on the tls.Server object whenever a handshake\ntimes out.

      \n
    • \n
    • honorCipherOrder : When choosing a cipher, use the server's preferences\ninstead of the client preferences.

      \n

      Note that if SSLv2 is used, the server will send its list of preferences\nto the client, and the client chooses the cipher.

      \n

      Although, this option is disabled by default, it is recommended that you\nuse this option in conjunction with the ciphers option to mitigate\nBEAST attacks.

      \n
    • \n
    • requestCert: If true the server will request a certificate from\nclients that connect and attempt to verify that certificate. Default:\nfalse.

      \n
    • \n
    • rejectUnauthorized: If true the server will reject any connection\nwhich is not authorized with the list of supplied CAs. This option only\nhas an effect if requestCert is true. Default: false.

      \n
    • \n
    • NPNProtocols: An array or Buffer of possible NPN protocols. (Protocols\nshould be ordered by their priority).

      \n
    • \n
    • SNICallback: A function that will be called if client supports SNI TLS\nextension. Only one argument will be passed to it: servername. And\nSNICallback should return SecureContext instance.\n(You can use crypto.createCredentials(...).context to get proper\nSecureContext). If SNICallback wasn't provided - default callback with\nhigh-level API will be used (see below).

      \n
    • \n
    • sessionIdContext: A string containing a opaque identifier for session\nresumption. If requestCert is true, the default is MD5 hash value\ngenerated from command-line. Otherwise, the default is not provided.

      \n
    • \n
    • secureProtocol: The SSL method to use, e.g. SSLv3_method to force\nSSL version 3. The possible values depend on your installation of\nOpenSSL and are defined in the constant [SSL_METHODS][].

      \n
    • \n
    \n

    Here is a simple example echo server:\n\n

    \n
    var tls = require('tls');\nvar fs = require('fs');\n\nvar options = {\n  key: fs.readFileSync('server-key.pem'),\n  cert: fs.readFileSync('server-cert.pem'),\n\n  // This is necessary only if using the client certificate authentication.\n  requestCert: true,\n\n  // This is necessary only if the client uses the self-signed certificate.\n  ca: [ fs.readFileSync('client-cert.pem') ]\n};\n\nvar server = tls.createServer(options, function(cleartextStream) {\n  console.log('server connected',\n              cleartextStream.authorized ? 'authorized' : 'unauthorized');\n  cleartextStream.write("welcome!\\n");\n  cleartextStream.setEncoding('utf8');\n  cleartextStream.pipe(cleartextStream);\n});\nserver.listen(8000, function() {\n  console.log('server bound');\n});
    \n

    Or\n\n

    \n
    var tls = require('tls');\nvar fs = require('fs');\n\nvar options = {\n  pfx: fs.readFileSync('server.pfx'),\n\n  // This is necessary only if using the client certificate authentication.\n  requestCert: true,\n\n};\n\nvar server = tls.createServer(options, function(cleartextStream) {\n  console.log('server connected',\n              cleartextStream.authorized ? 'authorized' : 'unauthorized');\n  cleartextStream.write("welcome!\\n");\n  cleartextStream.setEncoding('utf8');\n  cleartextStream.pipe(cleartextStream);\n});\nserver.listen(8000, function() {\n  console.log('server bound');\n});
    \n

    You can test this server by connecting to it with openssl s_client:\n\n\n

    \n
    openssl s_client -connect 127.0.0.1:8000
    \n", "signatures": [ { "params": [ { "name": "options" }, { "name": "secureConnectionListener", "optional": true } ] } ] }, { "textRaw": "tls.connect(options, [callback])", "type": "method", "name": "connect", "desc": "

    Creates a new client connection to the given port and host (old API) or\noptions.port and options.host. (If host is omitted, it defaults to\nlocalhost.) options should be an object which specifies:\n\n

    \n
      \n
    • host: Host the client should connect to

      \n
    • \n
    • port: Port the client should connect to

      \n
    • \n
    • socket: Establish secure connection on a given socket rather than\ncreating a new socket. If this option is specified, host and port\nare ignored.

      \n
    • \n
    • pfx: A string or Buffer containing the private key, certificate and\nCA certs of the server in PFX or PKCS12 format.

      \n
    • \n
    • key: A string or Buffer containing the private key of the client in\nPEM format.

      \n
    • \n
    • passphrase: A string of passphrase for the private key or pfx.

      \n
    • \n
    • cert: A string or Buffer containing the certificate key of the client in\nPEM format.

      \n
    • \n
    • ca: An array of strings or Buffers of trusted certificates in PEM\nformat. If this is omitted several well known "root" CAs will be used,\nlike VeriSign. These are used to authorize connections.

      \n
    • \n
    • rejectUnauthorized: If true, the server certificate is verified against\nthe list of supplied CAs. An 'error' event is emitted if verification\nfails. Default: true.

      \n
    • \n
    • NPNProtocols: An array of strings or Buffers containing supported NPN\nprotocols. Buffers should have following format: 0x05hello0x05world,\nwhere first byte is next protocol name's length. (Passing array should\nusually be much simpler: ['hello', 'world'].)

      \n
    • \n
    • servername: Servername for SNI (Server Name Indication) TLS extension.

      \n
    • \n
    • secureProtocol: The SSL method to use, e.g. SSLv3_method to force\nSSL version 3. The possible values depend on your installation of\nOpenSSL and are defined in the constant [SSL_METHODS][].

      \n
    • \n
    \n

    The callback parameter will be added as a listener for the\n['secureConnect'][] event.\n\n

    \n

    tls.connect() returns a [CleartextStream][] object.\n\n

    \n

    Here is an example of a client of echo server as described previously:\n\n

    \n
    var tls = require('tls');\nvar fs = require('fs');\n\nvar options = {\n  // These are necessary only if using the client certificate authentication\n  key: fs.readFileSync('client-key.pem'),\n  cert: fs.readFileSync('client-cert.pem'),\n\n  // This is necessary only if the server uses the self-signed certificate\n  ca: [ fs.readFileSync('server-cert.pem') ]\n};\n\nvar cleartextStream = tls.connect(8000, options, function() {\n  console.log('client connected',\n              cleartextStream.authorized ? 'authorized' : 'unauthorized');\n  process.stdin.pipe(cleartextStream);\n  process.stdin.resume();\n});\ncleartextStream.setEncoding('utf8');\ncleartextStream.on('data', function(data) {\n  console.log(data);\n});\ncleartextStream.on('end', function() {\n  server.close();\n});
    \n

    Or\n\n

    \n
    var tls = require('tls');\nvar fs = require('fs');\n\nvar options = {\n  pfx: fs.readFileSync('client.pfx')\n};\n\nvar cleartextStream = tls.connect(8000, options, function() {\n  console.log('client connected',\n              cleartextStream.authorized ? 'authorized' : 'unauthorized');\n  process.stdin.pipe(cleartextStream);\n  process.stdin.resume();\n});\ncleartextStream.setEncoding('utf8');\ncleartextStream.on('data', function(data) {\n  console.log(data);\n});\ncleartextStream.on('end', function() {\n  server.close();\n});
    \n", "signatures": [ { "params": [ { "name": "port" }, { "name": "host", "optional": true }, { "name": "options", "optional": true }, { "name": "callback", "optional": true } ] }, { "params": [ { "name": "options" }, { "name": "callback", "optional": true } ] } ] }, { "textRaw": "tls.connect(port, [host], [options], [callback])", "type": "method", "name": "connect", "desc": "

    Creates a new client connection to the given port and host (old API) or\noptions.port and options.host. (If host is omitted, it defaults to\nlocalhost.) options should be an object which specifies:\n\n

    \n
      \n
    • host: Host the client should connect to

      \n
    • \n
    • port: Port the client should connect to

      \n
    • \n
    • socket: Establish secure connection on a given socket rather than\ncreating a new socket. If this option is specified, host and port\nare ignored.

      \n
    • \n
    • pfx: A string or Buffer containing the private key, certificate and\nCA certs of the server in PFX or PKCS12 format.

      \n
    • \n
    • key: A string or Buffer containing the private key of the client in\nPEM format.

      \n
    • \n
    • passphrase: A string of passphrase for the private key or pfx.

      \n
    • \n
    • cert: A string or Buffer containing the certificate key of the client in\nPEM format.

      \n
    • \n
    • ca: An array of strings or Buffers of trusted certificates in PEM\nformat. If this is omitted several well known "root" CAs will be used,\nlike VeriSign. These are used to authorize connections.

      \n
    • \n
    • rejectUnauthorized: If true, the server certificate is verified against\nthe list of supplied CAs. An 'error' event is emitted if verification\nfails. Default: true.

      \n
    • \n
    • NPNProtocols: An array of strings or Buffers containing supported NPN\nprotocols. Buffers should have following format: 0x05hello0x05world,\nwhere first byte is next protocol name's length. (Passing array should\nusually be much simpler: ['hello', 'world'].)

      \n
    • \n
    • servername: Servername for SNI (Server Name Indication) TLS extension.

      \n
    • \n
    • secureProtocol: The SSL method to use, e.g. SSLv3_method to force\nSSL version 3. The possible values depend on your installation of\nOpenSSL and are defined in the constant [SSL_METHODS][].

      \n
    • \n
    \n

    The callback parameter will be added as a listener for the\n['secureConnect'][] event.\n\n

    \n

    tls.connect() returns a [CleartextStream][] object.\n\n

    \n

    Here is an example of a client of echo server as described previously:\n\n

    \n
    var tls = require('tls');\nvar fs = require('fs');\n\nvar options = {\n  // These are necessary only if using the client certificate authentication\n  key: fs.readFileSync('client-key.pem'),\n  cert: fs.readFileSync('client-cert.pem'),\n\n  // This is necessary only if the server uses the self-signed certificate\n  ca: [ fs.readFileSync('server-cert.pem') ]\n};\n\nvar cleartextStream = tls.connect(8000, options, function() {\n  console.log('client connected',\n              cleartextStream.authorized ? 'authorized' : 'unauthorized');\n  process.stdin.pipe(cleartextStream);\n  process.stdin.resume();\n});\ncleartextStream.setEncoding('utf8');\ncleartextStream.on('data', function(data) {\n  console.log(data);\n});\ncleartextStream.on('end', function() {\n  server.close();\n});
    \n

    Or\n\n

    \n
    var tls = require('tls');\nvar fs = require('fs');\n\nvar options = {\n  pfx: fs.readFileSync('client.pfx')\n};\n\nvar cleartextStream = tls.connect(8000, options, function() {\n  console.log('client connected',\n              cleartextStream.authorized ? 'authorized' : 'unauthorized');\n  process.stdin.pipe(cleartextStream);\n  process.stdin.resume();\n});\ncleartextStream.setEncoding('utf8');\ncleartextStream.on('data', function(data) {\n  console.log(data);\n});\ncleartextStream.on('end', function() {\n  server.close();\n});
    \n", "signatures": [ { "params": [ { "name": "port" }, { "name": "host", "optional": true }, { "name": "options", "optional": true }, { "name": "callback", "optional": true } ] } ] }, { "textRaw": "tls.createSecurePair([credentials], [isServer], [requestCert], [rejectUnauthorized])", "type": "method", "name": "createSecurePair", "desc": "

    Creates a new secure pair object with two streams, one of which reads/writes\nencrypted data, and one reads/writes cleartext data.\nGenerally the encrypted one is piped to/from an incoming encrypted data stream,\nand the cleartext one is used as a replacement for the initial encrypted stream.\n\n

    \n
      \n
    • credentials: A credentials object from crypto.createCredentials( ... )

      \n
    • \n
    • isServer: A boolean indicating whether this tls connection should be\nopened as a server or a client.

      \n
    • \n
    • requestCert: A boolean indicating whether a server should request a\ncertificate from a connecting client. Only applies to server connections.

      \n
    • \n
    • rejectUnauthorized: A boolean indicating whether a server should\nautomatically reject clients with invalid certificates. Only applies to\nservers with requestCert enabled.

      \n
    • \n
    \n

    tls.createSecurePair() returns a SecurePair object with [cleartext][] and\nencrypted stream properties.\n\n

    \n", "signatures": [ { "params": [ { "name": "credentials", "optional": true }, { "name": "isServer", "optional": true }, { "name": "requestCert", "optional": true }, { "name": "rejectUnauthorized", "optional": true } ] } ] } ], "properties": [ { "textRaw": "tls.SLAB_BUFFER_SIZE", "name": "SLAB_BUFFER_SIZE", "desc": "

    Size of slab buffer used by all tls servers and clients.\nDefault: 10 * 1024 * 1024.\n\n\n

    \n

    Don't change the defaults unless you know what you are doing.\n\n\n

    \n" } ], "classes": [ { "textRaw": "Class: SecurePair", "type": "class", "name": "SecurePair", "desc": "

    Returned by tls.createSecurePair.\n\n

    \n", "events": [ { "textRaw": "Event: 'secure'", "type": "event", "name": "secure", "desc": "

    The event is emitted from the SecurePair once the pair has successfully\nestablished a secure connection.\n\n

    \n

    Similarly to the checking for the server 'secureConnection' event,\npair.cleartext.authorized should be checked to confirm whether the certificate\nused properly authorized.\n\n

    \n", "params": [] } ] }, { "textRaw": "Class: tls.Server", "type": "class", "name": "tls.Server", "desc": "

    This class is a subclass of net.Server and has the same methods on it.\nInstead of accepting just raw TCP connections, this accepts encrypted\nconnections using TLS or SSL.\n\n

    \n", "events": [ { "textRaw": "Event: 'secureConnection'", "type": "event", "name": "secureConnection", "desc": "

    function (cleartextStream) {}\n\n

    \n

    This event is emitted after a new connection has been successfully\nhandshaked. The argument is a instance of [CleartextStream][]. It has all the\ncommon stream methods and events.\n\n

    \n

    cleartextStream.authorized is a boolean value which indicates if the\nclient has verified by one of the supplied certificate authorities for the\nserver. If cleartextStream.authorized is false, then\ncleartextStream.authorizationError is set to describe how authorization\nfailed. Implied but worth mentioning: depending on the settings of the TLS\nserver, you unauthorized connections may be accepted.\ncleartextStream.npnProtocol is a string containing selected NPN protocol.\ncleartextStream.servername is a string containing servername requested with\nSNI.\n\n\n

    \n", "params": [] }, { "textRaw": "Event: 'clientError'", "type": "event", "name": "clientError", "desc": "

    function (exception, securePair) { }\n\n

    \n

    When a client connection emits an 'error' event before secure connection is\nestablished - it will be forwarded here.\n\n

    \n

    securePair is the tls.SecurePair that the error originated from.\n\n\n

    \n", "params": [] }, { "textRaw": "Event: 'newSession'", "type": "event", "name": "newSession", "desc": "

    function (sessionId, sessionData) { }\n\n

    \n

    Emitted on creation of TLS session. May be used to store sessions in external\nstorage.\n\n\n

    \n", "params": [] }, { "textRaw": "Event: 'resumeSession'", "type": "event", "name": "resumeSession", "desc": "

    function (sessionId, callback) { }\n\n

    \n

    Emitted when client wants to resume previous TLS session. Event listener may\nperform lookup in external storage using given sessionId, and invoke\ncallback(null, sessionData) once finished. If session can't be resumed\n(i.e. doesn't exist in storage) one may call callback(null, null). Calling\ncallback(err) will terminate incoming connection and destroy socket.\n\n\n

    \n", "params": [] } ], "methods": [ { "textRaw": "server.listen(port, [host], [callback])", "type": "method", "name": "listen", "desc": "

    Begin accepting connections on the specified port and host. If the\nhost is omitted, the server will accept connections directed to any\nIPv4 address (INADDR_ANY).\n\n

    \n

    This function is asynchronous. The last parameter callback will be called\nwhen the server has been bound.\n\n

    \n

    See net.Server for more information.\n\n\n

    \n", "signatures": [ { "params": [ { "name": "port" }, { "name": "host", "optional": true }, { "name": "callback", "optional": true } ] } ] }, { "textRaw": "server.close()", "type": "method", "name": "close", "desc": "

    Stops the server from accepting new connections. This function is\nasynchronous, the server is finally closed when the server emits a 'close'\nevent.\n\n

    \n", "signatures": [ { "params": [] } ] }, { "textRaw": "server.address()", "type": "method", "name": "address", "desc": "

    Returns the bound address, the address family name and port of the\nserver as reported by the operating system. See [net.Server.address()][] for\nmore information.\n\n

    \n", "signatures": [ { "params": [] } ] }, { "textRaw": "server.addContext(hostname, credentials)", "type": "method", "name": "addContext", "desc": "

    Add secure context that will be used if client request's SNI hostname is\nmatching passed hostname (wildcards can be used). credentials can contain\nkey, cert and ca.\n\n

    \n", "signatures": [ { "params": [ { "name": "hostname" }, { "name": "credentials" } ] } ] } ], "properties": [ { "textRaw": "server.maxConnections", "name": "maxConnections", "desc": "

    Set this property to reject connections when the server's connection count\ngets high.\n\n

    \n" }, { "textRaw": "server.connections", "name": "connections", "desc": "

    The number of concurrent connections on the server.\n\n\n

    \n" } ] }, { "textRaw": "Class: CryptoStream", "type": "class", "name": "CryptoStream", "desc": "

    This is an encrypted stream.\n\n

    \n", "properties": [ { "textRaw": "cryptoStream.bytesWritten", "name": "bytesWritten", "desc": "

    A proxy to the underlying socket's bytesWritten accessor, this will return\nthe total bytes written to the socket, including the TLS overhead.\n\n

    \n" } ] }, { "textRaw": "Class: tls.CleartextStream", "type": "class", "name": "tls.CleartextStream", "desc": "

    This is a stream on top of the Encrypted stream that makes it possible to\nread/write an encrypted data as a cleartext data.\n\n

    \n

    This instance implements a duplex [Stream][] interfaces. It has all the\ncommon stream methods and events.\n\n

    \n

    A ClearTextStream is the clear member of a SecurePair object.\n\n

    \n", "events": [ { "textRaw": "Event: 'secureConnect'", "type": "event", "name": "secureConnect", "desc": "

    This event is emitted after a new connection has been successfully handshaked. \nThe listener will be called no matter if the server's certificate was\nauthorized or not. It is up to the user to test cleartextStream.authorized\nto see if the server certificate was signed by one of the specified CAs.\nIf cleartextStream.authorized === false then the error can be found in\ncleartextStream.authorizationError. Also if NPN was used - you can check\ncleartextStream.npnProtocol for negotiated protocol.\n\n

    \n", "params": [] } ], "properties": [ { "textRaw": "cleartextStream.authorized", "name": "authorized", "desc": "

    A boolean that is true if the peer certificate was signed by one of the\nspecified CAs, otherwise false\n\n

    \n" }, { "textRaw": "cleartextStream.authorizationError", "name": "authorizationError", "desc": "

    The reason why the peer's certificate has not been verified. This property\nbecomes available only when cleartextStream.authorized === false.\n\n

    \n" }, { "textRaw": "cleartextStream.remoteAddress", "name": "remoteAddress", "desc": "

    The string representation of the remote IP address. For example,\n'74.125.127.100' or '2001:4860:a005::68'.\n\n

    \n" }, { "textRaw": "cleartextStream.remotePort", "name": "remotePort", "desc": "

    The numeric representation of the remote port. For example, 443.\n\n

    \n" } ], "methods": [ { "textRaw": "cleartextStream.getPeerCertificate()", "type": "method", "name": "getPeerCertificate", "desc": "

    Returns an object representing the peer's certificate. The returned object has\nsome properties corresponding to the field of the certificate.\n\n

    \n

    Example:\n\n

    \n
    { subject: \n   { C: 'UK',\n     ST: 'Acknack Ltd',\n     L: 'Rhys Jones',\n     O: 'node.js',\n     OU: 'Test TLS Certificate',\n     CN: 'localhost' },\n  issuer: \n   { C: 'UK',\n     ST: 'Acknack Ltd',\n     L: 'Rhys Jones',\n     O: 'node.js',\n     OU: 'Test TLS Certificate',\n     CN: 'localhost' },\n  valid_from: 'Nov 11 09:52:22 2009 GMT',\n  valid_to: 'Nov  6 09:52:22 2029 GMT',\n  fingerprint: '2A:7A:C2:DD:E5:F9:CC:53:72:35:99:7A:02:5A:71:38:52:EC:8A:DF' }
    \n

    If the peer does not provide a certificate, it returns null or an empty\nobject.\n\n

    \n", "signatures": [ { "params": [] } ] }, { "textRaw": "cleartextStream.getCipher()", "type": "method", "name": "getCipher", "desc": "

    Returns an object representing the cipher name and the SSL/TLS\nprotocol version of the current connection.\n\n

    \n

    Example:\n{ name: 'AES256-SHA', version: 'TLSv1/SSLv3' }\n\n

    \n

    See SSL_CIPHER_get_name() and SSL_CIPHER_get_version() in\nhttp://www.openssl.org/docs/ssl/ssl.html#DEALING_WITH_CIPHERS for more\ninformation.\n\n

    \n", "signatures": [ { "params": [] } ] }, { "textRaw": "cleartextStream.address()", "type": "method", "name": "address", "desc": "

    Returns the bound address, the address family name and port of the\nunderlying socket as reported by the operating system. Returns an\nobject with three properties, e.g.\n{ port: 12346, family: 'IPv4', address: '127.0.0.1' }\n\n

    \n", "signatures": [ { "params": [] } ] } ] } ], "type": "module", "displayName": "TLS (SSL)" } ] } node-v0.10.25~dfsg2/doc/api/_toc.html0000644000000000000000000001172212270264601015747 0ustar rootroot Node.js v0.10.25 Manual & Documentation node-v0.10.25~dfsg2/doc/api/dns.markdown0000644000000000000000000001300112270121457016456 0ustar rootroot# DNS Stability: 3 - Stable Use `require('dns')` to access this module. All methods in the dns module use C-Ares except for `dns.lookup` which uses `getaddrinfo(3)` in a thread pool. C-Ares is much faster than `getaddrinfo` but the system resolver is more consistent with how other programs operate. When a user does `net.connect(80, 'google.com')` or `http.get({ host: 'google.com' })` the `dns.lookup` method is used. Users who need to do a large number of lookups quickly should use the methods that go through C-Ares. Here is an example which resolves `'www.google.com'` then reverse resolves the IP addresses which are returned. var dns = require('dns'); dns.resolve4('www.google.com', function (err, addresses) { if (err) throw err; console.log('addresses: ' + JSON.stringify(addresses)); addresses.forEach(function (a) { dns.reverse(a, function (err, domains) { if (err) { throw err; } console.log('reverse for ' + a + ': ' + JSON.stringify(domains)); }); }); }); ## dns.lookup(domain, [family], callback) Resolves a domain (e.g. `'google.com'`) into the first found A (IPv4) or AAAA (IPv6) record. The `family` can be the integer `4` or `6`. Defaults to `null` that indicates both Ip v4 and v6 address family. The callback has arguments `(err, address, family)`. The `address` argument is a string representation of a IP v4 or v6 address. The `family` argument is either the integer 4 or 6 and denotes the family of `address` (not necessarily the value initially passed to `lookup`). On error, `err` is an `Error` object, where `err.code` is the error code. Keep in mind that `err.code` will be set to `'ENOENT'` not only when the domain does not exist but also when the lookup fails in other ways such as no available file descriptors. ## dns.resolve(domain, [rrtype], callback) Resolves a domain (e.g. `'google.com'`) into an array of the record types specified by rrtype. Valid rrtypes are `'A'` (IPV4 addresses, default), `'AAAA'` (IPV6 addresses), `'MX'` (mail exchange records), `'TXT'` (text records), `'SRV'` (SRV records), `'PTR'` (used for reverse IP lookups), `'NS'` (name server records) and `'CNAME'` (canonical name records). The callback has arguments `(err, addresses)`. The type of each item in `addresses` is determined by the record type, and described in the documentation for the corresponding lookup methods below. On error, `err` is an `Error` object, where `err.code` is one of the error codes listed below. ## dns.resolve4(domain, callback) The same as `dns.resolve()`, but only for IPv4 queries (`A` records). `addresses` is an array of IPv4 addresses (e.g. `['74.125.79.104', '74.125.79.105', '74.125.79.106']`). ## dns.resolve6(domain, callback) The same as `dns.resolve4()` except for IPv6 queries (an `AAAA` query). ## dns.resolveMx(domain, callback) The same as `dns.resolve()`, but only for mail exchange queries (`MX` records). `addresses` is an array of MX records, each with a priority and an exchange attribute (e.g. `[{'priority': 10, 'exchange': 'mx.example.com'},...]`). ## dns.resolveTxt(domain, callback) The same as `dns.resolve()`, but only for text queries (`TXT` records). `addresses` is an array of the text records available for `domain` (e.g., `['v=spf1 ip4:0.0.0.0 ~all']`). ## dns.resolveSrv(domain, callback) The same as `dns.resolve()`, but only for service records (`SRV` records). `addresses` is an array of the SRV records available for `domain`. Properties of SRV records are priority, weight, port, and name (e.g., `[{'priority': 10, {'weight': 5, 'port': 21223, 'name': 'service.example.com'}, ...]`). ## dns.resolveNs(domain, callback) The same as `dns.resolve()`, but only for name server records (`NS` records). `addresses` is an array of the name server records available for `domain` (e.g., `['ns1.example.com', 'ns2.example.com']`). ## dns.resolveCname(domain, callback) The same as `dns.resolve()`, but only for canonical name records (`CNAME` records). `addresses` is an array of the canonical name records available for `domain` (e.g., `['bar.example.com']`). ## dns.reverse(ip, callback) Reverse resolves an ip address to an array of domain names. The callback has arguments `(err, domains)`. On error, `err` is an `Error` object, where `err.code` is one of the error codes listed below. ## Error codes Each DNS query can return one of the following error codes: - `dns.NODATA`: DNS server returned answer with no data. - `dns.FORMERR`: DNS server claims query was misformatted. - `dns.SERVFAIL`: DNS server returned general failure. - `dns.NOTFOUND`: Domain name not found. - `dns.NOTIMP`: DNS server does not implement requested operation. - `dns.REFUSED`: DNS server refused query. - `dns.BADQUERY`: Misformatted DNS query. - `dns.BADNAME`: Misformatted domain name. - `dns.BADFAMILY`: Unsupported address family. - `dns.BADRESP`: Misformatted DNS reply. - `dns.CONNREFUSED`: Could not contact DNS servers. - `dns.TIMEOUT`: Timeout while contacting DNS servers. - `dns.EOF`: End of file. - `dns.FILE`: Error reading file. - `dns.NOMEM`: Out of memory. - `dns.DESTRUCTION`: Channel is being destroyed. - `dns.BADSTR`: Misformatted string. - `dns.BADFLAGS`: Illegal flags specified. - `dns.NONAME`: Given hostname is not numeric. - `dns.BADHINTS`: Illegal hints flags specified. - `dns.NOTINITIALIZED`: c-ares library initialization not yet performed. - `dns.LOADIPHLPAPI`: Error loading iphlpapi.dll. - `dns.ADDRGETNETWORKPARAMS`: Could not find GetNetworkParams function. - `dns.CANCELLED`: DNS query cancelled. node-v0.10.25~dfsg2/doc/api/documentation.html0000644000000000000000000001600512270264601017673 0ustar rootroot About this Documentation Node.js v0.10.25 Manual & Documentation

    Node.js v0.10.25 Manual & Documentation


    About this Documentation#

    The goal of this documentation is to comprehensively explain the Node.js API, both from a reference as well as a conceptual point of view. Each section describes a built-in module or high-level concept.

    Where appropriate, property types, method arguments, and the arguments provided to event handlers are detailed in a list underneath the topic heading.

    Every .html document has a corresponding .json document presenting the same information in a structured manner. This feature is experimental, and added for the benefit of IDEs and other utilities that wish to do programmatic things with the documentation.

    Every .html and .json file is generated based on the corresponding .markdown file in the doc/api/ folder in node's source tree. The documentation is generated using the tools/doc/generate.js program. The HTML template is located at doc/template.html.

    Stability Index#

    Throughout the documentation, you will see indications of a section's stability. The Node.js API is still somewhat changing, and as it matures, certain parts are more reliable than others. Some are so proven, and so relied upon, that they are unlikely to ever change at all. Others are brand new and experimental, or known to be hazardous and in the process of being redesigned.

    The stability indices are as follows:

    Stability: 0 - Deprecated
    This feature is known to be problematic, and changes are
    planned.  Do not rely on it.  Use of the feature may cause warnings.  Backwards
    compatibility should not be expected.
    Stability: 1 - Experimental
    This feature was introduced recently, and may change
    or be removed in future versions.  Please try it out and provide feedback.
    If it addresses a use-case that is important to you, tell the node core team.
    Stability: 2 - Unstable
    The API is in the process of settling, but has not yet had
    sufficient real-world testing to be considered stable. Backwards-compatibility
    will be maintained if reasonable.
    Stability: 3 - Stable
    The API has proven satisfactory, but cleanup in the underlying
    code may cause minor changes.  Backwards-compatibility is guaranteed.
    Stability: 4 - API Frozen
    This API has been tested extensively in production and is
    unlikely to ever have to change.
    Stability: 5 - Locked
    Unless serious bugs are found, this code will not ever
    change.  Please do not suggest changes in this area; they will be refused.

    JSON Output#

    Stability: 1 - Experimental

    Every HTML file in the markdown has a corresponding JSON file with the same data.

    This feature is new as of node v0.6.12. It is experimental.

    node-v0.10.25~dfsg2/doc/api/synopsis.json0000644000000000000000000000160312270264601016714 0ustar rootroot{ "source": "doc/api/synopsis.markdown", "miscs": [ { "textRaw": "Synopsis", "name": "Synopsis", "type": "misc", "desc": "

    An example of a web server written with Node which responds with 'Hello\nWorld':\n\n

    \n
    var http = require('http');\n\nhttp.createServer(function (request, response) {\n  response.writeHead(200, {'Content-Type': 'text/plain'});\n  response.end('Hello World\\n');\n}).listen(8124);\n\nconsole.log('Server running at http://127.0.0.1:8124/');
    \n

    To run the server, put the code into a file called example.js and execute\nit with the node program\n\n

    \n
    > node example.js\nServer running at http://127.0.0.1:8124/
    \n

    All of the examples in the documentation can be run similarly.\n

    \n" } ] } node-v0.10.25~dfsg2/doc/api/https.html0000644000000000000000000003211112270264601016160 0ustar rootroot HTTPS Node.js v0.10.25 Manual & Documentation

    Node.js v0.10.25 Manual & Documentation


    HTTPS#

    Stability: 3 - Stable

    HTTPS is the HTTP protocol over TLS/SSL. In Node this is implemented as a separate module.

    Class: https.Server#

    This class is a subclass of tls.Server and emits events same as http.Server. See http.Server for more information.

    https.createServer(options, [requestListener])#

    Returns a new HTTPS web server object. The options is similar to tls.createServer(). The requestListener is a function which is automatically added to the 'request' event.

    Example:

    // curl -k https://localhost:8000/
    var https = require('https');
    var fs = require('fs');
    
    var options = {
      key: fs.readFileSync('test/fixtures/keys/agent2-key.pem'),
      cert: fs.readFileSync('test/fixtures/keys/agent2-cert.pem')
    };
    
    https.createServer(options, function (req, res) {
      res.writeHead(200);
      res.end("hello world\n");
    }).listen(8000);

    Or

    var https = require('https');
    var fs = require('fs');
    
    var options = {
      pfx: fs.readFileSync('server.pfx')
    };
    
    https.createServer(options, function (req, res) {
      res.writeHead(200);
      res.end("hello world\n");
    }).listen(8000);

    server.listen(port, [host], [backlog], [callback])#

    server.listen(path, [callback])#

    server.listen(handle, [callback])#

    See http.listen() for details.

    server.close([callback])#

    See http.close() for details.

    https.request(options, callback)#

    Makes a request to a secure web server.

    options can be an object or a string. If options is a string, it is automatically parsed with url.parse().

    All options from http.request() are valid.

    Example:

    var https = require('https');
    
    var options = {
      hostname: 'encrypted.google.com',
      port: 443,
      path: '/',
      method: 'GET'
    };
    
    var req = https.request(options, function(res) {
      console.log("statusCode: ", res.statusCode);
      console.log("headers: ", res.headers);
    
      res.on('data', function(d) {
        process.stdout.write(d);
      });
    });
    req.end();
    
    req.on('error', function(e) {
      console.error(e);
    });

    The options argument has the following options

    • host: A domain name or IP address of the server to issue the request to. Defaults to 'localhost'.
    • hostname: To support url.parse() hostname is preferred over host
    • port: Port of remote server. Defaults to 443.
    • method: A string specifying the HTTP request method. Defaults to 'GET'.
    • path: Request path. Defaults to '/'. Should include query string if any. E.G. '/index.html?page=12'
    • headers: An object containing request headers.
    • auth: Basic authentication i.e. 'user:password' to compute an Authorization header.
    • agent: Controls Agent behavior. When an Agent is used request will default to Connection: keep-alive. Possible values:
      • undefined (default): use globalAgent for this host and port.
      • Agent object: explicitly use the passed in Agent.
      • false: opts out of connection pooling with an Agent, defaults request to Connection: close.

    The following options from tls.connect() can also be specified. However, a globalAgent silently ignores these.

    • pfx: Certificate, Private key and CA certificates to use for SSL. Default null.
    • key: Private key to use for SSL. Default null.
    • passphrase: A string of passphrase for the private key or pfx. Default null.
    • cert: Public x509 certificate to use. Default null.
    • ca: An authority certificate or array of authority certificates to check the remote host against.
    • ciphers: A string describing the ciphers to use or exclude. Consult http://www.openssl.org/docs/apps/ciphers.html#CIPHER_LIST_FORMAT for details on the format.
    • rejectUnauthorized: If true, the server certificate is verified against the list of supplied CAs. An 'error' event is emitted if verification fails. Verification happens at the connection level, before the HTTP request is sent. Default true.
    • secureProtocol: The SSL method to use, e.g. SSLv3_method to force SSL version 3. The possible values depend on your installation of OpenSSL and are defined in the constant SSL_METHODS.

    In order to specify these options, use a custom Agent.

    Example:

    var options = {
      hostname: 'encrypted.google.com',
      port: 443,
      path: '/',
      method: 'GET',
      key: fs.readFileSync('test/fixtures/keys/agent2-key.pem'),
      cert: fs.readFileSync('test/fixtures/keys/agent2-cert.pem')
    };
    options.agent = new https.Agent(options);
    
    var req = https.request(options, function(res) {
      ...
    }

    Or does not use an Agent.

    Example:

    var options = {
      hostname: 'encrypted.google.com',
      port: 443,
      path: '/',
      method: 'GET',
      key: fs.readFileSync('test/fixtures/keys/agent2-key.pem'),
      cert: fs.readFileSync('test/fixtures/keys/agent2-cert.pem'),
      agent: false
    };
    
    var req = https.request(options, function(res) {
      ...
    }

    https.get(options, callback)#

    Like http.get() but for HTTPS.

    options can be an object or a string. If options is a string, it is automatically parsed with url.parse().

    Example:

    var https = require('https');
    
    https.get('https://encrypted.google.com/', function(res) {
      console.log("statusCode: ", res.statusCode);
      console.log("headers: ", res.headers);
    
      res.on('data', function(d) {
        process.stdout.write(d);
      });
    
    }).on('error', function(e) {
      console.error(e);
    });

    Class: https.Agent#

    An Agent object for HTTPS similar to http.Agent. See https.request() for more information.

    https.globalAgent#

    Global instance of https.Agent for all HTTPS client requests.

    node-v0.10.25~dfsg2/doc/api/readline.json0000644000000000000000000003527012270264601016617 0ustar rootroot{ "source": "doc/api/readline.markdown", "modules": [ { "textRaw": "Readline", "name": "readline", "stability": 2, "stabilityText": "Unstable", "desc": "

    To use this module, do require('readline'). Readline allows reading of a\nstream (such as process.stdin) on a line-by-line basis.\n\n

    \n

    Note that once you've invoked this module, your node program will not\nterminate until you've closed the interface. Here's how to allow your\nprogram to gracefully exit:\n\n

    \n
    var readline = require('readline');\n\nvar rl = readline.createInterface({\n  input: process.stdin,\n  output: process.stdout\n});\n\nrl.question("What do you think of node.js? ", function(answer) {\n  // TODO: Log the answer in a database\n  console.log("Thank you for your valuable feedback:", answer);\n\n  rl.close();\n});
    \n", "methods": [ { "textRaw": "readline.createInterface(options)", "type": "method", "name": "createInterface", "desc": "

    Creates a readline Interface instance. Accepts an "options" Object that takes\nthe following values:\n\n

    \n
      \n
    • input - the readable stream to listen to (Required).

      \n
    • \n
    • output - the writable stream to write readline data to (Required).

      \n
    • \n
    • completer - an optional function that is used for Tab autocompletion. See\nbelow for an example of using this.

      \n
    • \n
    • terminal - pass true if the input and output streams should be\ntreated like a TTY, and have ANSI/VT100 escape codes written to it.\nDefaults to checking isTTY on the output stream upon instantiation.

      \n
    • \n
    \n

    The completer function is given a the current line entered by the user, and\nis supposed to return an Array with 2 entries:\n\n

    \n
      \n
    1. An Array with matching entries for the completion.

      \n
    2. \n
    3. The substring that was used for the matching.

      \n
    4. \n
    \n

    Which ends up looking something like:\n[[substr1, substr2, ...], originalsubstring].\n\n

    \n

    Example:\n\n

    \n
    function completer(line) {\n  var completions = '.help .error .exit .quit .q'.split(' ')\n  var hits = completions.filter(function(c) { return c.indexOf(line) == 0 })\n  // show all completions if none found\n  return [hits.length ? hits : completions, line]\n}
    \n

    Also completer can be run in async mode if it accepts two arguments:\n\n

    \n
    function completer(linePartial, callback) {\n  callback(null, [['123'], linePartial]);\n}
    \n

    createInterface is commonly used with process.stdin and\nprocess.stdout in order to accept user input:\n\n

    \n
    var readline = require('readline');\nvar rl = readline.createInterface({\n  input: process.stdin,\n  output: process.stdout\n});
    \n

    Once you have a readline instance, you most commonly listen for the\n"line" event.\n\n

    \n

    If terminal is true for this instance then the output stream will get\nthe best compatibility if it defines an output.columns property, and fires\na "resize" event on the output if/when the columns ever change\n(process.stdout does this automatically when it is a TTY).\n\n

    \n", "signatures": [ { "params": [ { "name": "options" } ] } ] } ], "classes": [ { "textRaw": "Class: Interface", "type": "class", "name": "Interface", "desc": "

    The class that represents a readline interface with an input and output\nstream.\n\n

    \n", "methods": [ { "textRaw": "rl.setPrompt(prompt, length)", "type": "method", "name": "setPrompt", "desc": "

    Sets the prompt, for example when you run node on the command line, you see\n> , which is node's prompt.\n\n

    \n", "signatures": [ { "params": [ { "name": "prompt" }, { "name": "length" } ] } ] }, { "textRaw": "rl.prompt([preserveCursor])", "type": "method", "name": "prompt", "desc": "

    Readies readline for input from the user, putting the current setPrompt\noptions on a new line, giving the user a new spot to write. Set preserveCursor\nto true to prevent the cursor placement being reset to 0.\n\n

    \n

    This will also resume the input stream used with createInterface if it has\nbeen paused.\n\n

    \n", "signatures": [ { "params": [ { "name": "preserveCursor", "optional": true } ] } ] }, { "textRaw": "rl.question(query, callback)", "type": "method", "name": "question", "desc": "

    Prepends the prompt with query and invokes callback with the user's\nresponse. Displays the query to the user, and then invokes callback\nwith the user's response after it has been typed.\n\n

    \n

    This will also resume the input stream used with createInterface if\nit has been paused.\n\n

    \n

    Example usage:\n\n

    \n
    interface.question('What is your favorite food?', function(answer) {\n  console.log('Oh, so your favorite food is ' + answer);\n});
    \n", "signatures": [ { "params": [ { "name": "query" }, { "name": "callback" } ] } ] }, { "textRaw": "rl.pause()", "type": "method", "name": "pause", "desc": "

    Pauses the readline input stream, allowing it to be resumed later if needed.\n\n

    \n", "signatures": [ { "params": [] } ] }, { "textRaw": "rl.resume()", "type": "method", "name": "resume", "desc": "

    Resumes the readline input stream.\n\n

    \n", "signatures": [ { "params": [] } ] }, { "textRaw": "rl.close()", "type": "method", "name": "close", "desc": "

    Closes the Interface instance, relinquishing control on the input and\noutput streams. The "close" event will also be emitted.\n\n

    \n", "signatures": [ { "params": [] } ] }, { "textRaw": "rl.write(data, [key])", "type": "method", "name": "write", "desc": "

    Writes data to output stream. key is an object literal to represent a key\nsequence; available if the terminal is a TTY.\n\n

    \n

    This will also resume the input stream if it has been paused.\n\n

    \n

    Example:\n\n

    \n
    rl.write('Delete me!');\n// Simulate ctrl+u to delete the line written previously\nrl.write(null, {ctrl: true, name: 'u'});
    \n", "signatures": [ { "params": [ { "name": "data" }, { "name": "key", "optional": true } ] } ] } ] } ], "modules": [ { "textRaw": "Events", "name": "events", "events": [ { "textRaw": "Event: 'line'", "type": "event", "name": "line", "desc": "

    function (line) {}\n\n

    \n

    Emitted whenever the input stream receives a \\n, usually received when the\nuser hits enter, or return. This is a good hook to listen for user input.\n\n

    \n

    Example of listening for line:\n\n

    \n
    rl.on('line', function (cmd) {\n  console.log('You just typed: '+cmd);\n});
    \n", "params": [] }, { "textRaw": "Event: 'pause'", "type": "event", "name": "pause", "desc": "

    function () {}\n\n

    \n

    Emitted whenever the input stream is paused.\n\n

    \n

    Also emitted whenever the input stream is not paused and receives the\nSIGCONT event. (See events SIGTSTP and SIGCONT)\n\n

    \n

    Example of listening for pause:\n\n

    \n
    rl.on('pause', function() {\n  console.log('Readline paused.');\n});
    \n", "params": [] }, { "textRaw": "Event: 'resume'", "type": "event", "name": "resume", "desc": "

    function () {}\n\n

    \n

    Emitted whenever the input stream is resumed.\n\n

    \n

    Example of listening for resume:\n\n

    \n
    rl.on('resume', function() {\n  console.log('Readline resumed.');\n});
    \n", "params": [] }, { "textRaw": "Event: 'close'", "type": "event", "name": "close", "desc": "

    function () {}\n\n

    \n

    Emitted when close() is called.\n\n

    \n

    Also emitted when the input stream receives its "end" event. The Interface\ninstance should be considered "finished" once this is emitted. For example, when\nthe input stream receives ^D, respectively known as EOT.\n\n

    \n

    This event is also called if there is no SIGINT event listener present when\nthe input stream receives a ^C, respectively known as SIGINT.\n\n

    \n", "params": [] }, { "textRaw": "Event: 'SIGINT'", "type": "event", "name": "SIGINT", "desc": "

    function () {}\n\n

    \n

    Emitted whenever the input stream receives a ^C, respectively known as\nSIGINT. If there is no SIGINT event listener present when the input\nstream receives a SIGINT, pause will be triggered.\n\n

    \n

    Example of listening for SIGINT:\n\n

    \n
    rl.on('SIGINT', function() {\n  rl.question('Are you sure you want to exit?', function(answer) {\n    if (answer.match(/^y(es)?$/i)) rl.pause();\n  });\n});
    \n", "params": [] }, { "textRaw": "Event: 'SIGTSTP'", "type": "event", "name": "SIGTSTP", "desc": "

    function () {}\n\n

    \n

    This does not work on Windows.\n\n

    \n

    Emitted whenever the input stream receives a ^Z, respectively known as\nSIGTSTP. If there is no SIGTSTP event listener present when the input\nstream receives a SIGTSTP, the program will be sent to the background.\n\n

    \n

    When the program is resumed with fg, the pause and SIGCONT events will be\nemitted. You can use either to resume the stream.\n\n

    \n

    The pause and SIGCONT events will not be triggered if the stream was paused\nbefore the program was sent to the background.\n\n

    \n

    Example of listening for SIGTSTP:\n\n

    \n
    rl.on('SIGTSTP', function() {\n  // This will override SIGTSTP and prevent the program from going to the\n  // background.\n  console.log('Caught SIGTSTP.');\n});
    \n", "params": [] }, { "textRaw": "Event: 'SIGCONT'", "type": "event", "name": "SIGCONT", "desc": "

    function () {}\n\n

    \n

    This does not work on Windows.\n\n

    \n

    Emitted whenever the input stream is sent to the background with ^Z,\nrespectively known as SIGTSTP, and then continued with fg(1). This event\nonly emits if the stream was not paused before sending the program to the\nbackground.\n\n

    \n

    Example of listening for SIGCONT:\n\n

    \n
    rl.on('SIGCONT', function() {\n  // `prompt` will automatically resume the stream\n  rl.prompt();\n});
    \n

    Example: Tiny CLI

    \n

    Here's an example of how to use all these together to craft a tiny command\nline interface:\n\n

    \n
    var readline = require('readline'),\n    rl = readline.createInterface(process.stdin, process.stdout);\n\nrl.setPrompt('OHAI> ');\nrl.prompt();\n\nrl.on('line', function(line) {\n  switch(line.trim()) {\n    case 'hello':\n      console.log('world!');\n      break;\n    default:\n      console.log('Say what? I might have heard `' + line.trim() + '`');\n      break;\n  }\n  rl.prompt();\n}).on('close', function() {\n  console.log('Have a great day!');\n  process.exit(0);\n});
    \n", "params": [] } ], "type": "module", "displayName": "Events" } ], "type": "module", "displayName": "Readline" } ] } node-v0.10.25~dfsg2/doc/api/debugger.html0000644000000000000000000002522112270264601016606 0ustar rootroot Debugger Node.js v0.10.25 Manual & Documentation

    Node.js v0.10.25 Manual & Documentation


    Debugger#

    Stability: 3 - Stable

    V8 comes with an extensive debugger which is accessible out-of-process via a simple TCP protocol. Node has a built-in client for this debugger. To use this, start Node with the debug argument; a prompt will appear:

    % node debug myscript.js
    < debugger listening on port 5858
    connecting... ok
    break in /home/indutny/Code/git/indutny/myscript.js:1
      1 x = 5;
      2 setTimeout(function () {
      3   debugger;
    debug>

    Node's debugger client doesn't support the full range of commands, but simple step and inspection is possible. By putting the statement debugger; into the source code of your script, you will enable a breakpoint.

    For example, suppose myscript.js looked like this:

    // myscript.js
    x = 5;
    setTimeout(function () {
      debugger;
      console.log("world");
    }, 1000);
    console.log("hello");

    Then once the debugger is run, it will break on line 4.

    % node debug myscript.js
    < debugger listening on port 5858
    connecting... ok
    break in /home/indutny/Code/git/indutny/myscript.js:1
      1 x = 5;
      2 setTimeout(function () {
      3   debugger;
    debug> cont
    < hello
    break in /home/indutny/Code/git/indutny/myscript.js:3
      1 x = 5;
      2 setTimeout(function () {
      3   debugger;
      4   console.log("world");
      5 }, 1000);
    debug> next
    break in /home/indutny/Code/git/indutny/myscript.js:4
      2 setTimeout(function () {
      3   debugger;
      4   console.log("world");
      5 }, 1000);
      6 console.log("hello");
    debug> repl
    Press Ctrl + C to leave debug repl
    > x
    5
    > 2+2
    4
    debug> next
    < world
    break in /home/indutny/Code/git/indutny/myscript.js:5
      3   debugger;
      4   console.log("world");
      5 }, 1000);
      6 console.log("hello");
      7
    debug> quit
    %

    The repl command allows you to evaluate code remotely. The next command steps over to the next line. There are a few other commands available and more to come. Type help to see others.

    Watchers#

    You can watch expression and variable values while debugging your code. On every breakpoint each expression from the watchers list will be evaluated in the current context and displayed just before the breakpoint's source code listing.

    To start watching an expression, type watch("my_expression"). watchers prints the active watchers. To remove a watcher, type unwatch("my_expression").

    Commands reference#

    Stepping#

    • cont, c - Continue execution
    • next, n - Step next
    • step, s - Step in
    • out, o - Step out
    • pause - Pause running code (like pause button in Developer Tools)

    Breakpoints#

    • setBreakpoint(), sb() - Set breakpoint on current line
    • setBreakpoint(line), sb(line) - Set breakpoint on specific line
    • setBreakpoint('fn()'), sb(...) - Set breakpoint on a first statement in functions body
    • setBreakpoint('script.js', 1), sb(...) - Set breakpoint on first line of script.js
    • clearBreakpoint, cb(...) - Clear breakpoint

    It is also possible to set a breakpoint in a file (module) that isn't loaded yet:

    % ./node debug test/fixtures/break-in-module/main.js
    < debugger listening on port 5858
    connecting to port 5858... ok
    break in test/fixtures/break-in-module/main.js:1
      1 var mod = require('./mod.js');
      2 mod.hello();
      3 mod.hello();
    debug> setBreakpoint('mod.js', 23)
    Warning: script 'mod.js' was not loaded yet.
      1 var mod = require('./mod.js');
      2 mod.hello();
      3 mod.hello();
    debug> c
    break in test/fixtures/break-in-module/mod.js:23
     21
     22 exports.hello = function() {
     23   return 'hello from module';
     24 };
     25
    debug>

    Info#

    • backtrace, bt - Print backtrace of current execution frame
    • list(5) - List scripts source code with 5 line context (5 lines before and after)
    • watch(expr) - Add expression to watch list
    • unwatch(expr) - Remove expression from watch list
    • watchers - List all watchers and their values (automatically listed on each breakpoint)
    • repl - Open debugger's repl for evaluation in debugging script's context

    Execution control#

    • run - Run script (automatically runs on debugger's start)
    • restart - Restart script
    • kill - Kill script

    Various#

    • scripts - List all loaded scripts
    • version - Display v8's version

    Advanced Usage#

    The V8 debugger can be enabled and accessed either by starting Node with the --debug command-line flag or by signaling an existing Node process with SIGUSR1.

    Once a process has been set in debug mode with this it can be connected to with the node debugger. Either connect to the pid or the URI to the debugger. The syntax is:

    • node debug -p <pid> - Connects to the process via the pid
    • node debug <URI> - Connects to the process via the URI such as localhost:5858
    node-v0.10.25~dfsg2/doc/api/index.markdown0000644000000000000000000000002712270121457017005 0ustar rootroot@include _toc.markdown node-v0.10.25~dfsg2/doc/community/0000755000000000000000000000000012270121457015406 5ustar rootrootnode-v0.10.25~dfsg2/doc/community/index.html0000644000000000000000000002545212270121457017413 0ustar rootroot node.js

    Node's most valuable feature is the friendly and colorful community of developers. There are many places where this group congregates on the internet. This page attempts to highlight the best forums.

    Documentation

    Official API docs detail the Node API.

    NodeSchool.io will teach you Node.js concepts via interactive command-line games.

    Stack Overflow node.js tag collects new information every day.

    docs.nodejitsu.com answers many of the common problems people come across.

    How To Node has a growing number of useful tutorials.

    GitHub

    All development takes place at github.com/joyent/node. This is where discussion regarding core development occurs.

    If you are interested in contributing to Node.js, please first read the contribution guide.

    Discussion

    The mailing list is used for announcements and discussion about Node.

    The github issues list is the place for discussion of Node.js core features

    Many Node users are active on Twitter as well.

    Periodicals

    Node.js Weekly is an email list that gathers up the latest events and news from around the Node.js community.

    Planet Node is an aggregator of Node developer blogs.

    NodeUp is a podcast covering the latest Node news in the community.

    NodeJS Reactions captures the Node.js experience in the form of animated GIFs.

    Real Life Events

    Node Meatspace is a webpage listing upcoming meetups and events in different places.

    NodeConf conferences are the main event in the United States; they are organized by Mikeal Rogers.

    NodeConf EU is a Node conference in Europe, organized by Cian O'Maiden.

    NodeFest (東京Node学園祭) is organized by the Node.js Japan user group.

    NodeCamp.de in Cologne, Germany is organized by Rails Love.

    An Italian Node.js Conference exists as well.

    Node Summit is a conference in San Francisco focusing on the adoption of Node in larger companies.

    JSConf organizes the main JavaScript conferences.

    Localized Sites

    nodejs.org does not maintain any translations into other languages. However there are community websites in various languages with mailing lists and translations of the website.

    nodejs.org.au Australian Node.js blog & developers listing
    NodeBR.com Brazilian community of Node.js
    CNodeJS.org Chinese community
    FR . Node.js Google+ Community of Node.js French users
    HKNoJ Hong Kong community
    nodejs.ir Iran group in Persian
    nodejs.co.il Israeli wiki
    nodejs.jp Japan user group
    OctoberSkyJs Korea Node.js community
    nodejs.geek.nz Node.js site for Kiwis
    nodejs.ru Russian blog.
    nodejs.rs Serbian Node.js community website Node Hispano Spanish language community
    Node.js Español Node.js in Spanish
    nodejs.tw Taiwan community
    Node.js Türkiye Node.js in Turkish
    Node.js Viet Nam Node.js in Vietnamese

    IRC

    For real-time chat about Node development go to irc.freenode.net in the #node.js channel with an IRC client or connect in your web browser to the channel using freenode's WebChat.

    node-v0.10.25~dfsg2/doc/rss.xml0000644000000000000000000000322712270121457014717 0ustar rootroot Node.js Blog http://blog.nodejs.org/ The Blog about Node.js <%= new Date().toUTCString() %> en weekly 1 http://nodejs.org/ http://nodejs.org/images/logo-light.png Node.js http://blog.nodejs.org/ <% posts.forEach(function(post) { %> <%= post.title %> http://blog.nodejs.org<%= post.permalink %> <%= post.date.toUTCString() %> <%= post.author %> ]]> http://blog.nodejs.org<%= post.permalink %> ]]> ]]> <% }); %> node-v0.10.25~dfsg2/doc/logos/0000755000000000000000000000000012270121457014505 5ustar rootrootnode-v0.10.25~dfsg2/doc/logos/index.html0000644000000000000000000001233112270121457016502 0ustar rootroot node.js node-v0.10.25~dfsg2/doc/index.html0000644000000000000000000002141212270121457015357 0ustar rootroot node.js

    Node.js is a platform built on Chrome's JavaScript runtime for easily building fast, scalable network applications. Node.js uses an event-driven, non-blocking I/O model that makes it lightweight and efficient, perfect for data-intensive real-time applications that run across distributed devices.

    Current Version: __VERSION__

    Fork me on GitHub

    Node.js in the Industry

    • Node gives Azure users the first end-to-end JavaScript experience for the development of a whole new class of real-time applications.
      Claudio Caldato
      Principal Program Manager, Microsoft Open Technologies, Inc.

    • Node’s evented I/O model freed us from worrying about locking and concurrency issues that are common with multithreaded async I/O.
      Subbu Allamarju
      Principal Member, Technical Staff

    • On the server side, our entire mobile software stack is completely built in Node. One reason was scale. The second is Node showed us huge performance gains.
      Kiran Prasad
      Director of Engineering, Mobile

    • Node.js is the execution core of Manhattan. Allowing developers to build one code base using one language – that is the nirvana for developers.
      Renaud Waldura
      Sr. Product Manger, Cocktail

    An example: Webserver

    This simple web server written in Node responds with "Hello World" for every request.

    var http = require('http');
    http.createServer(function (req, res) {
      res.writeHead(200, {'Content-Type': 'text/plain'});
      res.end('Hello World\n');
    }).listen(1337, '127.0.0.1');
    console.log('Server running at http://127.0.0.1:1337/');

    To run the server, put the code into a file example.js and execute it with the node program from the command line:

    % node example.js
    Server running at http://127.0.0.1:1337/

    Here is an example of a simple TCP server which listens on port 1337 and echoes whatever you send it:

    var net = require('net');
    
    var server = net.createServer(function (socket) {
      socket.write('Echo server\r\n');
      socket.pipe(socket);
    });
    
    server.listen(1337, '127.0.0.1');

    Featured

    A guided introduction to Node

    Explore Node.js

    node-v0.10.25~dfsg2/doc/pipe.css0000644000000000000000000003005312270121457015032 0ustar rootroothtml { -webkit-font-smoothing: antialiased; -webkit-text-stroke: .1px; } body { background: #46483e; color: #eee; font-size: 12px; line-height: 180%; font-family: "Lucida Grande", "Lucida Sans Unicode", "Lucida Sans", Verdana, Tahoma, sans-serif; margin: 0; padding-top: 40px; border-top: 6px #8cc84b solid; } body.alt { background: white; color: #46483e; } body.int { padding-top: 49px; } img { border: 0; } ul { margin: 0px; padding: 0px; } @media all and (min-height: 650px) { #toc { position: fixed; } } #toctitle { display: none; } h1, h2, h3, h4 { color: #d2d8ba; font-family: Helvetica, Arial, sans-serif; margin-top: 2em; margin-right: 0; margin-bottom: 10px; margin-left: 0; text-transform: uppercase; } h1 { font-family: Georgia, FreeSerif, Times, serif; font-size: 30px; line-height: 36px; text-transform: none; color: #669900; font-weight: normal; margin: 15px 0 11px; } h2 { font-size: 12px; font-weight: normal; } h1 code, h2 code, h3 code, h4 code, h1 a, h2 a, h3 a, h4 a { color: inherit; font-size: inherit; } #intro { width: 775px; margin: 0 auto; text-align: center; color: #d2d8ba; } #intro p { width: 680px; line-height: 180%; padding-top: 30px; margin: 0 auto; font-size: 14px; } #intro.interior #logo { margin-left: -298px; } #intro p.version { padding-top: 10px; font-size: 12px; } #intro .buttons { height: auto; overflow: hidden; _zoom: 1; width: 300px; margin: 0 auto; } #intro .button { font-family: helvetica,arial,sans-serif; font-size: 12px; line-height: 36px; -webkit-text-transform: uppercase; -moz-text-transform: uppercase; text-transform: uppercase; -webkit-border-radius: 2px; -moz-border-radius: 2px; border-radius: 2px; -webkit-transition: .2s all ease-in-out; -moz-transition: .2s all ease-in-out; transition: .2s all ease-in-out; margin: 10px 4px; display: inline-block; color: #46483e; background-color: #9a9f8b; width: 96px; } #intro .forkme { position: absolute; top: 0; right: 0; border: 0; } #intro .button:hover { text-decoration: none; background-color: #aab293; } #intro #docsbutton { clear: left; } #intro .downloadbutton { background-color: #8BC84B; width: 200px; font-size: 14px; font-weight: bold; display: block; margin: 30px auto 0px auto; } #intro .downloadbutton:hover { background-color: #73a53e; } #quotes { text-align: center; width: 100%; background-color: #33342d; margin-top: 40px; padding-top: 20px; padding-bottom: 20px; } #quotes h2 { margin-top: 0; } #quotes ul { display: block; width: 775px; margin: 0 auto; padding-top: 20px; } #quotes ul li { display: block; text-align: left; width: 180px; float: left; padding-right: 15px; font-size: 11px; } #quotes ul li:last-child { padding-right: 0; } #quotes ul li p span { font-size: 10px; } #quotes ul li p { color: #D2D8BA } #content { width: 775px; margin: 0 auto; overflow: visible; clear: both; display: block; } .int #content { width: 953px; } #column1 { width: 460px; float: left; } #content p, #content ul { font-size: 14px; line-height: 24px; } #content ul { margin-top: 1em; } #content table { font-size: 14px; line-height: 24px; width: 100%; } #download-page #installers { width: 600px; display: table; margin-bottom: 1em; } #download-page #installers ul { width: auto; text-align: center; margin: 0 auto; display: table-row; width: 600px; } #download-page #installers ul img { display: block; margin: 0 auto; } #download-page #installers ul a { display: block; width: 100%; text-decoration: none; font-size: 16px; padding-top: 1em; } #download-page #installers ul a:hover, #download-page #installers ul a:active { background: #666; color: #8cc84b; } #download-page #installers ul li { width: 33%; display: table-cell; } #download-page #installers a small { font-size: 10px; display: block; color: #eee; } #download-page #content th { text-align: left; width: 33%; } #download-page #content table { table-collapse: separate; } #download-page #content td, #download-page #content th { border: 1px solid #666; } #download-page #content td a { display: block; height: 100%; width: 100%; text-align: center; } #download-page #content td a:hover, #download-page #content td a:active { background: #666; color: #8cc84b; } #front #content p { font-size: 12px; } #content h1 + p { font-size: 18px; line-height: 30px; color: #46483e; font-family: Georgia, FreeSerif, Times, serif; } #column2 { width: 260px; float: right; } #column1.interior { width: 600px; float: right; padding-top: 11px; font-size: 18px; padding-right: 150px; } #column2.interior { width: 140px; float: left; margin-top: -54px; overflow: visible; } #column2.interior ul { margin-left: 0; } #column2.interior li { list-style-type: none; } #column2.interior li a { display: block; padding: 0 0 0 35px; color: #878b78; text-transform: uppercase; text-decoration: none; font-size: 11px; line-height: 23px; } #column2.interior li a.home { background: url(http://nodejs.org/images/icons-interior.png) no-repeat -156px 3px; } #column2.interior li a.download { background: url(http://nodejs.org/images/icons-interior.png) no-repeat -156px -21px; } #column2.interior li a.about { background: url(http://nodejs.org/images/icons-interior.png) no-repeat -156px -45px; } #column2.interior li a.npm { background: url(http://nodejs.org/images/icons-interior.png) no-repeat -156px -69px; } #column2.interior li a.docs { background: url(http://nodejs.org/images/icons-interior.png) no-repeat -156px -93px; } #column2.interior li a.blog { background: url(http://nodejs.org/images/icons-interior.png) no-repeat -156px -117px; } #column2.interior li a.community { background: url(http://nodejs.org/images/icons-interior.png) no-repeat -156px -141px; } #column2.interior li a.logos { background: url(http://nodejs.org/images/icons-interior.png) no-repeat -156px -165px; } #column2.interior li a.jobs { background: url(http://nodejs.org/images/icons-interior.png) no-repeat -156px -189px; } #column2.interior li a.home.current { background-position: 2px 3px; } #column2.interior li a.download.current { background-position: 2px -21px; } #column2.interior li a.about.current { background-position: 2px -45px; } #column2.interior li a.npm.current { background-position: 2px -69px; } #column2.interior li a.docs.current { background-position: 2px -93px; } #column2.interior li a.blog.current { background-position: 2px -117px; } #column2.interior li a.community.current { background-position: 2px -141px; } #column2.interior li a.logos.current { background-position: 2px -165px; } #column2.interior li a.jobs.current { background-position: 2px -189px; } #column2.interior li a.home:hover { background-position: -331px 3px; } #column2.interior li a.download:hover { background-position: -331px -21px; } #column2.interior li a.about:hover { background-position: -331px -45px; } #column2.interior li a.npm:hover { background-position: -331px -69px; } #column2.interior li a.docs:hover { background-position: -331px -93px; } #column2.interior li a.blog:hover { background-position: -331px -117px; } #column2.interior li a.community:hover { background-position: -331px -141px; } #column2.interior li a.logos:hover { background-position: -331px -165px; } #column2.interior li a.jobs:hover { background-position: -331px -189px; } #column2.interior li a.current { color: #8cc84b; font-weight: bold; } #column2.interior li a:hover { color: #000000; text-decoration: none; } #column2.interior li + li { border-top: 1px solid #c1c7ac; border-top: 1px solid #65675c; } .alt #column2.interior li + li { border-top: 1px solid #c1c7ac; } #column2.interior p.twitter { padding-top: 20px; } #column2.interior p.twitter a { background: url(http://nodejs.org/images/twitter-bird.png) no-repeat 0 4px; padding-left: 37px; } .row { padding-top: 10px; padding-bottom: 10px; } .row + .row { border-top: 1px solid #626557; } .row h2 { font-size: 24px; color: white; text-transform: none; font-family: Georgia, FreeSerif, Times, serif; background: url(http://nodejs.org/images/community-icons.png) no-repeat; padding-left: 45px; padding-top: 6px; padding-bottom: 10px; margin-top: 10px; } .row h2.github { background-position: left -92px; } .row h2.mailing { background-position: left -308px; } .row h2.periodicals { background-position: left -198px; padding-top: 9px; margin-top: 7px; } .row h2.conferences { background-position: left -522px; } .row h2.localized { background-position: left -414px; } .row h2.irc { background-position: left -626px; } .row h2.installers { background-position: left -522px; } .block { width: 280px; float: left; } .block + .block { margin-left: 20px; width: 300px; } #content .block p { font-size: 13px; line-height: 21px; } #explore { background: url(http://nodejs.org/images/home-icons.png) no-repeat left 17px; } #explore li { font-size: 12px; list-style-type: none; color: #d2d8ba; line-height: 14px; padding: 10px 0 10px 40px; border-top: 1px solid #626557; } #explore li span { } #explore li a.explore { text-transform: uppercase; } #explore ol.jobs { padding: 0; } #explore ol.jobs li { display: inline; padding: 0; border: none; } #explore ol.jobs li:after { content: ', '; } #explore ol.jobs li:last-child:after { content: ''; } #footer { width: 942px; margin: 150px auto 55px auto; padding: 0; } #footer .joyent-logo { display:block; position:absolute; overflow:hidden; text-indent:-999em; height:100px; width:190px; z-index:999; } #footer p { font-size: 11px; line-height: 1em; padding: 0 0 0 195px; color: #666; font-family: "Lucida Grande", "Lucida Sans Unicode", "Lucida Sans", Verdana, Tahoma, sans-serif; } #front #footer { width: 775px; margin: 50px auto 30px auto; padding-top: 15px; } #front #footer ul { margin-right: 0; padding-right: 0; } #footer a { text-decoration: none; border: none; color: #690; } #footer a:hover { color: #000; } #front #footer a:hover { color: #fff; } #footer p a { border-bottom: 1px dotted #690; color: #878b78; } #footer ul { background: url(http://nodejs.org/images/footer-logo.png) left 17px no-repeat; border-top: 1px solid #626557; border-color: #90918b; padding-top: 23px; padding-left: 195px; height: 26px; margin-right: 137px; } .alt #footer ul { background-image: url(http://nodejs.org/images/footer-logo-alt.png); } #footer ul li { list-style-type: none; float: left; font-size: 12px; margin: 0 !important; height: 12px; } #footer ul li a { margin: 0; padding: 0 6px 0 0; display: block; height: 12px; line-height: 12px; } #footer ul li + li { margin-left: 3px; } #footer ul li + li a { padding: 0 6px 0 6px; border-left: 1px solid #878b78; } #footer ul li a.twitter { background: url(http://nodejs.org/images/twitter-bird.png) no-repeat 5px 0px; padding-left: 25px; } pre, tt, code { color: #d2d8ba; font-size: 14px; line-height: 22px; font-family: Monaco, Consolas, "Lucida Console", monospace; margin: 0; padding: 0; } #front pre, #front tt, #front code { font-size: 12px; line-height: 22px; } pre { padding-left: 1em; margin-left: -1em; border-left-width: 1px; border-left-style: solid; border-left-color: #626557; } .alt pre { font-size: 14px; margin-left: 0; border-left: 2px solid #dadad7; background-color: #f4f4f2; color: #46483e; padding: 1em 1.5em; line-height: 2em; } .alt code { color: #996633; } dd { margin: 1em 0; margin-left: 1em; } a { color: #690; text-decoration: none; } a:hover { text-decoration: underline; } .alt a { background-color: #eff2db; padding: 0 2px; } .alt #intro a, .alt #footer a { background-color: transparent; } .highlight { background: #733; padding: 0.2em 0; } .desktops { font-size: 12px; } .release { margin: 0 0 0 2em; } /* simpler clearfix */ .clearfix:after { content: "."; display: block; height: 0; clear: both; visibility: hidden; } node-v0.10.25~dfsg2/doc/about/0000755000000000000000000000000012270121457014474 5ustar rootrootnode-v0.10.25~dfsg2/doc/about/index.html0000644000000000000000000001670112270121457016476 0ustar rootroot node.js

    Node's goal is to provide an easy way to build scalable network programs

    In the "hello world" web server example below, many client connections can be handled concurrently. Node tells the operating system (through epoll, kqueue, /dev/poll, or select) that it should be notified when a new connection is made, and then it goes to sleep. If someone new connects, then it executes the callback. Each connection is only a small heap allocation.

    var http = require('http');
    http.createServer(function (req, res) {
      res.writeHead(200, {'Content-Type': 'text/plain'});
      res.end('Hello World\n');
    }).listen(1337, "127.0.0.1");
    console.log('Server running at http://127.0.0.1:1337/');

    This is in contrast to today's more common concurrency model where OS threads are employed. Thread-based networking is relatively inefficient and very difficult to use. See: this and this. Node will show much better memory efficiency under high-loads than systems which allocate 2mb thread stacks for each connection. Furthermore, users of Node are free from worries of dead-locking the process—there are no locks. Almost no function in Node directly performs I/O, so the process never blocks. Because nothing blocks, less-than-expert programmers are able to develop fast systems.

    Node is similar in design to and influenced by systems like Ruby's Event Machine or Python's Twisted. Node takes the event model a bit further—it presents the event loop as a language construct instead of as a library. In other systems there is always a blocking call to start the event-loop. Typically one defines behavior through callbacks at the beginning of a script and at the end starts a server through a blocking call like EventMachine::run(). In Node there is no such start-the-event-loop call. Node simply enters the event loop after executing the input script. Node exits the event loop when there are no more callbacks to perform. This behavior is like browser javascript—the event loop is hidden from the user.

    HTTP is a first class protocol in Node. Node's HTTP library has grown out of the author's experiences developing and working with web servers. For example, streaming data through most web frameworks is impossible. Node attempts to correct these problems in its HTTP parser and API. Coupled with Node's purely evented infrastructure, it makes a good foundation for web libraries or frameworks.

    But what about multiple-processor concurrency? Aren't threads necessary to scale programs to multi-core computers? You can start new processes via child_process.fork() these other processes will be scheduled in parallel. For load balancing incoming connections across multiple processes use the cluster module.

    See also:

    node-v0.10.25~dfsg2/doc/cla.html0000644000000000000000000001346612270121457015021 0ustar rootroot

    NodeJS

    Contributor License Agreement ("Agreement")

    Thank you for your interest in the NodeJS open source project being administered by Joyent, Inc , dba NodeJS ("NodeJS"). The form of license below is a document that clarifies the terms under which You, the person listed below, may contribute software, bug fixes, configuration changes, documentation, or any other materials that you send to us related to the Project (each a "Contribution") to the project. We appreciate your participation in our project, and your help in improving the project, so we want you to understand what will be done with the Contributions. This license is for your protection as well as the protection of NodeJS and its licensees; it does not change your rights to use your own Contributions for any other purpose. Please complete the following information about you and the Contributions and sign electronically by filling out the form below.

    If you have questions about these terms, please contact us at isaacs@joyent.com.

    Corporate Contributions:

    If you are employed as a software engineer, or if your employer is in the business of developing software, or otherwise may claim rights in the Contributions, please provide information about your employer's policy on contributing to open source projects, including the name of the supervisor to contact in connection with such contributions.

    You and NodeJS agree:

    1. You grant us the ability to use the Contributions in any way. You hereby grant to NodeJS, a non-exclusive, irrevocable, worldwide, royalty-free, sublicenseable, transferable license under all of Your relevant intellectual property rights (including copyright, patent, and any other rights), to use, copy, prepare derivative works of, distribute and publicly perform and display the Contributions on any licensing terms, including without limitation: (a) open source licenses like the GNU General Public License (GPL), the GNU Lesser General Public License (LGPL), the Common Public License, or the Berkeley Software Distribution license (BSD); and (b) binary, proprietary, or commercial licenses. Except for the licenses granted herein, You reserve all right, title, and interest in and to the Contribution.
    2. You are able to grant us these rights. You represent that You are legally entitled to grant the above license. If Your employer has rights to intellectual property that You create, You represent that You have received permission to make the Contributions on behalf of that employer, or that Your employer has waived such rights for the Contributions.
    3. The Contributions are your original work. You represent that the Contributions are Your original works of authorship, and to Your knowledge, no other person claims, or has the right to claim, any right in any invention or patent related to the Contributions. You also represent that You are not legally obligated, whether by entering into an agreement or otherwise, in any way that conflicts with the terms of this license. For example, if you have signed an agreement requiring you to assign the intellectual property rights in the Contributions to an employer or customer, that would conflict with the terms of this license.
    4. We determine the code that is in our project. You understand that the decision to include the Contribution in any project or source repository is entirely that of NodeJS, and this agreement does not guarantee that the Contributions will be included in any product.
    5. No Implied Warranties. NodeJS acknowledges that, except as explicitly described in this Agreement, the Contribution is provided on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, EITHER EXPRESS OR IMPLIED, INCLUDING, WITHOUT LIMITATION, ANY WARRANTIES OR CONDITIONS OF TITLE, NON-INFRINGEMENT, MERCHANTABILITY, OR FITNESS FOR A PARTICULAR PURPOSE.

    Sign Electronically

    As an alternative to electronic signing, you may also print the document and send the original to:

    Joyent, Inc
    One Embarcadero Center, 9th Floor
    San Francisco, CA 94111
    U.S.A.

    Scanned agreements may also be emailed in PDF format to isaacs@joyent.com. You should also keep a copy for your own records.

    Full name: _________________________________________________
    
    Mailing Address: ___________________________________________
    
    ____________________________________________________________
    
    Country:   _________________________________________________
    
    Telephone: _________________________________________________
    
    Facsimile: _________________________________________________
    
    E-Mail:    _________________________________________________
    
    Employer:  _________________________________________________
    
    Employer Contact:   ________________________________________
    
    Employer Open Source Contribution Policy:  _________________
    
    ____________________________________________________________
    
    ____________________________________________________________
    
    Please sign: _______________________________________________
    
    Date: ______________________________________________________
    
    node-v0.10.25~dfsg2/doc/thin-white-stripe.jpg0000644000000000000000000000636412270121457017461 0ustar rootrootJFIFC       C :" E U!1A "aQq#27Ru6Br$8DSbfsv0!RaA1Q"q2B ?|-C-ΫB{R ,K.MmuZݡUo)0,K v[oVheh[vD (큿$ݖUomuZݢ4`o7eh[v[oVh@..MmuZݡUo)0,K v[oVheh[vD (큿$ݖUomuZݢ4`o7eh[v[oVh@..MmuZݡUo)0,K v[oVheh[vD (큿$ݖUomuZݢ4`o7eh[v[oVh@..MmuZݡUo)0,K v[oVheh[vD (큿$ݖUomuZݢ4`o7eh[v[oVh@..MmuZݡUo)0,K v[oVheh[vD (큿$ݖUomuZݢ4`o7eh[v[oVh@..MmuZݡUo)0,K v[oVheh[vD (큿$ݖUomuZݢ4`o7eh[v[oVh@..MmuZݡUo)0,K v[oVheh[vt+*ݨ]4IRLE370>rHův[7ѮU s2#/_ 'wavߓeh[v[oVh@..MmuZݡUo)0,K v[oVheh[vD (큿$ݖUomuZݢ4`o|ۏs>_ 2rAO"zb8#%"CL9N=nJ+5:2C1JN{V_Dd44Ž;!0J1+6ҰF,#m`k|"RT)/!B!'/ K\s)- /B숈zC-TݤS)#lJ3 M7 {$0"xG6r7= _'+@(tWNn PYl y+ -qNәC S䝬6ȗrwC}>>fl:fDr:{*d %,U:߼Fz?'?Om/ږEfJ}N0qg\^L~'x+n3ѾA ?UiE: $xEr^/XB9s!z߈ 3᜝ 7JS`SZpSwXW}0>u{)M^c\Q7Z?u Epڕ0sHFȈnZ*Kg^;ⁿ$n-(W2}P^ ò,nQeWwA=Gé1HV[X^#/+9eu`aJ'̟đC'|56ĩT=sk'5 yD_/_e-"DkTS31sʊ s|l-bHOFM:?4&DhQ= p헅֫ 3bu:#pB*"b6 p="6u(Ǖ$HVY"! +G%/JrG*rs)5rZ7di*%W4NU1Sp߂}!q.9Ƞ:F/ t▂g=+0Bkdd$ӥe9`iaO!F[-|EF|J&4jyk^ɿD]node-v0.10.25~dfsg2/doc/download/0000755000000000000000000000000012270121457015171 5ustar rootrootnode-v0.10.25~dfsg2/doc/download/index.html0000644000000000000000000002032512270121457017170 0ustar rootroot node.js

    Download the Node.js source code or a pre-built installer for your platform, and start developing today.

    Current version: __VERSION__

    Windows Installer (.msi) 32-bit 64-bit
    Windows Binary (.exe) 32-bit 64-bit
    Mac OS X Installer (.pkg) Universal
    Mac OS X Binaries (.tar.gz) 32-bit 64-bit
    Linux Binaries (.tar.gz) 32-bit 64-bit
    SunOS Binaries (.tar.gz) 32-bit 64-bit
    Source Code node-__VERSION__.tar.gz

    Note: Python 2.6 or 2.7 is required to build from source tarballs.

    Other Info

    License

    Node.js is released under the MIT license, and bundles other liberally licensed OSS components. Download the license

    node-v0.10.25~dfsg2/doc/sh_vim-dark.css0000644000000000000000000000103612270121457016300 0ustar rootroot.sh_sourceCode { font-weight: normal; font-style: normal; } .sh_sourceCode .sh_symbol , .sh_sourceCode .sh_cbracket { color: #fff; } .sh_sourceCode .sh_keyword { font-style: italic; } .sh_sourceCode .sh_string, .sh_sourceCode .sh_regexp, .sh_sourceCode .sh_number, .sh_sourceCode .sh_specialchar { color: #a0c874; } .sh_sourceCode .sh_comment { color: #777; } .alt .sh_sourceCode .sh_keyword { font-style: normal; color: #996633; } .alt .sh_sourceCode .sh_symbol , .alt .sh_sourceCode .sh_cbracket { color: #46483e; } node-v0.10.25~dfsg2/common.gypi0000644000000000000000000002072412270121457015004 0ustar rootroot{ 'variables': { 'visibility%': 'hidden', # V8's visibility setting 'target_arch%': 'ia32', # set v8's target architecture 'host_arch%': 'ia32', # set v8's host architecture 'want_separate_host_toolset': 0, # V8 should not build target and host 'library%': 'static_library', # allow override to 'shared_library' for DLL/.so builds 'component%': 'static_library', # NB. these names match with what V8 expects 'msvs_multi_core_compile': '0', # we do enable multicore compiles, but not using the V8 way 'gcc_version%': 'unknown', 'clang%': 0, 'python%': 'python', # Turn on optimizations that may trigger compiler bugs. # Use at your own risk. Do *NOT* report bugs if this option is enabled. 'node_unsafe_optimizations%': 0, # Enable V8's post-mortem debugging only on unix flavors. 'conditions': [ ['OS != "win"', { 'v8_postmortem_support': 'true' }], ['GENERATOR == "ninja"', { 'OBJ_DIR': '<(PRODUCT_DIR)/obj', 'V8_BASE': '<(PRODUCT_DIR)/libv8_base.a', }, { 'OBJ_DIR': '<(PRODUCT_DIR)/obj.target', 'V8_BASE': '<(PRODUCT_DIR)/obj.target/deps/v8/tools/gyp/libv8_base.a', }], ], }, 'target_defaults': { 'default_configuration': 'Release', 'configurations': { 'Debug': { 'defines': [ 'DEBUG', '_DEBUG' ], 'cflags': [ '-g', '-O0' ], 'conditions': [ ['target_arch=="x64"', { 'msvs_configuration_platform': 'x64', }], ], 'msvs_settings': { 'VCCLCompilerTool': { 'RuntimeLibrary': 1, # static debug 'Optimization': 0, # /Od, no optimization 'MinimalRebuild': 'false', 'OmitFramePointers': 'false', 'BasicRuntimeChecks': 3, # /RTC1 }, 'VCLinkerTool': { 'LinkIncremental': 2, # enable incremental linking }, }, 'xcode_settings': { 'GCC_OPTIMIZATION_LEVEL': '0', # stop gyp from defaulting to -Os }, }, 'Release': { 'conditions': [ ['target_arch=="x64"', { 'msvs_configuration_platform': 'x64', }], ['node_unsafe_optimizations==1', { 'cflags': [ '-O3', '-ffunction-sections', '-fdata-sections' ], 'ldflags': [ '-Wl,--gc-sections' ], }, { 'cflags': [ '-O2', '-fno-strict-aliasing' ], 'cflags!': [ '-O3', '-fstrict-aliasing' ], 'conditions': [ # Required by the dtrace post-processor. Unfortunately, # some gcc/binutils combos generate bad code when # -ffunction-sections is enabled. Let's hope for the best. ['OS=="solaris"', { 'cflags': [ '-ffunction-sections', '-fdata-sections' ], }, { 'cflags!': [ '-ffunction-sections', '-fdata-sections' ], }], ['clang == 0 and gcc_version >= 40', { 'cflags': [ '-fno-tree-vrp' ], }], ['clang == 0 and gcc_version <= 44', { 'cflags': [ '-fno-tree-sink' ], }], ], }], ['OS=="solaris"', { # pull in V8's postmortem metadata 'ldflags': [ '-Wl,-z,allextract' ] }], ['OS!="mac" and OS!="win"', { 'cflags': [ '-fno-omit-frame-pointer' ], }], ], 'msvs_settings': { 'VCCLCompilerTool': { 'RuntimeLibrary': 0, # static release 'Optimization': 3, # /Ox, full optimization 'FavorSizeOrSpeed': 1, # /Ot, favour speed over size 'InlineFunctionExpansion': 2, # /Ob2, inline anything eligible 'WholeProgramOptimization': 'true', # /GL, whole program optimization, needed for LTCG 'OmitFramePointers': 'true', 'EnableFunctionLevelLinking': 'true', 'EnableIntrinsicFunctions': 'true', 'RuntimeTypeInfo': 'false', 'ExceptionHandling': '0', 'AdditionalOptions': [ '/MP', # compile across multiple CPUs ], }, 'VCLibrarianTool': { 'AdditionalOptions': [ '/LTCG', # link time code generation ], }, 'VCLinkerTool': { 'LinkTimeCodeGeneration': 1, # link-time code generation 'OptimizeReferences': 2, # /OPT:REF 'EnableCOMDATFolding': 2, # /OPT:ICF 'LinkIncremental': 1, # disable incremental linking }, }, } }, 'msvs_settings': { 'VCCLCompilerTool': { 'StringPooling': 'true', # pool string literals 'DebugInformationFormat': 3, # Generate a PDB 'WarningLevel': 3, 'BufferSecurityCheck': 'true', 'ExceptionHandling': 1, # /EHsc 'SuppressStartupBanner': 'true', 'WarnAsError': 'false', }, 'VCLibrarianTool': { }, 'VCLinkerTool': { 'conditions': [ ['target_arch=="x64"', { 'TargetMachine' : 17 # /MACHINE:X64 }], ], 'GenerateDebugInformation': 'true', 'RandomizedBaseAddress': 2, # enable ASLR 'DataExecutionPrevention': 2, # enable DEP 'AllowIsolation': 'true', 'SuppressStartupBanner': 'true', 'target_conditions': [ ['_type=="executable"', { 'SubSystem': 1, # console executable }], ], }, }, 'conditions': [ ['OS == "win"', { 'msvs_cygwin_shell': 0, # prevent actions from trying to use cygwin 'defines': [ 'WIN32', # we don't really want VC++ warning us about # how dangerous C functions are... '_CRT_SECURE_NO_DEPRECATE', # ... or that C implementations shouldn't use # POSIX names '_CRT_NONSTDC_NO_DEPRECATE', 'BUILDING_V8_SHARED=1', 'BUILDING_UV_SHARED=1', ], }], [ 'OS=="linux" or OS=="freebsd" or OS=="openbsd" or OS=="solaris"', { 'cflags': [ '-Wall', '-Wextra', '-Wno-unused-parameter', '-pthread', ], 'cflags_cc': [ '-fno-rtti', '-fno-exceptions' ], 'ldflags': [ '-pthread', '-rdynamic' ], 'target_conditions': [ ['_type=="static_library"', { 'standalone_static_library': 1, # disable thin archive which needs binutils >= 2.19 }], ], 'conditions': [ [ 'target_arch=="ia32"', { 'cflags': [ '-m32' ], 'ldflags': [ '-m32' ], }], [ 'target_arch=="x64"', { 'cflags': [ '-m64' ], 'ldflags': [ '-m64' ], }], [ 'OS=="solaris"', { 'cflags': [ '-pthreads' ], 'ldflags': [ '-pthreads' ], 'cflags!': [ '-pthread' ], 'ldflags!': [ '-pthread' ], }], ], }], ['OS=="mac"', { 'defines': ['_DARWIN_USE_64_BIT_INODE=1'], 'xcode_settings': { 'ALWAYS_SEARCH_USER_PATHS': 'NO', 'GCC_CW_ASM_SYNTAX': 'NO', # No -fasm-blocks 'GCC_DYNAMIC_NO_PIC': 'NO', # No -mdynamic-no-pic # (Equivalent to -fPIC) 'GCC_ENABLE_CPP_EXCEPTIONS': 'NO', # -fno-exceptions 'GCC_ENABLE_CPP_RTTI': 'NO', # -fno-rtti 'GCC_ENABLE_PASCAL_STRINGS': 'NO', # No -mpascal-strings 'GCC_THREADSAFE_STATICS': 'NO', # -fno-threadsafe-statics 'PREBINDING': 'NO', # No -Wl,-prebind 'MACOSX_DEPLOYMENT_TARGET': '10.5', # -mmacosx-version-min=10.5 'USE_HEADERMAP': 'NO', 'OTHER_CFLAGS': [ '-fno-strict-aliasing', ], 'WARNING_CFLAGS': [ '-Wall', '-Wendif-labels', '-W', '-Wno-unused-parameter', ], }, 'target_conditions': [ ['_type!="static_library"', { 'xcode_settings': {'OTHER_LDFLAGS': ['-Wl,-search_paths_first']}, }], ], 'conditions': [ ['target_arch=="ia32"', { 'xcode_settings': {'ARCHS': ['i386']}, }], ['target_arch=="x64"', { 'xcode_settings': {'ARCHS': ['x86_64']}, }], ], }], ['OS=="freebsd" and node_use_dtrace=="true"', { 'libraries': [ '-lelf' ], }] ], } } node-v0.10.25~dfsg2/test/0000755000000000000000000000000012270121457013574 5ustar rootrootnode-v0.10.25~dfsg2/test/message/0000755000000000000000000000000012270121457015220 5ustar rootrootnode-v0.10.25~dfsg2/test/message/2100bytes.js0000644000000000000000000000676412270121457017224 0ustar rootroot// Copyright Joyent, Inc. and other Node contributors. // // Permission is hereby granted, free of charge, to any person obtaining a // copy of this software and associated documentation files (the // "Software"), to deal in the Software without restriction, including // without limitation the rights to use, copy, modify, merge, publish, // distribute, sublicense, and/or sell copies of the Software, and to permit // persons to whom the Software is furnished to do so, subject to the // following conditions: // // The above copyright notice and this permission notice shall be included // in all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS // OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF // MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN // NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, // DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR // OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE // USE OR OTHER DEALINGS IN THE SOFTWARE. var common = require('../common'); var assert = require('assert'); var util = require('util'); console.log([ '_______________________________________________50', '______________________________________________100', '______________________________________________150', '______________________________________________200', '______________________________________________250', '______________________________________________300', '______________________________________________350', '______________________________________________400', '______________________________________________450', '______________________________________________500', '______________________________________________550', '______________________________________________600', '______________________________________________650', '______________________________________________700', '______________________________________________750', '______________________________________________800', '______________________________________________850', '______________________________________________900', '______________________________________________950', '_____________________________________________1000', '_____________________________________________1050', '_____________________________________________1100', '_____________________________________________1150', '_____________________________________________1200', '_____________________________________________1250', '_____________________________________________1300', '_____________________________________________1350', '_____________________________________________1400', '_____________________________________________1450', '_____________________________________________1500', '_____________________________________________1550', '_____________________________________________1600', '_____________________________________________1650', '_____________________________________________1700', '_____________________________________________1750', '_____________________________________________1800', '_____________________________________________1850', '_____________________________________________1900', '_____________________________________________1950', '_____________________________________________2000', '_____________________________________________2050', '_____________________________________________2100' ].join('\n')); node-v0.10.25~dfsg2/test/message/max_tick_depth_trace.js0000644000000000000000000000250512270121457021721 0ustar rootroot// Copyright Joyent, Inc. and other Node contributors. // // Permission is hereby granted, free of charge, to any person obtaining a // copy of this software and associated documentation files (the // "Software"), to deal in the Software without restriction, including // without limitation the rights to use, copy, modify, merge, publish, // distribute, sublicense, and/or sell copies of the Software, and to permit // persons to whom the Software is furnished to do so, subject to the // following conditions: // // The above copyright notice and this permission notice shall be included // in all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS // OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF // MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN // NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, // DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR // OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE // USE OR OTHER DEALINGS IN THE SOFTWARE. var common = require('../common'); process.maxTickDepth = 10; process.traceDeprecation = true; var i = 20; process.nextTick(function f() { console.error('tick %d', i); if (i-- > 0) process.nextTick(f); }); node-v0.10.25~dfsg2/test/message/hello_world.js0000644000000000000000000000232112270121457020066 0ustar rootroot// Copyright Joyent, Inc. and other Node contributors. // // Permission is hereby granted, free of charge, to any person obtaining a // copy of this software and associated documentation files (the // "Software"), to deal in the Software without restriction, including // without limitation the rights to use, copy, modify, merge, publish, // distribute, sublicense, and/or sell copies of the Software, and to permit // persons to whom the Software is furnished to do so, subject to the // following conditions: // // The above copyright notice and this permission notice shall be included // in all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS // OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF // MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN // NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, // DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR // OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE // USE OR OTHER DEALINGS IN THE SOFTWARE. var common = require('../common'); var assert = require('assert'); console.log('hello world'); node-v0.10.25~dfsg2/test/message/timeout_throw.out0000644000000000000000000000037512270121457020667 0ustar rootroot*test*message*timeout_throw.js:* undefined_reference_error_maker; ^ ReferenceError: undefined_reference_error_maker is not defined at null._onTimeout (*test*message*timeout_throw.js:*:*) at Timer.listOnTimeout [as ontimeout] (timers.js:*:*) node-v0.10.25~dfsg2/test/message/stdin_messages.out0000644000000000000000000000334012270121457020761 0ustar rootroot[stdin] [stdin]:1 with(this){__filename} ^^^^ SyntaxError: Strict mode code may not include a with statement at Object. ([stdin]-wrapper:*:*) at Module._compile (module.js:*:*) at evalScript (node.js:*:*) at Socket. (node.js:*:*) at Socket.EventEmitter.emit (events.js:*:*) at _stream_readable.js:*:* at process._tickCallback (node.js:*:*) 42 42 [stdin]:1 throw new Error("hello") ^ Error: hello at [stdin]:1:* at Object. ([stdin]-wrapper:*:*) at Module._compile (module.js:*:*) at evalScript (node.js:*:*) at Socket. (node.js:*:*) at Socket.EventEmitter.emit (events.js:*:*) at _stream_readable.js:*:* at process._tickCallback (node.js:*:*) [stdin]:1 throw new Error("hello") ^ Error: hello at [stdin]:1:* at Object. ([stdin]-wrapper:*:*) at Module._compile (module.js:*:*) at evalScript (node.js:*:*) at Socket. (node.js:*:*) at Socket.EventEmitter.emit (events.js:*:*) at _stream_readable.js:*:* at process._tickCallback (node.js:*:*) 100 [stdin]:1 var x = 100; y = x; ^ ReferenceError: y is not defined at [stdin]:1:16 at Object. ([stdin]-wrapper:*:*) at Module._compile (module.js:*:*) at evalScript (node.js:*:*) at Socket. (node.js:*:*) at Socket.EventEmitter.emit (events.js:*:*) at _stream_readable.js:*:* at process._tickCallback (node.js:*:*) [stdin]:1 var ______________________________________________; throw 10 ^ 10 [stdin]:1 var ______________________________________________; throw 10 ^ 10 done node-v0.10.25~dfsg2/test/message/2100bytes.out0000644000000000000000000000406412270121457017406 0ustar rootroot_______________________________________________50 ______________________________________________100 ______________________________________________150 ______________________________________________200 ______________________________________________250 ______________________________________________300 ______________________________________________350 ______________________________________________400 ______________________________________________450 ______________________________________________500 ______________________________________________550 ______________________________________________600 ______________________________________________650 ______________________________________________700 ______________________________________________750 ______________________________________________800 ______________________________________________850 ______________________________________________900 ______________________________________________950 _____________________________________________1000 _____________________________________________1050 _____________________________________________1100 _____________________________________________1150 _____________________________________________1200 _____________________________________________1250 _____________________________________________1300 _____________________________________________1350 _____________________________________________1400 _____________________________________________1450 _____________________________________________1500 _____________________________________________1550 _____________________________________________1600 _____________________________________________1650 _____________________________________________1700 _____________________________________________1750 _____________________________________________1800 _____________________________________________1850 _____________________________________________1900 _____________________________________________1950 _____________________________________________2000 _____________________________________________2050 _____________________________________________2100 node-v0.10.25~dfsg2/test/message/throw_in_line_with_tabs.out0000644000000000000000000000014012270121457022650 0ustar rootrootbefore *test*message*throw_in_line_with_tabs.js:32 throw ({ foo: 'bar' }); ^ [object Object] node-v0.10.25~dfsg2/test/message/throw_non_error.js0000644000000000000000000000242712270121457021011 0ustar rootroot// Copyright Joyent, Inc. and other Node contributors. // // Permission is hereby granted, free of charge, to any person obtaining a // copy of this software and associated documentation files (the // "Software"), to deal in the Software without restriction, including // without limitation the rights to use, copy, modify, merge, publish, // distribute, sublicense, and/or sell copies of the Software, and to permit // persons to whom the Software is furnished to do so, subject to the // following conditions: // // The above copyright notice and this permission notice shall be included // in all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS // OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF // MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN // NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, // DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR // OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE // USE OR OTHER DEALINGS IN THE SOFTWARE. var common = require('../common'); var assert = require('assert'); common.error('before'); // custom error throwing throw ({ foo: 'bar' }); common.error('after'); node-v0.10.25~dfsg2/test/message/stdin_messages.js0000644000000000000000000000347712270121457020601 0ustar rootroot // Copyright Joyent, Inc. and other Node contributors. // // Permission is hereby granted, free of charge, to any person obtaining a // copy of this software and associated documentation files (the // "Software"), to deal in the Software without restriction, including // without limitation the rights to use, copy, modify, merge, publish, // distribute, sublicense, and/or sell copies of the Software, and to permit // persons to whom the Software is furnished to do so, subject to the // following conditions: // // The above copyright notice and this permission notice shall be included // in all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS // OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF // MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN // NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, // DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR // OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE // USE OR OTHER DEALINGS IN THE SOFTWARE. var common = require('../common'); var assert = require('assert'); var spawn = require('child_process').spawn; function run(cmd, strict, cb) { var args = []; if (strict) args.push('--use_strict'); args.push('-p'); var child = spawn(process.execPath, args); child.stdout.pipe(process.stdout); child.stderr.pipe(process.stdout); child.stdin.end(cmd); child.on('close', cb); } var queue = [ 'with(this){__filename}', '42', 'throw new Error("hello")', 'var x = 100; y = x;', 'var ______________________________________________; throw 10' ]; function go() { var c = queue.shift(); if (!c) return console.log('done'); run(c, false, function() { run(c, true, go); }); } go(); node-v0.10.25~dfsg2/test/message/throw_in_line_with_tabs.js0000644000000000000000000000247012270121457022465 0ustar rootroot// Copyright Joyent, Inc. and other Node contributors. // // Permission is hereby granted, free of charge, to any person obtaining a // copy of this software and associated documentation files (the // "Software"), to deal in the Software without restriction, including // without limitation the rights to use, copy, modify, merge, publish, // distribute, sublicense, and/or sell copies of the Software, and to permit // persons to whom the Software is furnished to do so, subject to the // following conditions: // // The above copyright notice and this permission notice shall be included // in all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS // OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF // MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN // NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, // DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR // OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE // USE OR OTHER DEALINGS IN THE SOFTWARE. var common = require('../common'); var assert = require('assert'); common.error('before'); (function () { // these lines should contain tab! throw ({ foo: 'bar' }); })(); common.error('after'); node-v0.10.25~dfsg2/test/message/undefined_reference_in_new_context.out0000644000000000000000000000074512270121457025041 0ustar rootrootbefore *test*message*undefined_reference_in_new_context.js:34 script.runInNewContext(); ^ ReferenceError: foo is not defined at evalmachine.:* at Object. (*test*message*undefined_reference_in_new_context.js:*) at Module._compile (module.js:*) at *..js (module.js:*) at Module.load (module.js:*) at Function.Module._load (module.js:*:*) at Function.Module.runMain (module.js:*:*) at startup (node.js:*:*) at node.js:*:* node-v0.10.25~dfsg2/test/message/eval_messages.out0000644000000000000000000000241212270121457020566 0ustar rootroot[eval] [eval]:1 with(this){__filename} ^^^^ SyntaxError: Strict mode code may not include a with statement at Object. ([eval]-wrapper:*:*) at Module._compile (module.js:*:*) at evalScript (node.js:*:*) at startup (node.js:*:*) at node.js:*:* 42 42 [eval]:1 throw new Error("hello") ^ Error: hello at [eval]:1:7 at Object. ([eval]-wrapper:*:*) at Module._compile (module.js:*:*) at evalScript (node.js:*:*) at startup (node.js:*:*) at node.js:*:* [eval]:1 throw new Error("hello") ^ Error: hello at [eval]:1:7 at Object. ([eval]-wrapper:*:*) at Module._compile (module.js:*:*) at evalScript (node.js:*:*) at startup (node.js:*:*) at node.js:*:* 100 [eval]:1 var x = 100; y = x; ^ ReferenceError: y is not defined at [eval]:1:16 at Object. ([eval]-wrapper:*:*) at Module._compile (module.js:*:*) at evalScript (node.js:*:*) at startup (node.js:*:*) at node.js:*:* [eval]:1 var ______________________________________________; throw 10 ^ 10 [eval]:1 var ______________________________________________; throw 10 ^ 10 done node-v0.10.25~dfsg2/test/message/undefined_reference_in_new_context.js0000644000000000000000000000256312270121457024646 0ustar rootroot// Copyright Joyent, Inc. and other Node contributors. // // Permission is hereby granted, free of charge, to any person obtaining a // copy of this software and associated documentation files (the // "Software"), to deal in the Software without restriction, including // without limitation the rights to use, copy, modify, merge, publish, // distribute, sublicense, and/or sell copies of the Software, and to permit // persons to whom the Software is furnished to do so, subject to the // following conditions: // // The above copyright notice and this permission notice shall be included // in all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS // OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF // MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN // NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, // DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR // OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE // USE OR OTHER DEALINGS IN THE SOFTWARE. var common = require('../common'); var assert = require('assert'); common.error('before'); var Script = process.binding('evals').NodeScript; // undefined reference var script = new Script('foo.bar = 5;'); script.runInNewContext(); common.error('after'); node-v0.10.25~dfsg2/test/message/max_tick_depth.out0000644000000000000000000000070212270121457020733 0ustar rootroottick 20 tick 19 tick 18 tick 17 tick 16 tick 15 tick 14 tick 13 tick 12 tick 11 (node) warning: Recursive process.nextTick detected. This will break in the next version of node. Please use setImmediate for recursive deferral. tick 10 tick 9 tick 8 tick 7 tick 6 tick 5 tick 4 tick 3 tick 2 tick 1 (node) warning: Recursive process.nextTick detected. This will break in the next version of node. Please use setImmediate for recursive deferral. tick 0 node-v0.10.25~dfsg2/test/message/hello_world.out0000644000000000000000000000001412270121457020256 0ustar rootroothello world node-v0.10.25~dfsg2/test/message/nexttick_throw.js0000644000000000000000000000257312270121457020641 0ustar rootroot// Copyright Joyent, Inc. and other Node contributors. // // Permission is hereby granted, free of charge, to any person obtaining a // copy of this software and associated documentation files (the // "Software"), to deal in the Software without restriction, including // without limitation the rights to use, copy, modify, merge, publish, // distribute, sublicense, and/or sell copies of the Software, and to permit // persons to whom the Software is furnished to do so, subject to the // following conditions: // // The above copyright notice and this permission notice shall be included // in all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS // OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF // MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN // NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, // DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR // OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE // USE OR OTHER DEALINGS IN THE SOFTWARE. var common = require('../common'); var assert = require('assert'); process.nextTick(function() { process.nextTick(function() { process.nextTick(function() { process.nextTick(function() { undefined_reference_error_maker; }); }); }); }); node-v0.10.25~dfsg2/test/message/eval_messages.js0000644000000000000000000000345512270121457020403 0ustar rootroot // Copyright Joyent, Inc. and other Node contributors. // // Permission is hereby granted, free of charge, to any person obtaining a // copy of this software and associated documentation files (the // "Software"), to deal in the Software without restriction, including // without limitation the rights to use, copy, modify, merge, publish, // distribute, sublicense, and/or sell copies of the Software, and to permit // persons to whom the Software is furnished to do so, subject to the // following conditions: // // The above copyright notice and this permission notice shall be included // in all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS // OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF // MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN // NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, // DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR // OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE // USE OR OTHER DEALINGS IN THE SOFTWARE. var common = require('../common'); var assert = require('assert'); var spawn = require('child_process').spawn; function run(cmd, strict, cb) { var args = []; if (strict) args.push('--use_strict'); args.push('-pe', cmd); var child = spawn(process.execPath, args); child.stdout.pipe(process.stdout); child.stderr.pipe(process.stdout); child.on('close', cb); } var queue = [ 'with(this){__filename}', '42', 'throw new Error("hello")', 'var x = 100; y = x;', 'var ______________________________________________; throw 10' ]; function go() { var c = queue.shift(); if (!c) return console.log('done'); run(c, false, function() { run(c, true, go); }); } go(); node-v0.10.25~dfsg2/test/message/throw_custom_error.out0000644000000000000000000000024112270121457021714 0ustar rootrootbefore *test*message*throw_custom_error.js:31 throw ({ name: 'MyCustomError', message: 'This is a custom message' }); ^ MyCustomError: This is a custom message node-v0.10.25~dfsg2/test/message/max_tick_depth_trace.out0000644000000000000000000000165312270121457022117 0ustar rootroottick 20 tick 19 tick 18 tick 17 tick 16 tick 15 tick 14 tick 13 tick 12 tick 11 Trace: (node) warning: Recursive process.nextTick detected. This will break in the next version of node. Please use setImmediate for recursive deferral. at maxTickWarn (node.js:*:*) at process.nextTick (node.js:*:*) at f (*test*message*max_tick_depth_trace.js:*:*) at process._tickCallback (node.js:*:*) at Function.Module.runMain (module.js:*:*) at startup (node.js:*:*) at node.js:*:* tick 10 tick 9 tick 8 tick 7 tick 6 tick 5 tick 4 tick 3 tick 2 tick 1 Trace: (node) warning: Recursive process.nextTick detected. This will break in the next version of node. Please use setImmediate for recursive deferral. at maxTickWarn (node.js:*:*) at process.nextTick (node.js:*:*) at f (*test*message*max_tick_depth_trace.js:*:*) at process._tickCallback (node.js:*:*) at process._tickFromSpinner (node.js:*:*) tick 0 node-v0.10.25~dfsg2/test/message/max_tick_depth.js0000644000000000000000000000244412270121457020545 0ustar rootroot// Copyright Joyent, Inc. and other Node contributors. // // Permission is hereby granted, free of charge, to any person obtaining a // copy of this software and associated documentation files (the // "Software"), to deal in the Software without restriction, including // without limitation the rights to use, copy, modify, merge, publish, // distribute, sublicense, and/or sell copies of the Software, and to permit // persons to whom the Software is furnished to do so, subject to the // following conditions: // // The above copyright notice and this permission notice shall be included // in all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS // OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF // MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN // NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, // DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR // OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE // USE OR OTHER DEALINGS IN THE SOFTWARE. var common = require('../common'); process.maxTickDepth = 10; var i = 20; process.nextTick(function f() { console.error('tick %d', i); if (i-- > 0) process.nextTick(f); }); node-v0.10.25~dfsg2/test/message/nexttick_throw.out0000644000000000000000000000051212270121457021023 0ustar rootroot *test*message*nexttick_throw.js:* undefined_reference_error_maker; ^ ReferenceError: undefined_reference_error_maker is not defined at *test*message*nexttick_throw.js:*:* at process._tickCallback (node.js:*:*) at Function.Module.runMain (module.js:*:*) at startup (node.js:*:*) at node.js:*:* node-v0.10.25~dfsg2/test/message/throw_non_error.out0000644000000000000000000000012612270121457021176 0ustar rootrootbefore *test*message*throw_non_error.js:31 throw ({ foo: 'bar' }); ^ [object Object] node-v0.10.25~dfsg2/test/message/testcfg.py0000644000000000000000000001226112270121457017233 0ustar rootroot# Copyright 2008 the V8 project authors. All rights reserved. # Redistribution and use in source and binary forms, with or without # modification, are permitted provided that the following conditions are # met: # # * Redistributions of source code must retain the above copyright # notice, this list of conditions and the following disclaimer. # * Redistributions in binary form must reproduce the above # copyright notice, this list of conditions and the following # disclaimer in the documentation and/or other materials provided # with the distribution. # * Neither the name of Google Inc. nor the names of its # contributors may be used to endorse or promote products derived # from this software without specific prior written permission. # # THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS # "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT # LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR # A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT # OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, # SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT # LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, # DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY # THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT # (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE # OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. import test import os from os.path import join, dirname, exists, basename, isdir import re FLAGS_PATTERN = re.compile(r"//\s+Flags:(.*)") class MessageTestCase(test.TestCase): def __init__(self, path, file, expected, mode, context, config): super(MessageTestCase, self).__init__(context, path, mode) self.file = file self.expected = expected self.config = config self.mode = mode def IgnoreLine(self, str): """Ignore empty lines and valgrind output.""" if not str.strip(): return True else: return str.startswith('==') or str.startswith('**') def IsFailureOutput(self, output): f = file(self.expected) # Skip initial '#' comment and spaces #for line in f: # if (not line.startswith('#')) and (not line.strip()): # break # Convert output lines to regexps that we can match env = { 'basename': basename(self.file) } patterns = [ ] for line in f: if not line.strip(): continue pattern = re.escape(line.rstrip() % env) pattern = pattern.replace('\\*', '.*') pattern = '^%s$' % pattern patterns.append(pattern) # Compare actual output with the expected raw_lines = (output.stdout + output.stderr).split('\n') outlines = [ s for s in raw_lines if not self.IgnoreLine(s) ] if len(outlines) != len(patterns): print "length differs." print "expect=%d" % len(patterns) print "actual=%d" % len(outlines) print "patterns:" for i in xrange(len(patterns)): print "pattern = %s" % patterns[i] print "outlines:" for i in xrange(len(outlines)): print "outline = %s" % outlines[i] return True for i in xrange(len(patterns)): if not re.match(patterns[i], outlines[i]): print "match failed" print "line=%d" % i print "expect=%s" % patterns[i] print "actual=%s" % outlines[i] return True return False def GetLabel(self): return "%s %s" % (self.mode, self.GetName()) def GetName(self): return self.path[-1] def GetCommand(self): result = [self.config.context.GetVm(self.mode)] source = open(self.file).read() flags_match = FLAGS_PATTERN.search(source) if flags_match: result += flags_match.group(1).strip().split() result.append(self.file) return result def GetSource(self): return (open(self.file).read() + "\n--- expected output ---\n" + open(self.expected).read()) class MessageTestConfiguration(test.TestConfiguration): def __init__(self, context, root): super(MessageTestConfiguration, self).__init__(context, root) def Ls(self, path): if isdir(path): return [f[:-3] for f in os.listdir(path) if f.endswith('.js')] else: return [] def ListTests(self, current_path, path, mode): all_tests = [current_path + [t] for t in self.Ls(self.root)] result = [] for test in all_tests: if self.Contains(path, test): file_prefix = join(self.root, reduce(join, test[1:], "")) file_path = file_prefix + ".js" output_path = file_prefix + ".out" if not exists(output_path): print "Could not find %s" % output_path continue result.append(MessageTestCase(test, file_path, output_path, mode, self.context, self)) return result def GetBuildRequirements(self): return ['sample', 'sample=shell'] def GetTestStatus(self, sections, defs): status_file = join(self.root, 'message.status') if exists(status_file): test.ReadConfigurationInto(status_file, sections, defs) def GetConfiguration(context, root): return MessageTestConfiguration(context, root) node-v0.10.25~dfsg2/test/message/error_exit.out0000644000000000000000000000065512270121457020141 0ustar rootrootExiting with code=1 assert.js:* throw new assert.AssertionError({ ^ AssertionError: 1 == 2 at Object. (*test*message*error_exit.js:*:*) at Module._compile (module.js:*:*) at Object.Module._extensions..js (module.js:*:*) at Module.load (module.js:*:*) at Function.Module._load (module.js:*:*) at Function.Module.runMain (module.js:*:*) at startup (node.js:*:*) at node.js:*:* node-v0.10.25~dfsg2/test/message/timeout_throw.js0000644000000000000000000000236112270121457020471 0ustar rootroot// Copyright Joyent, Inc. and other Node contributors. // // Permission is hereby granted, free of charge, to any person obtaining a // copy of this software and associated documentation files (the // "Software"), to deal in the Software without restriction, including // without limitation the rights to use, copy, modify, merge, publish, // distribute, sublicense, and/or sell copies of the Software, and to permit // persons to whom the Software is furnished to do so, subject to the // following conditions: // // The above copyright notice and this permission notice shall be included // in all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS // OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF // MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN // NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, // DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR // OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE // USE OR OTHER DEALINGS IN THE SOFTWARE. var common = require('../common'); var assert = require('assert'); setTimeout(function() { undefined_reference_error_maker; }); node-v0.10.25~dfsg2/test/message/stack_overflow.out0000644000000000000000000000021312270121457020775 0ustar rootrootbefore *test*message*stack_overflow.js:31 function stackOverflow() { ^ RangeError: Maximum call stack size exceeded node-v0.10.25~dfsg2/test/message/throw_custom_error.js0000644000000000000000000000250712270121457021530 0ustar rootroot// Copyright Joyent, Inc. and other Node contributors. // // Permission is hereby granted, free of charge, to any person obtaining a // copy of this software and associated documentation files (the // "Software"), to deal in the Software without restriction, including // without limitation the rights to use, copy, modify, merge, publish, // distribute, sublicense, and/or sell copies of the Software, and to permit // persons to whom the Software is furnished to do so, subject to the // following conditions: // // The above copyright notice and this permission notice shall be included // in all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS // OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF // MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN // NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, // DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR // OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE // USE OR OTHER DEALINGS IN THE SOFTWARE. var common = require('../common'); var assert = require('assert'); common.error('before'); // custom error throwing throw ({ name: 'MyCustomError', message: 'This is a custom message' }); common.error('after'); node-v0.10.25~dfsg2/test/message/stack_overflow.js0000644000000000000000000000247112270121457020612 0ustar rootroot// Copyright Joyent, Inc. and other Node contributors. // // Permission is hereby granted, free of charge, to any person obtaining a // copy of this software and associated documentation files (the // "Software"), to deal in the Software without restriction, including // without limitation the rights to use, copy, modify, merge, publish, // distribute, sublicense, and/or sell copies of the Software, and to permit // persons to whom the Software is furnished to do so, subject to the // following conditions: // // The above copyright notice and this permission notice shall be included // in all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS // OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF // MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN // NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, // DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR // OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE // USE OR OTHER DEALINGS IN THE SOFTWARE. var common = require('../common'); var assert = require('assert'); common.error('before'); // stack overflow function stackOverflow() { stackOverflow(); } stackOverflow(); common.error('after'); node-v0.10.25~dfsg2/test/message/error_exit.js0000644000000000000000000000244112270121457017741 0ustar rootroot// Copyright Joyent, Inc. and other Node contributors. // // Permission is hereby granted, free of charge, to any person obtaining a // copy of this software and associated documentation files (the // "Software"), to deal in the Software without restriction, including // without limitation the rights to use, copy, modify, merge, publish, // distribute, sublicense, and/or sell copies of the Software, and to permit // persons to whom the Software is furnished to do so, subject to the // following conditions: // // The above copyright notice and this permission notice shall be included // in all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS // OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF // MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN // NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, // DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR // OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE // USE OR OTHER DEALINGS IN THE SOFTWARE. var common = require('../common.js'); var assert = require('assert'); process.on('exit', function(code) { console.error('Exiting with code=%d', code); }); assert.equal(1, 2); node-v0.10.25~dfsg2/test/internet/0000755000000000000000000000000012270121457015424 5ustar rootrootnode-v0.10.25~dfsg2/test/internet/test-net-connect-unref.js0000644000000000000000000000322612270121457022274 0ustar rootroot// Copyright Joyent, Inc. and other Node contributors. // // Permission is hereby granted, free of charge, to any person obtaining a // copy of this software and associated documentation files (the // "Software"), to deal in the Software without restriction, including // without limitation the rights to use, copy, modify, merge, publish, // distribute, sublicense, and/or sell copies of the Software, and to permit // persons to whom the Software is furnished to do so, subject to the // following conditions: // // The above copyright notice and this permission notice shall be included // in all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS // OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF // MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN // NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, // DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR // OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE // USE OR OTHER DEALINGS IN THE SOFTWARE. var common = require('../common'); var assert = require('assert'); var net = require('net'); var client, killed = false, ended = false; var TIMEOUT = 10 * 1000 client = net.createConnection(53, '8.8.8.8', function() { client.unref(); }); client.on('close', function() { ended = true; }); setTimeout(function() { killed = true; client.end(); }, TIMEOUT).unref(); process.on('exit', function() { assert.strictEqual(killed, false, 'A client should have connected'); assert.strictEqual(ended, false, 'A client should stay connected'); }); node-v0.10.25~dfsg2/test/internet/internet.status0000644000000000000000000000002012270121457020511 0ustar rootrootprefix internet node-v0.10.25~dfsg2/test/internet/test-net-connect-timeout.js0000644000000000000000000000477412270121457022654 0ustar rootroot// Copyright Joyent, Inc. and other Node contributors. // // Permission is hereby granted, free of charge, to any person obtaining a // copy of this software and associated documentation files (the // "Software"), to deal in the Software without restriction, including // without limitation the rights to use, copy, modify, merge, publish, // distribute, sublicense, and/or sell copies of the Software, and to permit // persons to whom the Software is furnished to do so, subject to the // following conditions: // // The above copyright notice and this permission notice shall be included // in all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS // OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF // MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN // NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, // DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR // OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE // USE OR OTHER DEALINGS IN THE SOFTWARE. // This example attempts to time out before the connection is established // https://groups.google.com/forum/#!topic/nodejs/UE0ZbfLt6t8 // https://groups.google.com/forum/#!topic/nodejs-dev/jR7-5UDqXkw // // TODO: how to do this without relying on the responses of specific sites? var common = require('../common'); var net = require('net'); var assert = require('assert'); var start = new Date(); var gotTimeout0 = false; var gotTimeout1 = false; var gotConnect0 = false; var gotConnect1 = false; var T = 100; // With DNS var socket0 = net.createConnection(9999, 'google.com'); socket0.setTimeout(T); socket0.on('timeout', function() { console.error('timeout'); gotTimeout0 = true; var now = new Date(); assert.ok(now - start < T + 500); socket0.destroy(); }); socket0.on('connect', function() { console.error('connect'); gotConnect0 = true; socket0.destroy(); }); // Without DNS var socket1 = net.createConnection(9999, '24.24.24.24'); socket1.setTimeout(T); socket1.on('timeout', function() { console.error('timeout'); gotTimeout1 = true; var now = new Date(); assert.ok(now - start < T + 500); socket1.destroy(); }); socket1.on('connect', function() { console.error('connect'); gotConnect1 = true; socket1.destroy(); }); process.on('exit', function() { assert.ok(gotTimeout0); assert.ok(!gotConnect0); assert.ok(gotTimeout1); assert.ok(!gotConnect1); }); node-v0.10.25~dfsg2/test/internet/test-http-dns-fail.js0000644000000000000000000000362112270121457021413 0ustar rootroot// Copyright Joyent, Inc. and other Node contributors. // // Permission is hereby granted, free of charge, to any person obtaining a // copy of this software and associated documentation files (the // "Software"), to deal in the Software without restriction, including // without limitation the rights to use, copy, modify, merge, publish, // distribute, sublicense, and/or sell copies of the Software, and to permit // persons to whom the Software is furnished to do so, subject to the // following conditions: // // The above copyright notice and this permission notice shall be included // in all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS // OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF // MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN // NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, // DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR // OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE // USE OR OTHER DEALINGS IN THE SOFTWARE. /* * Repeated requests for a domain that fails to resolve * should trigger the error event after each attempt. */ var common = require('../common'); var assert = require('assert'); var http = require('http'); var resDespiteError = false; var hadError = 0; function httpreq(count) { if (1 < count) return; var req = http.request({ host: 'not-a-real-domain-name.nobody-would-register-this-as-a-tld', port: 80, path: '/', method: 'GET' }, function(res) { resDespiteError = true; }); req.on('error', function(e) { console.log(e.message); assert.strictEqual(e.code, 'ENOTFOUND'); hadError++; httpreq(count + 1); }); req.end(); } httpreq(0); process.on('exit', function() { assert.equal(false, resDespiteError); assert.equal(2, hadError); }); node-v0.10.25~dfsg2/test/internet/test-dns.js0000644000000000000000000002205412270121457017526 0ustar rootroot// Copyright Joyent, Inc. and other Node contributors. // // Permission is hereby granted, free of charge, to any person obtaining a // copy of this software and associated documentation files (the // "Software"), to deal in the Software without restriction, including // without limitation the rights to use, copy, modify, merge, publish, // distribute, sublicense, and/or sell copies of the Software, and to permit // persons to whom the Software is furnished to do so, subject to the // following conditions: // // The above copyright notice and this permission notice shall be included // in all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS // OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF // MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN // NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, // DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR // OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE // USE OR OTHER DEALINGS IN THE SOFTWARE. var common = require('../common'); var assert = require('assert'), dns = require('dns'), net = require('net'), isIP = net.isIP, isIPv4 = net.isIPv4, isIPv6 = net.isIPv6; var expected = 0, completed = 0, running = false, queue = []; function TEST(f) { function next() { var f = queue.shift(); if (f) { running = true; console.log(f.name); f(done); } } function done() { running = false; completed++; process.nextTick(next); } expected++; queue.push(f); if (!running) { next(); } } function checkWrap(req) { assert.ok(typeof req === 'object'); } TEST(function test_resolve4(done) { var req = dns.resolve4('www.google.com', function(err, ips) { if (err) throw err; assert.ok(ips.length > 0); for (var i = 0; i < ips.length; i++) { assert.ok(isIPv4(ips[i])); } done(); }); checkWrap(req); }); TEST(function test_resolve6(done) { var req = dns.resolve6('ipv6.google.com', function(err, ips) { if (err) throw err; assert.ok(ips.length > 0); for (var i = 0; i < ips.length; i++) { assert.ok(isIPv6(ips[i])); } done(); }); checkWrap(req); }); TEST(function test_reverse_ipv4(done) { var req = dns.reverse('8.8.8.8', function(err, domains) { if (err) throw err; assert.ok(domains.length > 0); for (var i = 0; i < domains.length; i++) { assert.ok(domains[i]); assert.ok(typeof domains[i] === 'string'); } done(); }); checkWrap(req); }); TEST(function test_reverse_ipv6(done) { var req = dns.reverse('2001:4860:4860::8888', function(err, domains) { if (err) throw err; assert.ok(domains.length > 0); for (var i = 0; i < domains.length; i++) { assert.ok(domains[i]); assert.ok(typeof domains[i] === 'string'); } done(); }); checkWrap(req); }); TEST(function test_reverse_bogus(done) { var error; try { var req = dns.reverse('bogus ip', function() { assert.ok(false); }); } catch (e) { error = e; } assert.ok(error instanceof Error); assert.strictEqual(error.errno, 'ENOTIMP'); done(); }); TEST(function test_resolveMx(done) { var req = dns.resolveMx('gmail.com', function(err, result) { if (err) throw err; assert.ok(result.length > 0); for (var i = 0; i < result.length; i++) { var item = result[i]; assert.ok(item); assert.ok(typeof item === 'object'); assert.ok(item.exchange); assert.ok(typeof item.exchange === 'string'); assert.ok(typeof item.priority === 'number'); } done(); }); checkWrap(req); }); TEST(function test_resolveNs(done) { var req = dns.resolveNs('rackspace.com', function(err, names) { if (err) throw err; assert.ok(names.length > 0); for (var i = 0; i < names.length; i++) { var name = names[i]; assert.ok(name); assert.ok(typeof name === 'string'); } done(); }); checkWrap(req); }); TEST(function test_resolveSrv(done) { var req = dns.resolveSrv('_jabber._tcp.google.com', function(err, result) { if (err) throw err; assert.ok(result.length > 0); for (var i = 0; i < result.length; i++) { var item = result[i]; assert.ok(item); assert.ok(typeof item === 'object'); assert.ok(item.name); assert.ok(typeof item.name === 'string'); assert.ok(typeof item.port === 'number'); assert.ok(typeof item.priority === 'number'); assert.ok(typeof item.weight === 'number'); } done(); }); checkWrap(req); }); TEST(function test_resolveNaptr(done) { var req = dns.resolveNaptr('sip2sip.info', function(err, result) { if (err) throw err; assert.ok(result.length > 0); for (var i = 0; i < result.length; i++) { var item = result[i]; assert.ok(item); assert.ok(typeof item === 'object'); assert.ok(typeof item.flags === 'string'); assert.ok(typeof item.service === 'string'); assert.ok(typeof item.regexp === 'string'); assert.ok(typeof item.replacement === 'string'); assert.ok(typeof item.order === 'number'); assert.ok(typeof item.preference === 'number'); } done(); }); checkWrap(req); }); TEST(function test_resolveCname(done) { var req = dns.resolveCname('www.microsoft.com', function(err, names) { if (err) throw err; assert.ok(names.length > 0); for (var i = 0; i < names.length; i++) { var name = names[i]; assert.ok(name); assert.ok(typeof name === 'string'); } done(); }); checkWrap(req); }); TEST(function test_resolveTxt(done) { var req = dns.resolveTxt('google.com', function(err, records) { if (err) throw err; assert.equal(records.length, 1); assert.equal(records[0].indexOf('v=spf1'), 0); done(); }); checkWrap(req); }); TEST(function test_lookup_ipv4_explicit(done) { var req = dns.lookup('www.google.com', 4, function(err, ip, family) { if (err) throw err; assert.ok(net.isIPv4(ip)); assert.strictEqual(family, 4); done(); }); checkWrap(req); }); TEST(function test_lookup_ipv4_implicit(done) { var req = dns.lookup('www.google.com', function(err, ip, family) { if (err) throw err; assert.ok(net.isIPv4(ip)); assert.strictEqual(family, 4); done(); }); checkWrap(req); }); TEST(function test_lookup_ipv6_explicit(done) { var req = dns.lookup('ipv6.google.com', 6, function(err, ip, family) { if (err) throw err; assert.ok(net.isIPv6(ip)); assert.strictEqual(family, 6); done(); }); checkWrap(req); }); TEST(function test_lookup_ipv6_implicit(done) { var req = dns.lookup('ipv6.google.com', function(err, ip, family) { if (err) throw err; assert.ok(net.isIPv6(ip)); assert.strictEqual(family, 6); done(); }); checkWrap(req); }); TEST(function test_lookup_failure(done) { var req = dns.lookup('does.not.exist', 4, function(err, ip, family) { assert.ok(err instanceof Error); assert.strictEqual(err.errno, dns.NOTFOUND); assert.strictEqual(err.errno, 'ENOTFOUND'); assert.ok(!/ENOENT/.test(err.message)); done(); }); checkWrap(req); }); TEST(function test_lookup_null(done) { var req = dns.lookup(null, function(err, ip, family) { if (err) throw err; assert.strictEqual(ip, null); assert.strictEqual(family, 4); done(); }); checkWrap(req); }); TEST(function test_lookup_ip_ipv4(done) { var req = dns.lookup('127.0.0.1', function(err, ip, family) { if (err) throw err; assert.strictEqual(ip, '127.0.0.1'); assert.strictEqual(family, 4); done(); }); checkWrap(req); }); TEST(function test_lookup_ip_ipv6(done) { var req = dns.lookup('::1', function(err, ip, family) { if (err) throw err; assert.ok(net.isIPv6(ip)); assert.strictEqual(family, 6); done(); }); checkWrap(req); }); TEST(function test_lookup_localhost_ipv4(done) { var req = dns.lookup('localhost', 4, function(err, ip, family) { if (err) throw err; assert.strictEqual(ip, '127.0.0.1'); assert.strictEqual(family, 4); done(); }); checkWrap(req); }); /* Disabled because it appears to be not working on linux. */ /* TEST(function test_lookup_localhost_ipv6(done) { var req = dns.lookup('localhost', 6, function(err, ip, family) { if (err) throw err; assert.ok(net.isIPv6(ip)); assert.strictEqual(family, 6); done(); }); checkWrap(req); }); */ var getaddrinfoCallbackCalled = false; console.log('looking up nodejs.org...'); var req = process.binding('cares_wrap').getaddrinfo('nodejs.org'); req.oncomplete = function(domains) { console.log('nodejs.org = ', domains); assert.ok(Array.isArray(domains)); assert.ok(domains.length >= 1); assert.ok(typeof domains[0] == 'string'); getaddrinfoCallbackCalled = true; }; process.on('exit', function() { console.log(completed + ' tests completed'); assert.equal(running, false); assert.strictEqual(expected, completed); assert.ok(getaddrinfoCallbackCalled); }); node-v0.10.25~dfsg2/test/internet/test-dgram-multicast-multi-process.js0000644000000000000000000001574112270121457024650 0ustar rootroot// Copyright Joyent, Inc. and other Node contributors. // // Permission is hereby granted, free of charge, to any person obtaining a // copy of this software and associated documentation files (the // "Software"), to deal in the Software without restriction, including // without limitation the rights to use, copy, modify, merge, publish, // distribute, sublicense, and/or sell copies of the Software, and to permit // persons to whom the Software is furnished to do so, subject to the // following conditions: // // The above copyright notice and this permission notice shall be included // in all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS // OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF // MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN // NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, // DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR // OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE // USE OR OTHER DEALINGS IN THE SOFTWARE. var common = require('../common'), assert = require('assert'), dgram = require('dgram'), util = require('util'), assert = require('assert'), Buffer = require('buffer').Buffer, fork = require('child_process').fork, LOCAL_BROADCAST_HOST = '224.0.0.114', TIMEOUT = 5000, messages = [ new Buffer('First message to send'), new Buffer('Second message to send'), new Buffer('Third message to send'), new Buffer('Fourth message to send') ]; if (process.argv[2] !== 'child') { var workers = {}, listeners = 3, listening = 0, dead = 0, i = 0, done = 0, timer = null; //exit the test if it doesn't succeed within TIMEOUT timer = setTimeout(function() { console.error('[PARENT] Responses were not received within %d ms.', TIMEOUT); console.error('[PARENT] Fail'); killChildren(workers); process.exit(1); }, TIMEOUT); //launch child processes for (var x = 0; x < listeners; x++) { (function() { var worker = fork(process.argv[1], ['child']); workers[worker.pid] = worker; worker.messagesReceived = []; //handle the death of workers worker.on('exit', function(code, signal) { // don't consider this the true death if the // worker has finished successfully // or if the exit code is 0 if (worker.isDone || code === 0) { return; } dead += 1; console.error('[PARENT] Worker %d died. %d dead of %d', worker.pid, dead, listeners); if (dead === listeners) { console.error('[PARENT] All workers have died.'); console.error('[PARENT] Fail'); killChildren(workers); process.exit(1); } }); worker.on('message', function(msg) { if (msg.listening) { listening += 1; if (listening === listeners) { //all child process are listening, so start sending sendSocket.sendNext(); } } else if (msg.message) { worker.messagesReceived.push(msg.message); if (worker.messagesReceived.length === messages.length) { done += 1; worker.isDone = true; console.error('[PARENT] %d received %d messages total.', worker.pid, worker.messagesReceived.length); } if (done === listeners) { console.error('[PARENT] All workers have received the ' + 'required number of messages. Will now compare.'); Object.keys(workers).forEach(function(pid) { var worker = workers[pid]; var count = 0; worker.messagesReceived.forEach(function(buf) { for (var i = 0; i < messages.length; ++i) { if (buf.toString() === messages[i].toString()) { count++; break; } } }); console.error('[PARENT] %d received %d matching messages.', worker.pid, count); assert.equal(count, messages.length, 'A worker received an invalid multicast message'); }); clearTimeout(timer); console.error('[PARENT] Success'); killChildren(workers); } } }); })(x); } var sendSocket = dgram.createSocket('udp4'); // FIXME a libuv limitation makes it necessary to bind() // before calling any of the set*() functions - the bind() // call is what creates the actual socket... sendSocket.bind(); // The socket is actually created async now sendSocket.on('listening', function () { sendSocket.setTTL(1); sendSocket.setBroadcast(true); sendSocket.setMulticastTTL(1); sendSocket.setMulticastLoopback(true); }); sendSocket.on('close', function() { console.error('[PARENT] sendSocket closed'); }); sendSocket.sendNext = function() { var buf = messages[i++]; if (!buf) { try { sendSocket.close(); } catch (e) {} return; } sendSocket.send(buf, 0, buf.length, common.PORT, LOCAL_BROADCAST_HOST, function(err) { if (err) throw err; console.error('[PARENT] sent %s to %s:%s', util.inspect(buf.toString()), LOCAL_BROADCAST_HOST, common.PORT); process.nextTick(sendSocket.sendNext); }); }; function killChildren(children) { Object.keys(children).forEach(function(key) { var child = children[key]; child.kill(); }); } } if (process.argv[2] === 'child') { var receivedMessages = []; var listenSocket = dgram.createSocket('udp4'); listenSocket.on('message', function(buf, rinfo) { console.error('[CHILD] %s received %s from %j', process.pid, util.inspect(buf.toString()), rinfo); receivedMessages.push(buf); process.send({ message: buf.toString() }); if (receivedMessages.length == messages.length) { listenSocket.dropMembership(LOCAL_BROADCAST_HOST); process.nextTick(function() { // TODO should be changed to below. // listenSocket.dropMembership(LOCAL_BROADCAST_HOST, function() { listenSocket.close(); }); } }); listenSocket.on('close', function() { //HACK: Wait to exit the process to ensure that the parent //process has had time to receive all messages via process.send() //This may be indicitave of some other issue. setTimeout(function() { process.exit(); }, 1000); }); listenSocket.on('listening', function() { process.send({ listening: true }); }); listenSocket.bind(common.PORT); listenSocket.on('listening', function () { listenSocket.addMembership(LOCAL_BROADCAST_HOST); }); } node-v0.10.25~dfsg2/test/internet/testcfg.py0000644000000000000000000001043612270121457017441 0ustar rootroot# Copyright 2008 the V8 project authors. All rights reserved. # Redistribution and use in source and binary forms, with or without # modification, are permitted provided that the following conditions are # met: # # * Redistributions of source code must retain the above copyright # notice, this list of conditions and the following disclaimer. # * Redistributions in binary form must reproduce the above # copyright notice, this list of conditions and the following # disclaimer in the documentation and/or other materials provided # with the distribution. # * Neither the name of Google Inc. nor the names of its # contributors may be used to endorse or promote products derived # from this software without specific prior written permission. # # THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS # "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT # LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR # A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT # OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, # SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT # LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, # DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY # THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT # (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE # OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. import test import os import shutil from shutil import rmtree from os import mkdir from glob import glob from os.path import join, dirname, exists import re FLAGS_PATTERN = re.compile(r"//\s+Flags:(.*)") FILES_PATTERN = re.compile(r"//\s+Files:(.*)") class InternetTestCase(test.TestCase): def __init__(self, path, file, mode, context, config): super(InternetTestCase, self).__init__(context, path, mode) self.file = file self.config = config self.mode = mode self.tmpdir = join(dirname(self.config.root), 'tmp') def AfterRun(self, result): # delete the whole tmp dir try: rmtree(self.tmpdir) except: pass # make it again. try: mkdir(self.tmpdir) except: pass def BeforeRun(self): # delete the whole tmp dir try: rmtree(self.tmpdir) except: pass # make it again. # intermittently fails on win32, so keep trying while not os.path.exists(self.tmpdir): try: mkdir(self.tmpdir) except: pass def GetLabel(self): return "%s %s" % (self.mode, self.GetName()) def GetName(self): return self.path[-1] def GetCommand(self): result = [self.config.context.GetVm(self.mode)] source = open(self.file).read() flags_match = FLAGS_PATTERN.search(source) if flags_match: result += flags_match.group(1).strip().split() files_match = FILES_PATTERN.search(source); additional_files = [] if files_match: additional_files += files_match.group(1).strip().split() for a_file in additional_files: result.append(join(dirname(self.config.root), '..', a_file)) result += [self.file] return result def GetSource(self): return open(self.file).read() class InternetTestConfiguration(test.TestConfiguration): def __init__(self, context, root): super(InternetTestConfiguration, self).__init__(context, root) def Ls(self, path): def SelectTest(name): return name.startswith('test-') and name.endswith('.js') return [f[:-3] for f in os.listdir(path) if SelectTest(f)] def ListTests(self, current_path, path, mode): all_tests = [current_path + [t] for t in self.Ls(join(self.root))] result = [] for test in all_tests: if self.Contains(path, test): file_path = join(self.root, reduce(join, test[1:], "") + ".js") result.append(InternetTestCase(test, file_path, mode, self.context, self)) return result def GetBuildRequirements(self): return ['sample', 'sample=shell'] def GetTestStatus(self, sections, defs): status_file = join(self.root, 'simple.status') if exists(status_file): test.ReadConfigurationInto(status_file, sections, defs) def GetConfiguration(context, root): return InternetTestConfiguration(context, root) node-v0.10.25~dfsg2/test/common.js0000644000000000000000000001362012270121457015424 0ustar rootroot// Copyright Joyent, Inc. and other Node contributors. // // Permission is hereby granted, free of charge, to any person obtaining a // copy of this software and associated documentation files (the // "Software"), to deal in the Software without restriction, including // without limitation the rights to use, copy, modify, merge, publish, // distribute, sublicense, and/or sell copies of the Software, and to permit // persons to whom the Software is furnished to do so, subject to the // following conditions: // // The above copyright notice and this permission notice shall be included // in all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS // OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF // MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN // NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, // DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR // OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE // USE OR OTHER DEALINGS IN THE SOFTWARE. var path = require('path'); var assert = require('assert'); exports.testDir = path.dirname(__filename); exports.fixturesDir = path.join(exports.testDir, 'fixtures'); exports.libDir = path.join(exports.testDir, '../lib'); exports.tmpDir = path.join(exports.testDir, 'tmp'); exports.PORT = +process.env.NODE_COMMON_PORT || 12346; if (process.platform === 'win32') { exports.PIPE = '\\\\.\\pipe\\libuv-test'; } else { exports.PIPE = exports.tmpDir + '/test.sock'; } var util = require('util'); for (var i in util) exports[i] = util[i]; //for (var i in exports) global[i] = exports[i]; function protoCtrChain(o) { var result = []; for (; o; o = o.__proto__) { result.push(o.constructor); } return result.join(); } exports.indirectInstanceOf = function(obj, cls) { if (obj instanceof cls) { return true; } var clsChain = protoCtrChain(cls.prototype); var objChain = protoCtrChain(obj); return objChain.slice(-clsChain.length) === clsChain; }; exports.ddCommand = function(filename, kilobytes) { if (process.platform === 'win32') { var p = path.resolve(exports.fixturesDir, 'create-file.js'); return '"' + process.argv[0] + '" "' + p + '" "' + filename + '" ' + (kilobytes * 1024); } else { return 'dd if=/dev/zero of="' + filename + '" bs=1024 count=' + kilobytes; } }; exports.spawnCat = function(options) { var spawn = require('child_process').spawn; if (process.platform === 'win32') { return spawn('more', [], options); } else { return spawn('cat', [], options); } }; exports.spawnPwd = function(options) { var spawn = require('child_process').spawn; if (process.platform === 'win32') { return spawn('cmd.exe', ['/c', 'cd'], options); } else { return spawn('pwd', [], options); } }; // Turn this off if the test should not check for global leaks. exports.globalCheck = true; process.on('exit', function() { if (!exports.globalCheck) return; var knownGlobals = [setTimeout, setInterval, setImmediate, clearTimeout, clearInterval, clearImmediate, console, Buffer, process, global]; if (global.gc) { knownGlobals.push(gc); } if (global.DTRACE_HTTP_SERVER_RESPONSE) { knownGlobals.push(DTRACE_HTTP_SERVER_RESPONSE); knownGlobals.push(DTRACE_HTTP_SERVER_REQUEST); knownGlobals.push(DTRACE_HTTP_CLIENT_RESPONSE); knownGlobals.push(DTRACE_HTTP_CLIENT_REQUEST); knownGlobals.push(DTRACE_NET_STREAM_END); knownGlobals.push(DTRACE_NET_SERVER_CONNECTION); knownGlobals.push(DTRACE_NET_SOCKET_READ); knownGlobals.push(DTRACE_NET_SOCKET_WRITE); } if (global.COUNTER_NET_SERVER_CONNECTION) { knownGlobals.push(COUNTER_NET_SERVER_CONNECTION); knownGlobals.push(COUNTER_NET_SERVER_CONNECTION_CLOSE); knownGlobals.push(COUNTER_HTTP_SERVER_REQUEST); knownGlobals.push(COUNTER_HTTP_SERVER_RESPONSE); knownGlobals.push(COUNTER_HTTP_CLIENT_REQUEST); knownGlobals.push(COUNTER_HTTP_CLIENT_RESPONSE); } if (global.ArrayBuffer) { knownGlobals.push(ArrayBuffer); knownGlobals.push(Int8Array); knownGlobals.push(Uint8Array); knownGlobals.push(Uint8ClampedArray); knownGlobals.push(Int16Array); knownGlobals.push(Uint16Array); knownGlobals.push(Int32Array); knownGlobals.push(Uint32Array); knownGlobals.push(Float32Array); knownGlobals.push(Float64Array); knownGlobals.push(DataView); } for (var x in global) { var found = false; for (var y in knownGlobals) { if (global[x] === knownGlobals[y]) { found = true; break; } } if (!found) { console.error('Unknown global: %s', x); assert.ok(false, 'Unknown global found'); } } }); var mustCallChecks = []; function runCallChecks(exitCode) { if (exitCode !== 0) return; var failed = mustCallChecks.filter(function(context) { return context.actual !== context.expected; }); failed.forEach(function(context) { console.log('Mismatched %s function calls. Expected %d, actual %d.', context.name, context.expected, context.actual); console.log(context.stack.split('\n').slice(2).join('\n')); }); if (failed.length) process.exit(1); } exports.mustCall = function(fn, expected) { if (typeof expected !== 'number') expected = 1; var context = { expected: expected, actual: 0, stack: (new Error).stack, name: fn.name || '' }; // add the exit listener only once to avoid listener leak warnings if (mustCallChecks.length === 0) process.on('exit', runCallChecks); mustCallChecks.push(context); return function() { context.actual++; return fn.apply(this, arguments); }; }; node-v0.10.25~dfsg2/test/simple/0000755000000000000000000000000012270121457015065 5ustar rootrootnode-v0.10.25~dfsg2/test/simple/test-arraybuffer-slice.js0000644000000000000000000000455312270121457022014 0ustar rootroot// Copyright Joyent, Inc. and other Node contributors. // Permission is hereby granted, free of charge, to any person obtaining a // copy of this software and associated documentation files (the // "Software"), to deal in the Software without restriction, including // without limitation the rights to use, copy, modify, merge, publish, // distribute, sublicense, and/or sell copies of the Software, and to permit // persons to whom the Software is furnished to do so, subject to the // following conditions: // The above copyright notice and this permission notice shall be included // in all copies or substantial portions of the Software. // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS // OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF // MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN // NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, // DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR // OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE // USE OR OTHER DEALINGS IN THE SOFTWARE. /* * Tests to verify slice functionality of ArrayBuffer. * (http://www.khronos.org/registry/typedarray/specs/latest/#5) */ var common = require('../common'); var assert = require('assert'); var buffer = new ArrayBuffer(8); var sub; var i; for (var i = 0; i < 8; i++) { buffer[i] = i; } // slice a copy of buffer sub = buffer.slice(2, 6); // make sure it copied correctly assert.ok(sub instanceof ArrayBuffer); assert.equal(sub.byteLength, 4); for (i = 0; i < 4; i++) { assert.equal(sub[i], i+2); } // modifications to the new slice shouldn't affect the original sub[0] = 999; for (i = 0; i < 8; i++) { assert.equal(buffer[i], i); } // test optional end param sub = buffer.slice(5); assert.ok(sub instanceof ArrayBuffer); assert.equal(sub.byteLength, 3); for (i = 0; i < 3; i++) { assert.equal(sub[i], i+5); } // test clamping sub = buffer.slice(-3, -1); assert.ok(sub instanceof ArrayBuffer); assert.equal(sub.byteLength, 2); for (i = 0; i < 2; i++) { assert.equal(sub[i], i+5); } // test invalid clamping range sub = buffer.slice(-1, -3); assert.ok(sub instanceof ArrayBuffer); assert.equal(sub.byteLength, 0); // test wrong number of arguments var gotError = false; try { sub = buffer.slice(); } catch (e) { gotError = true; } assert.ok(gotError);node-v0.10.25~dfsg2/test/simple/test-net-buffersize.js0000644000000000000000000000326612270121457021337 0ustar rootroot// Copyright Joyent, Inc. and other Node contributors. // // Permission is hereby granted, free of charge, to any person obtaining a // copy of this software and associated documentation files (the // "Software"), to deal in the Software without restriction, including // without limitation the rights to use, copy, modify, merge, publish, // distribute, sublicense, and/or sell copies of the Software, and to permit // persons to whom the Software is furnished to do so, subject to the // following conditions: // // The above copyright notice and this permission notice shall be included // in all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS // OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF // MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN // NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, // DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR // OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE // USE OR OTHER DEALINGS IN THE SOFTWARE. var common = require('../common'); var assert = require('assert'); var net = require('net'); var iter = 10; var server = net.createServer(function(socket) { socket.on('readable', function() { socket.read(); }); socket.on('end', function() { server.close(); }); }); server.listen(common.PORT, function() { var client = net.connect(common.PORT); client.on('finish', function() { assert.strictEqual(client.bufferSize, 0); }); for (var i = 1; i < iter; i++) { client.write('a'); assert.strictEqual(client.bufferSize, i); } client.end(); }); node-v0.10.25~dfsg2/test/simple/test-http-set-cookies.js0000644000000000000000000000520312270121457021602 0ustar rootroot// Copyright Joyent, Inc. and other Node contributors. // // Permission is hereby granted, free of charge, to any person obtaining a // copy of this software and associated documentation files (the // "Software"), to deal in the Software without restriction, including // without limitation the rights to use, copy, modify, merge, publish, // distribute, sublicense, and/or sell copies of the Software, and to permit // persons to whom the Software is furnished to do so, subject to the // following conditions: // // The above copyright notice and this permission notice shall be included // in all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS // OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF // MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN // NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, // DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR // OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE // USE OR OTHER DEALINGS IN THE SOFTWARE. var common = require('../common'); var assert = require('assert'); var http = require('http'); var nresponses = 0; var server = http.createServer(function(req, res) { if (req.url == '/one') { res.writeHead(200, [['set-cookie', 'A'], ['content-type', 'text/plain']]); res.end('one\n'); } else { res.writeHead(200, [['set-cookie', 'A'], ['set-cookie', 'B'], ['content-type', 'text/plain']]); res.end('two\n'); } }); server.listen(common.PORT); server.on('listening', function() { // // one set-cookie header // http.get({ port: common.PORT, path: '/one' }, function(res) { // set-cookie headers are always return in an array. // even if there is only one. assert.deepEqual(['A'], res.headers['set-cookie']); assert.equal('text/plain', res.headers['content-type']); res.on('data', function(chunk) { console.log(chunk.toString()); }); res.on('end', function() { if (++nresponses == 2) { server.close(); } }); }); // two set-cookie headers http.get({ port: common.PORT, path: '/two' }, function(res) { assert.deepEqual(['A', 'B'], res.headers['set-cookie']); assert.equal('text/plain', res.headers['content-type']); res.on('data', function(chunk) { console.log(chunk.toString()); }); res.on('end', function() { if (++nresponses == 2) { server.close(); } }); }); }); process.on('exit', function() { assert.equal(2, nresponses); }); node-v0.10.25~dfsg2/test/simple/test-listen-fd-detached-inherit.js0000644000000000000000000001012712270121457023465 0ustar rootroot// Copyright Joyent, Inc. and other Node contributors. // // Permission is hereby granted, free of charge, to any person obtaining a // copy of this software and associated documentation files (the // "Software"), to deal in the Software without restriction, including // without limitation the rights to use, copy, modify, merge, publish, // distribute, sublicense, and/or sell copies of the Software, and to permit // persons to whom the Software is furnished to do so, subject to the // following conditions: // // The above copyright notice and this permission notice shall be included // in all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS // OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF // MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN // NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, // DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR // OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE // USE OR OTHER DEALINGS IN THE SOFTWARE. var common = require('../common'); var assert = require('assert'); var http = require('http'); var net = require('net'); var PORT = common.PORT; var spawn = require('child_process').spawn; if (process.platform === 'win32') { console.error('This test is disabled on windows.'); return; } switch (process.argv[2]) { case 'child': return child(); case 'parent': return parent(); default: return test(); } // spawn the parent, and listen for it to tell us the pid of the child. // WARNING: This is an example of listening on some arbitrary FD number // that has already been bound elsewhere in advance. However, binding // server handles to stdio fd's is NOT a good or reliable way to do // concurrency in HTTP servers! Use the cluster module, or if you want // a more low-level approach, use child process IPC manually. function test() { var parent = spawn(process.execPath, [__filename, 'parent'], { stdio: [ 0, 'pipe', 2 ] }); var json = ''; parent.stdout.on('data', function(c) { json += c.toString(); if (json.indexOf('\n') !== -1) next(); }); function next() { console.error('output from parent = %s', json); var child = JSON.parse(json); // now make sure that we can request to the child, then kill it. http.get({ server: 'localhost', port: PORT, path: '/', }).on('response', function (res) { var s = ''; res.on('data', function(c) { s += c.toString(); }); res.on('end', function() { // kill the child before we start doing asserts. // it's really annoying when tests leave orphans! process.kill(child.pid, 'SIGKILL'); try { parent.kill(); } catch (e) {} assert.equal(s, 'hello from child\n'); assert.equal(res.statusCode, 200); }); }) } } // Listen on PORT, and then pass the handle to the detached child. // Then output the child's pid, and immediately exit. function parent() { var server = net.createServer(function(conn) { throw new Error('Should not see connections on parent'); conn.end('HTTP/1.1 403 Forbidden\r\n\r\nI got problems.\r\n'); }).listen(PORT, function() { console.error('server listening on %d', PORT); var child = spawn(process.execPath, [__filename, 'child'], { stdio: [ 0, 1, 2, server._handle ], detached: true }); console.log('%j\n', { pid: child.pid }); // Now close the parent, so that the child is the only thing // referencing that handle. Note that connections will still // be accepted, because the child has the fd open, but the parent // will exit gracefully. server.close(); child.unref(); }); } // Run as a child of the parent() mode. function child() { // start a server on fd=3 http.createServer(function(req, res) { console.error('request on child'); console.error('%s %s', req.method, req.url, req.headers); res.end('hello from child\n'); }).listen({ fd: 3 }, function() { console.error('child listening on fd=3'); }); } node-v0.10.25~dfsg2/test/simple/test-url.js0000644000000000000000000012505312270121457017210 0ustar rootroot// Copyright Joyent, Inc. and other Node contributors. // // Permission is hereby granted, free of charge, to any person obtaining a // copy of this software and associated documentation files (the // "Software"), to deal in the Software without restriction, including // without limitation the rights to use, copy, modify, merge, publish, // distribute, sublicense, and/or sell copies of the Software, and to permit // persons to whom the Software is furnished to do so, subject to the // following conditions: // // The above copyright notice and this permission notice shall be included // in all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS // OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF // MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN // NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, // DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR // OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE // USE OR OTHER DEALINGS IN THE SOFTWARE. var common = require('../common'); var assert = require('assert'); var url = require('url'), util = require('util'); // URLs to parse, and expected data // { url : parsed } var parseTests = { '//some_path' : { 'href': '//some_path', 'pathname': '//some_path', 'path': '//some_path' }, 'HTTP://www.example.com/' : { 'href': 'http://www.example.com/', 'protocol': 'http:', 'slashes': true, 'host': 'www.example.com', 'hostname': 'www.example.com', 'pathname': '/', 'path': '/' }, 'HTTP://www.example.com' : { 'href': 'http://www.example.com/', 'protocol': 'http:', 'slashes': true, 'host': 'www.example.com', 'hostname': 'www.example.com', 'pathname': '/', 'path': '/' }, 'http://www.ExAmPlE.com/' : { 'href': 'http://www.example.com/', 'protocol': 'http:', 'slashes': true, 'host': 'www.example.com', 'hostname': 'www.example.com', 'pathname': '/', 'path': '/' }, 'http://user:pw@www.ExAmPlE.com/' : { 'href': 'http://user:pw@www.example.com/', 'protocol': 'http:', 'slashes': true, 'auth': 'user:pw', 'host': 'www.example.com', 'hostname': 'www.example.com', 'pathname': '/', 'path': '/' }, 'http://USER:PW@www.ExAmPlE.com/' : { 'href': 'http://USER:PW@www.example.com/', 'protocol': 'http:', 'slashes': true, 'auth': 'USER:PW', 'host': 'www.example.com', 'hostname': 'www.example.com', 'pathname': '/', 'path': '/' }, 'http://user@www.example.com/' : { 'href': 'http://user@www.example.com/', 'protocol': 'http:', 'slashes': true, 'auth': 'user', 'host': 'www.example.com', 'hostname': 'www.example.com', 'pathname': '/', 'path': '/' }, 'http://user%3Apw@www.example.com/' : { 'href': 'http://user:pw@www.example.com/', 'protocol': 'http:', 'slashes': true, 'auth': 'user:pw', 'host': 'www.example.com', 'hostname': 'www.example.com', 'pathname': '/', 'path': '/' }, 'http://x.com/path?that\'s#all, folks' : { 'href': 'http://x.com/path?that%27s#all,%20folks', 'protocol': 'http:', 'slashes': true, 'host': 'x.com', 'hostname': 'x.com', 'search': '?that%27s', 'query': 'that%27s', 'pathname': '/path', 'hash': '#all,%20folks', 'path': '/path?that%27s' }, 'HTTP://X.COM/Y' : { 'href': 'http://x.com/Y', 'protocol': 'http:', 'slashes': true, 'host': 'x.com', 'hostname': 'x.com', 'pathname': '/Y', 'path': '/Y' }, // an unexpected invalid char in the hostname. 'HtTp://x.y.cOm*a/b/c?d=e#f gi' : { 'href': 'http://x.y.com/*a/b/c?d=e#f%20g%3Ch%3Ei', 'protocol': 'http:', 'slashes': true, 'host': 'x.y.com', 'hostname': 'x.y.com', 'pathname': '/*a/b/c', 'search': '?d=e', 'query': 'd=e', 'hash': '#f%20g%3Ch%3Ei', 'path': '/*a/b/c?d=e' }, // make sure that we don't accidentally lcast the path parts. 'HtTp://x.y.cOm*A/b/c?d=e#f gi' : { 'href': 'http://x.y.com/*A/b/c?d=e#f%20g%3Ch%3Ei', 'protocol': 'http:', 'slashes': true, 'host': 'x.y.com', 'hostname': 'x.y.com', 'pathname': '/*A/b/c', 'search': '?d=e', 'query': 'd=e', 'hash': '#f%20g%3Ch%3Ei', 'path': '/*A/b/c?d=e' }, 'http://x...y...#p': { 'href': 'http://x...y.../#p', 'protocol': 'http:', 'slashes': true, 'host': 'x...y...', 'hostname': 'x...y...', 'hash': '#p', 'pathname': '/', 'path': '/' }, 'http://x/p/"quoted"': { 'href': 'http://x/p/%22quoted%22', 'protocol': 'http:', 'slashes': true, 'host': 'x', 'hostname': 'x', 'pathname': '/p/%22quoted%22', 'path': '/p/%22quoted%22' }, ' Is a URL!': { 'href': '%3Chttp://goo.corn/bread%3E%20Is%20a%20URL!', 'pathname': '%3Chttp://goo.corn/bread%3E%20Is%20a%20URL!', 'path': '%3Chttp://goo.corn/bread%3E%20Is%20a%20URL!' }, 'http://www.narwhaljs.org/blog/categories?id=news' : { 'href': 'http://www.narwhaljs.org/blog/categories?id=news', 'protocol': 'http:', 'slashes': true, 'host': 'www.narwhaljs.org', 'hostname': 'www.narwhaljs.org', 'search': '?id=news', 'query': 'id=news', 'pathname': '/blog/categories', 'path': '/blog/categories?id=news' }, 'http://mt0.google.com/vt/lyrs=m@114&hl=en&src=api&x=2&y=2&z=3&s=' : { 'href': 'http://mt0.google.com/vt/lyrs=m@114&hl=en&src=api&x=2&y=2&z=3&s=', 'protocol': 'http:', 'slashes': true, 'host': 'mt0.google.com', 'hostname': 'mt0.google.com', 'pathname': '/vt/lyrs=m@114&hl=en&src=api&x=2&y=2&z=3&s=', 'path': '/vt/lyrs=m@114&hl=en&src=api&x=2&y=2&z=3&s=' }, 'http://mt0.google.com/vt/lyrs=m@114???&hl=en&src=api&x=2&y=2&z=3&s=' : { 'href': 'http://mt0.google.com/vt/lyrs=m@114???&hl=en&src=api' + '&x=2&y=2&z=3&s=', 'protocol': 'http:', 'slashes': true, 'host': 'mt0.google.com', 'hostname': 'mt0.google.com', 'search': '???&hl=en&src=api&x=2&y=2&z=3&s=', 'query': '??&hl=en&src=api&x=2&y=2&z=3&s=', 'pathname': '/vt/lyrs=m@114', 'path': '/vt/lyrs=m@114???&hl=en&src=api&x=2&y=2&z=3&s=' }, 'http://user:pass@mt0.google.com/vt/lyrs=m@114???&hl=en&src=api&x=2&y=2&z=3&s=': { 'href': 'http://user:pass@mt0.google.com/vt/lyrs=m@114???' + '&hl=en&src=api&x=2&y=2&z=3&s=', 'protocol': 'http:', 'slashes': true, 'host': 'mt0.google.com', 'auth': 'user:pass', 'hostname': 'mt0.google.com', 'search': '???&hl=en&src=api&x=2&y=2&z=3&s=', 'query': '??&hl=en&src=api&x=2&y=2&z=3&s=', 'pathname': '/vt/lyrs=m@114', 'path': '/vt/lyrs=m@114???&hl=en&src=api&x=2&y=2&z=3&s=' }, 'file:///etc/passwd' : { 'href': 'file:///etc/passwd', 'slashes': true, 'protocol': 'file:', 'pathname': '/etc/passwd', 'hostname': '', 'host': '', 'path': '/etc/passwd' }, 'file://localhost/etc/passwd' : { 'href': 'file://localhost/etc/passwd', 'protocol': 'file:', 'slashes': true, 'pathname': '/etc/passwd', 'hostname': 'localhost', 'host': 'localhost', 'path': '/etc/passwd' }, 'file://foo/etc/passwd' : { 'href': 'file://foo/etc/passwd', 'protocol': 'file:', 'slashes': true, 'pathname': '/etc/passwd', 'hostname': 'foo', 'host': 'foo', 'path': '/etc/passwd' }, 'file:///etc/node/' : { 'href': 'file:///etc/node/', 'slashes': true, 'protocol': 'file:', 'pathname': '/etc/node/', 'hostname': '', 'host': '', 'path': '/etc/node/' }, 'file://localhost/etc/node/' : { 'href': 'file://localhost/etc/node/', 'protocol': 'file:', 'slashes': true, 'pathname': '/etc/node/', 'hostname': 'localhost', 'host': 'localhost', 'path': '/etc/node/' }, 'file://foo/etc/node/' : { 'href': 'file://foo/etc/node/', 'protocol': 'file:', 'slashes': true, 'pathname': '/etc/node/', 'hostname': 'foo', 'host': 'foo', 'path': '/etc/node/' }, 'http:/baz/../foo/bar' : { 'href': 'http:/baz/../foo/bar', 'protocol': 'http:', 'pathname': '/baz/../foo/bar', 'path': '/baz/../foo/bar' }, 'http://user:pass@example.com:8000/foo/bar?baz=quux#frag' : { 'href': 'http://user:pass@example.com:8000/foo/bar?baz=quux#frag', 'protocol': 'http:', 'slashes': true, 'host': 'example.com:8000', 'auth': 'user:pass', 'port': '8000', 'hostname': 'example.com', 'hash': '#frag', 'search': '?baz=quux', 'query': 'baz=quux', 'pathname': '/foo/bar', 'path': '/foo/bar?baz=quux' }, '//user:pass@example.com:8000/foo/bar?baz=quux#frag' : { 'href': '//user:pass@example.com:8000/foo/bar?baz=quux#frag', 'slashes': true, 'host': 'example.com:8000', 'auth': 'user:pass', 'port': '8000', 'hostname': 'example.com', 'hash': '#frag', 'search': '?baz=quux', 'query': 'baz=quux', 'pathname': '/foo/bar', 'path': '/foo/bar?baz=quux' }, '/foo/bar?baz=quux#frag' : { 'href': '/foo/bar?baz=quux#frag', 'hash': '#frag', 'search': '?baz=quux', 'query': 'baz=quux', 'pathname': '/foo/bar', 'path': '/foo/bar?baz=quux' }, 'http:/foo/bar?baz=quux#frag' : { 'href': 'http:/foo/bar?baz=quux#frag', 'protocol': 'http:', 'hash': '#frag', 'search': '?baz=quux', 'query': 'baz=quux', 'pathname': '/foo/bar', 'path': '/foo/bar?baz=quux' }, 'mailto:foo@bar.com?subject=hello' : { 'href': 'mailto:foo@bar.com?subject=hello', 'protocol': 'mailto:', 'host': 'bar.com', 'auth' : 'foo', 'hostname' : 'bar.com', 'search': '?subject=hello', 'query': 'subject=hello', 'path': '?subject=hello' }, 'javascript:alert(\'hello\');' : { 'href': 'javascript:alert(\'hello\');', 'protocol': 'javascript:', 'pathname': 'alert(\'hello\');', 'path': 'alert(\'hello\');' }, 'xmpp:isaacschlueter@jabber.org' : { 'href': 'xmpp:isaacschlueter@jabber.org', 'protocol': 'xmpp:', 'host': 'jabber.org', 'auth': 'isaacschlueter', 'hostname': 'jabber.org' }, 'http://atpass:foo%40bar@127.0.0.1:8080/path?search=foo#bar' : { 'href' : 'http://atpass:foo%40bar@127.0.0.1:8080/path?search=foo#bar', 'protocol' : 'http:', 'slashes': true, 'host' : '127.0.0.1:8080', 'auth' : 'atpass:foo@bar', 'hostname' : '127.0.0.1', 'port' : '8080', 'pathname': '/path', 'search' : '?search=foo', 'query' : 'search=foo', 'hash' : '#bar', 'path': '/path?search=foo' }, 'svn+ssh://foo/bar': { 'href': 'svn+ssh://foo/bar', 'host': 'foo', 'hostname': 'foo', 'protocol': 'svn+ssh:', 'pathname': '/bar', 'path': '/bar', 'slashes': true }, 'dash-test://foo/bar': { 'href': 'dash-test://foo/bar', 'host': 'foo', 'hostname': 'foo', 'protocol': 'dash-test:', 'pathname': '/bar', 'path': '/bar', 'slashes': true }, 'dash-test:foo/bar': { 'href': 'dash-test:foo/bar', 'host': 'foo', 'hostname': 'foo', 'protocol': 'dash-test:', 'pathname': '/bar', 'path': '/bar' }, 'dot.test://foo/bar': { 'href': 'dot.test://foo/bar', 'host': 'foo', 'hostname': 'foo', 'protocol': 'dot.test:', 'pathname': '/bar', 'path': '/bar', 'slashes': true }, 'dot.test:foo/bar': { 'href': 'dot.test:foo/bar', 'host': 'foo', 'hostname': 'foo', 'protocol': 'dot.test:', 'pathname': '/bar', 'path': '/bar' }, // IDNA tests 'http://www.日本語.com/' : { 'href': 'http://www.xn--wgv71a119e.com/', 'protocol': 'http:', 'slashes': true, 'host': 'www.xn--wgv71a119e.com', 'hostname': 'www.xn--wgv71a119e.com', 'pathname': '/', 'path': '/' }, 'http://example.Bücher.com/' : { 'href': 'http://example.xn--bcher-kva.com/', 'protocol': 'http:', 'slashes': true, 'host': 'example.xn--bcher-kva.com', 'hostname': 'example.xn--bcher-kva.com', 'pathname': '/', 'path': '/' }, 'http://www.Äffchen.com/' : { 'href': 'http://www.xn--ffchen-9ta.com/', 'protocol': 'http:', 'slashes': true, 'host': 'www.xn--ffchen-9ta.com', 'hostname': 'www.xn--ffchen-9ta.com', 'pathname': '/', 'path': '/' }, 'http://www.Äffchen.cOm*A/b/c?d=e#f gi' : { 'href': 'http://www.xn--ffchen-9ta.com/*A/b/c?d=e#f%20g%3Ch%3Ei', 'protocol': 'http:', 'slashes': true, 'host': 'www.xn--ffchen-9ta.com', 'hostname': 'www.xn--ffchen-9ta.com', 'pathname': '/*A/b/c', 'search': '?d=e', 'query': 'd=e', 'hash': '#f%20g%3Ch%3Ei', 'path': '/*A/b/c?d=e' }, 'http://SÉLIER.COM/' : { 'href': 'http://xn--slier-bsa.com/', 'protocol': 'http:', 'slashes': true, 'host': 'xn--slier-bsa.com', 'hostname': 'xn--slier-bsa.com', 'pathname': '/', 'path': '/' }, 'http://ليهمابتكلموشعربي؟.ي؟/' : { 'href': 'http://xn--egbpdaj6bu4bxfgehfvwxn.xn--egb9f/', 'protocol': 'http:', 'slashes': true, 'host': 'xn--egbpdaj6bu4bxfgehfvwxn.xn--egb9f', 'hostname': 'xn--egbpdaj6bu4bxfgehfvwxn.xn--egb9f', 'pathname': '/', 'path': '/' }, 'http://➡.ws/➡' : { 'href': 'http://xn--hgi.ws/➡', 'protocol': 'http:', 'slashes': true, 'host': 'xn--hgi.ws', 'hostname': 'xn--hgi.ws', 'pathname': '/➡', 'path': '/➡' }, 'http://bucket_name.s3.amazonaws.com/image.jpg': { protocol: 'http:', 'slashes': true, slashes: true, host: 'bucket_name.s3.amazonaws.com', hostname: 'bucket_name.s3.amazonaws.com', pathname: '/image.jpg', href: 'http://bucket_name.s3.amazonaws.com/image.jpg', 'path': '/image.jpg' }, 'git+http://github.com/joyent/node.git': { protocol: 'git+http:', slashes: true, host: 'github.com', hostname: 'github.com', pathname: '/joyent/node.git', path: '/joyent/node.git', href: 'git+http://github.com/joyent/node.git' }, //if local1@domain1 is uses as a relative URL it may //be parse into auth@hostname, but here there is no //way to make it work in url.parse, I add the test to be explicit 'local1@domain1': { 'pathname': 'local1@domain1', 'path': 'local1@domain1', 'href': 'local1@domain1' }, //While this may seem counter-intuitive, a browser will parse // as a path. 'www.example.com' : { 'href': 'www.example.com', 'pathname': 'www.example.com', 'path': 'www.example.com' }, // ipv6 support '[fe80::1]': { 'href': '[fe80::1]', 'pathname': '[fe80::1]', 'path': '[fe80::1]' }, 'coap://[FEDC:BA98:7654:3210:FEDC:BA98:7654:3210]': { 'protocol': 'coap:', 'slashes': true, 'host': '[fedc:ba98:7654:3210:fedc:ba98:7654:3210]', 'hostname': 'fedc:ba98:7654:3210:fedc:ba98:7654:3210', 'href': 'coap://[fedc:ba98:7654:3210:fedc:ba98:7654:3210]/', 'pathname': '/', 'path': '/' }, 'coap://[1080:0:0:0:8:800:200C:417A]:61616/': { 'protocol': 'coap:', 'slashes': true, 'host': '[1080:0:0:0:8:800:200c:417a]:61616', 'port': '61616', 'hostname': '1080:0:0:0:8:800:200c:417a', 'href': 'coap://[1080:0:0:0:8:800:200c:417a]:61616/', 'pathname': '/', 'path': '/' }, 'http://user:password@[3ffe:2a00:100:7031::1]:8080': { 'protocol': 'http:', 'slashes': true, 'auth': 'user:password', 'host': '[3ffe:2a00:100:7031::1]:8080', 'port': '8080', 'hostname': '3ffe:2a00:100:7031::1', 'href': 'http://user:password@[3ffe:2a00:100:7031::1]:8080/', 'pathname': '/', 'path': '/' }, 'coap://u:p@[::192.9.5.5]:61616/.well-known/r?n=Temperature': { 'protocol': 'coap:', 'slashes': true, 'auth': 'u:p', 'host': '[::192.9.5.5]:61616', 'port': '61616', 'hostname': '::192.9.5.5', 'href': 'coap://u:p@[::192.9.5.5]:61616/.well-known/r?n=Temperature', 'search': '?n=Temperature', 'query': 'n=Temperature', 'pathname': '/.well-known/r', 'path': '/.well-known/r?n=Temperature' }, // empty port 'http://example.com:': { 'protocol': 'http:', 'slashes': true, 'host': 'example.com', 'hostname': 'example.com', 'href': 'http://example.com/', 'pathname': '/', 'path': '/' }, 'http://example.com:/a/b.html': { 'protocol': 'http:', 'slashes': true, 'host': 'example.com', 'hostname': 'example.com', 'href': 'http://example.com/a/b.html', 'pathname': '/a/b.html', 'path': '/a/b.html' }, 'http://example.com:?a=b': { 'protocol': 'http:', 'slashes': true, 'host': 'example.com', 'hostname': 'example.com', 'href': 'http://example.com/?a=b', 'search': '?a=b', 'query': 'a=b', 'pathname': '/', 'path': '/?a=b' }, 'http://example.com:#abc': { 'protocol': 'http:', 'slashes': true, 'host': 'example.com', 'hostname': 'example.com', 'href': 'http://example.com/#abc', 'hash': '#abc', 'pathname': '/', 'path': '/' }, 'http://[fe80::1]:/a/b?a=b#abc': { 'protocol': 'http:', 'slashes': true, 'host': '[fe80::1]', 'hostname': 'fe80::1', 'href': 'http://[fe80::1]/a/b?a=b#abc', 'search': '?a=b', 'query': 'a=b', 'hash': '#abc', 'pathname': '/a/b', 'path': '/a/b?a=b' }, 'http://-lovemonsterz.tumblr.com/rss': { 'protocol': 'http:', 'slashes': true, 'host': '-lovemonsterz.tumblr.com', 'hostname': '-lovemonsterz.tumblr.com', 'href': 'http://-lovemonsterz.tumblr.com/rss', 'pathname': '/rss', 'path': '/rss', }, 'http://-lovemonsterz.tumblr.com:80/rss': { 'protocol': 'http:', 'slashes': true, 'port': '80', 'host': '-lovemonsterz.tumblr.com:80', 'hostname': '-lovemonsterz.tumblr.com', 'href': 'http://-lovemonsterz.tumblr.com:80/rss', 'pathname': '/rss', 'path': '/rss', }, 'http://user:pass@-lovemonsterz.tumblr.com/rss': { 'protocol': 'http:', 'slashes': true, 'auth': 'user:pass', 'host': '-lovemonsterz.tumblr.com', 'hostname': '-lovemonsterz.tumblr.com', 'href': 'http://user:pass@-lovemonsterz.tumblr.com/rss', 'pathname': '/rss', 'path': '/rss', }, 'http://user:pass@-lovemonsterz.tumblr.com:80/rss': { 'protocol': 'http:', 'slashes': true, 'auth': 'user:pass', 'port': '80', 'host': '-lovemonsterz.tumblr.com:80', 'hostname': '-lovemonsterz.tumblr.com', 'href': 'http://user:pass@-lovemonsterz.tumblr.com:80/rss', 'pathname': '/rss', 'path': '/rss', }, 'http://_jabber._tcp.google.com/test': { 'protocol': 'http:', 'slashes': true, 'host': '_jabber._tcp.google.com', 'hostname': '_jabber._tcp.google.com', 'href': 'http://_jabber._tcp.google.com/test', 'pathname': '/test', 'path': '/test', }, 'http://user:pass@_jabber._tcp.google.com/test': { 'protocol': 'http:', 'slashes': true, 'auth': 'user:pass', 'host': '_jabber._tcp.google.com', 'hostname': '_jabber._tcp.google.com', 'href': 'http://user:pass@_jabber._tcp.google.com/test', 'pathname': '/test', 'path': '/test', }, 'http://_jabber._tcp.google.com:80/test': { 'protocol': 'http:', 'slashes': true, 'port': '80', 'host': '_jabber._tcp.google.com:80', 'hostname': '_jabber._tcp.google.com', 'href': 'http://_jabber._tcp.google.com:80/test', 'pathname': '/test', 'path': '/test', }, 'http://user:pass@_jabber._tcp.google.com:80/test': { 'protocol': 'http:', 'slashes': true, 'auth': 'user:pass', 'port': '80', 'host': '_jabber._tcp.google.com:80', 'hostname': '_jabber._tcp.google.com', 'href': 'http://user:pass@_jabber._tcp.google.com:80/test', 'pathname': '/test', 'path': '/test', }, 'http://a@b@c/': { protocol: 'http:', slashes: true, auth: 'a@b', host: 'c', hostname: 'c', href: 'http://a%40b@c/', path: '/', pathname: '/' }, 'http://a@b?@c': { protocol: 'http:', slashes: true, auth: 'a', host: 'b', hostname: 'b', href: 'http://a@b/?@c', path: '/?@c', pathname: '/', search: '?@c', query: '@c' }, 'http://a\r" \t\n<\'b:b@c\r\nd/e?f':{ protocol: 'http:', slashes: true, auth: 'a\r" \t\n<\'b:b', host: 'c', port: null, hostname: 'c', hash: null, search: '?f', query: 'f', pathname: '%0D%0Ad/e', path: '%0D%0Ad/e?f', href: 'http://a%0D%22%20%09%0A%3C\'b:b@c/%0D%0Ad/e?f' } }; for (var u in parseTests) { var actual = url.parse(u), spaced = url.parse(' \t ' + u + '\n\t'); expected = parseTests[u]; Object.keys(actual).forEach(function (i) { if (expected[i] === undefined && actual[i] === null) { expected[i] = null; } }); assert.deepEqual(actual, expected); assert.deepEqual(spaced, expected); var expected = parseTests[u].href, actual = url.format(parseTests[u]); assert.equal(actual, expected, 'format(' + u + ') == ' + u + '\nactual:' + actual); } var parseTestsWithQueryString = { '/foo/bar?baz=quux#frag' : { 'href': '/foo/bar?baz=quux#frag', 'hash': '#frag', 'search': '?baz=quux', 'query': { 'baz': 'quux' }, 'pathname': '/foo/bar', 'path': '/foo/bar?baz=quux' }, 'http://example.com' : { 'href': 'http://example.com/', 'protocol': 'http:', 'slashes': true, 'host': 'example.com', 'hostname': 'example.com', 'query': {}, 'search': '', 'pathname': '/', 'path': '/' } }; for (var u in parseTestsWithQueryString) { var actual = url.parse(u, true); var expected = parseTestsWithQueryString[u]; for (var i in actual) { if (actual[i] === null && expected[i] === undefined) { expected[i] = null; } } assert.deepEqual(actual, expected); } // some extra formatting tests, just to verify // that it'll format slightly wonky content to a valid url. var formatTests = { 'http://example.com?' : { 'href': 'http://example.com/?', 'protocol': 'http:', 'slashes': true, 'host': 'example.com', 'hostname': 'example.com', 'search': '?', 'query': {}, 'pathname': '/' }, 'http://example.com?foo=bar#frag' : { 'href': 'http://example.com/?foo=bar#frag', 'protocol': 'http:', 'host': 'example.com', 'hostname': 'example.com', 'hash': '#frag', 'search': '?foo=bar', 'query': 'foo=bar', 'pathname': '/' }, 'http://example.com?foo=@bar#frag' : { 'href': 'http://example.com/?foo=@bar#frag', 'protocol': 'http:', 'host': 'example.com', 'hostname': 'example.com', 'hash': '#frag', 'search': '?foo=@bar', 'query': 'foo=@bar', 'pathname': '/' }, 'http://example.com?foo=/bar/#frag' : { 'href': 'http://example.com/?foo=/bar/#frag', 'protocol': 'http:', 'host': 'example.com', 'hostname': 'example.com', 'hash': '#frag', 'search': '?foo=/bar/', 'query': 'foo=/bar/', 'pathname': '/' }, 'http://example.com?foo=?bar/#frag' : { 'href': 'http://example.com/?foo=?bar/#frag', 'protocol': 'http:', 'host': 'example.com', 'hostname': 'example.com', 'hash': '#frag', 'search': '?foo=?bar/', 'query': 'foo=?bar/', 'pathname': '/' }, 'http://example.com#frag=?bar/#frag' : { 'href': 'http://example.com/#frag=?bar/#frag', 'protocol': 'http:', 'host': 'example.com', 'hostname': 'example.com', 'hash': '#frag=?bar/#frag', 'pathname': '/' }, 'http://google.com" onload="alert(42)/' : { 'href': 'http://google.com/%22%20onload=%22alert(42)/', 'protocol': 'http:', 'host': 'google.com', 'pathname': '/%22%20onload=%22alert(42)/' }, 'http://a.com/a/b/c?s#h' : { 'href': 'http://a.com/a/b/c?s#h', 'protocol': 'http', 'host': 'a.com', 'pathname': 'a/b/c', 'hash': 'h', 'search': 's' }, 'xmpp:isaacschlueter@jabber.org' : { 'href': 'xmpp:isaacschlueter@jabber.org', 'protocol': 'xmpp:', 'host': 'jabber.org', 'auth': 'isaacschlueter', 'hostname': 'jabber.org' }, 'http://atpass:foo%40bar@127.0.0.1/' : { 'href': 'http://atpass:foo%40bar@127.0.0.1/', 'auth': 'atpass:foo@bar', 'hostname': '127.0.0.1', 'protocol': 'http:', 'pathname': '/' }, 'http://atslash%2F%40:%2F%40@foo/' : { 'href': 'http://atslash%2F%40:%2F%40@foo/', 'auth': 'atslash/@:/@', 'hostname': 'foo', 'protocol': 'http:', 'pathname': '/' }, 'svn+ssh://foo/bar': { 'href': 'svn+ssh://foo/bar', 'hostname': 'foo', 'protocol': 'svn+ssh:', 'pathname': '/bar', 'slashes': true }, 'dash-test://foo/bar': { 'href': 'dash-test://foo/bar', 'hostname': 'foo', 'protocol': 'dash-test:', 'pathname': '/bar', 'slashes': true }, 'dash-test:foo/bar': { 'href': 'dash-test:foo/bar', 'hostname': 'foo', 'protocol': 'dash-test:', 'pathname': '/bar' }, 'dot.test://foo/bar': { 'href': 'dot.test://foo/bar', 'hostname': 'foo', 'protocol': 'dot.test:', 'pathname': '/bar', 'slashes': true }, 'dot.test:foo/bar': { 'href': 'dot.test:foo/bar', 'hostname': 'foo', 'protocol': 'dot.test:', 'pathname': '/bar' }, // ipv6 support 'coap:u:p@[::1]:61616/.well-known/r?n=Temperature': { 'href': 'coap:u:p@[::1]:61616/.well-known/r?n=Temperature', 'protocol': 'coap:', 'auth': 'u:p', 'hostname': '::1', 'port': '61616', 'pathname': '/.well-known/r', 'search': 'n=Temperature' }, 'coap:[fedc:ba98:7654:3210:fedc:ba98:7654:3210]:61616/s/stopButton': { 'href': 'coap:[fedc:ba98:7654:3210:fedc:ba98:7654:3210]:61616/s/stopButton', 'protocol': 'coap', 'host': '[fedc:ba98:7654:3210:fedc:ba98:7654:3210]:61616', 'pathname': '/s/stopButton' }, // encode context-specific delimiters in path and query, but do not touch // other non-delimiter chars like `%`. // // `#`,`?` in path '/path/to/%%23%3F+=&.txt?foo=theA1#bar' : { href : '/path/to/%%23%3F+=&.txt?foo=theA1#bar', pathname: '/path/to/%#?+=&.txt', query: { foo: 'theA1' }, hash: "#bar" }, // `#`,`?` in path + `#` in query '/path/to/%%23%3F+=&.txt?foo=the%231#bar' : { href : '/path/to/%%23%3F+=&.txt?foo=the%231#bar', pathname: '/path/to/%#?+=&.txt', query: { foo: 'the#1' }, hash: "#bar" }, // `?` and `#` in path and search 'http://ex.com/foo%3F100%m%23r?abc=the%231?&foo=bar#frag': { href: 'http://ex.com/foo%3F100%m%23r?abc=the%231?&foo=bar#frag', protocol: 'http:', hostname: 'ex.com', hash: '#frag', search: '?abc=the#1?&foo=bar', pathname: '/foo?100%m#r', }, // `?` and `#` in search only 'http://ex.com/fooA100%mBr?abc=the%231?&foo=bar#frag': { href: 'http://ex.com/fooA100%mBr?abc=the%231?&foo=bar#frag', protocol: 'http:', hostname: 'ex.com', hash: '#frag', search: '?abc=the#1?&foo=bar', pathname: '/fooA100%mBr', } }; for (var u in formatTests) { var expect = formatTests[u].href; delete formatTests[u].href; var actual = url.format(u); var actualObj = url.format(formatTests[u]); assert.equal(actual, expect, 'wonky format(' + u + ') == ' + expect + '\nactual:' + actual); assert.equal(actualObj, expect, 'wonky format(' + JSON.stringify(formatTests[u]) + ') == ' + expect + '\nactual: ' + actualObj); } /* [from, path, expected] */ var relativeTests = [ ['/foo/bar/baz', 'quux', '/foo/bar/quux'], ['/foo/bar/baz', 'quux/asdf', '/foo/bar/quux/asdf'], ['/foo/bar/baz', 'quux/baz', '/foo/bar/quux/baz'], ['/foo/bar/baz', '../quux/baz', '/foo/quux/baz'], ['/foo/bar/baz', '/bar', '/bar'], ['/foo/bar/baz/', 'quux', '/foo/bar/baz/quux'], ['/foo/bar/baz/', 'quux/baz', '/foo/bar/baz/quux/baz'], ['/foo/bar/baz', '../../../../../../../../quux/baz', '/quux/baz'], ['/foo/bar/baz', '../../../../../../../quux/baz', '/quux/baz'], ['foo/bar', '../../../baz', '../../baz'], ['foo/bar/', '../../../baz', '../baz'], ['http://example.com/b//c//d;p?q#blarg', 'https:#hash2', 'https:///#hash2'], ['http://example.com/b//c//d;p?q#blarg', 'https:/p/a/t/h?s#hash2', 'https://p/a/t/h?s#hash2'], ['http://example.com/b//c//d;p?q#blarg', 'https://u:p@h.com/p/a/t/h?s#hash2', 'https://u:p@h.com/p/a/t/h?s#hash2'], ['http://example.com/b//c//d;p?q#blarg', 'https:/a/b/c/d', 'https://a/b/c/d'], ['http://example.com/b//c//d;p?q#blarg', 'http:#hash2', 'http://example.com/b//c//d;p?q#hash2'], ['http://example.com/b//c//d;p?q#blarg', 'http:/p/a/t/h?s#hash2', 'http://example.com/p/a/t/h?s#hash2'], ['http://example.com/b//c//d;p?q#blarg', 'http://u:p@h.com/p/a/t/h?s#hash2', 'http://u:p@h.com/p/a/t/h?s#hash2'], ['http://example.com/b//c//d;p?q#blarg', 'http:/a/b/c/d', 'http://example.com/a/b/c/d'], ['/foo/bar/baz', '/../etc/passwd', '/etc/passwd'] ]; relativeTests.forEach(function(relativeTest) { var a = url.resolve(relativeTest[0], relativeTest[1]), e = relativeTest[2]; assert.equal(a, e, 'resolve(' + [relativeTest[0], relativeTest[1]] + ') == ' + e + '\n actual=' + a); }); // https://github.com/joyent/node/issues/568 [ undefined, null, true, false, 0.0, 0, [], {} ].forEach(function(val) { assert.throws(function() { url.parse(val); }, TypeError); }); // // Tests below taken from Chiron // http://code.google.com/p/chironjs/source/browse/trunk/src/test/http/url.js // // Copyright (c) 2002-2008 Kris Kowal // used with permission under MIT License // // Changes marked with @isaacs var bases = [ 'http://a/b/c/d;p?q', 'http://a/b/c/d;p?q=1/2', 'http://a/b/c/d;p=1/2?q', 'fred:///s//a/b/c', 'http:///s//a/b/c' ]; //[to, from, result] var relativeTests2 = [ // http://lists.w3.org/Archives/Public/uri/2004Feb/0114.html ['../c', 'foo:a/b', 'foo:c'], ['foo:.', 'foo:a', 'foo:'], ['/foo/../../../bar', 'zz:abc', 'zz:/bar'], ['/foo/../bar', 'zz:abc', 'zz:/bar'], // @isaacs Disagree. Not how web browsers resolve this. ['foo/../../../bar', 'zz:abc', 'zz:bar'], // ['foo/../../../bar', 'zz:abc', 'zz:../../bar'], // @isaacs Added ['foo/../bar', 'zz:abc', 'zz:bar'], ['zz:.', 'zz:abc', 'zz:'], ['/.', bases[0], 'http://a/'], ['/.foo', bases[0], 'http://a/.foo'], ['.foo', bases[0], 'http://a/b/c/.foo'], // http://gbiv.com/protocols/uri/test/rel_examples1.html // examples from RFC 2396 ['g:h', bases[0], 'g:h'], ['g', bases[0], 'http://a/b/c/g'], ['./g', bases[0], 'http://a/b/c/g'], ['g/', bases[0], 'http://a/b/c/g/'], ['/g', bases[0], 'http://a/g'], ['//g', bases[0], 'http://g/'], // changed with RFC 2396bis //('?y', bases[0], 'http://a/b/c/d;p?y'], ['?y', bases[0], 'http://a/b/c/d;p?y'], ['g?y', bases[0], 'http://a/b/c/g?y'], // changed with RFC 2396bis //('#s', bases[0], CURRENT_DOC_URI + '#s'], ['#s', bases[0], 'http://a/b/c/d;p?q#s'], ['g#s', bases[0], 'http://a/b/c/g#s'], ['g?y#s', bases[0], 'http://a/b/c/g?y#s'], [';x', bases[0], 'http://a/b/c/;x'], ['g;x', bases[0], 'http://a/b/c/g;x'], ['g;x?y#s' , bases[0], 'http://a/b/c/g;x?y#s'], // changed with RFC 2396bis //('', bases[0], CURRENT_DOC_URI], ['', bases[0], 'http://a/b/c/d;p?q'], ['.', bases[0], 'http://a/b/c/'], ['./', bases[0], 'http://a/b/c/'], ['..', bases[0], 'http://a/b/'], ['../', bases[0], 'http://a/b/'], ['../g', bases[0], 'http://a/b/g'], ['../..', bases[0], 'http://a/'], ['../../', bases[0], 'http://a/'], ['../../g' , bases[0], 'http://a/g'], ['../../../g', bases[0], ('http://a/../g', 'http://a/g')], ['../../../../g', bases[0], ('http://a/../../g', 'http://a/g')], // changed with RFC 2396bis //('/./g', bases[0], 'http://a/./g'], ['/./g', bases[0], 'http://a/g'], // changed with RFC 2396bis //('/../g', bases[0], 'http://a/../g'], ['/../g', bases[0], 'http://a/g'], ['g.', bases[0], 'http://a/b/c/g.'], ['.g', bases[0], 'http://a/b/c/.g'], ['g..', bases[0], 'http://a/b/c/g..'], ['..g', bases[0], 'http://a/b/c/..g'], ['./../g', bases[0], 'http://a/b/g'], ['./g/.', bases[0], 'http://a/b/c/g/'], ['g/./h', bases[0], 'http://a/b/c/g/h'], ['g/../h', bases[0], 'http://a/b/c/h'], ['g;x=1/./y', bases[0], 'http://a/b/c/g;x=1/y'], ['g;x=1/../y', bases[0], 'http://a/b/c/y'], ['g?y/./x', bases[0], 'http://a/b/c/g?y/./x'], ['g?y/../x', bases[0], 'http://a/b/c/g?y/../x'], ['g#s/./x', bases[0], 'http://a/b/c/g#s/./x'], ['g#s/../x', bases[0], 'http://a/b/c/g#s/../x'], ['http:g', bases[0], ('http:g', 'http://a/b/c/g')], ['http:', bases[0], ('http:', bases[0])], // not sure where this one originated ['/a/b/c/./../../g', bases[0], 'http://a/a/g'], // http://gbiv.com/protocols/uri/test/rel_examples2.html // slashes in base URI's query args ['g', bases[1], 'http://a/b/c/g'], ['./g', bases[1], 'http://a/b/c/g'], ['g/', bases[1], 'http://a/b/c/g/'], ['/g', bases[1], 'http://a/g'], ['//g', bases[1], 'http://g/'], // changed in RFC 2396bis //('?y', bases[1], 'http://a/b/c/?y'], ['?y', bases[1], 'http://a/b/c/d;p?y'], ['g?y', bases[1], 'http://a/b/c/g?y'], ['g?y/./x' , bases[1], 'http://a/b/c/g?y/./x'], ['g?y/../x', bases[1], 'http://a/b/c/g?y/../x'], ['g#s', bases[1], 'http://a/b/c/g#s'], ['g#s/./x' , bases[1], 'http://a/b/c/g#s/./x'], ['g#s/../x', bases[1], 'http://a/b/c/g#s/../x'], ['./', bases[1], 'http://a/b/c/'], ['../', bases[1], 'http://a/b/'], ['../g', bases[1], 'http://a/b/g'], ['../../', bases[1], 'http://a/'], ['../../g' , bases[1], 'http://a/g'], // http://gbiv.com/protocols/uri/test/rel_examples3.html // slashes in path params // all of these changed in RFC 2396bis ['g', bases[2], 'http://a/b/c/d;p=1/g'], ['./g', bases[2], 'http://a/b/c/d;p=1/g'], ['g/', bases[2], 'http://a/b/c/d;p=1/g/'], ['g?y', bases[2], 'http://a/b/c/d;p=1/g?y'], [';x', bases[2], 'http://a/b/c/d;p=1/;x'], ['g;x', bases[2], 'http://a/b/c/d;p=1/g;x'], ['g;x=1/./y', bases[2], 'http://a/b/c/d;p=1/g;x=1/y'], ['g;x=1/../y', bases[2], 'http://a/b/c/d;p=1/y'], ['./', bases[2], 'http://a/b/c/d;p=1/'], ['../', bases[2], 'http://a/b/c/'], ['../g', bases[2], 'http://a/b/c/g'], ['../../', bases[2], 'http://a/b/'], ['../../g' , bases[2], 'http://a/b/g'], // http://gbiv.com/protocols/uri/test/rel_examples4.html // double and triple slash, unknown scheme ['g:h', bases[3], 'g:h'], ['g', bases[3], 'fred:///s//a/b/g'], ['./g', bases[3], 'fred:///s//a/b/g'], ['g/', bases[3], 'fred:///s//a/b/g/'], ['/g', bases[3], 'fred:///g'], // may change to fred:///s//a/g ['//g', bases[3], 'fred://g'], // may change to fred:///s//g ['//g/x', bases[3], 'fred://g/x'], // may change to fred:///s//g/x ['///g', bases[3], 'fred:///g'], ['./', bases[3], 'fred:///s//a/b/'], ['../', bases[3], 'fred:///s//a/'], ['../g', bases[3], 'fred:///s//a/g'], ['../../', bases[3], 'fred:///s//'], ['../../g' , bases[3], 'fred:///s//g'], ['../../../g', bases[3], 'fred:///s/g'], // may change to fred:///s//a/../../../g ['../../../../g', bases[3], 'fred:///g'], // http://gbiv.com/protocols/uri/test/rel_examples5.html // double and triple slash, well-known scheme ['g:h', bases[4], 'g:h'], ['g', bases[4], 'http:///s//a/b/g'], ['./g', bases[4], 'http:///s//a/b/g'], ['g/', bases[4], 'http:///s//a/b/g/'], ['/g', bases[4], 'http:///g'], // may change to http:///s//a/g ['//g', bases[4], 'http://g/'], // may change to http:///s//g ['//g/x', bases[4], 'http://g/x'], // may change to http:///s//g/x ['///g', bases[4], 'http:///g'], ['./', bases[4], 'http:///s//a/b/'], ['../', bases[4], 'http:///s//a/'], ['../g', bases[4], 'http:///s//a/g'], ['../../', bases[4], 'http:///s//'], ['../../g' , bases[4], 'http:///s//g'], // may change to http:///s//a/../../g ['../../../g', bases[4], 'http:///s/g'], // may change to http:///s//a/../../../g ['../../../../g', bases[4], 'http:///g'], // from Dan Connelly's tests in http://www.w3.org/2000/10/swap/uripath.py ['bar:abc', 'foo:xyz', 'bar:abc'], ['../abc', 'http://example/x/y/z', 'http://example/x/abc'], ['http://example/x/abc', 'http://example2/x/y/z', 'http://example/x/abc'], ['../r', 'http://ex/x/y/z', 'http://ex/x/r'], ['q/r', 'http://ex/x/y', 'http://ex/x/q/r'], ['q/r#s', 'http://ex/x/y', 'http://ex/x/q/r#s'], ['q/r#s/t', 'http://ex/x/y', 'http://ex/x/q/r#s/t'], ['ftp://ex/x/q/r', 'http://ex/x/y', 'ftp://ex/x/q/r'], ['', 'http://ex/x/y', 'http://ex/x/y'], ['', 'http://ex/x/y/', 'http://ex/x/y/'], ['', 'http://ex/x/y/pdq', 'http://ex/x/y/pdq'], ['z/', 'http://ex/x/y/', 'http://ex/x/y/z/'], ['#Animal', 'file:/swap/test/animal.rdf', 'file:/swap/test/animal.rdf#Animal'], ['../abc', 'file:/e/x/y/z', 'file:/e/x/abc'], ['/example/x/abc', 'file:/example2/x/y/z', 'file:/example/x/abc'], ['../r', 'file:/ex/x/y/z', 'file:/ex/x/r'], ['/r', 'file:/ex/x/y/z', 'file:/r'], ['q/r', 'file:/ex/x/y', 'file:/ex/x/q/r'], ['q/r#s', 'file:/ex/x/y', 'file:/ex/x/q/r#s'], ['q/r#', 'file:/ex/x/y', 'file:/ex/x/q/r#'], ['q/r#s/t', 'file:/ex/x/y', 'file:/ex/x/q/r#s/t'], ['ftp://ex/x/q/r', 'file:/ex/x/y', 'ftp://ex/x/q/r'], ['', 'file:/ex/x/y', 'file:/ex/x/y'], ['', 'file:/ex/x/y/', 'file:/ex/x/y/'], ['', 'file:/ex/x/y/pdq', 'file:/ex/x/y/pdq'], ['z/', 'file:/ex/x/y/', 'file:/ex/x/y/z/'], ['file://meetings.example.com/cal#m1', 'file:/devel/WWW/2000/10/swap/test/reluri-1.n3', 'file://meetings.example.com/cal#m1'], ['file://meetings.example.com/cal#m1', 'file:/home/connolly/w3ccvs/WWW/2000/10/swap/test/reluri-1.n3', 'file://meetings.example.com/cal#m1'], ['./#blort', 'file:/some/dir/foo', 'file:/some/dir/#blort'], ['./#', 'file:/some/dir/foo', 'file:/some/dir/#'], // Ryan Lee ['./', 'http://example/x/abc.efg', 'http://example/x/'], // Graham Klyne's tests // http://www.ninebynine.org/Software/HaskellUtils/Network/UriTest.xls // 01-31 are from Connelly's cases // 32-49 ['./q:r', 'http://ex/x/y', 'http://ex/x/q:r'], ['./p=q:r', 'http://ex/x/y', 'http://ex/x/p=q:r'], ['?pp/rr', 'http://ex/x/y?pp/qq', 'http://ex/x/y?pp/rr'], ['y/z', 'http://ex/x/y?pp/qq', 'http://ex/x/y/z'], ['local/qual@domain.org#frag', 'mailto:local', 'mailto:local/qual@domain.org#frag'], ['more/qual2@domain2.org#frag', 'mailto:local/qual1@domain1.org', 'mailto:local/more/qual2@domain2.org#frag'], ['y?q', 'http://ex/x/y?q', 'http://ex/x/y?q'], ['/x/y?q', 'http://ex?p', 'http://ex/x/y?q'], ['c/d', 'foo:a/b', 'foo:a/c/d'], ['/c/d', 'foo:a/b', 'foo:/c/d'], ['', 'foo:a/b?c#d', 'foo:a/b?c'], ['b/c', 'foo:a', 'foo:b/c'], ['../b/c', 'foo:/a/y/z', 'foo:/a/b/c'], ['./b/c', 'foo:a', 'foo:b/c'], ['/./b/c', 'foo:a', 'foo:/b/c'], ['../../d', 'foo://a//b/c', 'foo://a/d'], ['.', 'foo:a', 'foo:'], ['..', 'foo:a', 'foo:'], // 50-57[cf. TimBL comments -- // http://lists.w3.org/Archives/Public/uri/2003Feb/0028.html, // http://lists.w3.org/Archives/Public/uri/2003Jan/0008.html) ['abc', 'http://example/x/y%2Fz', 'http://example/x/abc'], ['../../x%2Fabc', 'http://example/a/x/y/z', 'http://example/a/x%2Fabc'], ['../x%2Fabc', 'http://example/a/x/y%2Fz', 'http://example/a/x%2Fabc'], ['abc', 'http://example/x%2Fy/z', 'http://example/x%2Fy/abc'], ['q%3Ar', 'http://ex/x/y', 'http://ex/x/q%3Ar'], ['/x%2Fabc', 'http://example/x/y%2Fz', 'http://example/x%2Fabc'], ['/x%2Fabc', 'http://example/x/y/z', 'http://example/x%2Fabc'], ['/x%2Fabc', 'http://example/x/y%2Fz', 'http://example/x%2Fabc'], // 70-77 ['local2@domain2', 'mailto:local1@domain1?query1', 'mailto:local2@domain2'], ['local2@domain2?query2', 'mailto:local1@domain1', 'mailto:local2@domain2?query2'], ['local2@domain2?query2', 'mailto:local1@domain1?query1', 'mailto:local2@domain2?query2'], ['?query2', 'mailto:local@domain?query1', 'mailto:local@domain?query2'], ['local@domain?query2', 'mailto:?query1', 'mailto:local@domain?query2'], ['?query2', 'mailto:local@domain?query1', 'mailto:local@domain?query2'], ['http://example/a/b?c/../d', 'foo:bar', 'http://example/a/b?c/../d'], ['http://example/a/b#c/../d', 'foo:bar', 'http://example/a/b#c/../d'], // 82-88 // @isaacs Disagree. Not how browsers do it. // ['http:this', 'http://example.org/base/uri', 'http:this'], // @isaacs Added ['http:this', 'http://example.org/base/uri', 'http://example.org/base/this'], ['http:this', 'http:base', 'http:this'], ['.//g', 'f:/a', 'f://g'], ['b/c//d/e', 'f://example.org/base/a', 'f://example.org/base/b/c//d/e'], ['m2@example.ord/c2@example.org', 'mid:m@example.ord/c@example.org', 'mid:m@example.ord/m2@example.ord/c2@example.org'], ['mini1.xml', 'file:///C:/DEV/Haskell/lib/HXmlToolbox-3.01/examples/', 'file:///C:/DEV/Haskell/lib/HXmlToolbox-3.01/examples/mini1.xml'], ['../b/c', 'foo:a/y/z', 'foo:a/b/c'], //changeing auth ['http://diff:auth@www.example.com', 'http://asdf:qwer@www.example.com', 'http://diff:auth@www.example.com/'] ]; relativeTests2.forEach(function(relativeTest) { var a = url.resolve(relativeTest[1], relativeTest[0]), e = relativeTest[2]; assert.equal(a, e, 'resolve(' + [relativeTest[1], relativeTest[0]] + ') == ' + e + '\n actual=' + a); }); //if format and parse are inverse operations then //resolveObject(parse(x), y) == parse(resolve(x, y)) //host and hostname are special, in this case a '' value is important var emptyIsImportant = {'host': true, 'hostname': ''}; //format: [from, path, expected] relativeTests.forEach(function(relativeTest) { var actual = url.resolveObject(url.parse(relativeTest[0]), relativeTest[1]), expected = url.parse(relativeTest[2]); assert.deepEqual(actual, expected); expected = relativeTest[2]; actual = url.format(actual); assert.equal(actual, expected, 'format(' + actual + ') == ' + expected + '\nactual:' + actual); }); //format: [to, from, result] // the test: ['.//g', 'f:/a', 'f://g'] is a fundimental problem // url.parse('f:/a') does not have a host // url.resolve('f:/a', './/g') does not have a host becuase you have moved // down to the g directory. i.e. f: //g, however when this url is parsed // f:// will indicate that the host is g which is not the case. // it is unclear to me how to keep this information from being lost // it may be that a pathname of ////g should colapse to /g but this seems // to be a lot of work for an edge case. Right now I remove the test if (relativeTests2[181][0] === './/g' && relativeTests2[181][1] === 'f:/a' && relativeTests2[181][2] === 'f://g') { relativeTests2.splice(181, 1); } relativeTests2.forEach(function(relativeTest) { var actual = url.resolveObject(url.parse(relativeTest[1]), relativeTest[0]), expected = url.parse(relativeTest[2]); assert.deepEqual(actual, expected); var expected = relativeTest[2], actual = url.format(actual); assert.equal(actual, expected, 'format(' + relativeTest[1] + ') == ' + expected + '\nactual:' + actual); }); node-v0.10.25~dfsg2/test/simple/test-stdout-cannot-be-closed-child-process-pipe.js0000644000000000000000000000343312270121457026530 0ustar rootroot// Copyright Joyent, Inc. and other Node contributors. // // Permission is hereby granted, free of charge, to any person obtaining a // copy of this software and associated documentation files (the // "Software"), to deal in the Software without restriction, including // without limitation the rights to use, copy, modify, merge, publish, // distribute, sublicense, and/or sell copies of the Software, and to permit // persons to whom the Software is furnished to do so, subject to the // following conditions: // // The above copyright notice and this permission notice shall be included // in all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS // OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF // MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN // NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, // DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR // OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE // USE OR OTHER DEALINGS IN THE SOFTWARE. var common = require('../common'); var assert = require('assert'); if (process.argv[2] === 'child') process.stdout.end('foo'); else parent(); function parent() { var spawn = require('child_process').spawn; var child = spawn(process.execPath, [__filename, 'child']); var out = ''; var err = ''; child.stdout.setEncoding('utf8'); child.stderr.setEncoding('utf8'); child.stdout.on('data', function(c) { out += c; }); child.stderr.on('data', function(c) { err += c; }); child.on('close', function(code, signal) { assert(code); assert.equal(out, 'foo'); assert(/process\.stdout cannot be closed/.test(err)); console.log('ok'); }); } node-v0.10.25~dfsg2/test/simple/test-regress-GH-4027.js0000644000000000000000000000320512270121457020740 0ustar rootroot// Copyright Joyent, Inc. and other Node contributors. // // Permission is hereby granted, free of charge, to any person obtaining a // copy of this software and associated documentation files (the // "Software"), to deal in the Software without restriction, including // without limitation the rights to use, copy, modify, merge, publish, // distribute, sublicense, and/or sell copies of the Software, and to permit // persons to whom the Software is furnished to do so, subject to the // following conditions: // // The above copyright notice and this permission notice shall be included // in all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS // OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF // MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN // NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, // DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR // OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE // USE OR OTHER DEALINGS IN THE SOFTWARE. var common = require('../common'); var assert = require('assert'); var path = require('path'); var fs = require('fs'); var filename = path.join(common.tmpDir, 'watched'); fs.writeFileSync(filename, 'quis custodiet ipsos custodes'); setTimeout(fs.unlinkSync, 100, filename); var seenEvent = 0; process.on('exit', function() { assert.equal(seenEvent, 1); }); fs.watchFile(filename, { interval: 50 }, function(curr, prev) { assert.equal(prev.nlink, 1); assert.equal(curr.nlink, 0); fs.unwatchFile(filename); seenEvent++; }); node-v0.10.25~dfsg2/test/simple/test-http-client-timeout-event.js0000644000000000000000000000361612270121457023444 0ustar rootroot// Copyright Joyent, Inc. and other Node contributors. // // Permission is hereby granted, free of charge, to any person obtaining a // copy of this software and associated documentation files (the // "Software"), to deal in the Software without restriction, including // without limitation the rights to use, copy, modify, merge, publish, // distribute, sublicense, and/or sell copies of the Software, and to permit // persons to whom the Software is furnished to do so, subject to the // following conditions: // // The above copyright notice and this permission notice shall be included // in all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS // OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF // MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN // NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, // DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR // OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE // USE OR OTHER DEALINGS IN THE SOFTWARE. var common = require('../common'); var assert = require('assert'); var http = require('http'); var options = { method: 'GET', port: common.PORT, host: '127.0.0.1', path: '/' }; var server = http.createServer(function(req, res) { // this space intentionally left blank }); server.listen(options.port, options.host, function() { var req = http.request(options, function(res) { // this space intentionally left blank }); req.on('error', function() { // this space is intentially left blank }); req.on('close', function() { server.close(); }); var timeout_events = 0; req.setTimeout(1); req.on('timeout', function () { timeout_events += 1; }); setTimeout(function () { req.destroy(); assert.equal(timeout_events, 1); }, 10); req.end(); }); node-v0.10.25~dfsg2/test/simple/test-tls-connect-simple.js0000644000000000000000000000401312270121457022116 0ustar rootroot// Copyright Joyent, Inc. and other Node contributors. // // Permission is hereby granted, free of charge, to any person obtaining a // copy of this software and associated documentation files (the // "Software"), to deal in the Software without restriction, including // without limitation the rights to use, copy, modify, merge, publish, // distribute, sublicense, and/or sell copies of the Software, and to permit // persons to whom the Software is furnished to do so, subject to the // following conditions: // // The above copyright notice and this permission notice shall be included // in all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS // OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF // MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN // NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, // DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR // OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE // USE OR OTHER DEALINGS IN THE SOFTWARE. var common = require('../common'); var assert = require('assert'); var tls = require('tls'); var fs = require('fs'); var clientConnected = 0; var serverConnected = 0; var options = { key: fs.readFileSync(common.fixturesDir + '/keys/agent1-key.pem'), cert: fs.readFileSync(common.fixturesDir + '/keys/agent1-cert.pem') }; var server = tls.Server(options, function(socket) { if (++serverConnected === 2) { server.close(); } }); server.listen(common.PORT, function() { var client1 = tls.connect({ port: common.PORT, rejectUnauthorized: false }, function() { ++clientConnected; client1.end(); }); var client2 = tls.connect({ port: common.PORT, rejectUnauthorized: false }); client2.on('secureConnect', function() { ++clientConnected; client2.end(); }); }); process.on('exit', function() { assert.equal(clientConnected, 2); assert.equal(serverConnected, 2); }); node-v0.10.25~dfsg2/test/simple/test-tty-wrap.js0000644000000000000000000000326512270121457020175 0ustar rootroot// Copyright Joyent, Inc. and other Node contributors. // // Permission is hereby granted, free of charge, to any person obtaining a // copy of this software and associated documentation files (the // "Software"), to deal in the Software without restriction, including // without limitation the rights to use, copy, modify, merge, publish, // distribute, sublicense, and/or sell copies of the Software, and to permit // persons to whom the Software is furnished to do so, subject to the // following conditions: // // The above copyright notice and this permission notice shall be included // in all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS // OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF // MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN // NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, // DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR // OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE // USE OR OTHER DEALINGS IN THE SOFTWARE. var common = require('../common'); var assert = require('assert'); var TTY = process.binding('tty_wrap').TTY; var isTTY = process.binding('tty_wrap').isTTY; if (isTTY(1) == false) { console.error('fd 1 is not a tty. skipping test.'); process.exit(0); } var handle = new TTY(1); var callbacks = 0; var req1 = handle.writeBuffer(Buffer('hello world\n')); req1.oncomplete = function() { callbacks++; }; var req2 = handle.writeBuffer(Buffer('hello world\n')); req2.oncomplete = function() { callbacks++; }; process.on('exit', function() { assert.equal(2, callbacks); }); node-v0.10.25~dfsg2/test/simple/test-console-not-call-toString.js0000644000000000000000000000254112270121457023362 0ustar rootroot// Copyright Joyent, Inc. and other Node contributors. // // Permission is hereby granted, free of charge, to any person obtaining a // copy of this software and associated documentation files (the // "Software"), to deal in the Software without restriction, including // without limitation the rights to use, copy, modify, merge, publish, // distribute, sublicense, and/or sell copies of the Software, and to permit // persons to whom the Software is furnished to do so, subject to the // following conditions: // // The above copyright notice and this permission notice shall be included // in all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS // OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF // MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN // NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, // DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR // OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE // USE OR OTHER DEALINGS IN THE SOFTWARE. var common = require('../common'); var assert = require('assert'); var func = function() {}; var toStringCalled = false; func.toString = function() { toStringCalled = true; }; require('util').inspect(func); assert.ok(!toStringCalled); node-v0.10.25~dfsg2/test/simple/test-stream2-compatibility.js0000644000000000000000000000324112270121457022624 0ustar rootroot// Copyright Joyent, Inc. and other Node contributors. // // Permission is hereby granted, free of charge, to any person obtaining a // copy of this software and associated documentation files (the // "Software"), to deal in the Software without restriction, including // without limitation the rights to use, copy, modify, merge, publish, // distribute, sublicense, and/or sell copies of the Software, and to permit // persons to whom the Software is furnished to do so, subject to the // following conditions: // // The above copyright notice and this permission notice shall be included // in all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS // OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF // MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN // NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, // DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR // OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE // USE OR OTHER DEALINGS IN THE SOFTWARE. var common = require('../common.js'); var R = require('_stream_readable'); var assert = require('assert'); var util = require('util'); var EE = require('events').EventEmitter; var ondataCalled = 0; function TestReader() { R.apply(this); this._buffer = new Buffer(100); this._buffer.fill('x'); this.on('data', function() { ondataCalled++; }); } util.inherits(TestReader, R); TestReader.prototype._read = function(n) { this.push(this._buffer); this._buffer = new Buffer(0); }; var reader = new TestReader(); assert.equal(ondataCalled, 1); node-v0.10.25~dfsg2/test/simple/test-event-emitter-remove-all-listeners.js0000644000000000000000000000601412270121457025240 0ustar rootroot// Copyright Joyent, Inc. and other Node contributors. // // Permission is hereby granted, free of charge, to any person obtaining a // copy of this software and associated documentation files (the // "Software"), to deal in the Software without restriction, including // without limitation the rights to use, copy, modify, merge, publish, // distribute, sublicense, and/or sell copies of the Software, and to permit // persons to whom the Software is furnished to do so, subject to the // following conditions: // // The above copyright notice and this permission notice shall be included // in all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS // OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF // MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN // NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, // DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR // OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE // USE OR OTHER DEALINGS IN THE SOFTWARE. var common = require('../common'); var assert = require('assert'); var events = require('events'); function expect(expected) { var actual = []; process.on('exit', function() { assert.deepEqual(actual.sort(), expected.sort()); }); function listener(name) { actual.push(name) } return common.mustCall(listener, expected.length); } function listener() {} var e1 = new events.EventEmitter(); e1.on('foo', listener); e1.on('bar', listener); e1.on('baz', listener); e1.on('baz', listener); var fooListeners = e1.listeners('foo'); var barListeners = e1.listeners('bar'); var bazListeners = e1.listeners('baz'); e1.on('removeListener', expect(['bar', 'baz', 'baz'])); e1.removeAllListeners('bar'); e1.removeAllListeners('baz'); assert.deepEqual(e1.listeners('foo'), [listener]); assert.deepEqual(e1.listeners('bar'), []); assert.deepEqual(e1.listeners('baz'), []); // after calling removeAllListeners, // the old listeners array should stay unchanged assert.deepEqual(fooListeners, [listener]); assert.deepEqual(barListeners, [listener]); assert.deepEqual(bazListeners, [listener, listener]); // after calling removeAllListeners, // new listeners arrays are different from the old assert.notEqual(e1.listeners('bar'), barListeners); assert.notEqual(e1.listeners('baz'), bazListeners); var e2 = new events.EventEmitter(); e2.on('foo', listener); e2.on('bar', listener); // expect LIFO order e2.on('removeListener', expect(['foo', 'bar', 'removeListener'])); e2.on('removeListener', expect(['foo', 'bar'])); e2.removeAllListeners(); console.error(e2); assert.deepEqual([], e2.listeners('foo')); assert.deepEqual([], e2.listeners('bar')); var e3 = new events.EventEmitter(); e3.on('removeListener', listener); // check for regression where removeAllListeners throws when // there exists a removeListener listener, but there exists // no listeners for the provided event type assert.doesNotThrow(e3.removeAllListeners.bind(e3, 'foo')); node-v0.10.25~dfsg2/test/simple/test-module-loading.js0000644000000000000000000002437312270121457021311 0ustar rootroot// Copyright Joyent, Inc. and other Node contributors. // // Permission is hereby granted, free of charge, to any person obtaining a // copy of this software and associated documentation files (the // "Software"), to deal in the Software without restriction, including // without limitation the rights to use, copy, modify, merge, publish, // distribute, sublicense, and/or sell copies of the Software, and to permit // persons to whom the Software is furnished to do so, subject to the // following conditions: // // The above copyright notice and this permission notice shall be included // in all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS // OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF // MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN // NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, // DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR // OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE // USE OR OTHER DEALINGS IN THE SOFTWARE. var common = require('../common'); var assert = require('assert'); var path = require('path'); var fs = require('fs'); common.debug('load test-module-loading.js'); // assert that this is the main module. assert.equal(require.main.id, '.', 'main module should have id of \'.\''); assert.equal(require.main, module, 'require.main should === module'); assert.equal(process.mainModule, module, 'process.mainModule should === module'); // assert that it's *not* the main module in the required module. require('../fixtures/not-main-module.js'); // require a file with a request that includes the extension var a_js = require('../fixtures/a.js'); assert.equal(42, a_js.number); // require a file without any extensions var foo_no_ext = require('../fixtures/foo'); assert.equal('ok', foo_no_ext.foo); var a = require('../fixtures/a'); var c = require('../fixtures/b/c'); var d = require('../fixtures/b/d'); var d2 = require('../fixtures/b/d'); // Absolute var d3 = require(path.join(__dirname, '../fixtures/b/d')); // Relative var d4 = require('../fixtures/b/d'); assert.equal(false, false, 'testing the test program.'); assert.equal(true, common.indirectInstanceOf(a.A, Function)); assert.equal('A', a.A()); assert.equal(true, common.indirectInstanceOf(a.C, Function)); assert.equal('C', a.C()); assert.equal(true, common.indirectInstanceOf(a.D, Function)); assert.equal('D', a.D()); assert.equal(true, common.indirectInstanceOf(d.D, Function)); assert.equal('D', d.D()); assert.equal(true, common.indirectInstanceOf(d2.D, Function)); assert.equal('D', d2.D()); assert.equal(true, common.indirectInstanceOf(d3.D, Function)); assert.equal('D', d3.D()); assert.equal(true, common.indirectInstanceOf(d4.D, Function)); assert.equal('D', d4.D()); assert.ok((new a.SomeClass) instanceof c.SomeClass); common.debug('test index.js modules ids and relative loading'); var one = require('../fixtures/nested-index/one'), two = require('../fixtures/nested-index/two'); assert.notEqual(one.hello, two.hello); common.debug('test index.js in a folder with a trailing slash'); var three = require('../fixtures/nested-index/three'), threeFolder = require('../fixtures/nested-index/three/'), threeIndex = require('../fixtures/nested-index/three/index.js'); assert.equal(threeFolder, threeIndex); assert.notEqual(threeFolder, three); common.debug('test package.json require() loading'); assert.equal(require('../fixtures/packages/main').ok, 'ok', 'Failed loading package'); assert.equal(require('../fixtures/packages/main-index').ok, 'ok', 'Failed loading package with index.js in main subdir'); common.debug('test cycles containing a .. path'); var root = require('../fixtures/cycles/root'), foo = require('../fixtures/cycles/folder/foo'); assert.equal(root.foo, foo); assert.equal(root.sayHello(), root.hello); common.debug('test node_modules folders'); // asserts are in the fixtures files themselves, // since they depend on the folder structure. require('../fixtures/node_modules/foo'); common.debug('test name clashes'); // this one exists and should import the local module var my_path = require('./path'); assert.ok(common.indirectInstanceOf(my_path.path_func, Function)); // this one does not exist and should throw assert.throws(function() { require('./utils')}); var errorThrown = false; try { require('../fixtures/throws_error'); } catch (e) { errorThrown = true; assert.equal('blah', e.message); } assert.equal(require('path').dirname(__filename), __dirname); common.debug('load custom file types with extensions'); require.extensions['.test'] = function(module, filename) { var content = fs.readFileSync(filename).toString(); assert.equal('this is custom source\n', content); content = content.replace('this is custom source', 'exports.test = \'passed\''); module._compile(content, filename); }; assert.equal(require('../fixtures/registerExt').test, 'passed'); // unknown extension, load as .js assert.equal(require('../fixtures/registerExt.hello.world').test, 'passed'); common.debug('load custom file types that return non-strings'); require.extensions['.test'] = function(module, filename) { module.exports = { custom: 'passed' }; }; assert.equal(require('../fixtures/registerExt2').custom, 'passed'); assert.equal(require('../fixtures/foo').foo, 'ok', 'require module with no extension'); assert.throws(function() { require.paths; }, /removed/, 'Accessing require.paths should throw.'); // Should not attempt to load a directory try { require('../fixtures/empty'); } catch (err) { assert.equal(err.message, 'Cannot find module \'../fixtures/empty\''); } // Check load order is as expected common.debug('load order'); var loadOrder = '../fixtures/module-load-order/', msg = 'Load order incorrect.'; require.extensions['.reg'] = require.extensions['.js']; require.extensions['.reg2'] = require.extensions['.js']; assert.equal(require(loadOrder + 'file1').file1, 'file1', msg); assert.equal(require(loadOrder + 'file2').file2, 'file2.js', msg); try { require(loadOrder + 'file3'); } catch (e) { // Not a real .node module, but we know we require'd the right thing. assert.ok(e.message.replace(/\\/g, '/').match(/file3\.node/)); } assert.equal(require(loadOrder + 'file4').file4, 'file4.reg', msg); assert.equal(require(loadOrder + 'file5').file5, 'file5.reg2', msg); assert.equal(require(loadOrder + 'file6').file6, 'file6/index.js', msg); try { require(loadOrder + 'file7'); } catch (e) { assert.ok(e.message.replace(/\\/g, '/').match(/file7\/index\.node/)); } assert.equal(require(loadOrder + 'file8').file8, 'file8/index.reg', msg); assert.equal(require(loadOrder + 'file9').file9, 'file9/index.reg2', msg); // make sure that module.require() is the same as // doing require() inside of that module. var parent = require('../fixtures/module-require/parent/'); var child = require('../fixtures/module-require/child/'); assert.equal(child.loaded, parent.loaded); // #1357 Loading JSON files with require() var json = require('../fixtures/packages/main/package.json'); assert.deepEqual(json, { name: 'package-name', version: '1.2.3', main: 'package-main-module' }); // now verify that module.children contains all the different // modules that we've required, and that all of them contain // the appropriate children, and so on. var children = module.children.reduce(function red(set, child) { var id = path.relative(path.dirname(__dirname), child.id) id = id.replace(/\\/g, '/'); set[id] = child.children.reduce(red, {}); return set; }, {}); assert.deepEqual(children, { 'common.js': {}, 'fixtures/not-main-module.js': {}, 'fixtures/a.js': { 'fixtures/b/c.js': { 'fixtures/b/d.js': {}, 'fixtures/b/package/index.js': {} } }, 'fixtures/foo': {}, 'fixtures/nested-index/one/index.js': { 'fixtures/nested-index/one/hello.js': {} }, 'fixtures/nested-index/two/index.js': { 'fixtures/nested-index/two/hello.js': {} }, 'fixtures/nested-index/three.js': {}, 'fixtures/nested-index/three/index.js': {}, 'fixtures/packages/main/package-main-module.js': {}, 'fixtures/packages/main-index/package-main-module/index.js': {}, 'fixtures/cycles/root.js': { 'fixtures/cycles/folder/foo.js': {} }, 'fixtures/node_modules/foo.js': { 'fixtures/node_modules/baz/index.js': { 'fixtures/node_modules/bar.js': {}, 'fixtures/node_modules/baz/node_modules/asdf.js': {} } }, 'simple/path.js': {}, 'fixtures/throws_error.js': {}, 'fixtures/registerExt.test': {}, 'fixtures/registerExt.hello.world': {}, 'fixtures/registerExt2.test': {}, 'fixtures/empty.js': {}, 'fixtures/module-load-order/file1': {}, 'fixtures/module-load-order/file2.js': {}, 'fixtures/module-load-order/file3.node': {}, 'fixtures/module-load-order/file4.reg': {}, 'fixtures/module-load-order/file5.reg2': {}, 'fixtures/module-load-order/file6/index.js': {}, 'fixtures/module-load-order/file7/index.node': {}, 'fixtures/module-load-order/file8/index.reg': {}, 'fixtures/module-load-order/file9/index.reg2': {}, 'fixtures/module-require/parent/index.js': { 'fixtures/module-require/child/index.js': { 'fixtures/module-require/child/node_modules/target.js': {} } }, 'fixtures/packages/main/package.json': {} }); // require() must take string, and must be truthy assert.throws(function() { console.error('require non-string'); require({ foo: 'bar' }); }, 'path must be a string'); assert.throws(function() { console.error('require empty string'); require(''); }, 'missing path'); process.on('exit', function() { assert.ok(common.indirectInstanceOf(a.A, Function)); assert.equal('A done', a.A()); assert.ok(common.indirectInstanceOf(a.C, Function)); assert.equal('C done', a.C()); assert.ok(common.indirectInstanceOf(a.D, Function)); assert.equal('D done', a.D()); assert.ok(common.indirectInstanceOf(d.D, Function)); assert.equal('D done', d.D()); assert.ok(common.indirectInstanceOf(d2.D, Function)); assert.equal('D done', d2.D()); assert.equal(true, errorThrown); console.log('exit'); }); // #1440 Loading files with a byte order marker. assert.equal(42, require('../fixtures/utf8-bom.js')); assert.equal(42, require('../fixtures/utf8-bom.json')); node-v0.10.25~dfsg2/test/simple/test-writedouble.js0000644000000000000000000001525712270121457020737 0ustar rootroot// Copyright Joyent, Inc. and other Node contributors. // // Permission is hereby granted, free of charge, to any person obtaining a // copy of this software and associated documentation files (the // "Software"), to deal in the Software without restriction, including // without limitation the rights to use, copy, modify, merge, publish, // distribute, sublicense, and/or sell copies of the Software, and to permit // persons to whom the Software is furnished to do so, subject to the // following conditions: // // The above copyright notice and this permission notice shall be included // in all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS // OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF // MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN // NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, // DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR // OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE // USE OR OTHER DEALINGS IN THE SOFTWARE. /* * Tests to verify we're writing doubles correctly */ var SlowBuffer = process.binding('buffer').SlowBuffer; var common = require('../common'); var ASSERT = require('assert'); function test(clazz) { var buffer = new clazz(16); buffer.writeDoubleBE(2.225073858507201e-308, 0); buffer.writeDoubleLE(2.225073858507201e-308, 8); ASSERT.equal(0x00, buffer[0]); ASSERT.equal(0x0f, buffer[1]); ASSERT.equal(0xff, buffer[2]); ASSERT.equal(0xff, buffer[3]); ASSERT.equal(0xff, buffer[4]); ASSERT.equal(0xff, buffer[5]); ASSERT.equal(0xff, buffer[6]); ASSERT.equal(0xff, buffer[7]); ASSERT.equal(0xff, buffer[8]); ASSERT.equal(0xff, buffer[9]); ASSERT.equal(0xff, buffer[10]); ASSERT.equal(0xff, buffer[11]); ASSERT.equal(0xff, buffer[12]); ASSERT.equal(0xff, buffer[13]); ASSERT.equal(0x0f, buffer[14]); ASSERT.equal(0x00, buffer[15]); buffer.writeDoubleBE(1.0000000000000004, 0); buffer.writeDoubleLE(1.0000000000000004, 8); ASSERT.equal(0x3f, buffer[0]); ASSERT.equal(0xf0, buffer[1]); ASSERT.equal(0x00, buffer[2]); ASSERT.equal(0x00, buffer[3]); ASSERT.equal(0x00, buffer[4]); ASSERT.equal(0x00, buffer[5]); ASSERT.equal(0x00, buffer[6]); ASSERT.equal(0x02, buffer[7]); ASSERT.equal(0x02, buffer[8]); ASSERT.equal(0x00, buffer[9]); ASSERT.equal(0x00, buffer[10]); ASSERT.equal(0x00, buffer[11]); ASSERT.equal(0x00, buffer[12]); ASSERT.equal(0x00, buffer[13]); ASSERT.equal(0xf0, buffer[14]); ASSERT.equal(0x3f, buffer[15]); buffer.writeDoubleBE(-2, 0); buffer.writeDoubleLE(-2, 8); ASSERT.equal(0xc0, buffer[0]); ASSERT.equal(0x00, buffer[1]); ASSERT.equal(0x00, buffer[2]); ASSERT.equal(0x00, buffer[3]); ASSERT.equal(0x00, buffer[4]); ASSERT.equal(0x00, buffer[5]); ASSERT.equal(0x00, buffer[6]); ASSERT.equal(0x00, buffer[7]); ASSERT.equal(0x00, buffer[8]); ASSERT.equal(0x00, buffer[9]); ASSERT.equal(0x00, buffer[10]); ASSERT.equal(0x00, buffer[11]); ASSERT.equal(0x00, buffer[12]); ASSERT.equal(0x00, buffer[13]); ASSERT.equal(0x00, buffer[14]); ASSERT.equal(0xc0, buffer[15]); buffer.writeDoubleBE(1.7976931348623157e+308, 0); buffer.writeDoubleLE(1.7976931348623157e+308, 8); ASSERT.equal(0x7f, buffer[0]); ASSERT.equal(0xef, buffer[1]); ASSERT.equal(0xff, buffer[2]); ASSERT.equal(0xff, buffer[3]); ASSERT.equal(0xff, buffer[4]); ASSERT.equal(0xff, buffer[5]); ASSERT.equal(0xff, buffer[6]); ASSERT.equal(0xff, buffer[7]); ASSERT.equal(0xff, buffer[8]); ASSERT.equal(0xff, buffer[9]); ASSERT.equal(0xff, buffer[10]); ASSERT.equal(0xff, buffer[11]); ASSERT.equal(0xff, buffer[12]); ASSERT.equal(0xff, buffer[13]); ASSERT.equal(0xef, buffer[14]); ASSERT.equal(0x7f, buffer[15]); buffer.writeDoubleBE(0 * -1, 0); buffer.writeDoubleLE(0 * -1, 8); ASSERT.equal(0x80, buffer[0]); ASSERT.equal(0x00, buffer[1]); ASSERT.equal(0x00, buffer[2]); ASSERT.equal(0x00, buffer[3]); ASSERT.equal(0x00, buffer[4]); ASSERT.equal(0x00, buffer[5]); ASSERT.equal(0x00, buffer[6]); ASSERT.equal(0x00, buffer[7]); ASSERT.equal(0x00, buffer[8]); ASSERT.equal(0x00, buffer[9]); ASSERT.equal(0x00, buffer[10]); ASSERT.equal(0x00, buffer[11]); ASSERT.equal(0x00, buffer[12]); ASSERT.equal(0x00, buffer[13]); ASSERT.equal(0x00, buffer[14]); ASSERT.equal(0x80, buffer[15]); buffer.writeDoubleBE(Infinity, 0); buffer.writeDoubleLE(Infinity, 8); ASSERT.equal(0x7F, buffer[0]); ASSERT.equal(0xF0, buffer[1]); ASSERT.equal(0x00, buffer[2]); ASSERT.equal(0x00, buffer[3]); ASSERT.equal(0x00, buffer[4]); ASSERT.equal(0x00, buffer[5]); ASSERT.equal(0x00, buffer[6]); ASSERT.equal(0x00, buffer[7]); ASSERT.equal(0x00, buffer[8]); ASSERT.equal(0x00, buffer[9]); ASSERT.equal(0x00, buffer[10]); ASSERT.equal(0x00, buffer[11]); ASSERT.equal(0x00, buffer[12]); ASSERT.equal(0x00, buffer[13]); ASSERT.equal(0xF0, buffer[14]); ASSERT.equal(0x7F, buffer[15]); ASSERT.equal(Infinity, buffer.readDoubleBE(0)); ASSERT.equal(Infinity, buffer.readDoubleLE(8)); buffer.writeDoubleBE(-Infinity, 0); buffer.writeDoubleLE(-Infinity, 8); ASSERT.equal(0xFF, buffer[0]); ASSERT.equal(0xF0, buffer[1]); ASSERT.equal(0x00, buffer[2]); ASSERT.equal(0x00, buffer[3]); ASSERT.equal(0x00, buffer[4]); ASSERT.equal(0x00, buffer[5]); ASSERT.equal(0x00, buffer[6]); ASSERT.equal(0x00, buffer[7]); ASSERT.equal(0x00, buffer[8]); ASSERT.equal(0x00, buffer[9]); ASSERT.equal(0x00, buffer[10]); ASSERT.equal(0x00, buffer[11]); ASSERT.equal(0x00, buffer[12]); ASSERT.equal(0x00, buffer[13]); ASSERT.equal(0xF0, buffer[14]); ASSERT.equal(0xFF, buffer[15]); ASSERT.equal(-Infinity, buffer.readDoubleBE(0)); ASSERT.equal(-Infinity, buffer.readDoubleLE(8)); buffer.writeDoubleBE(NaN, 0); buffer.writeDoubleLE(NaN, 8); // Darwin ia32 does the other kind of NaN. // Compiler bug. No one really cares. ASSERT(0x7F === buffer[0] || 0xFF === buffer[0]); ASSERT.equal(0xF8, buffer[1]); ASSERT.equal(0x00, buffer[2]); ASSERT.equal(0x00, buffer[3]); ASSERT.equal(0x00, buffer[4]); ASSERT.equal(0x00, buffer[5]); ASSERT.equal(0x00, buffer[6]); ASSERT.equal(0x00, buffer[7]); ASSERT.equal(0x00, buffer[8]); ASSERT.equal(0x00, buffer[9]); ASSERT.equal(0x00, buffer[10]); ASSERT.equal(0x00, buffer[11]); ASSERT.equal(0x00, buffer[12]); ASSERT.equal(0x00, buffer[13]); ASSERT.equal(0xF8, buffer[14]); // Darwin ia32 does the other kind of NaN. // Compiler bug. No one really cares. ASSERT(0x7F === buffer[15] || 0xFF === buffer[15]); ASSERT.ok(isNaN(buffer.readDoubleBE(0))); ASSERT.ok(isNaN(buffer.readDoubleLE(8))); } test(Buffer); test(SlowBuffer); node-v0.10.25~dfsg2/test/simple/test-pump-file2tcp.js0000644000000000000000000000416712270121457021077 0ustar rootroot// Copyright Joyent, Inc. and other Node contributors. // // Permission is hereby granted, free of charge, to any person obtaining a // copy of this software and associated documentation files (the // "Software"), to deal in the Software without restriction, including // without limitation the rights to use, copy, modify, merge, publish, // distribute, sublicense, and/or sell copies of the Software, and to permit // persons to whom the Software is furnished to do so, subject to the // following conditions: // // The above copyright notice and this permission notice shall be included // in all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS // OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF // MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN // NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, // DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR // OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE // USE OR OTHER DEALINGS IN THE SOFTWARE. var common = require('../common'); var assert = require('assert'); var net = require('net'); var fs = require('fs'); var util = require('util'); var path = require('path'); var fn = path.join(common.fixturesDir, 'elipses.txt'); var expected = fs.readFileSync(fn, 'utf8'); var server = net.createServer(function(stream) { common.error('pump!'); util.pump(fs.createReadStream(fn), stream, function() { common.error('server stream close'); common.error('server close'); server.close(); }); }); server.listen(common.PORT, function() { var conn = net.createConnection(common.PORT); conn.setEncoding('utf8'); conn.on('data', function(chunk) { common.error('recv data! nchars = ' + chunk.length); buffer += chunk; }); conn.on('end', function() { conn.end(); }); conn.on('close', function() { common.error('client connection close'); }); }); var buffer = ''; var count = 0; server.on('listening', function() { }); process.on('exit', function() { assert.equal(expected, buffer); }); node-v0.10.25~dfsg2/test/simple/test-dgram-close.js0000644000000000000000000000324612270121457020602 0ustar rootroot// Copyright Joyent, Inc. and other Node contributors. // // Permission is hereby granted, free of charge, to any person obtaining a // copy of this software and associated documentation files (the // "Software"), to deal in the Software without restriction, including // without limitation the rights to use, copy, modify, merge, publish, // distribute, sublicense, and/or sell copies of the Software, and to permit // persons to whom the Software is furnished to do so, subject to the // following conditions: // // The above copyright notice and this permission notice shall be included // in all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS // OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF // MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN // NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, // DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR // OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE // USE OR OTHER DEALINGS IN THE SOFTWARE. // Ensure that if a dgram socket is closed before the DNS lookup completes, it // won't crash. var assert = require('assert'), common = require('../common'), dgram = require('dgram'); var buf = new Buffer(1024); buf.fill(42); var socket = dgram.createSocket('udp4'); var handle = socket._handle; socket.send(buf, 0, buf.length, common.PORT, 'localhost'); socket.close(); socket = null; // Verify that accessing handle after closure doesn't throw setImmediate(function() { setImmediate(function() { console.log('Handle fd is: ', handle.fd); }); }); node-v0.10.25~dfsg2/test/simple/test-regress-GH-877.js0000644000000000000000000000443212270121457020674 0ustar rootroot// Copyright Joyent, Inc. and other Node contributors. // // Permission is hereby granted, free of charge, to any person obtaining a // copy of this software and associated documentation files (the // "Software"), to deal in the Software without restriction, including // without limitation the rights to use, copy, modify, merge, publish, // distribute, sublicense, and/or sell copies of the Software, and to permit // persons to whom the Software is furnished to do so, subject to the // following conditions: // // The above copyright notice and this permission notice shall be included // in all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS // OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF // MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN // NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, // DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR // OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE // USE OR OTHER DEALINGS IN THE SOFTWARE. var common = require('../common'); var http = require('http'); var assert = require('assert'); var N = 20; var responses = 0; var maxQueued = 0; var agent = http.globalAgent; agent.maxSockets = 10; var server = http.createServer(function(req, res) { res.writeHead(200); res.end('Hello World\n'); }); var addrString = '127.0.0.1:' + common.PORT; server.listen(common.PORT, '127.0.0.1', function() { for (var i = 0; i < N; i++) { var options = { host: '127.0.0.1', port: common.PORT }; var req = http.get(options, function(res) { if (++responses == N) { server.close(); } res.resume(); }); assert.equal(req.agent, agent); console.log('Socket: ' + agent.sockets[addrString].length + '/' + agent.maxSockets + ' queued: ' + (agent.requests[addrString] ? agent.requests['127.0.0.1:' + common.PORT].length : 0)); var agentRequests = agent.requests[addrString] ? agent.requests[addrString].length : 0; if (maxQueued < agentRequests) { maxQueued = agentRequests; } } }); process.on('exit', function() { assert.ok(responses == N); assert.ok(maxQueued <= 10); }); node-v0.10.25~dfsg2/test/simple/test-tls-securepair-client.js0000644000000000000000000001340412270121457022620 0ustar rootroot// Copyright Joyent, Inc. and other Node contributors. // // Permission is hereby granted, free of charge, to any person obtaining a // copy of this software and associated documentation files (the // "Software"), to deal in the Software without restriction, including // without limitation the rights to use, copy, modify, merge, publish, // distribute, sublicense, and/or sell copies of the Software, and to permit // persons to whom the Software is furnished to do so, subject to the // following conditions: // // The above copyright notice and this permission notice shall be included // in all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS // OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF // MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN // NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, // DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR // OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE // USE OR OTHER DEALINGS IN THE SOFTWARE. if (!process.versions.openssl) { console.error('Skipping because node compiled without OpenSSL.'); process.exit(0); } var common = require('../common'); var join = require('path').join; var net = require('net'); var assert = require('assert'); var fs = require('fs'); var crypto = require('crypto'); var tls = require('tls'); var exec = require('child_process').exec; var spawn = require('child_process').spawn; maybe(test1); // There is a bug with 'openssl s_server' which makes it not flush certain // important events to stdout when done over a pipe. Therefore we skip this // test for all openssl versions less than 1.0.0. function maybe(cb) { exec('openssl version', function(err, data) { if (err) throw err; if (/OpenSSL 0\./.test(data)) { console.error('Skipping due to old OpenSSL version.'); return; } cb(); }); } // simple/test-tls-securepair-client function test1() { test('agent.key', 'agent.crt', null, test2); } // simple/test-tls-ext-key-usage function test2() { function check(pair) { // "TLS Web Client Authentication" assert.equal(pair.cleartext.getPeerCertificate().ext_key_usage.length, 1); assert.equal(pair.cleartext.getPeerCertificate().ext_key_usage[0], '1.3.6.1.5.5.7.3.2'); } test('keys/agent4-key.pem', 'keys/agent4-cert.pem', check); } function test(keyfn, certfn, check, next) { // FIXME: Avoid the common PORT as this test currently hits a C-level // assertion error with node_g. The program aborts without HUPing // the openssl s_server thus causing many tests to fail with // EADDRINUSE. var PORT = common.PORT + 5; var connections = 0; keyfn = join(common.fixturesDir, keyfn); var key = fs.readFileSync(keyfn).toString(); certfn = join(common.fixturesDir, certfn); var cert = fs.readFileSync(certfn).toString(); var server = spawn('openssl', ['s_server', '-accept', PORT, '-cert', certfn, '-key', keyfn]); server.stdout.pipe(process.stdout); server.stderr.pipe(process.stdout); var state = 'WAIT-ACCEPT'; var serverStdoutBuffer = ''; server.stdout.setEncoding('utf8'); server.stdout.on('data', function(s) { serverStdoutBuffer += s; console.error(state); switch (state) { case 'WAIT-ACCEPT': if (/ACCEPT/g.test(serverStdoutBuffer)) { // Give s_server half a second to start up. setTimeout(startClient, 500); state = 'WAIT-HELLO'; } break; case 'WAIT-HELLO': if (/hello/g.test(serverStdoutBuffer)) { // End the current SSL connection and exit. // See s_server(1ssl). server.stdin.write('Q'); state = 'WAIT-SERVER-CLOSE'; } break; default: break; } }); var timeout = setTimeout(function() { server.kill(); process.exit(1); }, 5000); var gotWriteCallback = false; var serverExitCode = -1; server.on('exit', function(code) { serverExitCode = code; clearTimeout(timeout); if (next) next(); }); function startClient() { var s = new net.Stream(); var sslcontext = crypto.createCredentials({key: key, cert: cert}); sslcontext.context.setCiphers('RC4-SHA:AES128-SHA:AES256-SHA'); var pair = tls.createSecurePair(sslcontext, false); assert.ok(pair.encrypted.writable); assert.ok(pair.cleartext.writable); pair.encrypted.pipe(s); s.pipe(pair.encrypted); s.connect(PORT); s.on('connect', function() { console.log('client connected'); }); pair.on('secure', function() { console.log('client: connected+secure!'); console.log('client pair.cleartext.getPeerCertificate(): %j', pair.cleartext.getPeerCertificate()); console.log('client pair.cleartext.getCipher(): %j', pair.cleartext.getCipher()); if (check) check(pair); setTimeout(function() { pair.cleartext.write('hello\r\n', function() { gotWriteCallback = true; }); }, 500); }); pair.cleartext.on('data', function(d) { console.log('cleartext: %s', d.toString()); }); s.on('close', function() { console.log('client close'); }); pair.encrypted.on('error', function(err) { console.log('encrypted error: ' + err); }); s.on('error', function(err) { console.log('socket error: ' + err); }); pair.on('error', function(err) { console.log('secure error: ' + err); }); } process.on('exit', function() { assert.equal(0, serverExitCode); assert.equal('WAIT-SERVER-CLOSE', state); assert.ok(gotWriteCallback); }); } node-v0.10.25~dfsg2/test/simple/test-readuint.js0000644000000000000000000000722612270121457020222 0ustar rootroot// Copyright Joyent, Inc. and other Node contributors. // // Permission is hereby granted, free of charge, to any person obtaining a // copy of this software and associated documentation files (the // "Software"), to deal in the Software without restriction, including // without limitation the rights to use, copy, modify, merge, publish, // distribute, sublicense, and/or sell copies of the Software, and to permit // persons to whom the Software is furnished to do so, subject to the // following conditions: // // The above copyright notice and this permission notice shall be included // in all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS // OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF // MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN // NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, // DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR // OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE // USE OR OTHER DEALINGS IN THE SOFTWARE. /* * A battery of tests to help us read a series of uints */ var SlowBuffer = process.binding('buffer').SlowBuffer; var common = require('../common'); var ASSERT = require('assert'); /* * We need to check the following things: * - We are correctly resolving big endian (doesn't mean anything for 8 bit) * - Correctly resolving little endian (doesn't mean anything for 8 bit) * - Correctly using the offsets * - Correctly interpreting values that are beyond the signed range as unsigned */ function test8(clazz) { var data = new clazz(4); data[0] = 23; data[1] = 23; data[2] = 23; data[3] = 23; ASSERT.equal(23, data.readUInt8(0)); ASSERT.equal(23, data.readUInt8(1)); ASSERT.equal(23, data.readUInt8(2)); ASSERT.equal(23, data.readUInt8(3)); data[0] = 255; /* If it became a signed int, would be -1 */ ASSERT.equal(255, data.readUInt8(0)); } /* * Test 16 bit unsigned integers. We need to verify the same set as 8 bit, only * now some of the issues actually matter: * - We are correctly resolving big endian * - Correctly resolving little endian * - Correctly using the offsets * - Correctly interpreting values that are beyond the signed range as unsigned */ function test16(clazz) { var data = new clazz(4); data[0] = 0; data[1] = 0x23; data[2] = 0x42; data[3] = 0x3f; ASSERT.equal(0x23, data.readUInt16BE(0)); ASSERT.equal(0x2342, data.readUInt16BE(1)); ASSERT.equal(0x423f, data.readUInt16BE(2)); ASSERT.equal(0x2300, data.readUInt16LE(0)); ASSERT.equal(0x4223, data.readUInt16LE(1)); ASSERT.equal(0x3f42, data.readUInt16LE(2)); data[0] = 0xfe; data[1] = 0xfe; ASSERT.equal(0xfefe, data.readUInt16BE(0)); ASSERT.equal(0xfefe, data.readUInt16LE(0)); } /* * Test 32 bit unsigned integers. We need to verify the same set as 8 bit, only * now some of the issues actually matter: * - We are correctly resolving big endian * - Correctly using the offsets * - Correctly interpreting values that are beyond the signed range as unsigned */ function test32(clazz) { var data = new clazz(8); data[0] = 0x32; data[1] = 0x65; data[2] = 0x42; data[3] = 0x56; data[4] = 0x23; data[5] = 0xff; ASSERT.equal(0x32654256, data.readUInt32BE(0)); ASSERT.equal(0x65425623, data.readUInt32BE(1)); ASSERT.equal(0x425623ff, data.readUInt32BE(2)); ASSERT.equal(0x56426532, data.readUInt32LE(0)); ASSERT.equal(0x23564265, data.readUInt32LE(1)); ASSERT.equal(0xff235642, data.readUInt32LE(2)); } test8(Buffer); test8(SlowBuffer); test16(Buffer); test16(SlowBuffer); test32(Buffer); test32(SlowBuffer); node-v0.10.25~dfsg2/test/simple/test-stdin-pause-resume.js0000644000000000000000000000303312270121457022131 0ustar rootroot// Copyright Joyent, Inc. and other Node contributors. // // Permission is hereby granted, free of charge, to any person obtaining a // copy of this software and associated documentation files (the // "Software"), to deal in the Software without restriction, including // without limitation the rights to use, copy, modify, merge, publish, // distribute, sublicense, and/or sell copies of the Software, and to permit // persons to whom the Software is furnished to do so, subject to the // following conditions: // // The above copyright notice and this permission notice shall be included // in all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS // OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF // MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN // NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, // DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR // OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE // USE OR OTHER DEALINGS IN THE SOFTWARE. console.error('before opening stdin'); process.stdin.resume(); console.error('stdin opened'); setTimeout(function() { console.error('pausing stdin'); process.stdin.pause(); setTimeout(function() { console.error('opening again'); process.stdin.resume(); setTimeout(function() { console.error('pausing again'); process.stdin.pause(); console.error('should exit now'); }, 1); }, 1); }, 1); node-v0.10.25~dfsg2/test/simple/test-fs-read-stream.js0000644000000000000000000001234112270121457021213 0ustar rootroot// Copyright Joyent, Inc. and other Node contributors. // // Permission is hereby granted, free of charge, to any person obtaining a // copy of this software and associated documentation files (the // "Software"), to deal in the Software without restriction, including // without limitation the rights to use, copy, modify, merge, publish, // distribute, sublicense, and/or sell copies of the Software, and to permit // persons to whom the Software is furnished to do so, subject to the // following conditions: // // The above copyright notice and this permission notice shall be included // in all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS // OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF // MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN // NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, // DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR // OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE // USE OR OTHER DEALINGS IN THE SOFTWARE. var common = require('../common'); var assert = require('assert'); // TODO Improved this test. test_ca.pem is too small. A proper test would // great a large utf8 (with multibyte chars) file and stream it in, // performing sanity checks throughout. var path = require('path'); var fs = require('fs'); var fn = path.join(common.fixturesDir, 'elipses.txt'); var rangeFile = path.join(common.fixturesDir, 'x.txt'); var callbacks = { open: 0, end: 0, close: 0 }; var paused = false; var file = fs.ReadStream(fn); file.on('open', function(fd) { file.length = 0; callbacks.open++; assert.equal('number', typeof fd); assert.ok(file.readable); // GH-535 file.pause(); file.resume(); file.pause(); file.resume(); }); file.on('data', function(data) { assert.ok(data instanceof Buffer); assert.ok(!paused); file.length += data.length; paused = true; file.pause(); setTimeout(function() { paused = false; file.resume(); }, 10); }); file.on('end', function(chunk) { callbacks.end++; }); file.on('close', function() { callbacks.close++; //assert.equal(fs.readFileSync(fn), fileContent); }); var file3 = fs.createReadStream(fn, {encoding: 'utf8'}); file3.length = 0; file3.on('data', function(data) { assert.equal('string', typeof(data)); file3.length += data.length; for (var i = 0; i < data.length; i++) { // http://www.fileformat.info/info/unicode/char/2026/index.htm assert.equal('\u2026', data[i]); } }); file3.on('close', function() { callbacks.close++; }); process.on('exit', function() { assert.equal(1, callbacks.open); assert.equal(1, callbacks.end); assert.equal(2, callbacks.close); assert.equal(30000, file.length); assert.equal(10000, file3.length); console.error('ok'); }); var file4 = fs.createReadStream(rangeFile, {bufferSize: 1, start: 1, end: 2}); var contentRead = ''; file4.on('data', function(data) { contentRead += data.toString('utf-8'); }); file4.on('end', function(data) { assert.equal(contentRead, 'yz'); }); var file5 = fs.createReadStream(rangeFile, {bufferSize: 1, start: 1}); file5.data = ''; file5.on('data', function(data) { file5.data += data.toString('utf-8'); }); file5.on('end', function() { assert.equal(file5.data, 'yz\n'); }); // https://github.com/joyent/node/issues/2320 var file6 = fs.createReadStream(rangeFile, {bufferSize: 1.23, start: 1}); file6.data = ''; file6.on('data', function(data) { file6.data += data.toString('utf-8'); }); file6.on('end', function() { assert.equal(file6.data, 'yz\n'); }); assert.throws(function() { fs.createReadStream(rangeFile, {start: 10, end: 2}); }, /start must be <= end/); var stream = fs.createReadStream(rangeFile, { start: 0, end: 0 }); stream.data = ''; stream.on('data', function(chunk) { stream.data += chunk; }); stream.on('end', function() { assert.equal('x', stream.data); }); // pause and then resume immediately. var pauseRes = fs.createReadStream(rangeFile); pauseRes.pause(); pauseRes.resume(); var file7 = fs.createReadStream(rangeFile, {autoClose: false }); file7.on('data', function() {}); file7.on('end', function() { process.nextTick(function() { assert(!file7.closed); assert(!file7.destroyed); file7Next(); }); }); function file7Next(){ // This will tell us if the fd is usable again or not. file7 = fs.createReadStream(null, {fd: file7.fd, start: 0 }); file7.data = ''; file7.on('data', function(data) { file7.data += data; }); file7.on('end', function(err) { assert.equal(file7.data, 'xyz\n'); }); } // Just to make sure autoClose won't close the stream because of error. var file8 = fs.createReadStream(null, {fd: 13337, autoClose: false }); file8.on('data', function() {}); file8.on('error', common.mustCall(function() {})); // Make sure stream is destroyed when file does not exist. var file9 = fs.createReadStream('/path/to/file/that/does/not/exist'); file9.on('data', function() {}); file9.on('error', common.mustCall(function() {})); process.on('exit', function() { assert(file7.closed); assert(file7.destroyed); assert(!file8.closed); assert(!file8.destroyed); assert(file8.fd); assert(!file9.closed); assert(file9.destroyed); }); node-v0.10.25~dfsg2/test/simple/test-tls-timeout-server-2.js0000644000000000000000000000333612270121457022336 0ustar rootroot// Copyright Joyent, Inc. and other Node contributors. // // Permission is hereby granted, free of charge, to any person obtaining a // copy of this software and associated documentation files (the // "Software"), to deal in the Software without restriction, including // without limitation the rights to use, copy, modify, merge, publish, // distribute, sublicense, and/or sell copies of the Software, and to permit // persons to whom the Software is furnished to do so, subject to the // following conditions: // // The above copyright notice and this permission notice shall be included // in all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS // OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF // MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN // NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, // DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR // OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE // USE OR OTHER DEALINGS IN THE SOFTWARE. if (!process.versions.openssl) process.exit(); var common = require('../common'); var assert = require('assert'); var tls = require('tls'); var fs = require('fs'); var options = { key: fs.readFileSync(common.fixturesDir + '/keys/agent1-key.pem'), cert: fs.readFileSync(common.fixturesDir + '/keys/agent1-cert.pem') }; var server = tls.createServer(options, function(cleartext) { cleartext.setTimeout(50, function() { cleartext.destroy(); server.close(); }); }); server.listen(common.PORT, function() { tls.connect({ host: '127.0.0.1', port: common.PORT, rejectUnauthorized: false }); }); node-v0.10.25~dfsg2/test/simple/test-http-hex-write.js0000644000000000000000000000344412270121457021276 0ustar rootroot// Copyright Joyent, Inc. and other Node contributors. // // Permission is hereby granted, free of charge, to any person obtaining a // copy of this software and associated documentation files (the // "Software"), to deal in the Software without restriction, including // without limitation the rights to use, copy, modify, merge, publish, // distribute, sublicense, and/or sell copies of the Software, and to permit // persons to whom the Software is furnished to do so, subject to the // following conditions: // // The above copyright notice and this permission notice shall be included // in all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS // OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF // MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN // NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, // DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR // OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE // USE OR OTHER DEALINGS IN THE SOFTWARE. var common = require('../common'); var assert = require('assert'); var http = require('http'); var expect = 'hex\nutf8\n'; var data = ''; var ended = false; process.on('exit', function() { assert(ended); assert.equal(data, expect); console.log('ok'); }); http.createServer(function(q, s) { s.setHeader('content-length', expect.length); s.write('6865780a', 'hex'); s.write('utf8\n'); s.end(); this.close(); }).listen(common.PORT, function() { http.request({ port: common.PORT }).on('response', function(res) { res.setEncoding('ascii'); res.on('data', function(c) { data += c; }); res.on('end', function() { ended = true; }); }).end(); }); node-v0.10.25~dfsg2/test/simple/test-http-url.parse-auth.js0000644000000000000000000000344712270121457022237 0ustar rootroot// Copyright Joyent, Inc. and other Node contributors. // // Permission is hereby granted, free of charge, to any person obtaining a // copy of this software and associated documentation files (the // "Software"), to deal in the Software without restriction, including // without limitation the rights to use, copy, modify, merge, publish, // distribute, sublicense, and/or sell copies of the Software, and to permit // persons to whom the Software is furnished to do so, subject to the // following conditions: // // The above copyright notice and this permission notice shall be included // in all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS // OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF // MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN // NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, // DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR // OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE // USE OR OTHER DEALINGS IN THE SOFTWARE. var common = require('../common'); var assert = require('assert'); var http = require('http'); var url = require('url'); // username = "user", password = "pass:" var testURL = url.parse('http://user:pass%3A@localhost:' + common.PORT); function check(request) { // the correct authorization header is be passed assert.strictEqual(request.headers.authorization, 'Basic dXNlcjpwYXNzOg=='); } var server = http.createServer(function(request, response) { // run the check function check.call(this, request, response); response.writeHead(200, {}); response.end('ok'); server.close(); }); server.listen(common.PORT, function() { // make the request http.request(testURL).end(); }); node-v0.10.25~dfsg2/test/simple/test-stream2-fs.js0000644000000000000000000000417212270121457020367 0ustar rootroot// Copyright Joyent, Inc. and other Node contributors. // // Permission is hereby granted, free of charge, to any person obtaining a // copy of this software and associated documentation files (the // "Software"), to deal in the Software without restriction, including // without limitation the rights to use, copy, modify, merge, publish, // distribute, sublicense, and/or sell copies of the Software, and to permit // persons to whom the Software is furnished to do so, subject to the // following conditions: // // The above copyright notice and this permission notice shall be included // in all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS // OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF // MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN // NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, // DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR // OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE // USE OR OTHER DEALINGS IN THE SOFTWARE. var common = require('../common.js'); var R = require('_stream_readable'); var assert = require('assert'); var fs = require('fs'); var FSReadable = fs.ReadStream; var path = require('path'); var file = path.resolve(common.fixturesDir, 'x1024.txt'); var size = fs.statSync(file).size; var expectLengths = [1024]; var util = require('util'); var Stream = require('stream'); util.inherits(TestWriter, Stream); function TestWriter() { Stream.apply(this); this.buffer = []; this.length = 0; } TestWriter.prototype.write = function(c) { this.buffer.push(c.toString()); this.length += c.length; return true; }; TestWriter.prototype.end = function(c) { if (c) this.buffer.push(c.toString()); this.emit('results', this.buffer); } var r = new FSReadable(file); var w = new TestWriter(); w.on('results', function(res) { console.error(res, w.length); assert.equal(w.length, size); var l = 0; assert.deepEqual(res.map(function (c) { return c.length; }), expectLengths); console.log('ok'); }); r.pipe(w); node-v0.10.25~dfsg2/test/simple/test-http-wget.js0000644000000000000000000000564012270121457020330 0ustar rootroot// Copyright Joyent, Inc. and other Node contributors. // // Permission is hereby granted, free of charge, to any person obtaining a // copy of this software and associated documentation files (the // "Software"), to deal in the Software without restriction, including // without limitation the rights to use, copy, modify, merge, publish, // distribute, sublicense, and/or sell copies of the Software, and to permit // persons to whom the Software is furnished to do so, subject to the // following conditions: // // The above copyright notice and this permission notice shall be included // in all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS // OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF // MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN // NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, // DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR // OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE // USE OR OTHER DEALINGS IN THE SOFTWARE. var common = require('../common'); var assert = require('assert'); var net = require('net'); var http = require('http'); // wget sends an HTTP/1.0 request with Connection: Keep-Alive // // Sending back a chunked response to an HTTP/1.0 client would be wrong, // so what has to happen in this case is that the connection is closed // by the server after the entity body if the Content-Length was not // sent. // // If the Content-Length was sent, we can probably safely honor the // keep-alive request, even though HTTP 1.0 doesn't say that the // connection can be kept open. Presumably any client sending this // header knows that it is extending HTTP/1.0 and can handle the // response. We don't test that here however, just that if the // content-length is not provided, that the connection is in fact // closed. var server_response = ''; var client_got_eof = false; var connection_was_closed = false; var server = http.createServer(function(req, res) { res.writeHead(200, {'Content-Type': 'text/plain'}); res.write('hello '); res.write('world\n'); res.end(); }); server.listen(common.PORT); server.on('listening', function() { var c = net.createConnection(common.PORT); c.setEncoding('utf8'); c.on('connect', function() { c.write('GET / HTTP/1.0\r\n' + 'Connection: Keep-Alive\r\n\r\n'); }); c.on('data', function(chunk) { console.log(chunk); server_response += chunk; }); c.on('end', function() { client_got_eof = true; console.log('got end'); c.end(); }); c.on('close', function() { connection_was_closed = true; console.log('got close'); server.close(); }); }); process.on('exit', function() { var m = server_response.split('\r\n\r\n'); assert.equal(m[1], 'hello world\n'); assert.ok(client_got_eof); assert.ok(connection_was_closed); }); node-v0.10.25~dfsg2/test/simple/test-tls-connect-given-socket.js0000644000000000000000000000426512270121457023234 0ustar rootroot// Copyright Joyent, Inc. and other Node contributors. // // Permission is hereby granted, free of charge, to any person obtaining a // copy of this software and associated documentation files (the // "Software"), to deal in the Software without restriction, including // without limitation the rights to use, copy, modify, merge, publish, // distribute, sublicense, and/or sell copies of the Software, and to permit // persons to whom the Software is furnished to do so, subject to the // following conditions: // // The above copyright notice and this permission notice shall be included // in all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS // OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF // MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN // NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, // DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR // OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE // USE OR OTHER DEALINGS IN THE SOFTWARE. var common = require('../common'); var assert = require('assert'); var tls = require('tls'); var net = require('net'); var fs = require('fs'); var path = require('path'); var serverConnected = false; var clientConnected = false; var options = { key: fs.readFileSync(path.join(common.fixturesDir, 'test_key.pem')), cert: fs.readFileSync(path.join(common.fixturesDir, 'test_cert.pem')) }; var server = tls.createServer(options, function(socket) { serverConnected = true; socket.end('Hello'); }).listen(common.PORT, function() { var socket = net.connect({ port: common.PORT, rejectUnauthorized: false }, function() { var client = tls.connect({ rejectUnauthorized: false, socket: socket }, function() { clientConnected = true; var data = ''; client.on('data', function(chunk) { data += chunk.toString(); }); client.on('end', function() { assert.equal(data, 'Hello'); server.close(); }); }); }); }); process.on('exit', function() { assert(serverConnected); assert(clientConnected); }); node-v0.10.25~dfsg2/test/simple/test-event-emitter-listeners.js0000644000000000000000000000412512270121457023200 0ustar rootroot // Copyright Joyent, Inc. and other Node contributors. // // Permission is hereby granted, free of charge, to any person obtaining a // copy of this software and associated documentation files (the // "Software"), to deal in the Software without restriction, including // without limitation the rights to use, copy, modify, merge, publish, // distribute, sublicense, and/or sell copies of the Software, and to permit // persons to whom the Software is furnished to do so, subject to the // following conditions: // // The above copyright notice and this permission notice shall be included // in all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS // OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF // MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN // NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, // DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR // OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE // USE OR OTHER DEALINGS IN THE SOFTWARE. var common = require('../common'); var assert = require('assert'); var events = require('events'); function listener() {} function listener2() {} var e1 = new events.EventEmitter(); e1.on('foo', listener); var fooListeners = e1.listeners('foo'); assert.deepEqual(e1.listeners('foo'), [listener]); e1.removeAllListeners('foo'); assert.deepEqual(e1.listeners('foo'), []); assert.deepEqual(fooListeners, [listener]); var e2 = new events.EventEmitter(); e2.on('foo', listener); var e2ListenersCopy = e2.listeners('foo'); assert.deepEqual(e2ListenersCopy, [listener]); assert.deepEqual(e2.listeners('foo'), [listener]); e2ListenersCopy.push(listener2); assert.deepEqual(e2.listeners('foo'), [listener]); assert.deepEqual(e2ListenersCopy, [listener, listener2]); var e3 = new events.EventEmitter(); e3.on('foo', listener); var e3ListenersCopy = e3.listeners('foo'); e3.on('foo', listener2); assert.deepEqual(e3.listeners('foo'), [listener, listener2]); assert.deepEqual(e3ListenersCopy, [listener]); node-v0.10.25~dfsg2/test/simple/test-fs-write-stream-change-open.js0000644000000000000000000000356712270121457023626 0ustar rootroot// Copyright Joyent, Inc. and other Node contributors. // // Permission is hereby granted, free of charge, to any person obtaining a // copy of this software and associated documentation files (the // "Software"), to deal in the Software without restriction, including // without limitation the rights to use, copy, modify, merge, publish, // distribute, sublicense, and/or sell copies of the Software, and to permit // persons to whom the Software is furnished to do so, subject to the // following conditions: // // The above copyright notice and this permission notice shall be included // in all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS // OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF // MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN // NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, // DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR // OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE // USE OR OTHER DEALINGS IN THE SOFTWARE. var common = require('../common'); var assert = require('assert'); var path = require('path'), fs = require('fs'); var file = path.join(common.tmpDir, 'write.txt'); var stream = fs.WriteStream(file), _fs_close = fs.close, _fs_open = fs.open; // change the fs.open with an identical function after the WriteStream // has pushed it onto its internal action queue, but before it's // returned. This simulates AOP-style extension of the fs lib. fs.open = function() { return _fs_open.apply(fs, arguments); }; fs.close = function(fd) { assert.ok(fd, 'fs.close must not be called with an undefined fd.'); fs.close = _fs_close; fs.open = _fs_open; } stream.write('foo'); stream.end(); process.on('exit', function() { assert.equal(fs.open, _fs_open); }); node-v0.10.25~dfsg2/test/simple/test-file-write-stream3.js0000644000000000000000000001335012270121457022025 0ustar rootroot// Copyright Joyent, Inc. and other Node contributors. // // Permission is hereby granted, free of charge, to any person obtaining a // copy of this software and associated documentation files (the // "Software"), to deal in the Software without restriction, including // without limitation the rights to use, copy, modify, merge, publish, // distribute, sublicense, and/or sell copies of the Software, and to permit // persons to whom the Software is furnished to do so, subject to the // following conditions: // // The above copyright notice and this permission notice shall be included // in all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS // OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF // MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN // NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, // DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR // OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE // USE OR OTHER DEALINGS IN THE SOFTWARE. var common = require('../common'); var assert = require('assert'); var path = require('path'), fs = require('fs'), util = require('util'); var filepath = path.join(common.tmpDir, 'write_pos.txt'); var cb_expected = 'write open close write open close write open close ', cb_occurred = ''; var fileDataInitial = 'abcdefghijklmnopqrstuvwxyz'; var fileDataExpected_1 = 'abcdefghijklmnopqrstuvwxyz'; var fileDataExpected_2 = 'abcdefghij123456qrstuvwxyz'; var fileDataExpected_3 = 'abcdefghij\u2026\u2026qrstuvwxyz'; process.on('exit', function() { removeTestFile(); if (cb_occurred !== cb_expected) { console.log(' Test callback events missing or out of order:'); console.log(' expected: %j', cb_expected); console.log(' occurred: %j', cb_occurred); assert.strictEqual(cb_occurred, cb_expected, 'events missing or out of order: "' + cb_occurred + '" !== "' + cb_expected + '"'); } }); function removeTestFile() { try { fs.unlinkSync(filepath); } catch (ex) { } } removeTestFile(); function run_test_1() { var file, buffer, options; options = {}; file = fs.createWriteStream(filepath, options); console.log(' (debug: start ', file.start); console.log(' (debug: pos ', file.pos); file.on('open', function(fd) { cb_occurred += 'open '; }); file.on('close', function() { cb_occurred += 'close '; console.log(' (debug: bytesWritten ', file.bytesWritten); console.log(' (debug: start ', file.start); console.log(' (debug: pos ', file.pos); assert.strictEqual(file.bytesWritten, buffer.length); var fileData = fs.readFileSync(filepath, 'utf8'); console.log(' (debug: file data ', fileData); console.log(' (debug: expected ', fileDataExpected_1); assert.equal(fileData, fileDataExpected_1); run_test_2(); }); file.on('error', function(err) { cb_occurred += 'error '; console.log(' (debug: err event ', err); throw err; }); buffer = new Buffer(fileDataInitial); file.write(buffer); cb_occurred += 'write '; file.end(); } function run_test_2() { var file, buffer, options; buffer = new Buffer('123456'); options = { start: 10, flags: 'r+' }; file = fs.createWriteStream(filepath, options); console.log(' (debug: start ', file.start); console.log(' (debug: pos ', file.pos); file.on('open', function(fd) { cb_occurred += 'open '; }); file.on('close', function() { cb_occurred += 'close '; console.log(' (debug: bytesWritten ', file.bytesWritten); console.log(' (debug: start ', file.start); console.log(' (debug: pos ', file.pos); assert.strictEqual(file.bytesWritten, buffer.length); var fileData = fs.readFileSync(filepath, 'utf8'); console.log(' (debug: file data ', fileData); console.log(' (debug: expected ', fileDataExpected_2); assert.equal(fileData, fileDataExpected_2); run_test_3(); }); file.on('error', function(err) { cb_occurred += 'error '; console.log(' (debug: err event ', err); throw err; }); file.write(buffer); cb_occurred += 'write '; file.end(); } function run_test_3() { var file, buffer, options; var data = '\u2026\u2026', // 3 bytes * 2 = 6 bytes in UTF-8 fileData; options = { start: 10, flags: 'r+' }; file = fs.createWriteStream(filepath, options); console.log(' (debug: start ', file.start); console.log(' (debug: pos ', file.pos); file.on('open', function(fd) { cb_occurred += 'open '; }); file.on('close', function() { cb_occurred += 'close '; console.log(' (debug: bytesWritten ', file.bytesWritten); console.log(' (debug: start ', file.start); console.log(' (debug: pos ', file.pos); assert.strictEqual(file.bytesWritten, data.length * 3); fileData = fs.readFileSync(filepath, 'utf8'); console.log(' (debug: file data ', fileData); console.log(' (debug: expected ', fileDataExpected_3); assert.equal(fileData, fileDataExpected_3); run_test_4(); }); file.on('error', function(err) { cb_occurred += 'error '; console.log(' (debug: err event ', err); throw err; }); file.write(data, 'utf8'); cb_occurred += 'write '; file.end(); } function run_test_4() { var file, options; options = { start: -5, flags: 'r+' }; // Error: start must be >= zero assert.throws( function() { file = fs.createWriteStream(filepath, options); }, /start must be/ ); } run_test_1(); node-v0.10.25~dfsg2/test/simple/test-child-process-fork-close.js0000644000000000000000000000352612270121457023207 0ustar rootroot// Copyright Joyent, Inc. and other Node contributors. // // Permission is hereby granted, free of charge, to any person obtaining a // copy of this software and associated documentation files (the // "Software"), to deal in the Software without restriction, including // without limitation the rights to use, copy, modify, merge, publish, // distribute, sublicense, and/or sell copies of the Software, and to permit // persons to whom the Software is furnished to do so, subject to the // following conditions: // // The above copyright notice and this permission notice shall be included // in all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS // OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF // MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN // NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, // DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR // OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE // USE OR OTHER DEALINGS IN THE SOFTWARE. var assert = require('assert'), common = require('../common'), fork = require('child_process').fork, fork = require('child_process').fork; var cp = fork(common.fixturesDir + '/child-process-message-and-exit.js'); var gotMessage = false, gotExit = false, gotClose = false; cp.on('message', function(message) { assert(!gotMessage); assert(!gotClose); assert.strictEqual(message, 'hello'); gotMessage = true; }); cp.on('exit', function() { assert(!gotExit); assert(!gotClose); gotExit = true; }); cp.on('close', function() { assert(gotMessage); assert(gotExit); assert(!gotClose); gotClose = true; }); process.on('exit', function() { assert(gotMessage); assert(gotExit); assert(gotClose); }); node-v0.10.25~dfsg2/test/simple/test-child-process-fork-ref.js0000644000000000000000000000352312270121457022653 0ustar rootroot// Copyright Joyent, Inc. and other Node contributors. // // Permission is hereby granted, free of charge, to any person obtaining a // copy of this software and associated documentation files (the // "Software"), to deal in the Software without restriction, including // without limitation the rights to use, copy, modify, merge, publish, // distribute, sublicense, and/or sell copies of the Software, and to permit // persons to whom the Software is furnished to do so, subject to the // following conditions: // // The above copyright notice and this permission notice shall be included // in all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS // OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF // MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN // NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, // DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR // OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE // USE OR OTHER DEALINGS IN THE SOFTWARE. var common = require('../common'); var assert = require('assert'); var fork = require('child_process').fork; if (process.argv[2] === 'child') { process.send('1'); // check that child don't instantly die setTimeout(function() { process.send('2'); }, 200); process.on('disconnect', function () { process.stdout.write('3'); }); } else { var child = fork(__filename, ['child'], {silent: true}); var ipc = [], stdout = ''; child.on('message', function (msg) { ipc.push(msg); if (msg === '2') child.disconnect(); }); child.stdout.on('data', function (chunk) { stdout += chunk; }); child.once('exit', function () { assert.deepEqual(ipc, ['1', '2']); assert.equal(stdout, '3'); }); } node-v0.10.25~dfsg2/test/simple/test-repl-console.js0000644000000000000000000000327212270121457021006 0ustar rootroot// Copyright Joyent, Inc. and other Node contributors. // // Permission is hereby granted, free of charge, to any person obtaining a // copy of this software and associated documentation files (the // "Software"), to deal in the Software without restriction, including // without limitation the rights to use, copy, modify, merge, publish, // distribute, sublicense, and/or sell copies of the Software, and to permit // persons to whom the Software is furnished to do so, subject to the // following conditions: // // The above copyright notice and this permission notice shall be included // in all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS // OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF // MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN // NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, // DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR // OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE // USE OR OTHER DEALINGS IN THE SOFTWARE. var common = require('../common'), assert = require('assert'), Stream = require('stream'), repl = require('repl'); // create a dummy stream that does nothing var stream = new Stream(); stream.write = stream.pause = stream.resume = function(){}; stream.readable = stream.writable = true; var r = repl.start({ input: stream, output: stream, useGlobal: false }); // ensure that the repl context gets its own "console" instance assert(r.context.console); // ensure that the repl console instance is not the global one assert.notStrictEqual(r.context.console, console); node-v0.10.25~dfsg2/test/simple/test-debugger-repl-restart.js0000644000000000000000000000251112270121457022605 0ustar rootroot// Copyright Joyent, Inc. and other Node contributors. // // Permission is hereby granted, free of charge, to any person obtaining a // copy of this software and associated documentation files (the // "Software"), to deal in the Software without restriction, including // without limitation the rights to use, copy, modify, merge, publish, // distribute, sublicense, and/or sell copies of the Software, and to permit // persons to whom the Software is furnished to do so, subject to the // following conditions: // // The above copyright notice and this permission notice shall be included // in all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS // OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF // MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN // NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, // DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR // OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE // USE OR OTHER DEALINGS IN THE SOFTWARE. var repl = require('./helper-debugger-repl.js'); repl.startDebugger('breakpoints.js'); // Restart the debugged script repl.addTest('restart', [ /terminated/, ].concat(repl.initialLines)); repl.addTest('quit', []); node-v0.10.25~dfsg2/test/simple/test-http-conn-reset.js0000644000000000000000000000357112270121457021440 0ustar rootroot// Copyright Joyent, Inc. and other Node contributors. // // Permission is hereby granted, free of charge, to any person obtaining a // copy of this software and associated documentation files (the // "Software"), to deal in the Software without restriction, including // without limitation the rights to use, copy, modify, merge, publish, // distribute, sublicense, and/or sell copies of the Software, and to permit // persons to whom the Software is furnished to do so, subject to the // following conditions: // // The above copyright notice and this permission notice shall be included // in all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS // OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF // MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN // NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, // DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR // OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE // USE OR OTHER DEALINGS IN THE SOFTWARE. var common = require('../common'); var assert = require('assert'); var http = require('http'); var net = require('net'); var caughtError = false; var options = { host: '127.0.0.1', port: common.PORT }; // start a tcp server that closes incoming connections immediately var server = net.createServer(function(client) { client.destroy(); server.close(); }); server.listen(options.port, options.host, onListen); // do a GET request, expect it to fail function onListen() { var req = http.request(options, function(res) { assert.ok(false, 'this should never run'); }); req.on('error', function(err) { assert.equal(err.code, 'ECONNRESET'); caughtError = true; }); req.end(); } process.on('exit', function() { assert.equal(caughtError, true); }); node-v0.10.25~dfsg2/test/simple/test-process-wrap.js0000644000000000000000000000405612270121457021032 0ustar rootroot// Copyright Joyent, Inc. and other Node contributors. // // Permission is hereby granted, free of charge, to any person obtaining a // copy of this software and associated documentation files (the // "Software"), to deal in the Software without restriction, including // without limitation the rights to use, copy, modify, merge, publish, // distribute, sublicense, and/or sell copies of the Software, and to permit // persons to whom the Software is furnished to do so, subject to the // following conditions: // // The above copyright notice and this permission notice shall be included // in all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS // OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF // MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN // NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, // DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR // OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE // USE OR OTHER DEALINGS IN THE SOFTWARE. var common = require('../common'); var assert = require('assert'); var Process = process.binding('process_wrap').Process; var Pipe = process.binding('pipe_wrap').Pipe; var pipe = new Pipe(); var p = new Process(); var processExited = false; var gotPipeEOF = false; var gotPipeData = false; p.onexit = function(exitCode, signal) { console.log('exit'); p.close(); pipe.readStart(); assert.equal(0, exitCode); assert.equal(0, signal); processExited = true; }; pipe.onread = function(b, off, len) { assert.ok(processExited); if (b) { gotPipeData = true; console.log('read %d', len); } else { gotPipeEOF = true; pipe.close(); } }; p.spawn({ file: process.execPath, args: [process.execPath, '-v'], stdio: [ { type: 'ignore' }, { type: 'pipe', handle: pipe }, { type: 'ignore' } ] }); process.on('exit', function() { assert.ok(processExited); assert.ok(gotPipeEOF); assert.ok(gotPipeData); }); node-v0.10.25~dfsg2/test/simple/test-tls-check-server-identity.js0000644000000000000000000001142512270121457023413 0ustar rootroot// Copyright Joyent, Inc. and other Node contributors. // // Permission is hereby granted, free of charge, to any person obtaining a // copy of this software and associated documentation files (the // "Software"), to deal in the Software without restriction, including // without limitation the rights to use, copy, modify, merge, publish, // distribute, sublicense, and/or sell copies of the Software, and to permit // persons to whom the Software is furnished to do so, subject to the // following conditions: // // The above copyright notice and this permission notice shall be included // in all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS // OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF // MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN // NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, // DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR // OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE // USE OR OTHER DEALINGS IN THE SOFTWARE. var common = require('../common'); var assert = require('assert'); var util = require('util'); var tls = require('tls'); var tests = [ // Basic CN handling { host: 'a.com', cert: { subject: { CN: 'a.com' } }, result: true }, { host: 'a.com', cert: { subject: { CN: 'A.COM' } }, result: true }, { host: 'a.com', cert: { subject: { CN: 'b.com' } }, result: false }, { host: 'a.com', cert: { subject: { CN: 'a.com.' } }, result: true }, // Wildcards in CN { host: 'b.a.com', cert: { subject: { CN: '*.a.com' } }, result: true }, { host: 'b.a.com', cert: { subjectaltname: 'DNS:omg.com', subject: { CN: '*.a.com' } }, result: false }, // Multiple CN fields { host: 'foo.com', cert: { subject: { CN: ['foo.com', 'bar.com'] } // CN=foo.com; CN=bar.com; }, result: true }, // DNS names and CN { host: 'a.com', cert: { subjectaltname: 'DNS:*', subject: { CN: 'b.com' } }, result: false }, { host: 'a.com', cert: { subjectaltname: 'DNS:*.com', subject: { CN: 'b.com' } }, result: false }, { host: 'a.co.uk', cert: { subjectaltname: 'DNS:*.co.uk', subject: { CN: 'b.com' } }, result: true }, { host: 'a.com', cert: { subjectaltname: 'DNS:*.a.com', subject: { CN: 'a.com' } }, result: false }, { host: 'a.com', cert: { subjectaltname: 'DNS:*.a.com', subject: { CN: 'b.com' } }, result: false }, { host: 'a.com', cert: { subjectaltname: 'DNS:a.com', subject: { CN: 'b.com' } }, result: true }, { host: 'a.com', cert: { subjectaltname: 'DNS:A.COM', subject: { CN: 'b.com' } }, result: true }, // DNS names { host: 'a.com', cert: { subjectaltname: 'DNS:*.a.com', subject: {} }, result: false }, { host: 'b.a.com', cert: { subjectaltname: 'DNS:*.a.com', subject: {} }, result: true }, { host: 'c.b.a.com', cert: { subjectaltname: 'DNS:*.a.com', subject: {} }, result: false }, { host: 'b.a.com', cert: { subjectaltname: 'DNS:*b.a.com', subject: {} }, result: true }, { host: 'a-cb.a.com', cert: { subjectaltname: 'DNS:*b.a.com', subject: {} }, result: true }, { host: 'a.b.a.com', cert: { subjectaltname: 'DNS:*b.a.com', subject: {} }, result: false }, // Mutliple DNS names { host: 'a.b.a.com', cert: { subjectaltname: 'DNS:*b.a.com, DNS:a.b.a.com', subject: {} }, result: true }, // URI names { host: 'a.b.a.com', cert: { subjectaltname: 'URI:http://a.b.a.com/', subject: {} }, result: true }, { host: 'a.b.a.com', cert: { subjectaltname: 'URI:http://*.b.a.com/', subject: {} }, result: false }, // IP addresses { host: 'a.b.a.com', cert: { subjectaltname: 'IP Address:127.0.0.1', subject: {} }, result: false }, { host: '127.0.0.1', cert: { subjectaltname: 'IP Address:127.0.0.1', subject: {} }, result: true }, { host: '127.0.0.2', cert: { subjectaltname: 'IP Address:127.0.0.1', subject: {} }, result: false }, { host: '127.0.0.1', cert: { subjectaltname: 'DNS:a.com', subject: {} }, result: false }, { host: 'localhost', cert: { subjectaltname: 'DNS:a.com', subject: { CN: 'localhost' } }, result: false }, ]; tests.forEach(function(test, i) { assert.equal(tls.checkServerIdentity(test.host, test.cert), test.result, 'Test#' + i + ' failed: ' + util.inspect(test)); }); node-v0.10.25~dfsg2/test/simple/test-http-upgrade-server2.js0000644000000000000000000000441012270121457022371 0ustar rootroot// Copyright Joyent, Inc. and other Node contributors. // // Permission is hereby granted, free of charge, to any person obtaining a // copy of this software and associated documentation files (the // "Software"), to deal in the Software without restriction, including // without limitation the rights to use, copy, modify, merge, publish, // distribute, sublicense, and/or sell copies of the Software, and to permit // persons to whom the Software is furnished to do so, subject to the // following conditions: // // The above copyright notice and this permission notice shall be included // in all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS // OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF // MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN // NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, // DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR // OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE // USE OR OTHER DEALINGS IN THE SOFTWARE. var common = require('../common'); var assert = require('assert'); var http = require('http'); var net = require('net'); var server = http.createServer(function(req, res) { common.error('got req'); throw new Error('This shouldn\'t happen.'); }); server.on('upgrade', function(req, socket, upgradeHead) { common.error('got upgrade event'); // test that throwing an error from upgrade gets // is uncaught throw new Error('upgrade error'); }); var gotError = false; process.on('uncaughtException', function(e) { common.error('got \'clientError\' event'); assert.equal('upgrade error', e.message); gotError = true; process.exit(0); }); server.listen(common.PORT, function() { var c = net.createConnection(common.PORT); c.on('connect', function() { common.error('client wrote message'); c.write('GET /blah HTTP/1.1\r\n' + 'Upgrade: WebSocket\r\n' + 'Connection: Upgrade\r\n' + '\r\n\r\nhello world'); }); c.on('end', function() { c.end(); }); c.on('close', function() { common.error('client close'); server.close(); }); }); process.on('exit', function() { assert.ok(gotError); }); node-v0.10.25~dfsg2/test/simple/test-domain.js0000644000000000000000000001625512270121457017660 0ustar rootroot// Copyright Joyent, Inc. and other Node contributors. // // Permission is hereby granted, free of charge, to any person obtaining a // copy of this software and associated documentation files (the // "Software"), to deal in the Software without restriction, including // without limitation the rights to use, copy, modify, merge, publish, // distribute, sublicense, and/or sell copies of the Software, and to permit // persons to whom the Software is furnished to do so, subject to the // following conditions: // // The above copyright notice and this permission notice shall be included // in all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS // OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF // MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN // NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, // DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR // OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE // USE OR OTHER DEALINGS IN THE SOFTWARE. // Simple tests of most basic domain functionality. var common = require('../common'); var assert = require('assert'); var domain = require('domain'); var events = require('events'); var fs = require('fs'); var caught = 0; var expectCaught = 0; var d = new domain.Domain(); var e = new events.EventEmitter(); d.on('error', function(er) { console.error('caught', er && (er.message || er)); var er_message = er.message; var er_path = er.path // On windows, error messages can contain full path names. If this is the // case, remove the directory part. if (typeof er_path === 'string') { var slash = er_path.lastIndexOf('\\'); if (slash !== -1) { var dir = er_path.slice(0, slash + 1); er_path = er_path.replace(dir, ''); er_message = er_message.replace(dir, ''); } } switch (er_message) { case 'emitted': assert.equal(er.domain, d); assert.equal(er.domainEmitter, e); assert.equal(er.domainThrown, false); break; case 'bound': assert.ok(!er.domainEmitter); assert.equal(er.domain, d); assert.equal(er.domainBound, fn); assert.equal(er.domainThrown, false); break; case 'thrown': assert.ok(!er.domainEmitter); assert.equal(er.domain, d); assert.equal(er.domainThrown, true); break; case "ENOENT, open 'this file does not exist'": assert.equal(er.domain, d); assert.equal(er.domainThrown, false); assert.equal(typeof er.domainBound, 'function'); assert.ok(!er.domainEmitter); assert.equal(er.code, 'ENOENT'); assert.equal(er_path, 'this file does not exist'); assert.equal(typeof er.errno, 'number'); break; case "ENOENT, open 'stream for nonexistent file'": assert.equal(typeof er.errno, 'number'); assert.equal(er.code, 'ENOENT'); assert.equal(er_path, 'stream for nonexistent file'); assert.equal(er.domain, d); assert.equal(er.domainEmitter, fst); assert.ok(!er.domainBound); assert.equal(er.domainThrown, false); break; case 'implicit': assert.equal(er.domainEmitter, implicit); assert.equal(er.domain, d); assert.equal(er.domainThrown, false); assert.ok(!er.domainBound); break; case 'implicit timer': assert.equal(er.domain, d); assert.equal(er.domainThrown, true); assert.ok(!er.domainEmitter); assert.ok(!er.domainBound); break; case 'Cannot call method \'isDirectory\' of undefined': assert.equal(er.domain, d); assert.ok(!er.domainEmitter); assert.ok(!er.domainBound); break; case 'nextTick execution loop': assert.equal(er.domain, d); assert.ok(!er.domainEmitter); assert.ok(!er.domainBound); break; default: console.error('unexpected error, throwing %j', er.message, er); throw er; } caught++; }); process.on('exit', function() { console.error('exit', caught, expectCaught); assert.equal(caught, expectCaught, 'caught the expected number of errors'); console.log('ok'); }); // revert to using the domain when a callback is passed to nextTick in // the middle of a tickCallback loop d.run(function() { process.nextTick(function() { throw new Error('nextTick execution loop'); }); }); expectCaught++; // catch thrown errors no matter how many times we enter the event loop // this only uses implicit binding, except for the first function // passed to d.run(). The rest are implicitly bound by virtue of being // set up while in the scope of the d domain. d.run(function() { process.nextTick(function() { var i = setInterval(function () { clearInterval(i); setTimeout(function() { fs.stat('this file does not exist', function(er, stat) { // uh oh! stat isn't set! // pretty common error. console.log(stat.isDirectory()); }); }); }); }); }); expectCaught++; // implicit addition of a timer created within a domain-bound context. d.run(function() { setTimeout(function() { throw new Error('implicit timer'); }); }); expectCaught++; // Event emitters added to the domain have their errors routed. d.add(e); e.emit('error', new Error('emitted')); expectCaught++; // get rid of the `if (er) return cb(er)` malarky, by intercepting // the cb functions to the domain, and using the intercepted function // as a callback instead. function fn(er) { throw new Error('This function should never be called!'); process.exit(1); } var bound = d.intercept(fn); bound(new Error('bound')); expectCaught++; // intercepted should never pass first argument to callback function fn2(data) { assert.equal(data, 'data', 'should not be null err argument') } var bound = d.intercept(fn2); bound(null, 'data'); // intercepted should never pass first argument to callback // even if arguments length is more than 2. function fn3(data, data2) { assert.equal(data, 'data', 'should not be null err argument'); assert.equal(data2, 'data2', 'should not be data argument'); } bound = d.intercept(fn3); bound(null, 'data', 'data2'); // throwing in a bound fn is also caught, // even if it's asynchronous, by hitting the // global uncaughtException handler. This doesn't // require interception, since throws are always // caught by the domain. function thrower() { throw new Error('thrown'); } setTimeout(d.bind(thrower), 100); expectCaught++; // Pass an intercepted function to an fs operation that fails. fs.open('this file does not exist', 'r', d.intercept(function(er) { console.error('should not get here!', er); throw new Error('should not get here!'); }, true)); expectCaught++; // implicit addition by being created within a domain-bound context. var implicit; d.run(function() { implicit = new events.EventEmitter; }); setTimeout(function() { // escape from the domain, but implicit is still bound to it. implicit.emit('error', new Error('implicit')); }, 10); expectCaught++; var result = d.run(function () { return 'return value'; }); assert.equal(result, 'return value'); var fst = fs.createReadStream('stream for nonexistent file') d.add(fst) expectCaught++; node-v0.10.25~dfsg2/test/simple/test-zlib-dictionary-fail.js0000644000000000000000000000365012270121457022420 0ustar rootroot// Copyright Joyent, Inc. and other Node contributors. // // Permission is hereby granted, free of charge, to any person obtaining a // copy of this software and associated documentation files (the // "Software"), to deal in the Software without restriction, including // without limitation the rights to use, copy, modify, merge, publish, // distribute, sublicense, and/or sell copies of the Software, and to permit // persons to whom the Software is furnished to do so, subject to the // following conditions: // // The above copyright notice and this permission notice shall be included // in all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS // OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF // MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN // NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, // DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR // OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE // USE OR OTHER DEALINGS IN THE SOFTWARE. var common = require('../common.js'); var assert = require('assert'); var zlib = require('zlib'); // Should raise an error, not trigger an assertion in src/node_zlib.cc (function() { var stream = zlib.createInflate(); stream.on('error', common.mustCall(function(err) { assert(/Missing dictionary/.test(err.message)); })); // String "test" encoded with dictionary "dict". stream.write(Buffer([0x78,0xBB,0x04,0x09,0x01,0xA5])); })(); // Should raise an error, not trigger an assertion in src/node_zlib.cc (function() { var stream = zlib.createInflate({ dictionary: Buffer('fail') }); stream.on('error', common.mustCall(function(err) { assert(/Bad dictionary/.test(err.message)); })); // String "test" encoded with dictionary "dict". stream.write(Buffer([0x78,0xBB,0x04,0x09,0x01,0xA5])); })(); node-v0.10.25~dfsg2/test/simple/test-http-pause.js0000644000000000000000000000466012270121457020500 0ustar rootroot// Copyright Joyent, Inc. and other Node contributors. // // Permission is hereby granted, free of charge, to any person obtaining a // copy of this software and associated documentation files (the // "Software"), to deal in the Software without restriction, including // without limitation the rights to use, copy, modify, merge, publish, // distribute, sublicense, and/or sell copies of the Software, and to permit // persons to whom the Software is furnished to do so, subject to the // following conditions: // // The above copyright notice and this permission notice shall be included // in all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS // OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF // MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN // NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, // DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR // OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE // USE OR OTHER DEALINGS IN THE SOFTWARE. var common = require('../common'); var assert = require('assert'); var http = require('http'); var expectedServer = 'Request Body from Client'; var resultServer = ''; var expectedClient = 'Response Body from Server'; var resultClient = ''; var server = http.createServer(function(req, res) { common.debug('pause server request'); req.pause(); setTimeout(function() { common.debug('resume server request'); req.resume(); req.setEncoding('utf8'); req.on('data', function(chunk) { resultServer += chunk; }); req.on('end', function() { common.debug(resultServer); res.writeHead(200); res.end(expectedClient); }); }, 100); }); server.listen(common.PORT, function() { var req = http.request({ port: common.PORT, path: '/', method: 'POST' }, function(res) { common.debug('pause client response'); res.pause(); setTimeout(function() { common.debug('resume client response'); res.resume(); res.on('data', function(chunk) { resultClient += chunk; }); res.on('end', function() { common.debug(resultClient); server.close(); }); }, 100); }); req.end(expectedServer); }); process.on('exit', function() { assert.equal(expectedServer, resultServer); assert.equal(expectedClient, resultClient); }); node-v0.10.25~dfsg2/test/simple/test-https-agent.js0000644000000000000000000000436012270121457020641 0ustar rootroot// Copyright Joyent, Inc. and other Node contributors. // // Permission is hereby granted, free of charge, to any person obtaining a // copy of this software and associated documentation files (the // "Software"), to deal in the Software without restriction, including // without limitation the rights to use, copy, modify, merge, publish, // distribute, sublicense, and/or sell copies of the Software, and to permit // persons to whom the Software is furnished to do so, subject to the // following conditions: // // The above copyright notice and this permission notice shall be included // in all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS // OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF // MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN // NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, // DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR // OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE // USE OR OTHER DEALINGS IN THE SOFTWARE. if (!process.versions.openssl) { console.error('Skipping because node compiled without OpenSSL.'); process.exit(0); } var common = require('../common'); var assert = require('assert'); var https = require('https'); var fs = require('fs'); var options = { key: fs.readFileSync(common.fixturesDir + '/keys/agent1-key.pem'), cert: fs.readFileSync(common.fixturesDir + '/keys/agent1-cert.pem') }; var server = https.Server(options, function(req, res) { res.writeHead(200); res.end('hello world\n'); }); var responses = 0; var N = 10; var M = 10; server.listen(common.PORT, function() { for (var i = 0; i < N; i++) { setTimeout(function() { for (var j = 0; j < M; j++) { https.get({ path: '/', port: common.PORT, rejectUnauthorized: false }, function(res) { res.resume(); console.log(res.statusCode); if (++responses == N * M) server.close(); }).on('error', function(e) { console.log(e.message); process.exit(1); }); } }, i); } }); process.on('exit', function() { assert.equal(N * M, responses); }); node-v0.10.25~dfsg2/test/simple/test-https-localaddress-bind-error.js0000644000000000000000000000431712270121457024246 0ustar rootroot// Copyright Joyent, Inc. and other Node contributors. // // Permission is hereby granted, free of charge, to any person obtaining a // copy of this software and associated documentation files (the // "Software"), to deal in the Software without restriction, including // without limitation the rights to use, copy, modify, merge, publish, // distribute, sublicense, and/or sell copies of the Software, and to permit // persons to whom the Software is furnished to do so, subject to the // following conditions: // // The above copyright notice and this permission notice shall be included // in all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS // OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF // MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN // NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, // DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR // OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE // USE OR OTHER DEALINGS IN THE SOFTWARE. var common = require('../common'); var assert = require('assert'); var https = require('https'); var fs = require('fs'); var options = { key: fs.readFileSync(common.fixturesDir + '/keys/agent1-key.pem'), cert: fs.readFileSync(common.fixturesDir + '/keys/agent1-cert.pem') }; var invalidLocalAddress = '1.2.3.4'; var gotError = false; var server = https.createServer(options, function(req, res) { console.log("Connect from: " + req.connection.remoteAddress); req.on('end', function() { res.writeHead(200, { 'Content-Type': 'text/plain' }); res.end('You are from: ' + req.connection.remoteAddress); }); req.resume(); }); server.listen(common.PORT, "127.0.0.1", function() { var req = https.request({ host: 'localhost', port: common.PORT, path: '/', method: 'GET', localAddress: invalidLocalAddress }, function(res) { assert.fail('unexpectedly got response from server'); }).on('error', function(e) { console.log('client got error: ' + e.message); gotError = true; server.close(); }).end(); }); process.on('exit', function() { assert.ok(gotError); }); node-v0.10.25~dfsg2/test/simple/test-http-timeout-overflow.js0000644000000000000000000000362712270121457022714 0ustar rootroot// Copyright Joyent, Inc. and other Node contributors. // // Permission is hereby granted, free of charge, to any person obtaining a // copy of this software and associated documentation files (the // "Software"), to deal in the Software without restriction, including // without limitation the rights to use, copy, modify, merge, publish, // distribute, sublicense, and/or sell copies of the Software, and to permit // persons to whom the Software is furnished to do so, subject to the // following conditions: // // The above copyright notice and this permission notice shall be included // in all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS // OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF // MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN // NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, // DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR // OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE // USE OR OTHER DEALINGS IN THE SOFTWARE. var common = require('../common'); var assert = require('assert'); var http = require('http'); var port = common.PORT; var serverRequests = 0; var clientRequests = 0; var server = http.createServer(function(req, res) { serverRequests++; res.writeHead(200, {'Content-Type': 'text/plain'}); res.end('OK'); }); server.listen(port, function() { function callback(){} var req = http.request({ port: port, path: '/', agent: false }, function(res) { req.clearTimeout(callback); res.on('end', function() { clientRequests++; server.close(); }) res.resume(); }); // Overflow signed int32 req.setTimeout(0xffffffff, callback); req.end(); }); process.once('exit', function() { assert.equal(clientRequests, 1); assert.equal(serverRequests, 1); }); node-v0.10.25~dfsg2/test/simple/test-child-process-customfd-bounded.js0000644000000000000000000000243012270121457024376 0ustar rootroot// Copyright Joyent, Inc. and other Node contributors. // // Permission is hereby granted, free of charge, to any person obtaining a // copy of this software and associated documentation files (the // "Software"), to deal in the Software without restriction, including // without limitation the rights to use, copy, modify, merge, publish, // distribute, sublicense, and/or sell copies of the Software, and to permit // persons to whom the Software is furnished to do so, subject to the // following conditions: // // The above copyright notice and this permission notice shall be included // in all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS // OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF // MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN // NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, // DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR // OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE // USE OR OTHER DEALINGS IN THE SOFTWARE. var common = require('../common'); var bigish = Array(200); for (var i = 0, il = bigish.length; i < il; ++i) bigish[i] = -1; common.spawnPwd({ customFds: bigish }); node-v0.10.25~dfsg2/test/simple/test-repl-options.js0000644000000000000000000000466212270121457021043 0ustar rootroot// Copyright Joyent, Inc. and other Node contributors. // // Permission is hereby granted, free of charge, to any person obtaining a // copy of this software and associated documentation files (the // "Software"), to deal in the Software without restriction, including // without limitation the rights to use, copy, modify, merge, publish, // distribute, sublicense, and/or sell copies of the Software, and to permit // persons to whom the Software is furnished to do so, subject to the // following conditions: // // The above copyright notice and this permission notice shall be included // in all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS // OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF // MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN // NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, // DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR // OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE // USE OR OTHER DEALINGS IN THE SOFTWARE. var common = require('../common'), assert = require('assert'), Stream = require('stream'), repl = require('repl'); common.globalCheck = false; // create a dummy stream that does nothing var stream = new Stream(); stream.write = stream.pause = stream.resume = function(){}; stream.readable = stream.writable = true; // 1, mostly defaults var r1 = repl.start({ input: stream, output: stream, terminal: true }); assert.equal(r1.rli.input, stream); assert.equal(r1.rli.output, stream); assert.equal(r1.rli.input, r1.inputStream); assert.equal(r1.rli.output, r1.outputStream); assert.equal(r1.rli.terminal, true); assert.equal(r1.useColors, r1.rli.terminal); assert.equal(r1.useGlobal, false); assert.equal(r1.ignoreUndefined, false); // 2 function writer() {} function evaler() {} var r2 = repl.start({ input: stream, output: stream, terminal: false, useColors: true, useGlobal: true, ignoreUndefined: true, eval: evaler, writer: writer }); assert.equal(r2.rli.input, stream); assert.equal(r2.rli.output, stream); assert.equal(r2.rli.input, r2.inputStream); assert.equal(r2.rli.output, r2.outputStream); assert.equal(r2.rli.terminal, false); assert.equal(r2.useColors, true); assert.equal(r2.useGlobal, true); assert.equal(r2.ignoreUndefined, true); assert.equal(r2.eval, evaler); assert.equal(r2.writer, writer); node-v0.10.25~dfsg2/test/simple/test-net-pipe-connect-errors.js0000644000000000000000000000556512270121457023075 0ustar rootroot// Copyright Joyent, Inc. and other Node contributors. // // Permission is hereby granted, free of charge, to any person obtaining a // copy of this software and associated documentation files (the // "Software"), to deal in the Software without restriction, including // without limitation the rights to use, copy, modify, merge, publish, // distribute, sublicense, and/or sell copies of the Software, and to permit // persons to whom the Software is furnished to do so, subject to the // following conditions: // // The above copyright notice and this permission notice shall be included // in all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS // OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF // MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN // NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, // DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR // OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE // USE OR OTHER DEALINGS IN THE SOFTWARE. var fs = require('fs'); var net = require('net'); var path = require('path'); var assert = require('assert'); var common = require('../common'); var notSocketErrorFired = false; var noEntErrorFired = false; var accessErrorFired = false; // Test if ENOTSOCK is fired when trying to connect to a file which is not // a socket. var emptyTxt = path.join(common.fixturesDir, 'empty.txt'); var notSocketClient = net.createConnection(emptyTxt, function() { assert.ok(false); }); notSocketClient.on('error', function(err) { assert(err.code === 'ENOTSOCK' || err.code === 'ECONNREFUSED'); notSocketErrorFired = true; }); // Trying to connect to not-existing socket should result in ENOENT error var noEntSocketClient = net.createConnection('no-ent-file', function() { assert.ok(false); }); noEntSocketClient.on('error', function(err) { assert.equal(err.code, 'ENOENT'); noEntErrorFired = true; }); // On Windows or when running as root, a chmod has no effect on named pipes if (process.platform !== 'win32' && process.getuid() !== 0) { // Trying to connect to a socket one has no access to should result in EACCES var accessServer = net.createServer(function() { assert.ok(false); }); accessServer.listen(common.PIPE, function() { fs.chmodSync(common.PIPE, 0); var accessClient = net.createConnection(common.PIPE, function() { assert.ok(false); }); accessClient.on('error', function(err) { assert.equal(err.code, 'EACCES'); accessErrorFired = true; accessServer.close(); }); }); } // Assert that all error events were fired process.on('exit', function() { assert.ok(notSocketErrorFired); assert.ok(noEntErrorFired); if (process.platform !== 'win32' && process.getuid() !== 0) { assert.ok(accessErrorFired); } }); node-v0.10.25~dfsg2/test/simple/test-buffer.js0000644000000000000000000007610612270121457017663 0ustar rootroot// Copyright Joyent, Inc. and other Node contributors. // // Permission is hereby granted, free of charge, to any person obtaining a // copy of this software and associated documentation files (the // "Software"), to deal in the Software without restriction, including // without limitation the rights to use, copy, modify, merge, publish, // distribute, sublicense, and/or sell copies of the Software, and to permit // persons to whom the Software is furnished to do so, subject to the // following conditions: // // The above copyright notice and this permission notice shall be included // in all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS // OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF // MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN // NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, // DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR // OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE // USE OR OTHER DEALINGS IN THE SOFTWARE. var common = require('../common'); var assert = require('assert'); var SlowBuffer = require('buffer').SlowBuffer; var Buffer = require('buffer').Buffer; // counter to ensure unique value is always copied var cntr = 0; // Regression test for segfault introduced in commit e501ce4. ['base64','binary','ucs2','utf8','ascii'].forEach(function(encoding) { var buf = new SlowBuffer(0); buf.write('', encoding); }); var b = Buffer(1024); // safe constructor console.log('b.length == %d', b.length); assert.strictEqual(1024, b.length); b[0] = -1; assert.strictEqual(b[0], 255); for (var i = 0; i < 1024; i++) { b[i] = i % 256; } for (var i = 0; i < 1024; i++) { assert.strictEqual(i % 256, b[i]); } var c = new Buffer(512); console.log('c.length == %d', c.length); assert.strictEqual(512, c.length); // copy 512 bytes, from 0 to 512. b.fill(++cntr); c.fill(++cntr); var copied = b.copy(c, 0, 0, 512); console.log('copied %d bytes from b into c', copied); assert.strictEqual(512, copied); for (var i = 0; i < c.length; i++) { assert.strictEqual(b[i], c[i]); } // copy c into b, without specifying sourceEnd b.fill(++cntr); c.fill(++cntr); var copied = c.copy(b, 0, 0); console.log('copied %d bytes from c into b w/o sourceEnd', copied); assert.strictEqual(c.length, copied); for (var i = 0; i < c.length; i++) { assert.strictEqual(c[i], b[i]); } // copy c into b, without specifying sourceStart b.fill(++cntr); c.fill(++cntr); var copied = c.copy(b, 0); console.log('copied %d bytes from c into b w/o sourceStart', copied); assert.strictEqual(c.length, copied); for (var i = 0; i < c.length; i++) { assert.strictEqual(c[i], b[i]); } // copy longer buffer b to shorter c without targetStart b.fill(++cntr); c.fill(++cntr); var copied = b.copy(c); console.log('copied %d bytes from b into c w/o targetStart', copied); assert.strictEqual(c.length, copied); for (var i = 0; i < c.length; i++) { assert.strictEqual(b[i], c[i]); } // copy starting near end of b to c b.fill(++cntr); c.fill(++cntr); var copied = b.copy(c, 0, b.length - Math.floor(c.length / 2)); console.log('copied %d bytes from end of b into beginning of c', copied); assert.strictEqual(Math.floor(c.length / 2), copied); for (var i = 0; i < Math.floor(c.length / 2); i++) { assert.strictEqual(b[b.length - Math.floor(c.length / 2) + i], c[i]); } for (var i = Math.floor(c.length /2) + 1; i < c.length; i++) { assert.strictEqual(c[c.length-1], c[i]); } // try to copy 513 bytes, and check we don't overrun c b.fill(++cntr); c.fill(++cntr); var copied = b.copy(c, 0, 0, 513); console.log('copied %d bytes from b trying to overrun c', copied); assert.strictEqual(c.length, copied); for (var i = 0; i < c.length; i++) { assert.strictEqual(b[i], c[i]); } // copy 768 bytes from b into b b.fill(++cntr); b.fill(++cntr, 256); var copied = b.copy(b, 0, 256, 1024); console.log('copied %d bytes from b into b', copied); assert.strictEqual(768, copied); for (var i = 0; i < b.length; i++) { assert.strictEqual(cntr, b[i]); } // copy from fast to slow buffer var sb = new SlowBuffer(b.length); var copied = b.copy(sb); console.log('copied %d bytes from b into sb'); for (var i = 0; i < sb.length; i++) { assert.strictEqual(sb[i], b[i]); } var caught_error = null; // try to copy from before the beginning of b caught_error = null; try { var copied = b.copy(c, 0, 100, 10); } catch (err) { caught_error = err; } // copy from b to c with negative sourceStart b.fill(++cntr); c.fill(++cntr); var copied = b.copy(c, 0, -1); assert.strictEqual(c.length, copied); console.log('copied %d bytes from b into c w/ negative sourceStart', copied); for (var i = 0; i < c.length; i++) { assert.strictEqual(b[i], c[i]); } // check sourceEnd resets to targetEnd if former is greater than the latter b.fill(++cntr); c.fill(++cntr); var copied = b.copy(c, 0, 0, 1025); console.log('copied %d bytes from b into c', copied); for (var i = 0; i < c.length; i++) { assert.strictEqual(b[i], c[i]); } // copy from fast buffer to slow buffer without parameters var sb = new SlowBuffer(b.length); sb.fill(++cntr, 0, sb.length); b.fill(++cntr); var copied = b.copy(sb); console.log('copied %d bytes from fast buffer to slow buffer', copied); for (var i = 0 ; i < b.length; i++) { assert.strictEqual(b[i], sb[i]); } // throw with negative sourceEnd console.log('test copy at negative sourceEnd'); assert.throws(function() { b.copy(c, 0, 0, -1); }, RangeError); // throw when sourceStart is greater than sourceEnd assert.throws(function() { b.copy(c, 0, 100, 10); }, RangeError); // throw attempting to copy after end of c assert.throws(function() { b.copy(c, 512, 0, 10); }, RangeError); var caught_error; // invalid encoding for Buffer.toString caught_error = null; try { var copied = b.toString('invalid'); } catch (err) { caught_error = err; } assert.strictEqual('Unknown encoding: invalid', caught_error.message); // invalid encoding for Buffer.write caught_error = null; try { var copied = b.write('test string', 0, 5, 'invalid'); } catch (err) { caught_error = err; } assert.strictEqual('Unknown encoding: invalid', caught_error.message); // try to create 0-length buffers new Buffer(''); new Buffer('', 'ascii'); new Buffer('', 'binary'); new Buffer(0); // try to write a 0-length string beyond the end of b b.write('', 1024); b.write('', 2048); // throw when writing past bounds from the pool assert.throws(function() { b.write('a', 2048); }, RangeError); // throw when writing to negative offset assert.throws(function() { b.write('a', -1); }, RangeError); // try to copy 0 bytes worth of data into an empty buffer b.copy(new Buffer(0), 0, 0, 0); // try to copy 0 bytes past the end of the target buffer b.copy(new Buffer(0), 1, 1, 1); b.copy(new Buffer(1), 1, 1, 1); // try to copy 0 bytes from past the end of the source buffer b.copy(new Buffer(1), 0, 2048, 2048); // try to toString() a 0-length slice of a buffer, both within and without the // valid buffer range assert.equal(new Buffer('abc').toString('ascii', 0, 0), ''); assert.equal(new Buffer('abc').toString('ascii', -100, -100), ''); assert.equal(new Buffer('abc').toString('ascii', 100, 100), ''); // try toString() with a object as a encoding assert.equal(new Buffer('abc').toString({toString: function() { return 'ascii'; }}), 'abc'); // testing for smart defaults and ability to pass string values as offset var writeTest = new Buffer('abcdes'); writeTest.write('n', 'ascii'); writeTest.write('o', 'ascii', '1'); writeTest.write('d', '2', 'ascii'); writeTest.write('e', 3, 'ascii'); writeTest.write('j', 'ascii', 4); assert.equal(writeTest.toString(), 'nodejs'); var asciiString = 'hello world'; var offset = 100; for (var j = 0; j < 500; j++) { for (var i = 0; i < asciiString.length; i++) { b[i] = asciiString.charCodeAt(i); } var asciiSlice = b.toString('ascii', 0, asciiString.length); assert.equal(asciiString, asciiSlice); var written = b.write(asciiString, offset, 'ascii'); assert.equal(asciiString.length, written); var asciiSlice = b.toString('ascii', offset, offset + asciiString.length); assert.equal(asciiString, asciiSlice); var sliceA = b.slice(offset, offset + asciiString.length); var sliceB = b.slice(offset, offset + asciiString.length); for (var i = 0; i < asciiString.length; i++) { assert.equal(sliceA[i], sliceB[i]); } // TODO utf8 slice tests } for (var j = 0; j < 100; j++) { var slice = b.slice(100, 150); assert.equal(50, slice.length); for (var i = 0; i < 50; i++) { assert.equal(b[100 + i], slice[i]); } } // Bug regression test var testValue = '\u00F6\u65E5\u672C\u8A9E'; // ö日本語 var buffer = new Buffer(32); var size = buffer.write(testValue, 0, 'utf8'); console.log('bytes written to buffer: ' + size); var slice = buffer.toString('utf8', 0, size); assert.equal(slice, testValue); // Test triple slice var a = new Buffer(8); for (var i = 0; i < 8; i++) a[i] = i; var b = a.slice(4, 8); assert.equal(4, b[0]); assert.equal(5, b[1]); assert.equal(6, b[2]); assert.equal(7, b[3]); var c = b.slice(2, 4); assert.equal(6, c[0]); assert.equal(7, c[1]); var d = new Buffer([23, 42, 255]); assert.equal(d.length, 3); assert.equal(d[0], 23); assert.equal(d[1], 42); assert.equal(d[2], 255); assert.deepEqual(d, new Buffer(d)); var e = new Buffer('über'); console.error('uber: \'%s\'', e.toString()); assert.deepEqual(e, new Buffer([195, 188, 98, 101, 114])); var f = new Buffer('über', 'ascii'); console.error('f.length: %d (should be 4)', f.length); assert.deepEqual(f, new Buffer([252, 98, 101, 114])); ['ucs2', 'ucs-2', 'utf16le', 'utf-16le'].forEach(function(encoding) { var f = new Buffer('über', encoding); console.error('f.length: %d (should be 8)', f.length); assert.deepEqual(f, new Buffer([252, 0, 98, 0, 101, 0, 114, 0])); var f = new Buffer('привет', encoding); console.error('f.length: %d (should be 12)', f.length); assert.deepEqual(f, new Buffer([63, 4, 64, 4, 56, 4, 50, 4, 53, 4, 66, 4])); assert.equal(f.toString(encoding), 'привет'); var f = new Buffer([0, 0, 0, 0, 0]); assert.equal(f.length, 5); var size = f.write('あいうえお', encoding); var charsWritten = Buffer._charsWritten; // Copy value out. console.error('bytes written to buffer: %d (should be 4)', size); console.error('chars written to buffer: %d (should be 2)', charsWritten); assert.equal(size, 4); assert.equal(charsWritten, 2); assert.deepEqual(f, new Buffer([0x42, 0x30, 0x44, 0x30, 0x00])); }); var f = new Buffer('\uD83D\uDC4D', 'utf-16le'); // THUMBS UP SIGN (U+1F44D) assert.equal(f.length, 4); assert.deepEqual(f, new Buffer('3DD84DDC', 'hex')); var arrayIsh = {0: 0, 1: 1, 2: 2, 3: 3, length: 4}; var g = new Buffer(arrayIsh); assert.deepEqual(g, new Buffer([0, 1, 2, 3])); var strArrayIsh = {0: '0', 1: '1', 2: '2', 3: '3', length: 4}; g = new Buffer(strArrayIsh); assert.deepEqual(g, new Buffer([0, 1, 2, 3])); // // Test toString('base64') // assert.equal('TWFu', (new Buffer('Man')).toString('base64')); // test that regular and URL-safe base64 both work var expected = [0xff, 0xff, 0xbe, 0xff, 0xef, 0xbf, 0xfb, 0xef, 0xff]; assert.deepEqual(Buffer('//++/++/++//', 'base64'), Buffer(expected)); assert.deepEqual(Buffer('__--_--_--__', 'base64'), Buffer(expected)); // big example var quote = 'Man is distinguished, not only by his reason, but by this ' + 'singular passion from other animals, which is a lust ' + 'of the mind, that by a perseverance of delight in the continued ' + 'and indefatigable generation of knowledge, exceeds the short ' + 'vehemence of any carnal pleasure.'; var expected = 'TWFuIGlzIGRpc3Rpbmd1aXNoZWQsIG5vdCBvbmx5IGJ5IGhpcyByZWFzb24s' + 'IGJ1dCBieSB0aGlzIHNpbmd1bGFyIHBhc3Npb24gZnJvbSBvdGhlciBhbmltY' + 'WxzLCB3aGljaCBpcyBhIGx1c3Qgb2YgdGhlIG1pbmQsIHRoYXQgYnkgYSBwZX' + 'JzZXZlcmFuY2Ugb2YgZGVsaWdodCBpbiB0aGUgY29udGludWVkIGFuZCBpbmR' + 'lZmF0aWdhYmxlIGdlbmVyYXRpb24gb2Yga25vd2xlZGdlLCBleGNlZWRzIHRo' + 'ZSBzaG9ydCB2ZWhlbWVuY2Ugb2YgYW55IGNhcm5hbCBwbGVhc3VyZS4='; assert.equal(expected, (new Buffer(quote)).toString('base64')); b = new Buffer(1024); var bytesWritten = b.write(expected, 0, 'base64'); assert.equal(quote.length, bytesWritten); assert.equal(quote, b.toString('ascii', 0, quote.length)); // check that the base64 decoder ignores whitespace var expectedWhite = expected.slice(0, 60) + ' \n' + expected.slice(60, 120) + ' \n' + expected.slice(120, 180) + ' \n' + expected.slice(180, 240) + ' \n' + expected.slice(240, 300) + '\n' + expected.slice(300, 360) + '\n'; b = new Buffer(1024); bytesWritten = b.write(expectedWhite, 0, 'base64'); assert.equal(quote.length, bytesWritten); assert.equal(quote, b.toString('ascii', 0, quote.length)); // check that the base64 decoder on the constructor works // even in the presence of whitespace. b = new Buffer(expectedWhite, 'base64'); assert.equal(quote.length, b.length); assert.equal(quote, b.toString('ascii', 0, quote.length)); // check that the base64 decoder ignores illegal chars var expectedIllegal = expected.slice(0, 60) + ' \x80' + expected.slice(60, 120) + ' \xff' + expected.slice(120, 180) + ' \x00' + expected.slice(180, 240) + ' \x98' + expected.slice(240, 300) + '\x03' + expected.slice(300, 360); b = new Buffer(expectedIllegal, 'base64'); assert.equal(quote.length, b.length); assert.equal(quote, b.toString('ascii', 0, quote.length)); assert.equal(new Buffer('', 'base64').toString(), ''); assert.equal(new Buffer('K', 'base64').toString(), ''); // multiple-of-4 with padding assert.equal(new Buffer('Kg==', 'base64').toString(), '*'); assert.equal(new Buffer('Kio=', 'base64').toString(), '**'); assert.equal(new Buffer('Kioq', 'base64').toString(), '***'); assert.equal(new Buffer('KioqKg==', 'base64').toString(), '****'); assert.equal(new Buffer('KioqKio=', 'base64').toString(), '*****'); assert.equal(new Buffer('KioqKioq', 'base64').toString(), '******'); assert.equal(new Buffer('KioqKioqKg==', 'base64').toString(), '*******'); assert.equal(new Buffer('KioqKioqKio=', 'base64').toString(), '********'); assert.equal(new Buffer('KioqKioqKioq', 'base64').toString(), '*********'); assert.equal(new Buffer('KioqKioqKioqKg==', 'base64').toString(), '**********'); assert.equal(new Buffer('KioqKioqKioqKio=', 'base64').toString(), '***********'); assert.equal(new Buffer('KioqKioqKioqKioq', 'base64').toString(), '************'); assert.equal(new Buffer('KioqKioqKioqKioqKg==', 'base64').toString(), '*************'); assert.equal(new Buffer('KioqKioqKioqKioqKio=', 'base64').toString(), '**************'); assert.equal(new Buffer('KioqKioqKioqKioqKioq', 'base64').toString(), '***************'); assert.equal(new Buffer('KioqKioqKioqKioqKioqKg==', 'base64').toString(), '****************'); assert.equal(new Buffer('KioqKioqKioqKioqKioqKio=', 'base64').toString(), '*****************'); assert.equal(new Buffer('KioqKioqKioqKioqKioqKioq', 'base64').toString(), '******************'); assert.equal(new Buffer('KioqKioqKioqKioqKioqKioqKg==', 'base64').toString(), '*******************'); assert.equal(new Buffer('KioqKioqKioqKioqKioqKioqKio=', 'base64').toString(), '********************'); // no padding, not a multiple of 4 assert.equal(new Buffer('Kg', 'base64').toString(), '*'); assert.equal(new Buffer('Kio', 'base64').toString(), '**'); assert.equal(new Buffer('KioqKg', 'base64').toString(), '****'); assert.equal(new Buffer('KioqKio', 'base64').toString(), '*****'); assert.equal(new Buffer('KioqKioqKg', 'base64').toString(), '*******'); assert.equal(new Buffer('KioqKioqKio', 'base64').toString(), '********'); assert.equal(new Buffer('KioqKioqKioqKg', 'base64').toString(), '**********'); assert.equal(new Buffer('KioqKioqKioqKio', 'base64').toString(), '***********'); assert.equal(new Buffer('KioqKioqKioqKioqKg', 'base64').toString(), '*************'); assert.equal(new Buffer('KioqKioqKioqKioqKio', 'base64').toString(), '**************'); assert.equal(new Buffer('KioqKioqKioqKioqKioqKg', 'base64').toString(), '****************'); assert.equal(new Buffer('KioqKioqKioqKioqKioqKio', 'base64').toString(), '*****************'); assert.equal(new Buffer('KioqKioqKioqKioqKioqKioqKg', 'base64').toString(), '*******************'); assert.equal(new Buffer('KioqKioqKioqKioqKioqKioqKio', 'base64').toString(), '********************'); // handle padding graciously, multiple-of-4 or not assert.equal(new Buffer('72INjkR5fchcxk9+VgdGPFJDxUBFR5/rMFsghgxADiw==', 'base64').length, 32); assert.equal(new Buffer('72INjkR5fchcxk9+VgdGPFJDxUBFR5/rMFsghgxADiw=', 'base64').length, 32); assert.equal(new Buffer('72INjkR5fchcxk9+VgdGPFJDxUBFR5/rMFsghgxADiw', 'base64').length, 32); assert.equal(new Buffer('w69jACy6BgZmaFvv96HG6MYksWytuZu3T1FvGnulPg==', 'base64').length, 31); assert.equal(new Buffer('w69jACy6BgZmaFvv96HG6MYksWytuZu3T1FvGnulPg=', 'base64').length, 31); assert.equal(new Buffer('w69jACy6BgZmaFvv96HG6MYksWytuZu3T1FvGnulPg', 'base64').length, 31); // This string encodes single '.' character in UTF-16 var dot = new Buffer('//4uAA==', 'base64'); assert.equal(dot[0], 0xff); assert.equal(dot[1], 0xfe); assert.equal(dot[2], 0x2e); assert.equal(dot[3], 0x00); assert.equal(dot.toString('base64'), '//4uAA=='); // Writing base64 at a position > 0 should not mangle the result. // // https://github.com/joyent/node/issues/402 var segments = ['TWFkbmVzcz8h', 'IFRoaXM=', 'IGlz', 'IG5vZGUuanMh']; var buf = new Buffer(64); var pos = 0; for (var i = 0; i < segments.length; ++i) { pos += b.write(segments[i], pos, 'base64'); } assert.equal(b.toString('binary', 0, pos), 'Madness?! This is node.js!'); // Creating buffers larger than pool size. var l = Buffer.poolSize + 5; var s = ''; for (i = 0; i < l; i++) { s += 'h'; } var b = new Buffer(s); for (i = 0; i < l; i++) { assert.equal('h'.charCodeAt(0), b[i]); } var sb = b.toString(); assert.equal(sb.length, s.length); assert.equal(sb, s); // Single argument slice b = new Buffer('abcde'); assert.equal('bcde', b.slice(1).toString()); // byte length assert.equal(14, Buffer.byteLength('Il était tué')); assert.equal(14, Buffer.byteLength('Il était tué', 'utf8')); ['ucs2', 'ucs-2', 'utf16le', 'utf-16le'].forEach(function(encoding) { assert.equal(24, Buffer.byteLength('Il était tué', encoding)); }); assert.equal(12, Buffer.byteLength('Il était tué', 'ascii')); assert.equal(12, Buffer.byteLength('Il était tué', 'binary')); // slice(0,0).length === 0 assert.equal(0, Buffer('hello').slice(0, 0).length); // test hex toString console.log('Create hex string from buffer'); var hexb = new Buffer(256); for (var i = 0; i < 256; i++) { hexb[i] = i; } var hexStr = hexb.toString('hex'); assert.equal(hexStr, '000102030405060708090a0b0c0d0e0f' + '101112131415161718191a1b1c1d1e1f' + '202122232425262728292a2b2c2d2e2f' + '303132333435363738393a3b3c3d3e3f' + '404142434445464748494a4b4c4d4e4f' + '505152535455565758595a5b5c5d5e5f' + '606162636465666768696a6b6c6d6e6f' + '707172737475767778797a7b7c7d7e7f' + '808182838485868788898a8b8c8d8e8f' + '909192939495969798999a9b9c9d9e9f' + 'a0a1a2a3a4a5a6a7a8a9aaabacadaeaf' + 'b0b1b2b3b4b5b6b7b8b9babbbcbdbebf' + 'c0c1c2c3c4c5c6c7c8c9cacbcccdcecf' + 'd0d1d2d3d4d5d6d7d8d9dadbdcdddedf' + 'e0e1e2e3e4e5e6e7e8e9eaebecedeeef' + 'f0f1f2f3f4f5f6f7f8f9fafbfcfdfeff'); console.log('Create buffer from hex string'); var hexb2 = new Buffer(hexStr, 'hex'); for (var i = 0; i < 256; i++) { assert.equal(hexb2[i], hexb[i]); } // test an invalid slice end. console.log('Try to slice off the end of the buffer'); var b = new Buffer([1, 2, 3, 4, 5]); var b2 = b.toString('hex', 1, 10000); var b3 = b.toString('hex', 1, 5); var b4 = b.toString('hex', 1); assert.equal(b2, b3); assert.equal(b2, b4); // Test slice on SlowBuffer GH-843 var SlowBuffer = process.binding('buffer').SlowBuffer; function buildSlowBuffer(data) { if (Array.isArray(data)) { var buffer = new SlowBuffer(data.length); data.forEach(function(v, k) { buffer[k] = v; }); return buffer; } return null; } var x = buildSlowBuffer([0x81, 0xa3, 0x66, 0x6f, 0x6f, 0xa3, 0x62, 0x61, 0x72]); console.log(x.inspect()); assert.equal('', x.inspect()); var z = x.slice(4); console.log(z.inspect()); console.log(z.length); assert.equal(5, z.length); assert.equal(0x6f, z[0]); assert.equal(0xa3, z[1]); assert.equal(0x62, z[2]); assert.equal(0x61, z[3]); assert.equal(0x72, z[4]); var z = x.slice(0); console.log(z.inspect()); console.log(z.length); assert.equal(z.length, x.length); var z = x.slice(0, 4); console.log(z.inspect()); console.log(z.length); assert.equal(4, z.length); assert.equal(0x81, z[0]); assert.equal(0xa3, z[1]); var z = x.slice(0, 9); console.log(z.inspect()); console.log(z.length); assert.equal(9, z.length); var z = x.slice(1, 4); console.log(z.inspect()); console.log(z.length); assert.equal(3, z.length); assert.equal(0xa3, z[0]); var z = x.slice(2, 4); console.log(z.inspect()); console.log(z.length); assert.equal(2, z.length); assert.equal(0x66, z[0]); assert.equal(0x6f, z[1]); assert.equal(0, Buffer('hello').slice(0, 0).length); b = new Buffer(50); b.fill('h'); for (var i = 0; i < b.length; i++) { assert.equal('h'.charCodeAt(0), b[i]); } b.fill(0); for (var i = 0; i < b.length; i++) { assert.equal(0, b[i]); } b.fill(1, 16, 32); for (var i = 0; i < 16; i++) assert.equal(0, b[i]); for (; i < 32; i++) assert.equal(1, b[i]); for (; i < b.length; i++) assert.equal(0, b[i]); ['ucs2', 'ucs-2', 'utf16le', 'utf-16le'].forEach(function(encoding) { var b = new SlowBuffer(10); b.write('あいうえお', encoding); assert.equal(b.toString(encoding), 'あいうえお'); }); // Binary encoding should write only one byte per character. var b = Buffer([0xde, 0xad, 0xbe, 0xef]); var s = String.fromCharCode(0xffff); b.write(s, 0, 'binary'); assert.equal(0xff, b[0]); assert.equal(0xad, b[1]); assert.equal(0xbe, b[2]); assert.equal(0xef, b[3]); s = String.fromCharCode(0xaaee); b.write(s, 0, 'binary'); assert.equal(0xee, b[0]); assert.equal(0xad, b[1]); assert.equal(0xbe, b[2]); assert.equal(0xef, b[3]); // testing invalid encoding on SlowBuffer.toString caught_error = null; try { var copied = b.toString('invalid'); } catch (err) { caught_error = err; } assert.strictEqual('Unknown encoding: invalid', caught_error.message); // testing invalid encoding on SlowBuffer.write caught_error = null; try { var copied = b.write('some string', 0, 5, 'invalid'); } catch (err) { caught_error = err; } assert.strictEqual('Unknown encoding: invalid', caught_error.message); // This should not segfault the program. assert.throws(function() { new Buffer('"pong"', 0, 6, 8031, '127.0.0.1'); }); // #1210 Test UTF-8 string includes null character var buf = new Buffer('\0'); assert.equal(buf.length, 1); buf = new Buffer('\0\0'); assert.equal(buf.length, 2); buf = new Buffer(2); var written = buf.write(''); // 0byte assert.equal(written, 0); written = buf.write('\0'); // 1byte (v8 adds null terminator) assert.equal(written, 1); written = buf.write('a\0'); // 1byte * 2 assert.equal(written, 2); written = buf.write('あ'); // 3bytes assert.equal(written, 0); written = buf.write('\0あ'); // 1byte + 3bytes assert.equal(written, 1); written = buf.write('\0\0あ'); // 1byte * 2 + 3bytes assert.equal(written, 2); buf = new Buffer(10); written = buf.write('あいう'); // 3bytes * 3 (v8 adds null terminator) assert.equal(written, 9); written = buf.write('あいう\0'); // 3bytes * 3 + 1byte assert.equal(written, 10); // #243 Test write() with maxLength var buf = new Buffer(4); buf.fill(0xFF); var written = buf.write('abcd', 1, 2, 'utf8'); console.log(buf); assert.equal(written, 2); assert.equal(buf[0], 0xFF); assert.equal(buf[1], 0x61); assert.equal(buf[2], 0x62); assert.equal(buf[3], 0xFF); buf.fill(0xFF); written = buf.write('abcd', 1, 4); console.log(buf); assert.equal(written, 3); assert.equal(buf[0], 0xFF); assert.equal(buf[1], 0x61); assert.equal(buf[2], 0x62); assert.equal(buf[3], 0x63); buf.fill(0xFF); written = buf.write('abcd', 'utf8', 1, 2); // legacy style console.log(buf); assert.equal(written, 2); assert.equal(buf[0], 0xFF); assert.equal(buf[1], 0x61); assert.equal(buf[2], 0x62); assert.equal(buf[3], 0xFF); buf.fill(0xFF); written = buf.write('abcdef', 1, 2, 'hex'); console.log(buf); assert.equal(written, 2); assert.equal(buf[0], 0xFF); assert.equal(buf[1], 0xAB); assert.equal(buf[2], 0xCD); assert.equal(buf[3], 0xFF); ['ucs2', 'ucs-2', 'utf16le', 'utf-16le'].forEach(function(encoding) { buf.fill(0xFF); written = buf.write('abcd', 0, 2, encoding); console.log(buf); assert.equal(written, 2); assert.equal(buf[0], 0x61); assert.equal(buf[1], 0x00); assert.equal(buf[2], 0xFF); assert.equal(buf[3], 0xFF); }); // test for buffer overrun buf = new Buffer([0, 0, 0, 0, 0]); // length: 5 var sub = buf.slice(0, 4); // length: 4 written = sub.write('12345', 'binary'); assert.equal(written, 4); assert.equal(buf[4], 0); // test for _charsWritten buf = new Buffer(9); buf.write('あいうえ', 'utf8'); // 3bytes * 4 assert.equal(Buffer._charsWritten, 3); ['ucs2', 'ucs-2', 'utf16le', 'utf-16le'].forEach(function(encoding) { buf.write('あいうえお', encoding); // 2bytes * 5 assert.equal(Buffer._charsWritten, 4); }); buf.write('0123456789', 'ascii'); assert.equal(Buffer._charsWritten, 9); buf.write('0123456789', 'binary'); assert.equal(Buffer._charsWritten, 9); buf.write('123456', 'base64'); assert.equal(Buffer._charsWritten, 4); buf.write('00010203040506070809', 'hex'); assert.equal(Buffer._charsWritten, 18); // Check for fractional length args, junk length args, etc. // https://github.com/joyent/node/issues/1758 Buffer(3.3).toString(); // throws bad argument error in commit 43cb4ec assert.equal(Buffer(-1).length, 0); assert.equal(Buffer(NaN).length, 0); assert.equal(Buffer(3.3).length, 4); assert.equal(Buffer({length: 3.3}).length, 4); assert.equal(Buffer({length: 'BAM'}).length, 0); // Make sure that strings are not coerced to numbers. assert.equal(Buffer('99').length, 2); assert.equal(Buffer('13.37').length, 5); // Ensure that the length argument is respected. 'ascii utf8 hex base64 binary'.split(' ').forEach(function(enc) { assert.equal(Buffer(1).write('aaaaaa', 0, 1, enc), 1); }); // Regression test, guard against buffer overrun in the base64 decoder. var a = Buffer(3); var b = Buffer('xxx'); a.write('aaaaaaaa', 'base64'); assert.equal(b.toString(), 'xxx'); // issue GH-3416 Buffer(Buffer(0), 0, 0); [ 'hex', 'utf8', 'utf-8', 'ascii', 'binary', 'base64', 'ucs2', 'ucs-2', 'utf16le', 'utf-16le' ].forEach(function(enc) { assert.equal(Buffer.isEncoding(enc), true); }); [ 'utf9', 'utf-7', 'Unicode-FTW', 'new gnu gun' ].forEach(function(enc) { assert.equal(Buffer.isEncoding(enc), false); }); // GH-3905 assert.equal(JSON.stringify(Buffer('test')), '[116,101,115,116]'); // issue GH-4331 assert.throws(function() { new Buffer(0xFFFFFFFF); }, RangeError); assert.throws(function() { new Buffer(0xFFFFFFFFF); }, TypeError); // attempt to overflow buffers, similar to previous bug in array buffers assert.throws(function() { var buf = new Buffer(8); buf.readFloatLE(0xffffffff); }, /Trying to access beyond buffer length/); assert.throws(function() { var buf = new Buffer(8); buf.writeFloatLE(0.0, 0xffffffff); }, /Trying to access beyond buffer length/); assert.throws(function() { var buf = new SlowBuffer(8); buf.readFloatLE(0xffffffff); }, /Trying to read beyond buffer length/); assert.throws(function() { var buf = new SlowBuffer(8); buf.writeFloatLE(0.0, 0xffffffff); }, /Trying to write beyond buffer length/); // ensure negative values can't get past offset assert.throws(function() { var buf = new Buffer(8); buf.readFloatLE(-1); }, /offset is not uint/); assert.throws(function() { var buf = new Buffer(8); buf.writeFloatLE(0.0, -1); }, /offset is not uint/); assert.throws(function() { var buf = new SlowBuffer(8); buf.readFloatLE(-1); }, /offset is not uint/); assert.throws(function() { var buf = new SlowBuffer(8); buf.writeFloatLE(0.0, -1); }, /offset is not uint/); // offset checks var buf = new Buffer(0); assert.throws(function() { buf.readUInt8(0); }, /beyond buffer length/); assert.throws(function() { buf.readInt8(0); }, /beyond buffer length/); [16, 32].forEach(function(bits) { var buf = new Buffer(bits / 8 - 1); assert.throws( function() { buf['readUInt' + bits + 'BE'](0); }, /beyond buffer length/, 'readUInt' + bits + 'BE' ); assert.throws( function() { buf['readUInt' + bits + 'LE'](0); }, /beyond buffer length/, 'readUInt' + bits + 'LE' ); assert.throws( function() { buf['readInt' + bits + 'BE'](0); }, /beyond buffer length/, 'readInt' + bits + 'BE()' ); assert.throws( function() { buf['readInt' + bits + 'LE'](0); }, /beyond buffer length/, 'readInt' + bits + 'LE()' ); }); // SlowBuffer sanity checks. assert.throws(function() { var len = 0xfffff; var sbuf = new SlowBuffer(len); var buf = new Buffer(sbuf, len, 0); SlowBuffer.makeFastBuffer(sbuf, buf, -len, len); // Should throw. for (var i = 0; i < len; ++i) buf[i] = 0x42; // Try to force segfault. }, RangeError); assert.throws(function() { var len = 0xfffff; var sbuf = new SlowBuffer(len); var buf = new Buffer(sbuf, len, -len); // Should throw. for (var i = 0; i < len; ++i) buf[i] = 0x42; // Try to force segfault. }, RangeError); assert.throws(function() { var sbuf = new SlowBuffer(1); var buf = new Buffer(sbuf, 1, 0); buf.length = 0xffffffff; buf.slice(0xffffff0, 0xffffffe); // Should throw. }, Error); (function() { var buf = new Buffer('0123456789'); assert.equal(buf.slice(-10, 10), '0123456789'); assert.equal(buf.slice(-20, 10), '0123456789'); assert.equal(buf.slice(-20, -10), ''); assert.equal(buf.slice(0, -1), '012345678'); assert.equal(buf.slice(2, -2), '234567'); assert.equal(buf.slice(0, 65536), '0123456789'); assert.equal(buf.slice(65536, 0), ''); for (var i = 0, s = buf.toString(); i < buf.length; ++i) { assert.equal(buf.slice(-i), s.slice(-i)); assert.equal(buf.slice(0, -i), s.slice(0, -i)); } })(); // Make sure byteLength properly checks for base64 padding assert.equal(Buffer.byteLength('aaa=', 'base64'), 2); assert.equal(Buffer.byteLength('aaaa==', 'base64'), 3); // Regression test for #5482: should throw but not assert in C++ land. assert.throws(function() { Buffer('', 'buffer'); }, TypeError); assert.doesNotThrow(function () { var slow = new SlowBuffer(1); assert(slow.write('', Buffer.poolSize * 10) === 0); var fast = new Buffer(1); assert(fast.write('', Buffer.poolSize * 10) === 0); }); node-v0.10.25~dfsg2/test/simple/test-cli-eval.js0000644000000000000000000000625312270121457020102 0ustar rootroot// Copyright Joyent, Inc. and other Node contributors. // // Permission is hereby granted, free of charge, to any person obtaining a // copy of this software and associated documentation files (the // "Software"), to deal in the Software without restriction, including // without limitation the rights to use, copy, modify, merge, publish, // distribute, sublicense, and/or sell copies of the Software, and to permit // persons to whom the Software is furnished to do so, subject to the // following conditions: // // The above copyright notice and this permission notice shall be included // in all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS // OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF // MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN // NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, // DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR // OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE // USE OR OTHER DEALINGS IN THE SOFTWARE. if (module.parent) { // signal we've been loaded as a module console.log('Loaded as a module, exiting with status code 42.'); process.exit(42); } var common = require('../common.js'), assert = require('assert'), child = require('child_process'), nodejs = '"' + process.execPath + '"'; // replace \ by / because windows uses backslashes in paths, but they're still // interpreted as the escape character when put between quotes. var filename = __filename.replace(/\\/g, '/'); // assert that nothing is written to stdout child.exec(nodejs + ' --eval 42', function(err, stdout, stderr) { assert.equal(stdout, ''); assert.equal(stderr, ''); }); // assert that "42\n" is written to stderr child.exec(nodejs + ' --eval "console.error(42)"', function(err, stdout, stderr) { assert.equal(stdout, ''); assert.equal(stderr, '42\n'); }); // assert that the expected output is written to stdout ['--print', '-p -e', '-pe', '-p'].forEach(function(s) { var cmd = nodejs + ' ' + s + ' '; child.exec(cmd + '42', function(err, stdout, stderr) { assert.equal(stdout, '42\n'); assert.equal(stderr, ''); }); child.exec(cmd + "'[]'", function(err, stdout, stderr) { assert.equal(stdout, '[]\n'); assert.equal(stderr, ''); }); }); // assert that module loading works child.exec(nodejs + ' --eval "require(\'' + filename + '\')"', function(status, stdout, stderr) { assert.equal(status.code, 42); }); // module path resolve bug, regression test child.exec(nodejs + ' --eval "require(\'./test/simple/test-cli-eval.js\')"', function(status, stdout, stderr) { assert.equal(status.code, 42); }); // empty program should do nothing child.exec(nodejs + ' -e ""', function(status, stdout, stderr) { assert.equal(stdout, ''); assert.equal(stderr, ''); }); // "\\-42" should be interpreted as an escaped expression, not a switch child.exec(nodejs + ' -p "\\-42"', function(err, stdout, stderr) { assert.equal(stdout, '-42\n'); assert.equal(stderr, ''); }); node-v0.10.25~dfsg2/test/simple/test-repl.js0000644000000000000000000002777412270121457017363 0ustar rootroot// Copyright Joyent, Inc. and other Node contributors. // // Permission is hereby granted, free of charge, to any person obtaining a // copy of this software and associated documentation files (the // "Software"), to deal in the Software without restriction, including // without limitation the rights to use, copy, modify, merge, publish, // distribute, sublicense, and/or sell copies of the Software, and to permit // persons to whom the Software is furnished to do so, subject to the // following conditions: // // The above copyright notice and this permission notice shall be included // in all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS // OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF // MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN // NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, // DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR // OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE // USE OR OTHER DEALINGS IN THE SOFTWARE. var common = require('../common'); var assert = require('assert'); common.globalCheck = false; var net = require('net'), repl = require('repl'), message = 'Read, Eval, Print Loop', prompt_unix = 'node via Unix socket> ', prompt_tcp = 'node via TCP socket> ', prompt_multiline = '... ', prompt_npm = 'npm should be run outside of the ' + 'node repl, in your normal shell.\n' + '(Press Control-D to exit.)\n', expect_npm = prompt_npm + prompt_unix, server_tcp, server_unix, client_tcp, client_unix, timer; // absolute path to test/fixtures/a.js var moduleFilename = require('path').join(common.fixturesDir, 'a'); common.error('repl test'); // function for REPL to run invoke_me = function(arg) { return 'invoked ' + arg; }; function send_expect(list) { if (list.length > 0) { var cur = list.shift(); common.error('sending ' + JSON.stringify(cur.send)); cur.client.expect = cur.expect; cur.client.list = list; if (cur.send.length > 0) { cur.client.write(cur.send + '\n'); } } } function clean_up() { client_tcp.end(); client_unix.end(); clearTimeout(timer); } function error_test() { // The other stuff is done so reuse unix socket var read_buffer = ''; client_unix.removeAllListeners('data'); client_unix.on('data', function(data) { read_buffer += data.toString('ascii', 0, data.length); common.error('Unix data: ' + JSON.stringify(read_buffer) + ', expecting ' + (client_unix.expect.exec ? client_unix.expect : JSON.stringify(client_unix.expect))); if (read_buffer.indexOf(prompt_unix) !== -1) { // if it's an exact match, then don't do the regexp if (read_buffer !== client_unix.expect) { assert.ok(read_buffer.match(client_unix.expect)); common.error('match'); } read_buffer = ''; if (client_unix.list && client_unix.list.length > 0) { send_expect(client_unix.list); } else { common.error('End of Error test, running TCP test.'); tcp_test(); } } else if (read_buffer.indexOf(prompt_multiline) !== -1) { // Check that you meant to send a multiline test assert.strictEqual(prompt_multiline, client_unix.expect); read_buffer = ''; if (client_unix.list && client_unix.list.length > 0) { send_expect(client_unix.list); } else { common.error('End of Error test, running TCP test.\n'); tcp_test(); } } else { common.error('didn\'t see prompt yet, buffering.'); } }); send_expect([ // Uncaught error throws and prints out { client: client_unix, send: 'throw new Error(\'test error\');', expect: /^Error: test error/ }, // Common syntax error is treated as multiline command { client: client_unix, send: 'function test_func() {', expect: prompt_multiline }, // You can recover with the .break command { client: client_unix, send: '.break', expect: prompt_unix }, // Floating point numbers are not interpreted as REPL commands. { client: client_unix, send: '.1234', expect: '0.1234' }, // Floating point expressions are not interpreted as REPL commands { client: client_unix, send: '.1+.1', expect: '0.2' }, // Can parse valid JSON { client: client_unix, send: 'JSON.parse(\'{"valid": "json"}\');', expect: '{ valid: \'json\' }'}, // invalid input to JSON.parse error is special case of syntax error, // should throw { client: client_unix, send: 'JSON.parse(\'{invalid: \\\'json\\\'}\');', expect: /^SyntaxError: Unexpected token i/ }, // end of input to JSON.parse error is special case of syntax error, // should throw { client: client_unix, send: 'JSON.parse(\'066\');', expect: /^SyntaxError: Unexpected number/ }, // should throw { client: client_unix, send: 'JSON.parse(\'{\');', expect: /^SyntaxError: Unexpected end of input/ }, // invalid RegExps are a special case of syntax error, // should throw { client: client_unix, send: '/(/;', expect: /^SyntaxError: Invalid regular expression\:/ }, // invalid RegExp modifiers are a special case of syntax error, // should throw (GH-4012) { client: client_unix, send: 'new RegExp("foo", "wrong modifier");', expect: /^SyntaxError: Invalid flags supplied to RegExp constructor/ }, // strict mode syntax errors should be caught (GH-5178) { client: client_unix, send: '(function() { "use strict"; return 0755; })()', expect: /^SyntaxError: Octal literals are not allowed in strict mode/ }, { client: client_unix, send: '(function() { "use strict"; return { p: 1, p: 2 }; })()', expect: /^SyntaxError: Duplicate data property in object literal not allowed in strict mode/ }, { client: client_unix, send: '(function(a, a, b) { "use strict"; return a + b + c; })()', expect: /^SyntaxError: Strict mode function may not have duplicate parameter names/ }, { client: client_unix, send: '(function() { "use strict"; with (this) {} })()', expect: /^SyntaxError: Strict mode code may not include a with statement/ }, { client: client_unix, send: '(function() { "use strict"; var x; delete x; })()', expect: /^SyntaxError: Delete of an unqualified identifier in strict mode/ }, { client: client_unix, send: '(function() { "use strict"; eval = 17; })()', expect: /^SyntaxError: Assignment to eval or arguments is not allowed in strict mode/ }, { client: client_unix, send: '(function() { "use strict"; if (true){ function f() { } } })()', expect: /^SyntaxError: In strict mode code, functions can only be declared at top level or immediately within another function/ }, // Named functions can be used: { client: client_unix, send: 'function blah() { return 1; }', expect: prompt_unix }, { client: client_unix, send: 'blah()', expect: '1\n' + prompt_unix }, // Functions should not evaluate twice (#2773) { client: client_unix, send: 'var I = [1,2,3,function() {}]; I.pop()', expect: '[Function]' }, // Multiline object { client: client_unix, send: '{ a: ', expect: prompt_multiline }, { client: client_unix, send: '1 }', expect: '{ a: 1 }' }, // Multiline anonymous function with comment { client: client_unix, send: '(function () {', expect: prompt_multiline }, { client: client_unix, send: '// blah', expect: prompt_multiline }, { client: client_unix, send: 'return 1;', expect: prompt_multiline }, { client: client_unix, send: '})()', expect: '1' }, // npm prompt error message { client: client_unix, send: 'npm install foobar', expect: expect_npm }, { client: client_unix, send: '(function () {\n\nreturn 1;\n})()', expect: '1' }, { client: client_unix, send: '{\n\na: 1\n}', expect: '{ a: 1 }' }, { client: client_unix, send: 'url.format("http://google.com")', expect: 'http://google.com/' }, { client: client_unix, send: 'var path = 42; path', expect: '42' } ]); } function tcp_test() { server_tcp = net.createServer(function(socket) { assert.strictEqual(server_tcp, socket.server); socket.on('end', function() { socket.end(); }); repl.start(prompt_tcp, socket); }); server_tcp.listen(common.PORT, function() { var read_buffer = ''; client_tcp = net.createConnection(common.PORT); client_tcp.on('connect', function() { assert.equal(true, client_tcp.readable); assert.equal(true, client_tcp.writable); send_expect([ { client: client_tcp, send: '', expect: prompt_tcp }, { client: client_tcp, send: 'invoke_me(333)', expect: ('\'' + 'invoked 333' + '\'\n' + prompt_tcp) }, { client: client_tcp, send: 'a += 1', expect: ('12346' + '\n' + prompt_tcp) }, { client: client_tcp, send: 'require(' + JSON.stringify(moduleFilename) + ').number', expect: ('42' + '\n' + prompt_tcp) } ]); }); client_tcp.on('data', function(data) { read_buffer += data.toString('ascii', 0, data.length); common.error('TCP data: ' + JSON.stringify(read_buffer) + ', expecting ' + JSON.stringify(client_tcp.expect)); if (read_buffer.indexOf(prompt_tcp) !== -1) { assert.strictEqual(client_tcp.expect, read_buffer); common.error('match'); read_buffer = ''; if (client_tcp.list && client_tcp.list.length > 0) { send_expect(client_tcp.list); } else { common.error('End of TCP test.\n'); clean_up(); } } else { common.error('didn\'t see prompt yet, buffering'); } }); client_tcp.on('error', function(e) { throw e; }); client_tcp.on('close', function() { server_tcp.close(); }); }); } function unix_test() { server_unix = net.createServer(function(socket) { assert.strictEqual(server_unix, socket.server); socket.on('end', function() { socket.end(); }); repl.start({ prompt: prompt_unix, input: socket, output: socket, useGlobal: true }).context.message = message; }); server_unix.on('listening', function() { var read_buffer = ''; client_unix = net.createConnection(common.PIPE); client_unix.on('connect', function() { assert.equal(true, client_unix.readable); assert.equal(true, client_unix.writable); send_expect([ { client: client_unix, send: '', expect: prompt_unix }, { client: client_unix, send: 'message', expect: ('\'' + message + '\'\n' + prompt_unix) }, { client: client_unix, send: 'invoke_me(987)', expect: ('\'' + 'invoked 987' + '\'\n' + prompt_unix) }, { client: client_unix, send: 'a = 12345', expect: ('12345' + '\n' + prompt_unix) }, { client: client_unix, send: '{a:1}', expect: ('{ a: 1 }' + '\n' + prompt_unix) } ]); }); client_unix.on('data', function(data) { read_buffer += data.toString('ascii', 0, data.length); common.error('Unix data: ' + JSON.stringify(read_buffer) + ', expecting ' + JSON.stringify(client_unix.expect)); if (read_buffer.indexOf(prompt_unix) !== -1) { assert.strictEqual(client_unix.expect, read_buffer); common.error('match'); read_buffer = ''; if (client_unix.list && client_unix.list.length > 0) { send_expect(client_unix.list); } else { common.error('End of Unix test, running Error test.\n'); process.nextTick(error_test); } } else { common.error('didn\'t see prompt yet, buffering.'); } }); client_unix.on('error', function(e) { throw e; }); client_unix.on('close', function() { server_unix.close(); }); }); server_unix.listen(common.PIPE); } unix_test(); timer = setTimeout(function() { assert.fail('Timeout'); }, 5000); node-v0.10.25~dfsg2/test/simple/test-regress-GH-897.js0000644000000000000000000000254012270121457020674 0ustar rootroot// Copyright Joyent, Inc. and other Node contributors. // // Permission is hereby granted, free of charge, to any person obtaining a // copy of this software and associated documentation files (the // "Software"), to deal in the Software without restriction, including // without limitation the rights to use, copy, modify, merge, publish, // distribute, sublicense, and/or sell copies of the Software, and to permit // persons to whom the Software is furnished to do so, subject to the // following conditions: // // The above copyright notice and this permission notice shall be included // in all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS // OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF // MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN // NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, // DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR // OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE // USE OR OTHER DEALINGS IN THE SOFTWARE. var common = require('../common'); var assert = require('assert'); var t = Date.now(); var diff; setTimeout(function() { diff = Date.now() - t; console.error(diff); }, 0.1); process.on('exit', function() { assert.ok(diff < 100); }); node-v0.10.25~dfsg2/test/simple/test-executable-path.js0000644000000000000000000000426512270121457021462 0ustar rootroot// Copyright Joyent, Inc. and other Node contributors. // // Permission is hereby granted, free of charge, to any person obtaining a // copy of this software and associated documentation files (the // "Software"), to deal in the Software without restriction, including // without limitation the rights to use, copy, modify, merge, publish, // distribute, sublicense, and/or sell copies of the Software, and to permit // persons to whom the Software is furnished to do so, subject to the // following conditions: // // The above copyright notice and this permission notice shall be included // in all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS // OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF // MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN // NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, // DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR // OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE // USE OR OTHER DEALINGS IN THE SOFTWARE. var common = require('../common'); var assert = require('assert'); var path = require('path'); var match = false; var isDebug = process.features.debug; var debugPaths = [path.normalize(path.join(__dirname, '..', '..', 'out', 'Debug', 'node')), path.normalize(path.join(__dirname, '..', '..', 'Debug', 'node'))]; var defaultPaths = [path.normalize(path.join(__dirname, '..', '..', 'out', 'Release', 'node')), path.normalize(path.join(__dirname, '..', '..', 'Release', 'node'))]; console.error('debugPaths: ' + debugPaths); console.error('defaultPaths: ' + defaultPaths); console.error('process.execPath: ' + process.execPath); if (isDebug) { debugPaths.forEach(function(path) { match = match || process.execPath.indexOf(path) == 0; }); } else { defaultPaths.forEach(function(path) { match = match || process.execPath.indexOf(path) == 0; }); } assert.ok(match); node-v0.10.25~dfsg2/test/simple/test-net-create-connection.js0000644000000000000000000000341712270121457022571 0ustar rootroot// Copyright Joyent, Inc. and other Node contributors. // // Permission is hereby granted, free of charge, to any person obtaining a // copy of this software and associated documentation files (the // "Software"), to deal in the Software without restriction, including // without limitation the rights to use, copy, modify, merge, publish, // distribute, sublicense, and/or sell copies of the Software, and to permit // persons to whom the Software is furnished to do so, subject to the // following conditions: // // The above copyright notice and this permission notice shall be included // in all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS // OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF // MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN // NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, // DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR // OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE // USE OR OTHER DEALINGS IN THE SOFTWARE. var common = require('../common'); var assert = require('assert'); var net = require('net'); var tcpPort = common.PORT; var clientConnected = 0; var serverConnected = 0; var server = net.createServer(function(socket) { socket.end(); if (++serverConnected === 4) { server.close(); } }); server.listen(tcpPort, 'localhost', function() { function cb() { ++clientConnected; } net.createConnection(tcpPort).on('connect', cb); net.createConnection(tcpPort, 'localhost').on('connect', cb); net.createConnection(tcpPort, cb); net.createConnection(tcpPort, 'localhost', cb); }); process.on('exit', function() { assert.equal(clientConnected, 4); }); node-v0.10.25~dfsg2/test/simple/test-https-byteswritten.js0000644000000000000000000000400712270121457022304 0ustar rootroot// Copyright Joyent, Inc. and other Node contributors. // // Permission is hereby granted, free of charge, to any person obtaining a // copy of this software and associated documentation files (the // "Software"), to deal in the Software without restriction, including // without limitation the rights to use, copy, modify, merge, publish, // distribute, sublicense, and/or sell copies of the Software, and to permit // persons to whom the Software is furnished to do so, subject to the // following conditions: // // The above copyright notice and this permission notice shall be included // in all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS // OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF // MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN // NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, // DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR // OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE // USE OR OTHER DEALINGS IN THE SOFTWARE. if (!process.versions.openssl) { console.error('Skipping because node compiled without OpenSSL.'); process.exit(0); } var common = require('../common'); var assert = require('assert'); var fs = require('fs'); var http = require('http'); var https = require('https'); var options = { key: fs.readFileSync(common.fixturesDir + '/keys/agent1-key.pem'), cert: fs.readFileSync(common.fixturesDir + '/keys/agent1-cert.pem') }; var body = 'hello world\n'; var httpsServer = https.createServer(options, function(req, res) { res.on('finish', function() { assert(typeof(req.connection.bytesWritten) === 'number'); assert(req.connection.bytesWritten > 0); httpsServer.close(); console.log('ok'); }); res.writeHead(200, { 'Content-Type': 'text/plain' }); res.end(body); }); httpsServer.listen(common.PORT, function() { https.get({ port: common.PORT, rejectUnauthorized: false }); }); node-v0.10.25~dfsg2/test/simple/test-stream2-readable-wrap.js0000644000000000000000000000567512270121457022476 0ustar rootroot// Copyright Joyent, Inc. and other Node contributors. // // Permission is hereby granted, free of charge, to any person obtaining a // copy of this software and associated documentation files (the // "Software"), to deal in the Software without restriction, including // without limitation the rights to use, copy, modify, merge, publish, // distribute, sublicense, and/or sell copies of the Software, and to permit // persons to whom the Software is furnished to do so, subject to the // following conditions: // // The above copyright notice and this permission notice shall be included // in all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS // OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF // MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN // NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, // DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR // OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE // USE OR OTHER DEALINGS IN THE SOFTWARE. var common = require('../common'); var assert = require('assert'); var Readable = require('_stream_readable'); var Writable = require('_stream_writable'); var EE = require('events').EventEmitter; var testRuns = 0, completedRuns = 0; function runTest(highWaterMark, objectMode, produce) { testRuns++; var old = new EE; var r = new Readable({ highWaterMark: highWaterMark, objectMode: objectMode }); assert.equal(r, r.wrap(old)); var ended = false; r.on('end', function() { ended = true; }); var pauses = 0; var resumes = 0; old.pause = function() { pauses++; old.emit('pause'); flowing = false; }; old.resume = function() { resumes++; old.emit('resume'); flow(); }; var flowing; var chunks = 10; var oldEnded = false; var expected = []; function flow() { flowing = true; while (flowing && chunks-- > 0) { var item = produce(); expected.push(item); console.log('emit', chunks); old.emit('data', item); } if (chunks <= 0) { oldEnded = true; console.log('old end', chunks, flowing); old.emit('end'); } } var w = new Writable({ highWaterMark: highWaterMark * 2, objectMode: objectMode }); var written = []; w._write = function(chunk, encoding, cb) { console.log(chunk); written.push(chunk); setTimeout(cb); }; w.on('finish', function() { completedRuns++; performAsserts(); }); r.pipe(w); flow(); function performAsserts() { assert(ended); assert(oldEnded); assert.deepEqual(written, expected); assert.equal(pauses, 10); assert.equal(resumes, 9); } } runTest(10, false, function(){ return new Buffer('xxxxxxxxxx'); }); runTest(1, true, function(){ return { foo: 'bar' }; }); process.on('exit', function() { assert.equal(testRuns, completedRuns); console.log('ok'); }); node-v0.10.25~dfsg2/test/simple/test-http-1.0-keep-alive.js0000644000000000000000000001044112270121457021673 0ustar rootroot// Copyright Joyent, Inc. and other Node contributors. // // Permission is hereby granted, free of charge, to any person obtaining a // copy of this software and associated documentation files (the // "Software"), to deal in the Software without restriction, including // without limitation the rights to use, copy, modify, merge, publish, // distribute, sublicense, and/or sell copies of the Software, and to permit // persons to whom the Software is furnished to do so, subject to the // following conditions: // // The above copyright notice and this permission notice shall be included // in all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS // OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF // MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN // NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, // DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR // OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE // USE OR OTHER DEALINGS IN THE SOFTWARE. var common = require('../common'); var assert = require('assert'); var http = require('http'); var net = require('net'); // Check that our HTTP server correctly handles HTTP/1.0 keep-alive requests. check([{ name: 'keep-alive, no TE header', requests: [{ expectClose: true, data: 'POST / HTTP/1.0\r\n' + 'Connection: keep-alive\r\n' + '\r\n' }, { expectClose: true, data: 'POST / HTTP/1.0\r\n' + 'Connection: keep-alive\r\n' + '\r\n' }], responses: [{ headers: {'Connection': 'keep-alive'}, chunks: ['OK'] }, { chunks: [] }] }, { name: 'keep-alive, with TE: chunked', requests: [{ expectClose: false, data: 'POST / HTTP/1.0\r\n' + 'Connection: keep-alive\r\n' + 'TE: chunked\r\n' + '\r\n' }, { expectClose: true, data: 'POST / HTTP/1.0\r\n' + '\r\n' }], responses: [{ headers: {'Connection': 'keep-alive'}, chunks: ['OK'] }, { chunks: [] }] }, { name: 'keep-alive, with Transfer-Encoding: chunked', requests: [{ expectClose: false, data: 'POST / HTTP/1.0\r\n' + 'Connection: keep-alive\r\n' + '\r\n' }, { expectClose: true, data: 'POST / HTTP/1.0\r\n' + '\r\n' }], responses: [{ headers: {'Connection': 'keep-alive', 'Transfer-Encoding': 'chunked'}, chunks: ['OK'] }, { chunks: [] }] }, { name: 'keep-alive, with Content-Length', requests: [{ expectClose: false, data: 'POST / HTTP/1.0\r\n' + 'Connection: keep-alive\r\n' + '\r\n' }, { expectClose: true, data: 'POST / HTTP/1.0\r\n' + '\r\n' }], responses: [{ headers: {'Connection': 'keep-alive', 'Content-Length': '2'}, chunks: ['OK'] }, { chunks: [] }] }]); function check(tests) { var test = tests[0]; if (test) http.createServer(server).listen(common.PORT, '127.0.0.1', client); var current = 0; function next() { check(tests.slice(1)); } function server(req, res) { if (current + 1 === test.responses.length) this.close(); var ctx = test.responses[current]; console.error('< SERVER SENDING RESPONSE', ctx); res.writeHead(200, ctx.headers); ctx.chunks.slice(0, -1).forEach(function(chunk) { res.write(chunk) }); res.end(ctx.chunks[ctx.chunks.length - 1]); } function client() { if (current === test.requests.length) return next(); var conn = net.createConnection(common.PORT, '127.0.0.1', connected); function connected() { var ctx = test.requests[current]; console.error(' > CLIENT SENDING REQUEST', ctx); conn.setEncoding('utf8'); conn.write(ctx.data); function onclose() { console.error(' > CLIENT CLOSE'); if (!ctx.expectClose) throw new Error('unexpected close'); client(); } conn.on('close', onclose); function ondata(s) { console.error(' > CLIENT ONDATA %j %j', s.length, s.toString()); current++; if (ctx.expectClose) return; conn.removeListener('close', onclose); conn.removeListener('data', ondata);; connected(); } conn.on('data', ondata); } } } node-v0.10.25~dfsg2/test/simple/test-https-pfx.js0000644000000000000000000000375612270121457020350 0ustar rootroot// Copyright Joyent, Inc. and other Node contributors. // // Permission is hereby granted, free of charge, to any person obtaining a // copy of this software and associated documentation files (the // "Software"), to deal in the Software without restriction, including // without limitation the rights to use, copy, modify, merge, publish, // distribute, sublicense, and/or sell copies of the Software, and to permit // persons to whom the Software is furnished to do so, subject to the // following conditions: // // The above copyright notice and this permission notice shall be included // in all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS // OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF // MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN // NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, // DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR // OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE // USE OR OTHER DEALINGS IN THE SOFTWARE. var common = require('../common'); var assert = require('assert'); var https = require('https'); var fs = require('fs'); var pfx = fs.readFileSync(common.fixturesDir + '/test_cert.pfx'); var options = { host: '127.0.0.1', port: common.PORT, path: '/', pfx: pfx, passphrase: 'sample', requestCert: true, rejectUnauthorized: false }; var server = https.createServer(options, function(req, res) { assert.equal(req.socket.authorized, false); // not a client cert assert.equal(req.socket.authorizationError, 'DEPTH_ZERO_SELF_SIGNED_CERT'); res.writeHead(200); res.end('OK'); }); server.listen(options.port, options.host, function() { var data = ''; https.get(options, function(res) { res.on('data', function(data_) { data += data_ }); res.on('end', function() { server.close() }); }); process.on('exit', function() { assert.equal(data, 'OK'); }); }); node-v0.10.25~dfsg2/test/simple/test-fs-write-stream-err.js0000644000000000000000000000445312270121457022225 0ustar rootroot// Copyright Joyent, Inc. and other Node contributors. // // Permission is hereby granted, free of charge, to any person obtaining a // copy of this software and associated documentation files (the // "Software"), to deal in the Software without restriction, including // without limitation the rights to use, copy, modify, merge, publish, // distribute, sublicense, and/or sell copies of the Software, and to permit // persons to whom the Software is furnished to do so, subject to the // following conditions: // // The above copyright notice and this permission notice shall be included // in all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS // OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF // MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN // NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, // DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR // OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE // USE OR OTHER DEALINGS IN THE SOFTWARE. var common = require('../common'); var assert = require('assert'); var fs = require('fs'); var stream = fs.createWriteStream(common.tmpDir + '/out', { highWaterMark: 10 }); var err = new Error('BAM'); var write = fs.write; var writeCalls = 0; fs.write = function() { switch (writeCalls++) { case 0: console.error('first write'); // first time is ok. return write.apply(fs, arguments); case 1: // then it breaks console.error('second write'); var cb = arguments[arguments.length - 1]; return process.nextTick(function() { cb(err); }); default: // and should not be called again! throw new Error('BOOM!'); } }; fs.close = common.mustCall(function(fd_, cb) { console.error('fs.close', fd_, stream.fd); assert.equal(fd_, stream.fd); process.nextTick(cb); }); stream.on('error', common.mustCall(function(err_) { console.error('error handler'); assert.equal(stream.fd, null); assert.equal(err_, err); })); stream.write(new Buffer(256), function() { console.error('first cb'); stream.write(new Buffer(256), common.mustCall(function(err_) { console.error('second cb'); assert.equal(err_, err); })); }); node-v0.10.25~dfsg2/test/simple/test-process-hrtime.js0000644000000000000000000000335412270121457021351 0ustar rootroot// Copyright Joyent, Inc. and other Node contributors. // // Permission is hereby granted, free of charge, to any person obtaining a // copy of this software and associated documentation files (the // "Software"), to deal in the Software without restriction, including // without limitation the rights to use, copy, modify, merge, publish, // distribute, sublicense, and/or sell copies of the Software, and to permit // persons to whom the Software is furnished to do so, subject to the // following conditions: // // The above copyright notice and this permission notice shall be included // in all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS // OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF // MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN // NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, // DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR // OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE // USE OR OTHER DEALINGS IN THE SOFTWARE. var common = require('../common'); var assert = require('assert'); // the default behavior, return an Array "tuple" of numbers var tuple = process.hrtime(); // validate the default behavior validateTuple(tuple); // validate that passing an existing tuple returns another valid tuple validateTuple(process.hrtime(tuple)); // test that only an Array may be passed to process.hrtime() assert.throws(function() { process.hrtime(1); }); function validateTuple(tuple) { assert(Array.isArray(tuple)); assert.equal(2, tuple.length); tuple.forEach(function (v) { assert.equal('number', typeof v); assert(isFinite(v)); }); } node-v0.10.25~dfsg2/test/simple/test-regress-GH-1531.js0000644000000000000000000000403512270121457020737 0ustar rootroot// Copyright Joyent, Inc. and other Node contributors. // // Permission is hereby granted, free of charge, to any person obtaining a // copy of this software and associated documentation files (the // "Software"), to deal in the Software without restriction, including // without limitation the rights to use, copy, modify, merge, publish, // distribute, sublicense, and/or sell copies of the Software, and to permit // persons to whom the Software is furnished to do so, subject to the // following conditions: // // The above copyright notice and this permission notice shall be included // in all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS // OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF // MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN // NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, // DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR // OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE // USE OR OTHER DEALINGS IN THE SOFTWARE. if (!process.versions.openssl) { console.error('Skipping because node compiled without OpenSSL.'); process.exit(0); } var https = require('https'); var assert = require('assert'); var fs = require('fs'); var common = require('../common'); var options = { key: fs.readFileSync(common.fixturesDir + '/keys/agent1-key.pem'), cert: fs.readFileSync(common.fixturesDir + '/keys/agent1-cert.pem') }; var gotCallback = false; var server = https.createServer(options, function(req, res) { res.writeHead(200); res.end('hello world\n'); }); server.listen(common.PORT, function() { https.get({ agent: false, path: '/', port: common.PORT, rejectUnauthorized: false }, function(res) { console.error(res.statusCode); gotCallback = true; server.close(); }).on('error', function(e) { console.error(e.message); process.exit(1); }); }); process.on('exit', function() { assert.ok(gotCallback); }); node-v0.10.25~dfsg2/test/simple/test-child-process-fork-and-spawn.js0000644000000000000000000000347612270121457023776 0ustar rootroot// Copyright Joyent, Inc. and other Node contributors. // // Permission is hereby granted, free of charge, to any person obtaining a // copy of this software and associated documentation files (the // "Software"), to deal in the Software without restriction, including // without limitation the rights to use, copy, modify, merge, publish, // distribute, sublicense, and/or sell copies of the Software, and to permit // persons to whom the Software is furnished to do so, subject to the // following conditions: // // The above copyright notice and this permission notice shall be included // in all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS // OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF // MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN // NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, // DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR // OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE // USE OR OTHER DEALINGS IN THE SOFTWARE. var common = require('../common'); var assert = require('assert'); var spawn = require('child_process').spawn; var fork = require('child_process').fork; // Fork, then spawn. The spawned process should not hang. switch (process.argv[2] || '') { case '': fork(__filename, ['fork']).on('exit', checkExit); process.on('exit', haveExit); break; case 'fork': spawn(process.execPath, [__filename, 'spawn']).on('exit', checkExit); process.on('exit', haveExit); break; case 'spawn': break; default: assert(0); } var seenExit = false; function checkExit(statusCode) { seenExit = true; assert.equal(statusCode, 0); process.nextTick(process.exit); } function haveExit() { assert.equal(seenExit, true); } node-v0.10.25~dfsg2/test/simple/test-pipe-return-val.js0000644000000000000000000000272512270121457021440 0ustar rootroot// Copyright Joyent, Inc. and other Node contributors. // // Permission is hereby granted, free of charge, to any person obtaining a // copy of this software and associated documentation files (the // "Software"), to deal in the Software without restriction, including // without limitation the rights to use, copy, modify, merge, publish, // distribute, sublicense, and/or sell copies of the Software, and to permit // persons to whom the Software is furnished to do so, subject to the // following conditions: // // The above copyright notice and this permission notice shall be included // in all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS // OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF // MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN // NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, // DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR // OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE // USE OR OTHER DEALINGS IN THE SOFTWARE. // This test ensures SourceStream.pipe(DestStream) returns DestStream var common = require('../common'); var Stream = require('stream').Stream; var assert = require('assert'); var util = require('util'); var sourceStream = new Stream(); var destStream = new Stream(); var result = sourceStream.pipe(destStream); assert.strictEqual(result, destStream); node-v0.10.25~dfsg2/test/simple/test-socket-write-after-fin.js0000644000000000000000000000406512270121457022676 0ustar rootroot// Copyright Joyent, Inc. and other Node contributors. // // Permission is hereby granted, free of charge, to any person obtaining a // copy of this software and associated documentation files (the // "Software"), to deal in the Software without restriction, including // without limitation the rights to use, copy, modify, merge, publish, // distribute, sublicense, and/or sell copies of the Software, and to permit // persons to whom the Software is furnished to do so, subject to the // following conditions: // // The above copyright notice and this permission notice shall be included // in all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS // OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF // MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN // NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, // DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR // OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE // USE OR OTHER DEALINGS IN THE SOFTWARE. var common = require('../common'); var assert = require('assert'); var net = require('net'); var serverData = ''; var gotServerEnd = false; var clientData = ''; var gotClientEnd = false; var server = net.createServer({ allowHalfOpen: true }, function(sock) { sock.setEncoding('utf8'); sock.on('data', function(c) { serverData += c; }); sock.on('end', function() { gotServerEnd = true sock.end(serverData); server.close(); }); }); server.listen(common.PORT); var sock = net.connect(common.PORT); sock.setEncoding('utf8'); sock.on('data', function(c) { clientData += c; }); sock.on('end', function() { gotClientEnd = true; }); process.on('exit', function() { assert.equal(serverData, clientData); assert.equal(serverData, 'hello1hello2hello3\nTHUNDERMUSCLE!'); assert(gotClientEnd); assert(gotServerEnd); console.log('ok'); }); sock.write('hello1'); sock.write('hello2'); sock.write('hello3\n'); sock.end('THUNDERMUSCLE!'); node-v0.10.25~dfsg2/test/simple/test-event-emitter-memory-leak.js0000644000000000000000000000341112270121457023407 0ustar rootroot// Copyright Joyent, Inc. and other Node contributors. // // Permission is hereby granted, free of charge, to any person obtaining a // copy of this software and associated documentation files (the // "Software"), to deal in the Software without restriction, including // without limitation the rights to use, copy, modify, merge, publish, // distribute, sublicense, and/or sell copies of the Software, and to permit // persons to whom the Software is furnished to do so, subject to the // following conditions: // // The above copyright notice and this permission notice shall be included // in all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS // OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF // MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN // NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, // DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR // OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE // USE OR OTHER DEALINGS IN THE SOFTWARE. // Flags: --expose-gc // Add and remove a lot of different events to an EventEmitter, then check // that we didn't leak the event names. var common = require('../common'); var assert = require('assert'); var events = require('events'); assert.equal(typeof gc, 'function', 'Run this test with --expose-gc'); gc(); var before = process.memoryUsage().heapUsed; var e = new events.EventEmitter(); for (var i = 0; i < 2.5e5; ++i) { var name = 'a-pretty-long-event-name-' + i; e.on(name, assert.fail); e.removeListener(name, assert.fail); } gc(); var after = process.memoryUsage().heapUsed; assert(after - before < 1024*1024, 'EventEmitter leaks event names.'); node-v0.10.25~dfsg2/test/simple/test-stream-unshift-empty-chunk.js0000644000000000000000000000464212270121457023621 0ustar rootroot// Copyright Joyent, Inc. and other Node contributors. // // Permission is hereby granted, free of charge, to any person obtaining a // copy of this software and associated documentation files (the // "Software"), to deal in the Software without restriction, including // without limitation the rights to use, copy, modify, merge, publish, // distribute, sublicense, and/or sell copies of the Software, and to permit // persons to whom the Software is furnished to do so, subject to the // following conditions: // // The above copyright notice and this permission notice shall be included // in all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS // OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF // MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN // NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, // DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR // OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE // USE OR OTHER DEALINGS IN THE SOFTWARE. var common = require('../common'); var assert = require('assert'); // This test verifies that stream.unshift(Buffer(0)) or // stream.unshift('') does not set state.reading=false. var Readable = require('stream').Readable; var r = new Readable(); var nChunks = 10; var chunk = new Buffer(10); chunk.fill('x'); r._read = function(n) { setTimeout(function() { r.push(--nChunks === 0 ? null : chunk); }); }; var readAll = false; var seen = []; r.on('readable', function() { var chunk; while (chunk = r.read()) { seen.push(chunk.toString()); // simulate only reading a certain amount of the data, // and then putting the rest of the chunk back into the // stream, like a parser might do. We just fill it with // 'y' so that it's easy to see which bits were touched, // and which were not. var putBack = new Buffer(readAll ? 0 : 5); putBack.fill('y'); readAll = !readAll; r.unshift(putBack); } }); var expect = [ 'xxxxxxxxxx', 'yyyyy', 'xxxxxxxxxx', 'yyyyy', 'xxxxxxxxxx', 'yyyyy', 'xxxxxxxxxx', 'yyyyy', 'xxxxxxxxxx', 'yyyyy', 'xxxxxxxxxx', 'yyyyy', 'xxxxxxxxxx', 'yyyyy', 'xxxxxxxxxx', 'yyyyy', 'xxxxxxxxxx', 'yyyyy' ]; r.on('end', function() { assert.deepEqual(seen, expect); console.log('ok'); }); node-v0.10.25~dfsg2/test/simple/test-crypto-padding-aes256.js0000644000000000000000000000524312270121457022333 0ustar rootroot// Copyright Joyent, Inc. and other Node contributors. // // Permission is hereby granted, free of charge, to any person obtaining a // copy of this software and associated documentation files (the // "Software"), to deal in the Software without restriction, including // without limitation the rights to use, copy, modify, merge, publish, // distribute, sublicense, and/or sell copies of the Software, and to permit // persons to whom the Software is furnished to do so, subject to the // following conditions: // // The above copyright notice and this permission notice shall be included // in all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS // OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF // MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN // NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, // DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR // OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE // USE OR OTHER DEALINGS IN THE SOFTWARE. var common = require('../common'); var assert = require('assert'); try { var crypto = require('crypto'); } catch (e) { console.log('Not compiled with OpenSSL support.'); process.exit(); } crypto.DEFAULT_ENCODING = 'buffer'; function aes256(decipherFinal) { var iv = new Buffer('00000000000000000000000000000000', 'hex'); var key = new Buffer('0123456789abcdef0123456789abcdef' + '0123456789abcdef0123456789abcdef', 'hex'); function encrypt(val, pad) { var c = crypto.createCipheriv('aes256', key, iv); c.setAutoPadding(pad); return c.update(val, 'utf8', 'binary') + c.final('binary'); } function decrypt(val, pad) { var c = crypto.createDecipheriv('aes256', key, iv); c.setAutoPadding(pad); return c.update(val, 'binary', 'utf8') + c[decipherFinal]('utf8'); } // echo 0123456789abcdef0123456789abcdef \ // | openssl enc -e -aes256 -nopad -K -iv \ // | openssl enc -d -aes256 -nopad -K -iv var plaintext = '0123456789abcdef0123456789abcdef'; // multiple of block size var encrypted = encrypt(plaintext, false); var decrypted = decrypt(encrypted, false); assert.equal(decrypted, plaintext); // echo 0123456789abcdef0123456789abcde \ // | openssl enc -e -aes256 -K -iv \ // | openssl enc -d -aes256 -K -iv plaintext = '0123456789abcdef0123456789abcde'; // not a multiple encrypted = encrypt(plaintext, true); decrypted = decrypt(encrypted, true); assert.equal(decrypted, plaintext); } aes256('final'); aes256('finaltol'); node-v0.10.25~dfsg2/test/simple/test-child-process-recv-handle.js0000644000000000000000000000560112270121457023327 0ustar rootroot// Copyright Joyent, Inc. and other Node contributors. // // Permission is hereby granted, free of charge, to any person obtaining a // copy of this software and associated documentation files (the // "Software"), to deal in the Software without restriction, including // without limitation the rights to use, copy, modify, merge, publish, // distribute, sublicense, and/or sell copies of the Software, and to permit // persons to whom the Software is furnished to do so, subject to the // following conditions: // // The above copyright notice and this permission notice shall be included // in all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS // OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF // MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN // NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, // DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR // OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE // USE OR OTHER DEALINGS IN THE SOFTWARE. // Test that a Linux specific quirk in the handle passing protocol is handled // correctly. See https://github.com/joyent/node/issues/5330 for details. var common = require('../common'); var assert = require('assert'); var net = require('net'); var spawn = require('child_process').spawn; if (process.argv[2] === 'worker') worker(); else master(); function master() { // spawn() can only create one IPC channel so we use stdin/stdout as an // ad-hoc command channel. var proc = spawn(process.execPath, [__filename, 'worker'], { stdio: ['pipe', 'pipe', 'pipe', 'ipc'] }); var handle = null; proc.on('exit', function() { handle.close(); }); proc.stdout.on('data', function(data) { assert.equal(data, 'ok\r\n'); net.createServer(assert.fail).listen(common.PORT, function() { handle = this._handle; proc.send('one'); proc.send('two', handle); proc.send('three'); proc.stdin.write('ok\r\n'); }); }); proc.stderr.pipe(process.stderr); } function worker() { process._channel.readStop(); // Make messages batch up. process.stdout.ref(); process.stdout.write('ok\r\n'); process.stdin.once('data', function(data) { assert.equal(data, 'ok\r\n'); process._channel.readStart(); }); var n = 0; process.on('message', function(msg, handle) { n += 1; if (n === 1) { assert.equal(msg, 'one'); assert.equal(handle, undefined); } else if (n === 2) { assert.equal(msg, 'two'); assert.equal(typeof handle, 'object'); // Also matches null, therefore... assert.ok(handle); // also check that it's truthy. handle.close(); } else if (n === 3) { assert.equal(msg, 'three'); assert.equal(handle, undefined); process.exit(); } }); } node-v0.10.25~dfsg2/test/simple/test-tls-honorcipherorder.js0000644000000000000000000000610712270121457022560 0ustar rootroot// Copyright Joyent, Inc. and other Node contributors. // // Permission is hereby granted, free of charge, to any person obtaining a // copy of this software and associated documentation files (the // "Software"), to deal in the Software without restriction, including // without limitation the rights to use, copy, modify, merge, publish, // distribute, sublicense, and/or sell copies of the Software, and to permit // persons to whom the Software is furnished to do so, subject to the // following conditions: // // The above copyright notice and this permission notice shall be included // in all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS // OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF // MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN // NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, // DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR // OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE // USE OR OTHER DEALINGS IN THE SOFTWARE. var common = require('../common'); var assert = require('assert'); var tls = require('tls'); var fs = require('fs'); var nconns = 0; // test only in TLSv1 to use DES which is no longer supported TLSv1.2 // to be safe when the default method is updated in the future var SSL_Method = 'TLSv1_method'; var localhost = '127.0.0.1'; process.on('exit', function() { assert.equal(nconns, 4); }); function test(honorCipherOrder, clientCipher, expectedCipher, cb) { var soptions = { secureProtocol: SSL_Method, key: fs.readFileSync(common.fixturesDir + '/keys/agent2-key.pem'), cert: fs.readFileSync(common.fixturesDir + '/keys/agent2-cert.pem'), ciphers: 'AES256-SHA:RC4-SHA:DES-CBC-SHA', honorCipherOrder: !!honorCipherOrder }; var server = tls.createServer(soptions, function(cleartextStream) { nconns++; }); server.listen(common.PORT, localhost, function() { var coptions = { rejectUnauthorized: false, secureProtocol: SSL_Method }; if (clientCipher) { coptions.ciphers = clientCipher; } var client = tls.connect(common.PORT, localhost, coptions, function() { var cipher = client.getCipher(); client.end(); server.close(); assert.equal(cipher.name, expectedCipher); if (cb) cb(); }); }); } test1(); function test1() { // Client has the preference of cipher suites by default test(false, 'DES-CBC-SHA:RC4-SHA:AES256-SHA','DES-CBC-SHA', test2); } function test2() { // Server has the preference of cipher suites where AES256-SHA is in // the first. test(true, 'DES-CBC-SHA:RC4-SHA:AES256-SHA', 'AES256-SHA', test3); } function test3() { // Server has the preference of cipher suites. RC4-SHA is given // higher priority over DES-CBC-SHA among client cipher suites. test(true, 'DES-CBC-SHA:RC4-SHA', 'RC4-SHA', test4); } function test4() { // As client has only one cipher, server has no choice in regardless // of honorCipherOrder. test(true, 'DES-CBC-SHA', 'DES-CBC-SHA'); } node-v0.10.25~dfsg2/test/simple/test-fs-open.js0000644000000000000000000000347012270121457017753 0ustar rootroot// Copyright Joyent, Inc. and other Node contributors. // // Permission is hereby granted, free of charge, to any person obtaining a // copy of this software and associated documentation files (the // "Software"), to deal in the Software without restriction, including // without limitation the rights to use, copy, modify, merge, publish, // distribute, sublicense, and/or sell copies of the Software, and to permit // persons to whom the Software is furnished to do so, subject to the // following conditions: // // The above copyright notice and this permission notice shall be included // in all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS // OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF // MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN // NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, // DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR // OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE // USE OR OTHER DEALINGS IN THE SOFTWARE. var constants = require('constants'); var common = require('../common'); var assert = require('assert'); var fs = require('fs'); var caughtException = false; try { // should throw ENOENT, not EBADF // see https://github.com/joyent/node/pull/1228 fs.openSync('/path/to/file/that/does/not/exist', 'r'); } catch (e) { assert.equal(e.code, 'ENOENT'); caughtException = true; } assert.ok(caughtException); var openFd; fs.open(__filename, 'r', function(err, fd) { if (err) { throw err; } openFd = fd; }); var openFd2; fs.open(__filename, 'rs', function(err, fd) { if (err) { throw err; } openFd2 = fd; }); process.on('exit', function() { assert.ok(openFd); assert.ok(openFd2); }); node-v0.10.25~dfsg2/test/simple/test-child-process-disconnect.js0000644000000000000000000000610112270121457023264 0ustar rootroot// Copyright Joyent, Inc. and other Node contributors. // // Permission is hereby granted, free of charge, to any person obtaining a // copy of this software and associated documentation files (the // "Software"), to deal in the Software without restriction, including // without limitation the rights to use, copy, modify, merge, publish, // distribute, sublicense, and/or sell copies of the Software, and to permit // persons to whom the Software is furnished to do so, subject to the // following conditions: // // The above copyright notice and this permission notice shall be included // in all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS // OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF // MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN // NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, // DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR // OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE // USE OR OTHER DEALINGS IN THE SOFTWARE. var assert = require('assert'); var common = require('../common'); var fork = require('child_process').fork; var net = require('net'); // child if (process.argv[2] === 'child') { var server = net.createServer(); server.on('connection', function(socket) { socket.resume(); process.on('disconnect', function() { socket.end((process.connected).toString()); }); // when the socket is closed, we will close the server // allowing the process to self terminate socket.on('end', function() { server.close(); }); socket.write('ready'); }); // when the server is ready tell parent server.on('listening', function() { process.send('ready'); }); server.listen(common.PORT); } else { // testcase var child = fork(process.argv[1], ['child']); var childFlag = false; var childSelfTerminate = false; var parentEmit = false; var parentFlag = false; // when calling .disconnect the event should emit // and the disconnected flag should be true. child.on('disconnect', function() { parentEmit = true; parentFlag = child.connected; }); // the process should also self terminate without using signals child.on('exit', function() { childSelfTerminate = true; }); // when child is listning child.on('message', function(msg) { if (msg === 'ready') { // connect to child using TCP to know if disconnect was emitted var socket = net.connect(common.PORT); socket.on('data', function(data) { data = data.toString(); // ready to be disconnected if (data === 'ready') { child.disconnect(); assert.throws(child.disconnect.bind(child), Error); return; } // disconnect is emitted childFlag = (data === 'true'); }); } }); process.on('exit', function() { assert.equal(childFlag, false); assert.equal(parentFlag, false); assert.ok(childSelfTerminate); assert.ok(parentEmit); }); } node-v0.10.25~dfsg2/test/simple/test-net-can-reset-timeout.js0000644000000000000000000000370412270121457022535 0ustar rootroot// Copyright Joyent, Inc. and other Node contributors. // // Permission is hereby granted, free of charge, to any person obtaining a // copy of this software and associated documentation files (the // "Software"), to deal in the Software without restriction, including // without limitation the rights to use, copy, modify, merge, publish, // distribute, sublicense, and/or sell copies of the Software, and to permit // persons to whom the Software is furnished to do so, subject to the // following conditions: // // The above copyright notice and this permission notice shall be included // in all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS // OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF // MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN // NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, // DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR // OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE // USE OR OTHER DEALINGS IN THE SOFTWARE. var net = require('net'); var common = require('../common'); var assert = require('assert'); var timeoutCount = 0; var server = net.createServer(function(stream) { stream.setTimeout(100); stream.resume(); stream.on('timeout', function() { console.log('timeout'); // try to reset the timeout. stream.write('WHAT.'); // don't worry, the socket didn't *really* time out, we're just thinking // it did. timeoutCount += 1; }); stream.on('end', function() { console.log('server side end'); stream.end(); }); }); server.listen(common.PORT, function() { var c = net.createConnection(common.PORT); c.on('data', function() { c.end(); }); c.on('end', function() { console.log('client side end'); server.close(); }); }); process.on('exit', function() { assert.equal(1, timeoutCount); }); node-v0.10.25~dfsg2/test/simple/test-crypto-ecb.js0000644000000000000000000000367212270121457020457 0ustar rootroot// Copyright Joyent, Inc. and other Node contributors. // // Permission is hereby granted, free of charge, to any person obtaining a // copy of this software and associated documentation files (the // "Software"), to deal in the Software without restriction, including // without limitation the rights to use, copy, modify, merge, publish, // distribute, sublicense, and/or sell copies of the Software, and to permit // persons to whom the Software is furnished to do so, subject to the // following conditions: // // The above copyright notice and this permission notice shall be included // in all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS // OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF // MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN // NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, // DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR // OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE // USE OR OTHER DEALINGS IN THE SOFTWARE. var common = require('../common'); var assert = require('assert'); try { var crypto = require('crypto'); } catch (e) { console.log('Not compiled with OPENSSL support.'); process.exit(); } crypto.DEFAULT_ENCODING = 'buffer'; // Testing whether EVP_CipherInit_ex is functioning correctly. // Reference: bug#1997 (function() { var encrypt = crypto.createCipheriv('BF-ECB', 'SomeRandomBlahz0c5GZVnR', ''); var hex = encrypt.update('Hello World!', 'ascii', 'hex'); hex += encrypt.final('hex'); assert.equal(hex.toUpperCase(), '6D385F424AAB0CFBF0BB86E07FFB7D71'); }()); (function() { var decrypt = crypto.createDecipheriv('BF-ECB', 'SomeRandomBlahz0c5GZVnR', ''); var msg = decrypt.update('6D385F424AAB0CFBF0BB86E07FFB7D71', 'hex', 'ascii'); msg += decrypt.final('ascii'); assert.equal(msg, 'Hello World!'); }()); node-v0.10.25~dfsg2/test/simple/net-socket-readystate.js0000644000000000000000000000355212270121457021647 0ustar rootroot// Copyright Joyent, Inc. and other Node contributors. // // Permission is hereby granted, free of charge, to any person obtaining a // copy of this software and associated documentation files (the // "Software"), to deal in the Software without restriction, including // without limitation the rights to use, copy, modify, merge, publish, // distribute, sublicense, and/or sell copies of the Software, and to permit // persons to whom the Software is furnished to do so, subject to the // following conditions: // // The above copyright notice and this permission notice shall be included // in all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS // OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF // MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN // NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, // DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR // OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE // USE OR OTHER DEALINGS IN THE SOFTWARE. var common = require('../common'); var net = require('net'); var assert = require('assert'); var sock = new net.Socket(); var server = net.createServer().listen(common.PORT, function() { assert(!sock.readable); assert(!sock.writable); assert.equal(sock.readyState, 'closed'); sock.connect(common.PORT, function() { assert.equal(sock.readable, true); assert.equal(sock.writable, true); assert.equal(sock.readyState, 'open'); sock.end(); assert(!sock.writable); assert.equal(sock.readyState, 'readOnly'); server.close(); sock.on('close', function() { assert(!sock.readable); assert(!sock.writable); assert.equal(sock.readyState, 'closed'); }); }); assert.equal(sock.readyState, 'opening'); }); node-v0.10.25~dfsg2/test/simple/test-tls-getcipher.js0000644000000000000000000000404512270121457021155 0ustar rootroot// Copyright Joyent, Inc. and other Node contributors. // // Permission is hereby granted, free of charge, to any person obtaining a // copy of this software and associated documentation files (the // "Software"), to deal in the Software without restriction, including // without limitation the rights to use, copy, modify, merge, publish, // distribute, sublicense, and/or sell copies of the Software, and to permit // persons to whom the Software is furnished to do so, subject to the // following conditions: // // The above copyright notice and this permission notice shall be included // in all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS // OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF // MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN // NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, // DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR // OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE // USE OR OTHER DEALINGS IN THE SOFTWARE. var common = require('../common'); var assert = require('assert'); var tls = require('tls'); var fs = require('fs'); var cipher_list = ['RC4-SHA', 'AES256-SHA']; var cipher_version_pattern = /TLS|SSL/; var options = { key: fs.readFileSync(common.fixturesDir + '/keys/agent2-key.pem'), cert: fs.readFileSync(common.fixturesDir + '/keys/agent2-cert.pem'), ciphers: cipher_list.join(':'), honorCipherOrder: true }; var nconns = 0; process.on('exit', function() { assert.equal(nconns, 1); }); var server = tls.createServer(options, function(cleartextStream) { nconns++; }); server.listen(common.PORT, '127.0.0.1', function() { var client = tls.connect({ host: '127.0.0.1', port: common.PORT, rejectUnauthorized: false }, function() { var cipher = client.getCipher(); assert.equal(cipher.name, cipher_list[0]); assert(cipher_version_pattern.test(cipher.version)); client.end(); server.close(); }); }); node-v0.10.25~dfsg2/test/simple/test-tls-passphrase.js0000644000000000000000000000432712270121457021357 0ustar rootroot// Copyright Joyent, Inc. and other Node contributors. // // Permission is hereby granted, free of charge, to any person obtaining a // copy of this software and associated documentation files (the // "Software"), to deal in the Software without restriction, including // without limitation the rights to use, copy, modify, merge, publish, // distribute, sublicense, and/or sell copies of the Software, and to permit // persons to whom the Software is furnished to do so, subject to the // following conditions: // // The above copyright notice and this permission notice shall be included // in all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS // OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF // MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN // NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, // DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR // OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE // USE OR OTHER DEALINGS IN THE SOFTWARE. if (!process.versions.openssl) { console.error('Skipping because node compiled without OpenSSL.'); process.exit(0); } var common = require('../common'); var assert = require('assert'); var tls = require('tls'); var fs = require('fs'); var path = require('path'); var key = fs.readFileSync(path.join(common.fixturesDir, 'pass-key.pem')); var cert = fs.readFileSync(path.join(common.fixturesDir, 'pass-cert.pem')); var server = tls.Server({ key: key, passphrase: 'passphrase', cert: cert, ca: [cert], requestCert: true, rejectUnauthorized: true }, function(s) { s.end(); }); var connectCount = 0; server.listen(common.PORT, function() { var c = tls.connect({ port: common.PORT, key: key, passphrase: 'passphrase', cert: cert, rejectUnauthorized: false }, function() { ++connectCount; }); c.on('end', function() { server.close(); }); }); assert.throws(function() { tls.connect({ port: common.PORT, key: key, passphrase: 'invalid', cert: cert, rejectUnauthorized: false }); }); process.on('exit', function() { assert.equal(connectCount, 1); }); node-v0.10.25~dfsg2/test/simple/test-zlib.js0000644000000000000000000001550112270121457017342 0ustar rootroot// Copyright Joyent, Inc. and other Node contributors. // // Permission is hereby granted, free of charge, to any person obtaining a // copy of this software and associated documentation files (the // "Software"), to deal in the Software without restriction, including // without limitation the rights to use, copy, modify, merge, publish, // distribute, sublicense, and/or sell copies of the Software, and to permit // persons to whom the Software is furnished to do so, subject to the // following conditions: // // The above copyright notice and this permission notice shall be included // in all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS // OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF // MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN // NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, // DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR // OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE // USE OR OTHER DEALINGS IN THE SOFTWARE. var common = require('../common.js'); var assert = require('assert'); var zlib = require('zlib'); var path = require('path'); var zlibPairs = [[zlib.Deflate, zlib.Inflate], [zlib.Gzip, zlib.Gunzip], [zlib.Deflate, zlib.Unzip], [zlib.Gzip, zlib.Unzip], [zlib.DeflateRaw, zlib.InflateRaw]]; // how fast to trickle through the slowstream var trickle = [128, 1024, 1024 * 1024]; // tunable options for zlib classes. // several different chunk sizes var chunkSize = [128, 1024, 1024 * 16, 1024 * 1024]; // this is every possible value. var level = [-1, 0, 1, 2, 3, 4, 5, 6, 7, 8, 9]; var windowBits = [8, 9, 10, 11, 12, 13, 14, 15]; var memLevel = [1, 2, 3, 4, 5, 6, 7, 8, 9]; var strategy = [0, 1, 2, 3, 4]; // it's nice in theory to test every combination, but it // takes WAY too long. Maybe a pummel test could do this? if (!process.env.PUMMEL) { trickle = [1024]; chunkSize = [1024 * 16]; level = [6]; memLevel = [8]; windowBits = [15]; strategy = [0]; } var fs = require('fs'); var testFiles = ['person.jpg', 'elipses.txt', 'empty.txt']; if (process.env.FAST) { zlibPairs = [[zlib.Gzip, zlib.Unzip]]; var testFiles = ['person.jpg']; } var tests = {}; testFiles.forEach(function(file) { tests[file] = fs.readFileSync(path.resolve(common.fixturesDir, file)); }); var util = require('util'); var stream = require('stream'); // stream that saves everything function BufferStream() { this.chunks = []; this.length = 0; this.writable = true; this.readable = true; } util.inherits(BufferStream, stream.Stream); BufferStream.prototype.write = function(c) { this.chunks.push(c); this.length += c.length; return true; }; BufferStream.prototype.end = function(c) { if (c) this.write(c); // flatten var buf = new Buffer(this.length); var i = 0; this.chunks.forEach(function(c) { c.copy(buf, i); i += c.length; }); this.emit('data', buf); this.emit('end'); return true; }; function SlowStream(trickle) { this.trickle = trickle; this.offset = 0; this.readable = this.writable = true; } util.inherits(SlowStream, stream.Stream); SlowStream.prototype.write = function() { throw new Error('not implemented, just call ss.end(chunk)'); }; SlowStream.prototype.pause = function() { this.paused = true; this.emit('pause'); }; SlowStream.prototype.resume = function() { var self = this; if (self.ended) return; self.emit('resume'); if (!self.chunk) return; self.paused = false; emit(); function emit() { if (self.paused) return; if (self.offset >= self.length) { self.ended = true; return self.emit('end'); } var end = Math.min(self.offset + self.trickle, self.length); var c = self.chunk.slice(self.offset, end); self.offset += c.length; self.emit('data', c); process.nextTick(emit); } }; SlowStream.prototype.end = function(chunk) { // walk over the chunk in blocks. var self = this; self.chunk = chunk; self.length = chunk.length; self.resume(); return self.ended; }; // for each of the files, make sure that compressing and // decompressing results in the same data, for every combination // of the options set above. var failures = 0; var total = 0; var done = 0; Object.keys(tests).forEach(function(file) { var test = tests[file]; chunkSize.forEach(function(chunkSize) { trickle.forEach(function(trickle) { windowBits.forEach(function(windowBits) { level.forEach(function(level) { memLevel.forEach(function(memLevel) { strategy.forEach(function(strategy) { zlibPairs.forEach(function(pair) { var Def = pair[0]; var Inf = pair[1]; var opts = { level: level, windowBits: windowBits, memLevel: memLevel, strategy: strategy }; total++; var def = new Def(opts); var inf = new Inf(opts); var ss = new SlowStream(trickle); var buf = new BufferStream(); // verify that the same exact buffer comes out the other end. buf.on('data', function(c) { var msg = file + ' ' + chunkSize + ' ' + JSON.stringify(opts) + ' ' + Def.name + ' -> ' + Inf.name; var ok = true; var testNum = ++done; for (var i = 0; i < Math.max(c.length, test.length); i++) { if (c[i] !== test[i]) { ok = false; failures++; break; } } if (ok) { console.log('ok ' + (testNum) + ' ' + msg); } else { console.log('not ok ' + (testNum) + ' ' + msg); console.log(' ...'); console.log(' testfile: ' + file); console.log(' type: ' + Def.name + ' -> ' + Inf.name); console.log(' position: ' + i); console.log(' options: ' + JSON.stringify(opts)); console.log(' expect: ' + test[i]); console.log(' actual: ' + c[i]); console.log(' chunkSize: ' + chunkSize); console.log(' ---'); } }); // the magic happens here. ss.pipe(def).pipe(inf).pipe(buf); ss.end(test); }); }); }); }); }); }); }); // sad stallman is sad. }); process.on('exit', function(code) { console.log('1..' + done); assert.equal(done, total, (total - done) + ' tests left unfinished'); assert.ok(!failures, 'some test failures'); }); node-v0.10.25~dfsg2/test/simple/test-fs-fsync.js0000644000000000000000000000357712270121457020144 0ustar rootroot// Copyright Joyent, Inc. and other Node contributors. // // Permission is hereby granted, free of charge, to any person obtaining a // copy of this software and associated documentation files (the // "Software"), to deal in the Software without restriction, including // without limitation the rights to use, copy, modify, merge, publish, // distribute, sublicense, and/or sell copies of the Software, and to permit // persons to whom the Software is furnished to do so, subject to the // following conditions: // // The above copyright notice and this permission notice shall be included // in all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS // OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF // MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN // NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, // DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR // OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE // USE OR OTHER DEALINGS IN THE SOFTWARE. var common = require('../common'); var assert = require('assert'); var path = require('path'); var fs = require('fs'); var successes = 0; var file = path.join(common.fixturesDir, 'a.js'); common.error('open ' + file); fs.open(file, 'a', 0777, function(err, fd) { common.error('fd ' + fd); if (err) throw err; fs.fdatasyncSync(fd); common.error('fdatasync SYNC: ok'); successes++; fs.fsyncSync(fd); common.error('fsync SYNC: ok'); successes++; fs.fdatasync(fd, function(err) { if (err) throw err; common.error('fdatasync ASYNC: ok'); successes++; fs.fsync(fd, function(err) { if (err) throw err; common.error('fsync ASYNC: ok'); successes++; }); }); }); process.on('exit', function() { assert.equal(4, successes); }); node-v0.10.25~dfsg2/test/simple/test-child-process-kill.js0000644000000000000000000000364312270121457022076 0ustar rootroot// Copyright Joyent, Inc. and other Node contributors. // // Permission is hereby granted, free of charge, to any person obtaining a // copy of this software and associated documentation files (the // "Software"), to deal in the Software without restriction, including // without limitation the rights to use, copy, modify, merge, publish, // distribute, sublicense, and/or sell copies of the Software, and to permit // persons to whom the Software is furnished to do so, subject to the // following conditions: // // The above copyright notice and this permission notice shall be included // in all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS // OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF // MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN // NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, // DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR // OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE // USE OR OTHER DEALINGS IN THE SOFTWARE. var common = require('../common'); var assert = require('assert'); var spawn = require('child_process').spawn; var is_windows = process.platform === 'win32'; var exitCode; var termSignal; var gotStdoutEOF = false; var gotStderrEOF = false; var cat = spawn(is_windows ? 'cmd' : 'cat'); cat.stdout.on('end', function() { gotStdoutEOF = true; }); cat.stderr.on('data', function(chunk) { assert.ok(false); }); cat.stderr.on('end', function() { gotStderrEOF = true; }); cat.on('exit', function(code, signal) { exitCode = code; termSignal = signal; }); assert.equal(cat.killed, false); cat.kill(); assert.equal(cat.killed, true); process.on('exit', function() { assert.strictEqual(exitCode, null); assert.strictEqual(termSignal, 'SIGTERM'); assert.ok(gotStdoutEOF); assert.ok(gotStderrEOF); }); node-v0.10.25~dfsg2/test/simple/test-stream-transform-objectmode-falsey-value.js0000644000000000000000000000342212270121457026411 0ustar rootroot// Copyright Joyent, Inc. and other Node contributors. // // Permission is hereby granted, free of charge, to any person obtaining a // copy of this software and associated documentation files (the // "Software"), to deal in the Software without restriction, including // without limitation the rights to use, copy, modify, merge, publish, // distribute, sublicense, and/or sell copies of the Software, and to permit // persons to whom the Software is furnished to do so, subject to the // following conditions: // // The above copyright notice and this permission notice shall be included // in all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS // OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF // MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN // NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, // DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR // OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE // USE OR OTHER DEALINGS IN THE SOFTWARE. var common = require('../common'); var assert = require('assert'); var stream = require('stream'); var PassThrough = stream.PassThrough; var src = new PassThrough({ objectMode: true }); var tx = new PassThrough({ objectMode: true }); var dest = new PassThrough({ objectMode: true }); var expect = [ -1, 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10 ]; var results = []; process.on('exit', function() { assert.deepEqual(results, expect); console.log('ok'); }); dest.on('data', function(x) { results.push(x); }); src.pipe(tx).pipe(dest); var i = -1; var int = setInterval(function() { if (i > 10) { src.end(); clearInterval(int); } else { src.write(i++); } }); node-v0.10.25~dfsg2/test/simple/test-event-emitter-max-listeners.js0000644000000000000000000000323112270121457023760 0ustar rootroot// Copyright Joyent, Inc. and other Node contributors. // // Permission is hereby granted, free of charge, to any person obtaining a // copy of this software and associated documentation files (the // "Software"), to deal in the Software without restriction, including // without limitation the rights to use, copy, modify, merge, publish, // distribute, sublicense, and/or sell copies of the Software, and to permit // persons to whom the Software is furnished to do so, subject to the // following conditions: // // The above copyright notice and this permission notice shall be included // in all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS // OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF // MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN // NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, // DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR // OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE // USE OR OTHER DEALINGS IN THE SOFTWARE. var common = require('../common'); var assert = require('assert'); var events = require('events'); var gotEvent = false; process.on('exit', function() { assert(gotEvent); }); var e = new events.EventEmitter(); e.on('maxListeners', function() { gotEvent = true; }); // Should not corrupt the 'maxListeners' queue. e.setMaxListeners(42); assert.throws(function() { e.setMaxListeners(NaN); }); assert.throws(function() { e.setMaxListeners(-1); }); assert.throws(function() { e.setMaxListeners("and even this"); }); e.emit('maxListeners'); node-v0.10.25~dfsg2/test/simple/test-process-env.js0000644000000000000000000000664612270121457020660 0ustar rootroot// Copyright Joyent, Inc. and other Node contributors. // // Permission is hereby granted, free of charge, to any person obtaining a // copy of this software and associated documentation files (the // "Software"), to deal in the Software without restriction, including // without limitation the rights to use, copy, modify, merge, publish, // distribute, sublicense, and/or sell copies of the Software, and to permit // persons to whom the Software is furnished to do so, subject to the // following conditions: // // The above copyright notice and this permission notice shall be included // in all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS // OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF // MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN // NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, // DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR // OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE // USE OR OTHER DEALINGS IN THE SOFTWARE. // first things first, set the timezone; see tzset(3) process.env.TZ = 'Europe/Amsterdam'; var common = require('../common'); var assert = require('assert'); var spawn = require('child_process').spawn; /* For the moment we are not going to support setting the timezone via the * environment variables. The problem is that various V8 platform backends * deal with timezone in different ways. The windows platform backend caches * the timezone value while the Linux one hits libc for every query. https://github.com/joyent/node/blob/08782931205bc4f6d28102ebc29fd806e8ccdf1f/deps/v8/src/platform-linux.cc#L339-345 https://github.com/joyent/node/blob/08782931205bc4f6d28102ebc29fd806e8ccdf1f/deps/v8/src/platform-win32.cc#L590-596 // time difference between Greenwich and Amsterdam is +2 hours in the summer date = new Date('Fri, 10 Sep 1982 03:15:00 GMT'); assert.equal(3, date.getUTCHours()); assert.equal(5, date.getHours()); */ // changes in environment should be visible to child processes if (process.argv[2] == 'you-are-the-child') { // failed assertion results in process exiting with status code 1 assert.equal(false, 'NODE_PROCESS_ENV_DELETED' in process.env); assert.equal(42, process.env.NODE_PROCESS_ENV); assert.equal('asdf', process.env.hasOwnProperty); var hasOwnProperty = Object.prototype.hasOwnProperty; var has = hasOwnProperty.call(process.env, 'hasOwnProperty'); assert.equal(true, has); process.exit(0); } else { assert.equal(Object.prototype.hasOwnProperty, process.env.hasOwnProperty); var has = process.env.hasOwnProperty('hasOwnProperty'); assert.equal(false, has); process.env.hasOwnProperty = 'asdf'; process.env.NODE_PROCESS_ENV = 42; assert.equal(42, process.env.NODE_PROCESS_ENV); process.env.NODE_PROCESS_ENV_DELETED = 42; assert.equal(true, 'NODE_PROCESS_ENV_DELETED' in process.env); delete process.env.NODE_PROCESS_ENV_DELETED; assert.equal(false, 'NODE_PROCESS_ENV_DELETED' in process.env); var child = spawn(process.argv[0], [process.argv[1], 'you-are-the-child']); child.stdout.on('data', function(data) { console.log(data.toString()); }); child.stderr.on('data', function(data) { console.log(data.toString()); }); child.on('exit', function(statusCode) { if (statusCode != 0) { process.exit(statusCode); // failed assertion in child process } }); } node-v0.10.25~dfsg2/test/simple/test-http-response-close.js0000644000000000000000000000371212270121457022321 0ustar rootroot// Copyright Joyent, Inc. and other Node contributors. // // Permission is hereby granted, free of charge, to any person obtaining a // copy of this software and associated documentation files (the // "Software"), to deal in the Software without restriction, including // without limitation the rights to use, copy, modify, merge, publish, // distribute, sublicense, and/or sell copies of the Software, and to permit // persons to whom the Software is furnished to do so, subject to the // following conditions: // // The above copyright notice and this permission notice shall be included // in all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS // OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF // MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN // NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, // DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR // OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE // USE OR OTHER DEALINGS IN THE SOFTWARE. var common = require('../common'); var assert = require('assert'); var http = require('http'); var requestGotEnd = false; var responseGotEnd = false; var server = http.createServer(function(req, res) { res.writeHead(200); res.write('a'); req.on('close', function() { console.error('request aborted'); requestGotEnd = true; }); res.on('close', function() { console.error('response aborted'); responseGotEnd = true; }); }); server.listen(common.PORT); server.on('listening', function() { console.error('make req'); http.get({ port: common.PORT }, function(res) { console.error('got res'); res.on('data', function(data) { console.error('destroy res'); res.destroy(); server.close(); }); }); }); process.on('exit', function() { assert.ok(requestGotEnd); assert.ok(responseGotEnd); }); node-v0.10.25~dfsg2/test/simple/test-http-pipeline-flood.js0000644000000000000000000000650112270121457022265 0ustar rootroot// Copyright Joyent, Inc. and other Node contributors. // // Permission is hereby granted, free of charge, to any person obtaining a // copy of this software and associated documentation files (the // "Software"), to deal in the Software without restriction, including // without limitation the rights to use, copy, modify, merge, publish, // distribute, sublicense, and/or sell copies of the Software, and to permit // persons to whom the Software is furnished to do so, subject to the // following conditions: // // The above copyright notice and this permission notice shall be included // in all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS // OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF // MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN // NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, // DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR // OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE // USE OR OTHER DEALINGS IN THE SOFTWARE. var common = require('../common'); var assert = require('assert'); switch (process.argv[2]) { case undefined: return parent(); case 'child': return child(); default: throw new Error('wtf'); } function parent() { var http = require('http'); var bigResponse = new Buffer(10240) bigResponse.fill('x'); var gotTimeout = false; var childClosed = false; var requests = 0; var connections = 0; var server = http.createServer(function(req, res) { requests++; res.setHeader('content-length', bigResponse.length); res.end(bigResponse); }); server.on('connection', function(conn) { connections++; }); // kill the connection after a bit, verifying that the // flood of requests was eventually halted. server.setTimeout(200, function(conn) { gotTimeout = true; conn.destroy(); }); server.listen(common.PORT, function() { var spawn = require('child_process').spawn; var args = [__filename, 'child']; var child = spawn(process.execPath, args, { stdio: 'inherit' }); child.on('close', function(code) { assert(!code); childClosed = true; server.close(); }); }); process.on('exit', function() { assert(gotTimeout); assert(childClosed); assert.equal(connections, 1); // 1213 works out to be the number of requests we end up processing // before the outgoing connection backs up and requires a drain. // however, to avoid being unnecessarily tied to a specific magic number, // and making the test brittle, just assert that it's "a lot", which we // can safely assume is more than 500. assert(requests >= 500); console.log('ok'); }); } function child() { var net = require('net'); var gotEpipe = false; var conn = net.connect({ port: common.PORT }); var req = 'GET / HTTP/1.1\r\nHost: localhost:' + common.PORT + '\r\nAccept: */*\r\n\r\n'; req = new Array(10241).join(req); conn.on('connect', function() { write(); }); conn.on('drain', write); conn.on('error', function(er) { gotEpipe = true; }); process.on('exit', function() { assert(gotEpipe); console.log('ok - child'); }); function write() { while (false !== conn.write(req, 'ascii')); } } node-v0.10.25~dfsg2/test/simple/test-listen-fd-ebadf.js0000644000000000000000000000276312270121457021334 0ustar rootroot// Copyright Joyent, Inc. and other Node contributors. // // Permission is hereby granted, free of charge, to any person obtaining a // copy of this software and associated documentation files (the // "Software"), to deal in the Software without restriction, including // without limitation the rights to use, copy, modify, merge, publish, // distribute, sublicense, and/or sell copies of the Software, and to permit // persons to whom the Software is furnished to do so, subject to the // following conditions: // // The above copyright notice and this permission notice shall be included // in all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS // OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF // MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN // NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, // DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR // OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE // USE OR OTHER DEALINGS IN THE SOFTWARE. var common = require('../common'); var assert = require('assert'); var net = require('net'); var gotError = 0; process.on('exit', function() { assert.equal(gotError, 2); }); net.createServer(assert.fail).listen({fd:2}).on('error', onError); net.createServer(assert.fail).listen({fd:42}).on('error', onError); function onError(ex) { assert.equal(ex.code, 'EINVAL'); gotError++; } node-v0.10.25~dfsg2/test/simple/test-repl-domain.js0000644000000000000000000000411212270121457020605 0ustar rootroot// Copyright Joyent, Inc. and other Node contributors. // // Permission is hereby granted, free of charge, to any person obtaining a // copy of this software and associated documentation files (the // "Software"), to deal in the Software without restriction, including // without limitation the rights to use, copy, modify, merge, publish, // distribute, sublicense, and/or sell copies of the Software, and to permit // persons to whom the Software is furnished to do so, subject to the // following conditions: // // The above copyright notice and this permission notice shall be included // in all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS // OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF // MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN // NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, // DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR // OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE // USE OR OTHER DEALINGS IN THE SOFTWARE. var util = require('util'); var repl = require('repl'); // A stream to push an array into a REPL function ArrayStream() { this.run = function(data) { var self = this; data.forEach(function(line) { self.emit('data', line + '\n'); }); } } util.inherits(ArrayStream, require('stream').Stream); ArrayStream.prototype.readable = true; ArrayStream.prototype.writable = true; ArrayStream.prototype.resume = function() {}; ArrayStream.prototype.write = function() {}; var putIn = new ArrayStream(); var testMe = repl.start('', putIn); putIn.write = function(data) { // Don't use assert for this because the domain might catch it, and // give a false negative. Don't throw, just print and exit. if (data === 'OK\n') { console.log('ok'); } else { console.error(data); process.exit(1); } }; putIn.run([ 'require("domain").create().on("error", function () { console.log("OK") })' + '.run(function () { throw new Error("threw") })' ]); node-v0.10.25~dfsg2/test/simple/test-process-next-tick.js0000644000000000000000000000306612270121457021767 0ustar rootroot// Copyright Joyent, Inc. and other Node contributors. // // Permission is hereby granted, free of charge, to any person obtaining a // copy of this software and associated documentation files (the // "Software"), to deal in the Software without restriction, including // without limitation the rights to use, copy, modify, merge, publish, // distribute, sublicense, and/or sell copies of the Software, and to permit // persons to whom the Software is furnished to do so, subject to the // following conditions: // // The above copyright notice and this permission notice shall be included // in all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS // OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF // MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN // NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, // DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR // OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE // USE OR OTHER DEALINGS IN THE SOFTWARE. var common = require('../common'); var assert = require('assert'); var N = 2; var tickCount = 0; var exceptionCount = 0; function cb() { ++tickCount; throw new Error(); } for (var i = 0; i < N; ++i) { process.nextTick(cb); } process.on('uncaughtException', function() { ++exceptionCount; }); process.on('exit', function() { process.removeAllListeners('uncaughtException'); assert.equal(tickCount, N); assert.equal(exceptionCount, N); }); node-v0.10.25~dfsg2/test/simple/test-child-process-fork-exec-argv.js0000644000000000000000000000345212270121457023761 0ustar rootroot// Copyright Joyent, Inc. and other Node contributors. // // Permission is hereby granted, free of charge, to any person obtaining a // copy of this software and associated documentation files (the // "Software"), to deal in the Software without restriction, including // without limitation the rights to use, copy, modify, merge, publish, // distribute, sublicense, and/or sell copies of the Software, and to permit // persons to whom the Software is furnished to do so, subject to the // following conditions: // // The above copyright notice and this permission notice shall be included // in all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS // OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF // MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN // NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, // DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR // OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE // USE OR OTHER DEALINGS IN THE SOFTWARE. var assert = require('assert'); var child_process = require('child_process'); var spawn = child_process.spawn; var fork = child_process.fork; if (process.argv[2] === 'fork') { process.stdout.write(JSON.stringify(process.execArgv), function() { process.exit(); }); } else if (process.argv[2] === 'child') { fork(__filename, ['fork']); } else { var execArgv = ['--harmony_proxies', '--max-stack-size=0']; var args = [__filename, 'child', 'arg0']; var child = spawn(process.execPath, execArgv.concat(args)); var out = ''; child.stdout.on('data', function (chunk) { out += chunk; }); child.on('exit', function () { assert.deepEqual(JSON.parse(out), execArgv); }); } node-v0.10.25~dfsg2/test/simple/test-https-client-get-url.js0000644000000000000000000000406612270121457022401 0ustar rootroot// Copyright Joyent, Inc. and other Node contributors. // // Permission is hereby granted, free of charge, to any person obtaining a // copy of this software and associated documentation files (the // "Software"), to deal in the Software without restriction, including // without limitation the rights to use, copy, modify, merge, publish, // distribute, sublicense, and/or sell copies of the Software, and to permit // persons to whom the Software is furnished to do so, subject to the // following conditions: // // The above copyright notice and this permission notice shall be included // in all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS // OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF // MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN // NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, // DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR // OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE // USE OR OTHER DEALINGS IN THE SOFTWARE. if (!process.versions.openssl) { console.error('Skipping because node compiled without OpenSSL.'); process.exit(0); } // disable strict server certificate validation by the client process.env.NODE_TLS_REJECT_UNAUTHORIZED = '0'; var common = require('../common'); var assert = require('assert'); var https = require('https'); var fs = require('fs'); var seen_req = false; var options = { key: fs.readFileSync(common.fixturesDir + '/keys/agent1-key.pem'), cert: fs.readFileSync(common.fixturesDir + '/keys/agent1-cert.pem') }; var server = https.createServer(options, function(req, res) { assert.equal('GET', req.method); assert.equal('/foo?bar', req.url); res.writeHead(200, {'Content-Type': 'text/plain'}); res.write('hello\n'); res.end(); server.close(); seen_req = true; }); server.listen(common.PORT, function() { https.get('https://127.0.0.1:' + common.PORT + '/foo?bar'); }); process.on('exit', function() { assert(seen_req); }); node-v0.10.25~dfsg2/test/simple/test-child-process-exec-env.js0000644000000000000000000000411612270121457022651 0ustar rootroot// Copyright Joyent, Inc. and other Node contributors. // // Permission is hereby granted, free of charge, to any person obtaining a // copy of this software and associated documentation files (the // "Software"), to deal in the Software without restriction, including // without limitation the rights to use, copy, modify, merge, publish, // distribute, sublicense, and/or sell copies of the Software, and to permit // persons to whom the Software is furnished to do so, subject to the // following conditions: // // The above copyright notice and this permission notice shall be included // in all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS // OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF // MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN // NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, // DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR // OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE // USE OR OTHER DEALINGS IN THE SOFTWARE. var common = require('../common'); var assert = require('assert'); var exec = require('child_process').exec; var success_count = 0; var error_count = 0; var response = ''; var child; function after(err, stdout, stderr) { if (err) { error_count++; console.log('error!: ' + err.code); console.log('stdout: ' + JSON.stringify(stdout)); console.log('stderr: ' + JSON.stringify(stderr)); assert.equal(false, err.killed); } else { success_count++; assert.equal(true, stdout != ''); } } if (process.platform !== 'win32') { child = exec('/usr/bin/env', { env: { 'HELLO': 'WORLD' } }, after); } else { child = exec('set', { env: { 'HELLO': 'WORLD' } }, after); } child.stdout.setEncoding('utf8'); child.stdout.on('data', function(chunk) { response += chunk; }); process.on('exit', function() { console.log('response: ', response); assert.equal(1, success_count); assert.equal(0, error_count); assert.ok(response.indexOf('HELLO=WORLD') >= 0); }); node-v0.10.25~dfsg2/test/simple/test-domain-implicit-fs.js0000644000000000000000000000503412270121457022067 0ustar rootroot// Copyright Joyent, Inc. and other Node contributors. // // Permission is hereby granted, free of charge, to any person obtaining a // copy of this software and associated documentation files (the // "Software"), to deal in the Software without restriction, including // without limitation the rights to use, copy, modify, merge, publish, // distribute, sublicense, and/or sell copies of the Software, and to permit // persons to whom the Software is furnished to do so, subject to the // following conditions: // // The above copyright notice and this permission notice shall be included // in all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS // OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF // MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN // NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, // DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR // OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE // USE OR OTHER DEALINGS IN THE SOFTWARE. // Simple tests of most basic domain functionality. var common = require('../common'); var assert = require('assert'); var domain = require('domain'); var events = require('events'); var caught = 0; var expectCaught = 1; var d = new domain.Domain(); var e = new events.EventEmitter(); d.on('error', function(er) { console.error('caught', er); assert.strictEqual(er.domain, d); assert.strictEqual(er.domainThrown, true); assert.ok(!er.domainEmitter); assert.strictEqual(er.code, 'ENOENT'); assert.ok(/\bthis file does not exist\b/i.test(er.path)); assert.strictEqual(typeof er.errno, 'number'); caught++; }); process.on('exit', function() { console.error('exit'); assert.equal(caught, expectCaught); console.log('ok'); }); // implicit handling of thrown errors while in a domain, via the // single entry points of ReqWrap and MakeCallback. Even if // we try very hard to escape, there should be no way to, even if // we go many levels deep through timeouts and multiple IO calls. // Everything that happens between the domain.enter() and domain.exit() // calls will be bound to the domain, even if multiple levels of // handles are created. d.run(function() { setTimeout(function() { var fs = require('fs'); fs.readdir(__dirname, function() { fs.open('this file does not exist', 'r', function(er) { if (er) throw er; throw new Error('should not get here!'); }); }); }, 100); }); node-v0.10.25~dfsg2/test/simple/test-tls-client-verify.js0000644000000000000000000001020012270121457021751 0ustar rootroot// Copyright Joyent, Inc. and other Node contributors. // // Permission is hereby granted, free of charge, to any person obtaining a // copy of this software and associated documentation files (the // "Software"), to deal in the Software without restriction, including // without limitation the rights to use, copy, modify, merge, publish, // distribute, sublicense, and/or sell copies of the Software, and to permit // persons to whom the Software is furnished to do so, subject to the // following conditions: // // The above copyright notice and this permission notice shall be included // in all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS // OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF // MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN // NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, // DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR // OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE // USE OR OTHER DEALINGS IN THE SOFTWARE. if (!process.versions.openssl) { console.error('Skipping because node compiled without OpenSSL.'); process.exit(0); } var hosterr = 'Hostname/IP doesn\'t match certificate\'s altnames'; var testCases = [{ ca: ['ca1-cert'], key: 'agent2-key', cert: 'agent2-cert', servers: [ { ok: true, key: 'agent1-key', cert: 'agent1-cert' }, { ok: false, key: 'agent2-key', cert: 'agent2-cert' }, { ok: false, key: 'agent3-key', cert: 'agent3-cert' } ] }, { ca: [], key: 'agent2-key', cert: 'agent2-cert', servers: [ { ok: false, key: 'agent1-key', cert: 'agent1-cert' }, { ok: false, key: 'agent2-key', cert: 'agent2-cert' }, { ok: false, key: 'agent3-key', cert: 'agent3-cert' } ] }, { ca: ['ca1-cert', 'ca2-cert'], key: 'agent2-key', cert: 'agent2-cert', servers: [ { ok: true, key: 'agent1-key', cert: 'agent1-cert' }, { ok: false, key: 'agent2-key', cert: 'agent2-cert' }, { ok: true, key: 'agent3-key', cert: 'agent3-cert' } ] } ]; var common = require('../common'); var assert = require('assert'); var fs = require('fs'); var tls = require('tls'); function filenamePEM(n) { return require('path').join(common.fixturesDir, 'keys', n + '.pem'); } function loadPEM(n) { return fs.readFileSync(filenamePEM(n)); } var successfulTests = 0; function testServers(index, servers, clientOptions, cb) { var serverOptions = servers[index]; if (!serverOptions) { cb(); return; } var ok = serverOptions.ok; if (serverOptions.key) { serverOptions.key = loadPEM(serverOptions.key); } if (serverOptions.cert) { serverOptions.cert = loadPEM(serverOptions.cert); } var server = tls.createServer(serverOptions, function(s) { s.end('hello world\n'); }); server.listen(common.PORT, function() { var b = ''; console.error('connecting...'); var client = tls.connect(clientOptions, function() { var authorized = client.authorized || client.authorizationError === hosterr; console.error('expected: ' + ok + ' authed: ' + authorized); assert.equal(ok, authorized); server.close(); }); client.on('data', function(d) { b += d.toString(); }); client.on('end', function() { assert.equal('hello world\n', b); }); client.on('close', function() { testServers(index + 1, servers, clientOptions, cb); }); }); } function runTest(testIndex) { var tcase = testCases[testIndex]; if (!tcase) return; var clientOptions = { port: common.PORT, ca: tcase.ca.map(loadPEM), key: loadPEM(tcase.key), cert: loadPEM(tcase.cert), rejectUnauthorized: false }; testServers(0, tcase.servers, clientOptions, function() { successfulTests++; runTest(testIndex + 1); }); } runTest(0); process.on('exit', function() { console.log('successful tests: %d', successfulTests); assert.equal(successfulTests, testCases.length); }); node-v0.10.25~dfsg2/test/simple/simple.status0000644000000000000000000000001612270121457017620 0ustar rootrootprefix simple node-v0.10.25~dfsg2/test/simple/test-fs-read-stream-resume.js0000644000000000000000000000325112270121457022511 0ustar rootroot// Copyright Joyent, Inc. and other Node contributors. // // Permission is hereby granted, free of charge, to any person obtaining a // copy of this software and associated documentation files (the // "Software"), to deal in the Software without restriction, including // without limitation the rights to use, copy, modify, merge, publish, // distribute, sublicense, and/or sell copies of the Software, and to permit // persons to whom the Software is furnished to do so, subject to the // following conditions: // // The above copyright notice and this permission notice shall be included // in all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS // OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF // MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN // NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, // DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR // OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE // USE OR OTHER DEALINGS IN THE SOFTWARE. var common = require('../common'); var assert = require('assert'); var fs = require('fs'); var path = require('path'); var file = path.join(common.fixturesDir, 'x.txt'); var data = ''; var first = true; var stream = fs.createReadStream(file); stream.setEncoding('utf8'); stream.on('data', function(chunk) { data += chunk; if (first) { first = false; stream.resume(); } }); process.nextTick(function() { stream.pause(); setTimeout(function() { stream.resume(); }, 100); }); process.on('exit', function() { assert.equal(data, 'xyz\n'); }); node-v0.10.25~dfsg2/test/simple/test-http-request-methods.js0000644000000000000000000000440212270121457022506 0ustar rootroot// Copyright Joyent, Inc. and other Node contributors. // // Permission is hereby granted, free of charge, to any person obtaining a // copy of this software and associated documentation files (the // "Software"), to deal in the Software without restriction, including // without limitation the rights to use, copy, modify, merge, publish, // distribute, sublicense, and/or sell copies of the Software, and to permit // persons to whom the Software is furnished to do so, subject to the // following conditions: // // The above copyright notice and this permission notice shall be included // in all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS // OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF // MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN // NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, // DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR // OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE // USE OR OTHER DEALINGS IN THE SOFTWARE. var common = require('../common'); var assert = require('assert'); var net = require('net'); var http = require('http'); // Test that the PATCH and PURGE verbs get passed through correctly ['PATCH', 'PURGE'].forEach(function(method, index) { var port = common.PORT + index; var server_response = ''; var received_method = null; var server = http.createServer(function(req, res) { received_method = req.method; res.writeHead(200, {'Content-Type': 'text/plain'}); res.write('hello '); res.write('world\n'); res.end(); }); server.listen(port); server.on('listening', function() { var c = net.createConnection(port); c.setEncoding('utf8'); c.on('connect', function() { c.write(method + ' / HTTP/1.0\r\n\r\n'); }); c.on('data', function(chunk) { console.log(chunk); server_response += chunk; }); c.on('end', function() { c.end(); }); c.on('close', function() { server.close(); }); }); process.on('exit', function() { var m = server_response.split('\r\n\r\n'); assert.equal(m[1], 'hello world\n'); assert.equal(received_method, method); }); }); node-v0.10.25~dfsg2/test/simple/test-net-during-close.js0000644000000000000000000000337712270121457021571 0ustar rootroot// Copyright Joyent, Inc. and other Node contributors. // // Permission is hereby granted, free of charge, to any person obtaining a // copy of this software and associated documentation files (the // "Software"), to deal in the Software without restriction, including // without limitation the rights to use, copy, modify, merge, publish, // distribute, sublicense, and/or sell copies of the Software, and to permit // persons to whom the Software is furnished to do so, subject to the // following conditions: // // The above copyright notice and this permission notice shall be included // in all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS // OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF // MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN // NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, // DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR // OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE // USE OR OTHER DEALINGS IN THE SOFTWARE. var common = require('../common'); var assert = require('assert'); var net = require('net'); var accessedProperties = false; var server = net.createServer(function(socket) { socket.end(); }); server.listen(common.PORT, function() { var client = net.createConnection(common.PORT); server.close(); // server connection event has not yet fired // client is still attempting to connect assert.doesNotThrow(function() { client.remoteAddress; client.remotePort; }); accessedProperties = true; // exit now, do not wait for the client error event process.exit(0); }); process.on('exit', function() { assert(accessedProperties); }); node-v0.10.25~dfsg2/test/simple/test-fs-long-path.js0000644000000000000000000000361312270121457020702 0ustar rootroot// Copyright Joyent, Inc. and other Node contributors. // // Permission is hereby granted, free of charge, to any person obtaining a // copy of this software and associated documentation files (the // "Software"), to deal in the Software without restriction, including // without limitation the rights to use, copy, modify, merge, publish, // distribute, sublicense, and/or sell copies of the Software, and to permit // persons to whom the Software is furnished to do so, subject to the // following conditions: // // The above copyright notice and this permission notice shall be included // in all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS // OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF // MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN // NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, // DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR // OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE // USE OR OTHER DEALINGS IN THE SOFTWARE. var common = require('../common'); var fs = require('fs'); var path = require('path'); var assert = require('assert'); var successes = 0; // make a path that will be at least 260 chars long. var fileNameLen = Math.max(260 - common.tmpDir.length - 1, 1); var fileName = path.join(common.tmpDir, new Array(fileNameLen + 1).join('x')); var fullPath = path.resolve(fileName); try { fs.unlinkSync(fullPath); } catch (e) { // Ignore. } console.log({ filenameLength: fileName.length, fullPathLength: fullPath.length }); fs.writeFile(fullPath, 'ok', function(err) { if (err) throw err; successes++; fs.stat(fullPath, function(err, stats) { if (err) throw err; successes++; }); }); process.on('exit', function() { fs.unlinkSync(fullPath); assert.equal(2, successes); }); node-v0.10.25~dfsg2/test/simple/test-require-cache.js0000644000000000000000000000323312270121457021116 0ustar rootroot// Copyright Joyent, Inc. and other Node contributors. // // Permission is hereby granted, free of charge, to any person obtaining a // copy of this software and associated documentation files (the // "Software"), to deal in the Software without restriction, including // without limitation the rights to use, copy, modify, merge, publish, // distribute, sublicense, and/or sell copies of the Software, and to permit // persons to whom the Software is furnished to do so, subject to the // following conditions: // // The above copyright notice and this permission notice shall be included // in all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS // OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF // MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN // NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, // DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR // OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE // USE OR OTHER DEALINGS IN THE SOFTWARE. var common = require('../common'); var assert = require('assert'); (function testInjectFakeModule() { var relativePath = '../fixtures/semicolon'; var absolutePath = require.resolve(relativePath); var fakeModule = {}; require.cache[absolutePath] = {exports: fakeModule}; assert.strictEqual(require(relativePath), fakeModule); })(); (function testInjectFakeNativeModule() { var relativePath = 'fs'; var fakeModule = {}; require.cache[relativePath] = {exports: fakeModule}; assert.strictEqual(require(relativePath), fakeModule); })(); node-v0.10.25~dfsg2/test/simple/test-net-write-after-close.js0000644000000000000000000000346412270121457022527 0ustar rootroot// Copyright Joyent, Inc. and other Node contributors. // // Permission is hereby granted, free of charge, to any person obtaining a // copy of this software and associated documentation files (the // "Software"), to deal in the Software without restriction, including // without limitation the rights to use, copy, modify, merge, publish, // distribute, sublicense, and/or sell copies of the Software, and to permit // persons to whom the Software is furnished to do so, subject to the // following conditions: // // The above copyright notice and this permission notice shall be included // in all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS // OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF // MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN // NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, // DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR // OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE // USE OR OTHER DEALINGS IN THE SOFTWARE. var common = require('../common'); var assert = require('assert'); var net = require('net'); var gotError = false; var gotWriteCB = false; process.on('exit', function() { assert(gotError); assert(gotWriteCB); }); var server = net.createServer(function(socket) { socket.resume(); socket.on('error', function(error) { console.error('got error, closing server', error); server.close(); gotError = true; }); setTimeout(function() { console.error('about to try to write'); socket.write('test', function(e) { gotWriteCB = true; }); }, 250); }); server.listen(common.PORT, function() { var client = net.connect(common.PORT, function() { client.end(); }); }); node-v0.10.25~dfsg2/test/simple/test-regress-GH-4948.js0000644000000000000000000000412212270121457020753 0ustar rootroot// Copyright Joyent, Inc. and other Node contributors. // // Permission is hereby granted, free of charge, to any person obtaining a // copy of this software and associated documentation files (the // "Software"), to deal in the Software without restriction, including // without limitation the rights to use, copy, modify, merge, publish, // distribute, sublicense, and/or sell copies of the Software, and to permit // persons to whom the Software is furnished to do so, subject to the // following conditions: // // The above copyright notice and this permission notice shall be included // in all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS // OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF // MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN // NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, // DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR // OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE // USE OR OTHER DEALINGS IN THE SOFTWARE. // https://github.com/joyent/node/issues/4948 var common = require('../common'); var http = require('http'); var reqCount = 0; var server = http.createServer(function(serverReq, serverRes){ if (reqCount) { serverRes.end(); server.close(); return; } reqCount = 1; // normally the use case would be to call an external site // does not require connecting locally or to itself to fail var r = http.request({hostname: 'localhost', port: common.PORT}, function(res) { // required, just needs to be in the client response somewhere serverRes.end(); // required for test to fail res.on('data', function(data) { }); }); r.on('error', function(e) {}); r.end(); serverRes.write('some data'); }).listen(common.PORT); // simulate a client request that closes early var net = require('net'); var sock = new net.Socket(); sock.connect(common.PORT, 'localhost'); sock.on('connect', function() { sock.write('GET / HTTP/1.1\r\n\r\n'); sock.end(); });node-v0.10.25~dfsg2/test/simple/test-stream2-transform.js0000644000000000000000000002572312270121457021777 0ustar rootroot// Copyright Joyent, Inc. and other Node contributors. // // Permission is hereby granted, free of charge, to any person obtaining a // copy of this software and associated documentation files (the // "Software"), to deal in the Software without restriction, including // without limitation the rights to use, copy, modify, merge, publish, // distribute, sublicense, and/or sell copies of the Software, and to permit // persons to whom the Software is furnished to do so, subject to the // following conditions: // // The above copyright notice and this permission notice shall be included // in all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS // OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF // MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN // NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, // DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR // OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE // USE OR OTHER DEALINGS IN THE SOFTWARE. var assert = require('assert'); var common = require('../common.js'); var PassThrough = require('_stream_passthrough'); var Transform = require('_stream_transform'); // tiny node-tap lookalike. var tests = []; var count = 0; function test(name, fn) { count++; tests.push([name, fn]); } function run() { var next = tests.shift(); if (!next) return console.error('ok'); var name = next[0]; var fn = next[1]; console.log('# %s', name); fn({ same: assert.deepEqual, equal: assert.equal, ok: assert, end: function () { count--; run(); } }); } // ensure all tests have run process.on("exit", function () { assert.equal(count, 0); }); process.nextTick(run); ///// test('writable side consumption', function(t) { var tx = new Transform({ highWaterMark: 10 }); var transformed = 0; tx._transform = function(chunk, encoding, cb) { transformed += chunk.length; tx.push(chunk); cb(); }; for (var i = 1; i <= 10; i++) { tx.write(new Buffer(i)); } tx.end(); t.equal(tx._readableState.length, 10); t.equal(transformed, 10); t.equal(tx._transformState.writechunk.length, 5); t.same(tx._writableState.buffer.map(function(c) { return c.chunk.length; }), [6, 7, 8, 9, 10]); t.end(); }); test('passthrough', function(t) { var pt = new PassThrough(); pt.write(new Buffer('foog')); pt.write(new Buffer('bark')); pt.write(new Buffer('bazy')); pt.write(new Buffer('kuel')); pt.end(); t.equal(pt.read(5).toString(), 'foogb'); t.equal(pt.read(5).toString(), 'arkba'); t.equal(pt.read(5).toString(), 'zykue'); t.equal(pt.read(5).toString(), 'l'); t.end(); }); test('simple transform', function(t) { var pt = new Transform; pt._transform = function(c, e, cb) { var ret = new Buffer(c.length); ret.fill('x'); pt.push(ret); cb(); }; pt.write(new Buffer('foog')); pt.write(new Buffer('bark')); pt.write(new Buffer('bazy')); pt.write(new Buffer('kuel')); pt.end(); t.equal(pt.read(5).toString(), 'xxxxx'); t.equal(pt.read(5).toString(), 'xxxxx'); t.equal(pt.read(5).toString(), 'xxxxx'); t.equal(pt.read(5).toString(), 'x'); t.end(); }); test('async passthrough', function(t) { var pt = new Transform; pt._transform = function(chunk, encoding, cb) { setTimeout(function() { pt.push(chunk); cb(); }, 10); }; pt.write(new Buffer('foog')); pt.write(new Buffer('bark')); pt.write(new Buffer('bazy')); pt.write(new Buffer('kuel')); pt.end(); pt.on('finish', function() { t.equal(pt.read(5).toString(), 'foogb'); t.equal(pt.read(5).toString(), 'arkba'); t.equal(pt.read(5).toString(), 'zykue'); t.equal(pt.read(5).toString(), 'l'); t.end(); }); }); test('assymetric transform (expand)', function(t) { var pt = new Transform; // emit each chunk 2 times. pt._transform = function(chunk, encoding, cb) { setTimeout(function() { pt.push(chunk); setTimeout(function() { pt.push(chunk); cb(); }, 10) }, 10); }; pt.write(new Buffer('foog')); pt.write(new Buffer('bark')); pt.write(new Buffer('bazy')); pt.write(new Buffer('kuel')); pt.end(); pt.on('finish', function() { t.equal(pt.read(5).toString(), 'foogf'); t.equal(pt.read(5).toString(), 'oogba'); t.equal(pt.read(5).toString(), 'rkbar'); t.equal(pt.read(5).toString(), 'kbazy'); t.equal(pt.read(5).toString(), 'bazyk'); t.equal(pt.read(5).toString(), 'uelku'); t.equal(pt.read(5).toString(), 'el'); t.end(); }); }); test('assymetric transform (compress)', function(t) { var pt = new Transform; // each output is the first char of 3 consecutive chunks, // or whatever's left. pt.state = ''; pt._transform = function(chunk, encoding, cb) { if (!chunk) chunk = ''; var s = chunk.toString(); setTimeout(function() { this.state += s.charAt(0); if (this.state.length === 3) { pt.push(new Buffer(this.state)); this.state = ''; } cb(); }.bind(this), 10); }; pt._flush = function(cb) { // just output whatever we have. pt.push(new Buffer(this.state)); this.state = ''; cb(); }; pt.write(new Buffer('aaaa')); pt.write(new Buffer('bbbb')); pt.write(new Buffer('cccc')); pt.write(new Buffer('dddd')); pt.write(new Buffer('eeee')); pt.write(new Buffer('aaaa')); pt.write(new Buffer('bbbb')); pt.write(new Buffer('cccc')); pt.write(new Buffer('dddd')); pt.write(new Buffer('eeee')); pt.write(new Buffer('aaaa')); pt.write(new Buffer('bbbb')); pt.write(new Buffer('cccc')); pt.write(new Buffer('dddd')); pt.end(); // 'abcdeabcdeabcd' pt.on('finish', function() { t.equal(pt.read(5).toString(), 'abcde'); t.equal(pt.read(5).toString(), 'abcde'); t.equal(pt.read(5).toString(), 'abcd'); t.end(); }); }); // this tests for a stall when data is written to a full stream // that has empty transforms. test('complex transform', function(t) { var count = 0; var saved = null; var pt = new Transform({highWaterMark:3}); pt._transform = function(c, e, cb) { if (count++ === 1) saved = c; else { if (saved) { pt.push(saved); saved = null; } pt.push(c); } cb(); }; pt.once('readable', function() { process.nextTick(function() { pt.write(new Buffer('d')); pt.write(new Buffer('ef'), function() { pt.end(); t.end(); }); t.equal(pt.read().toString(), 'abc'); t.equal(pt.read().toString(), 'def'); t.equal(pt.read(), null); }); }); pt.write(new Buffer('abc')); }); test('passthrough event emission', function(t) { var pt = new PassThrough(); var emits = 0; pt.on('readable', function() { var state = pt._readableState; console.error('>>> emit readable %d', emits); emits++; }); var i = 0; pt.write(new Buffer('foog')); console.error('need emit 0'); pt.write(new Buffer('bark')); console.error('should have emitted readable now 1 === %d', emits); t.equal(emits, 1); t.equal(pt.read(5).toString(), 'foogb'); t.equal(pt.read(5) + '', 'null'); console.error('need emit 1'); pt.write(new Buffer('bazy')); console.error('should have emitted, but not again'); pt.write(new Buffer('kuel')); console.error('should have emitted readable now 2 === %d', emits); t.equal(emits, 2); t.equal(pt.read(5).toString(), 'arkba'); t.equal(pt.read(5).toString(), 'zykue'); t.equal(pt.read(5), null); console.error('need emit 2'); pt.end(); t.equal(emits, 3); t.equal(pt.read(5).toString(), 'l'); t.equal(pt.read(5), null); console.error('should not have emitted again'); t.equal(emits, 3); t.end(); }); test('passthrough event emission reordered', function(t) { var pt = new PassThrough; var emits = 0; pt.on('readable', function() { console.error('emit readable', emits) emits++; }); pt.write(new Buffer('foog')); console.error('need emit 0'); pt.write(new Buffer('bark')); console.error('should have emitted readable now 1 === %d', emits); t.equal(emits, 1); t.equal(pt.read(5).toString(), 'foogb'); t.equal(pt.read(5), null); console.error('need emit 1'); pt.once('readable', function() { t.equal(pt.read(5).toString(), 'arkba'); t.equal(pt.read(5), null); console.error('need emit 2'); pt.once('readable', function() { t.equal(pt.read(5).toString(), 'zykue'); t.equal(pt.read(5), null); pt.once('readable', function() { t.equal(pt.read(5).toString(), 'l'); t.equal(pt.read(5), null); t.equal(emits, 4); t.end(); }); pt.end(); }); pt.write(new Buffer('kuel')); }); pt.write(new Buffer('bazy')); }); test('passthrough facaded', function(t) { console.error('passthrough facaded'); var pt = new PassThrough; var datas = []; pt.on('data', function(chunk) { datas.push(chunk.toString()); }); pt.on('end', function() { t.same(datas, ['foog', 'bark', 'bazy', 'kuel']); t.end(); }); pt.write(new Buffer('foog')); setTimeout(function() { pt.write(new Buffer('bark')); setTimeout(function() { pt.write(new Buffer('bazy')); setTimeout(function() { pt.write(new Buffer('kuel')); setTimeout(function() { pt.end(); }, 10); }, 10); }, 10); }, 10); }); test('object transform (json parse)', function(t) { console.error('json parse stream'); var jp = new Transform({ objectMode: true }); jp._transform = function(data, encoding, cb) { try { jp.push(JSON.parse(data)); cb(); } catch (er) { cb(er); } }; // anything except null/undefined is fine. // those are "magic" in the stream API, because they signal EOF. var objects = [ { foo: 'bar' }, 100, "string", { nested: { things: [ { foo: 'bar' }, 100, "string" ] } } ]; var ended = false; jp.on('end', function() { ended = true; }); objects.forEach(function(obj) { jp.write(JSON.stringify(obj)); var res = jp.read(); t.same(res, obj); }); jp.end(); process.nextTick(function() { t.ok(ended); t.end(); }) }); test('object transform (json stringify)', function(t) { console.error('json parse stream'); var js = new Transform({ objectMode: true }); js._transform = function(data, encoding, cb) { try { js.push(JSON.stringify(data)); cb(); } catch (er) { cb(er); } }; // anything except null/undefined is fine. // those are "magic" in the stream API, because they signal EOF. var objects = [ { foo: 'bar' }, 100, "string", { nested: { things: [ { foo: 'bar' }, 100, "string" ] } } ]; var ended = false; js.on('end', function() { ended = true; }); objects.forEach(function(obj) { js.write(obj); var res = js.read(); t.equal(res, JSON.stringify(obj)); }); js.end(); process.nextTick(function() { t.ok(ended); t.end(); }) }); node-v0.10.25~dfsg2/test/simple/test-net-large-string.js0000644000000000000000000000353012270121457021563 0ustar rootroot// Copyright Joyent, Inc. and other Node contributors. // // Permission is hereby granted, free of charge, to any person obtaining a // copy of this software and associated documentation files (the // "Software"), to deal in the Software without restriction, including // without limitation the rights to use, copy, modify, merge, publish, // distribute, sublicense, and/or sell copies of the Software, and to permit // persons to whom the Software is furnished to do so, subject to the // following conditions: // // The above copyright notice and this permission notice shall be included // in all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS // OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF // MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN // NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, // DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR // OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE // USE OR OTHER DEALINGS IN THE SOFTWARE. var common = require('../common'); var assert = require('assert'); var net = require('net'); var kPoolSize = 40 * 1024; var data = ''; for (var i = 0; i < kPoolSize; ++i) { data += 'あ'; // 3bytes } var receivedSize = 0; var encoding = 'UTF-8'; var server = net.createServer(function(socket) { socket.setEncoding(encoding); socket.on('data', function(data) { receivedSize += data.length; }); socket.on('end', function() { socket.end(); }); }); server.listen(common.PORT, function() { var client = net.createConnection(common.PORT); client.on('end', function() { server.close(); }); client.write(data, encoding); client.end(); }); process.on('exit', function() { assert.equal(receivedSize, kPoolSize); }); node-v0.10.25~dfsg2/test/simple/test-regress-GH-746.js0000644000000000000000000000324712270121457020672 0ustar rootroot// Copyright Joyent, Inc. and other Node contributors. // // Permission is hereby granted, free of charge, to any person obtaining a // copy of this software and associated documentation files (the // "Software"), to deal in the Software without restriction, including // without limitation the rights to use, copy, modify, merge, publish, // distribute, sublicense, and/or sell copies of the Software, and to permit // persons to whom the Software is furnished to do so, subject to the // following conditions: // // The above copyright notice and this permission notice shall be included // in all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS // OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF // MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN // NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, // DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR // OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE // USE OR OTHER DEALINGS IN THE SOFTWARE. // Just test that destroying stdin doesn't mess up listening on a server. // This is a regression test for GH-746. var common = require('../common'); var assert = require('assert'); var net = require('net'); process.stdin.destroy(); var accepted = null; var server = net.createServer(function(socket) { console.log('accepted'); accepted = socket; socket.end(); server.close(); }); server.listen(common.PORT, function() { console.log('listening...'); net.createConnection(common.PORT); }); process.on('exit', function() { assert.ok(accepted); }); node-v0.10.25~dfsg2/test/simple/test-tls-securepair-server.js0000644000000000000000000001006012270121457022643 0ustar rootroot// Copyright Joyent, Inc. and other Node contributors. // // Permission is hereby granted, free of charge, to any person obtaining a // copy of this software and associated documentation files (the // "Software"), to deal in the Software without restriction, including // without limitation the rights to use, copy, modify, merge, publish, // distribute, sublicense, and/or sell copies of the Software, and to permit // persons to whom the Software is furnished to do so, subject to the // following conditions: // // The above copyright notice and this permission notice shall be included // in all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS // OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF // MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN // NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, // DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR // OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE // USE OR OTHER DEALINGS IN THE SOFTWARE. if (!process.versions.openssl) { console.error('Skipping because node compiled without OpenSSL.'); process.exit(0); } var common = require('../common'); var assert = require('assert'); var join = require('path').join; var net = require('net'); var fs = require('fs'); var crypto = require('crypto'); var tls = require('tls'); var spawn = require('child_process').spawn; var connections = 0; var key = fs.readFileSync(join(common.fixturesDir, 'agent.key')).toString(); var cert = fs.readFileSync(join(common.fixturesDir, 'agent.crt')).toString(); function log(a) { console.error('***server*** ' + a); } var server = net.createServer(function(socket) { connections++; log('connection fd=' + socket.fd); var sslcontext = crypto.createCredentials({key: key, cert: cert}); sslcontext.context.setCiphers('RC4-SHA:AES128-SHA:AES256-SHA'); var pair = tls.createSecurePair(sslcontext, true); assert.ok(pair.encrypted.writable); assert.ok(pair.cleartext.writable); pair.encrypted.pipe(socket); socket.pipe(pair.encrypted); log('i set it secure'); pair.on('secure', function() { log('connected+secure!'); pair.cleartext.write('hello\r\n'); log(pair.cleartext.getPeerCertificate()); log(pair.cleartext.getCipher()); }); pair.cleartext.on('data', function(data) { log('read bytes ' + data.length); pair.cleartext.write(data); }); socket.on('end', function() { log('socket end'); }); pair.cleartext.on('error', function(err) { log('got error: '); log(err); log(err.stack); socket.destroy(); }); pair.encrypted.on('error', function(err) { log('encrypted error: '); log(err); log(err.stack); socket.destroy(); }); socket.on('error', function(err) { log('socket error: '); log(err); log(err.stack); socket.destroy(); }); socket.on('close', function(err) { log('socket closed'); }); pair.on('error', function(err) { log('secure error: '); log(err); log(err.stack); socket.destroy(); }); }); var gotHello = false; var sentWorld = false; var gotWorld = false; var opensslExitCode = -1; server.listen(common.PORT, function() { // To test use: openssl s_client -connect localhost:8000 var client = spawn('openssl', ['s_client', '-connect', '127.0.0.1:' + common.PORT]); var out = ''; client.stdout.setEncoding('utf8'); client.stdout.on('data', function(d) { out += d; if (!gotHello && /hello/.test(out)) { gotHello = true; client.stdin.write('world\r\n'); sentWorld = true; } if (!gotWorld && /world/.test(out)) { gotWorld = true; client.stdin.end(); } }); client.stdout.pipe(process.stdout, { end: false }); client.on('exit', function(code) { opensslExitCode = code; server.close(); }); }); process.on('exit', function() { assert.equal(1, connections); assert.ok(gotHello); assert.ok(sentWorld); assert.ok(gotWorld); assert.equal(0, opensslExitCode); }); node-v0.10.25~dfsg2/test/simple/test-https-invalid-key.js0000644000000000000000000000420712270121457021757 0ustar rootroot// Copyright Joyent, Inc. and other Node contributors. // // Permission is hereby granted, free of charge, to any person obtaining a // copy of this software and associated documentation files (the // "Software"), to deal in the Software without restriction, including // without limitation the rights to use, copy, modify, merge, publish, // distribute, sublicense, and/or sell copies of the Software, and to permit // persons to whom the Software is furnished to do so, subject to the // following conditions: // // The above copyright notice and this permission notice shall be included // in all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS // OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF // MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN // NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, // DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR // OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE // USE OR OTHER DEALINGS IN THE SOFTWARE. if (!process.versions.openssl) { console.error('Skipping because node compiled without OpenSSL.'); process.exit(0); } var common = require('../common'); var assert = require('assert'); var https = require('https'); var fs = require('fs'); var path = require('path'); var options = { key: fs.readFileSync(path.join(common.fixturesDir, 'keys/agent1-key.pem')), cert: fs.readFileSync(path.join(common.fixturesDir, 'test_cert.pem')) }; var serverErrorHappened = false; var clientErrorHappened = false; var server = https.Server(options, function(req, res) { assert(false); }); server.on('clientError', function(err) { serverErrorHappened = true; common.debug('Server: ' + err); server.close(); }); server.listen(common.PORT, function() { var req = https.get({port: common.PORT}, function(res) { assert(false); }); req.on('error', function(err) { clientErrorHappened = true; common.debug('Client: ' + err); }); }); process.on('exit', function() { assert(serverErrorHappened); assert(clientErrorHappened); }); node-v0.10.25~dfsg2/test/simple/test-https-client-reject.js0000644000000000000000000000534512270121457022277 0ustar rootroot// Copyright Joyent, Inc. and other Node contributors. // // Permission is hereby granted, free of charge, to any person obtaining a // copy of this software and associated documentation files (the // "Software"), to deal in the Software without restriction, including // without limitation the rights to use, copy, modify, merge, publish, // distribute, sublicense, and/or sell copies of the Software, and to permit // persons to whom the Software is furnished to do so, subject to the // following conditions: // // The above copyright notice and this permission notice shall be included // in all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS // OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF // MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN // NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, // DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR // OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE // USE OR OTHER DEALINGS IN THE SOFTWARE. if (!process.versions.openssl) { console.error('Skipping because node compiled without OpenSSL.'); process.exit(0); } var common = require('../common'); var assert = require('assert'); var https = require('https'); var fs = require('fs'); var path = require('path'); var options = { key: fs.readFileSync(path.join(common.fixturesDir, 'test_key.pem')), cert: fs.readFileSync(path.join(common.fixturesDir, 'test_cert.pem')) }; var reqCount = 0; var server = https.createServer(options, function(req, res) { ++reqCount; res.writeHead(200); res.end(); req.resume(); }).listen(common.PORT, function() { unauthorized(); }); function unauthorized() { var req = https.request({ port: common.PORT, rejectUnauthorized: false }, function(res) { assert(!req.socket.authorized); res.resume(); rejectUnauthorized(); }); req.on('error', function(err) { throw err; }); req.end(); } function rejectUnauthorized() { var options = { port: common.PORT }; options.agent = new https.Agent(options); var req = https.request(options, function(res) { assert(false); }); req.on('error', function(err) { authorized(); }); req.end(); } function authorized() { var options = { port: common.PORT, ca: [fs.readFileSync(path.join(common.fixturesDir, 'test_cert.pem'))] }; options.agent = new https.Agent(options); var req = https.request(options, function(res) { res.resume(); assert(req.socket.authorized); server.close(); }); req.on('error', function(err) { assert(false); }); req.end(); } process.on('exit', function() { assert.equal(reqCount, 2); }); node-v0.10.25~dfsg2/test/simple/test-next-tick-doesnt-hang.js0000644000000000000000000000247412270121457022522 0ustar rootroot// Copyright Joyent, Inc. and other Node contributors. // // Permission is hereby granted, free of charge, to any person obtaining a // copy of this software and associated documentation files (the // "Software"), to deal in the Software without restriction, including // without limitation the rights to use, copy, modify, merge, publish, // distribute, sublicense, and/or sell copies of the Software, and to permit // persons to whom the Software is furnished to do so, subject to the // following conditions: // // The above copyright notice and this permission notice shall be included // in all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS // OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF // MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN // NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, // DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR // OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE // USE OR OTHER DEALINGS IN THE SOFTWARE. /* * This test verifies that having a single nextTick statement and nothing else * does not hang the event loop. If this test times out it has failed. */ process.nextTick(function() { // Nothing }); node-v0.10.25~dfsg2/test/simple/test-stream2-writable.js0000644000000000000000000002041512270121457021566 0ustar rootroot// Copyright Joyent, Inc. and other Node contributors. // // Permission is hereby granted, free of charge, to any person obtaining a // copy of this software and associated documentation files (the // "Software"), to deal in the Software without restriction, including // without limitation the rights to use, copy, modify, merge, publish, // distribute, sublicense, and/or sell copies of the Software, and to permit // persons to whom the Software is furnished to do so, subject to the // following conditions: // // The above copyright notice and this permission notice shall be included // in all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS // OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF // MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN // NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, // DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR // OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE // USE OR OTHER DEALINGS IN THE SOFTWARE. var common = require('../common.js'); var W = require('_stream_writable'); var D = require('_stream_duplex'); var assert = require('assert'); var util = require('util'); util.inherits(TestWriter, W); function TestWriter() { W.apply(this, arguments); this.buffer = []; this.written = 0; } TestWriter.prototype._write = function(chunk, encoding, cb) { // simulate a small unpredictable latency setTimeout(function() { this.buffer.push(chunk.toString()); this.written += chunk.length; cb(); }.bind(this), Math.floor(Math.random() * 10)); }; var chunks = new Array(50); for (var i = 0; i < chunks.length; i++) { chunks[i] = new Array(i + 1).join('x'); } // tiny node-tap lookalike. var tests = []; var count = 0; function test(name, fn) { count++; tests.push([name, fn]); } function run() { var next = tests.shift(); if (!next) return console.error('ok'); var name = next[0]; var fn = next[1]; console.log('# %s', name); fn({ same: assert.deepEqual, equal: assert.equal, end: function () { count--; run(); } }); } // ensure all tests have run process.on("exit", function () { assert.equal(count, 0); }); process.nextTick(run); test('write fast', function(t) { var tw = new TestWriter({ highWaterMark: 100 }); tw.on('finish', function() { t.same(tw.buffer, chunks, 'got chunks in the right order'); t.end(); }); chunks.forEach(function(chunk) { // screw backpressure. Just buffer it all up. tw.write(chunk); }); tw.end(); }); test('write slow', function(t) { var tw = new TestWriter({ highWaterMark: 100 }); tw.on('finish', function() { t.same(tw.buffer, chunks, 'got chunks in the right order'); t.end(); }); var i = 0; (function W() { tw.write(chunks[i++]); if (i < chunks.length) setTimeout(W, 10); else tw.end(); })(); }); test('write backpressure', function(t) { var tw = new TestWriter({ highWaterMark: 50 }); var drains = 0; tw.on('finish', function() { t.same(tw.buffer, chunks, 'got chunks in the right order'); t.equal(drains, 17); t.end(); }); tw.on('drain', function() { drains++; }); var i = 0; (function W() { do { var ret = tw.write(chunks[i++]); } while (ret !== false && i < chunks.length); if (i < chunks.length) { assert(tw._writableState.length >= 50); tw.once('drain', W); } else { tw.end(); } })(); }); test('write bufferize', function(t) { var tw = new TestWriter({ highWaterMark: 100 }); var encodings = [ 'hex', 'utf8', 'utf-8', 'ascii', 'binary', 'base64', 'ucs2', 'ucs-2', 'utf16le', 'utf-16le', undefined ]; tw.on('finish', function() { t.same(tw.buffer, chunks, 'got the expected chunks'); }); chunks.forEach(function(chunk, i) { var enc = encodings[ i % encodings.length ]; chunk = new Buffer(chunk); tw.write(chunk.toString(enc), enc); }); t.end(); }); test('write no bufferize', function(t) { var tw = new TestWriter({ highWaterMark: 100, decodeStrings: false }); tw._write = function(chunk, encoding, cb) { assert(typeof chunk === 'string'); chunk = new Buffer(chunk, encoding); return TestWriter.prototype._write.call(this, chunk, encoding, cb); }; var encodings = [ 'hex', 'utf8', 'utf-8', 'ascii', 'binary', 'base64', 'ucs2', 'ucs-2', 'utf16le', 'utf-16le', undefined ]; tw.on('finish', function() { t.same(tw.buffer, chunks, 'got the expected chunks'); }); chunks.forEach(function(chunk, i) { var enc = encodings[ i % encodings.length ]; chunk = new Buffer(chunk); tw.write(chunk.toString(enc), enc); }); t.end(); }); test('write callbacks', function (t) { var callbacks = chunks.map(function(chunk, i) { return [i, function(er) { callbacks._called[i] = chunk; }]; }).reduce(function(set, x) { set['callback-' + x[0]] = x[1]; return set; }, {}); callbacks._called = []; var tw = new TestWriter({ highWaterMark: 100 }); tw.on('finish', function() { process.nextTick(function() { t.same(tw.buffer, chunks, 'got chunks in the right order'); t.same(callbacks._called, chunks, 'called all callbacks'); t.end(); }); }); chunks.forEach(function(chunk, i) { tw.write(chunk, callbacks['callback-' + i]); }); tw.end(); }); test('end callback', function (t) { var tw = new TestWriter(); tw.end(function () { t.end(); }); }); test('end callback with chunk', function (t) { var tw = new TestWriter(); tw.end(new Buffer('hello world'), function () { t.end(); }); }); test('end callback with chunk and encoding', function (t) { var tw = new TestWriter(); tw.end('hello world', 'ascii', function () { t.end(); }); }); test('end callback after .write() call', function (t) { var tw = new TestWriter(); tw.write(new Buffer('hello world')); tw.end(function () { t.end(); }); }); test('end callback called after write callback', function (t) { var tw = new TestWriter(); var writeCalledback = false; tw.write(new Buffer('hello world'), function() { writeCalledback = true; }); tw.end(function () { t.equal(writeCalledback, true); t.end(); }); }); test('encoding should be ignored for buffers', function(t) { var tw = new W(); var hex = '018b5e9a8f6236ffe30e31baf80d2cf6eb'; tw._write = function(chunk, encoding, cb) { t.equal(chunk.toString('hex'), hex); t.end(); }; var buf = new Buffer(hex, 'hex'); tw.write(buf, 'binary'); }); test('writables are not pipable', function(t) { var w = new W(); w._write = function() {}; var gotError = false; w.on('error', function(er) { gotError = true; }); w.pipe(process.stdout); assert(gotError); t.end(); }); test('duplexes are pipable', function(t) { var d = new D(); d._read = function() {}; d._write = function() {}; var gotError = false; d.on('error', function(er) { gotError = true; }); d.pipe(process.stdout); assert(!gotError); t.end(); }); test('end(chunk) two times is an error', function(t) { var w = new W(); w._write = function() {}; var gotError = false; w.on('error', function(er) { gotError = true; t.equal(er.message, 'write after end'); }); w.end('this is the end'); w.end('and so is this'); process.nextTick(function() { assert(gotError); t.end(); }); }); test('dont end while writing', function(t) { var w = new W(); var wrote = false; w._write = function(chunk, e, cb) { assert(!this.writing); wrote = true; this.writing = true; setTimeout(function() { this.writing = false; cb(); }); }; w.on('finish', function() { assert(wrote); t.end(); }); w.write(Buffer(0)); w.end(); }); test('finish does not come before write cb', function(t) { var w = new W(); var writeCb = false; w._write = function(chunk, e, cb) { setTimeout(function() { writeCb = true; cb(); }, 10); }; w.on('finish', function() { assert(writeCb); t.end(); }); w.write(Buffer(0)); w.end(); }); node-v0.10.25~dfsg2/test/simple/test-regress-GH-4256.js0000644000000000000000000000236412270121457020751 0ustar rootroot// Copyright Joyent, Inc. and other Node contributors. // // Permission is hereby granted, free of charge, to any person obtaining a // copy of this software and associated documentation files (the // "Software"), to deal in the Software without restriction, including // without limitation the rights to use, copy, modify, merge, publish, // distribute, sublicense, and/or sell copies of the Software, and to permit // persons to whom the Software is furnished to do so, subject to the // following conditions: // // The above copyright notice and this permission notice shall be included // in all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS // OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF // MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN // NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, // DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR // OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE // USE OR OTHER DEALINGS IN THE SOFTWARE. process.domain = null; timer = setTimeout(function() { console.log("this console.log statement should not make node crash"); }, 1); node-v0.10.25~dfsg2/test/simple/test-stream2-readable-wrap-empty.js0000644000000000000000000000311412270121457023614 0ustar rootroot// Copyright Joyent, Inc. and other Node contributors. // // Permission is hereby granted, free of charge, to any person obtaining a // copy of this software and associated documentation files (the // "Software"), to deal in the Software without restriction, including // without limitation the rights to use, copy, modify, merge, publish, // distribute, sublicense, and/or sell copies of the Software, and to permit // persons to whom the Software is furnished to do so, subject to the // following conditions: // // The above copyright notice and this permission notice shall be included // in all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS // OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF // MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN // NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, // DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR // OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE // USE OR OTHER DEALINGS IN THE SOFTWARE. var common = require('../common'); var assert = require('assert'); var Readable = require('_stream_readable'); var EE = require('events').EventEmitter; var oldStream = new EE(); oldStream.pause = function(){}; oldStream.resume = function(){}; var newStream = new Readable().wrap(oldStream); var ended = false; newStream .on('readable', function(){}) .on('end', function(){ ended = true; }); oldStream.emit('end'); process.on('exit', function(){ assert.ok(ended); });node-v0.10.25~dfsg2/test/simple/test-http-header-read.js0000644000000000000000000000401112270121457021512 0ustar rootroot// Copyright Joyent, Inc. and other Node contributors. // // Permission is hereby granted, free of charge, to any person obtaining a // copy of this software and associated documentation files (the // "Software"), to deal in the Software without restriction, including // without limitation the rights to use, copy, modify, merge, publish, // distribute, sublicense, and/or sell copies of the Software, and to permit // persons to whom the Software is furnished to do so, subject to the // following conditions: // // The above copyright notice and this permission notice shall be included // in all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS // OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF // MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN // NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, // DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR // OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE // USE OR OTHER DEALINGS IN THE SOFTWARE. var common = require('../common'); var assert = require('assert'); var http = require('http'); // Verify that ServerResponse.getHeader() works correctly even after // the response header has been sent. Issue 752 on github. var s = http.createServer(function(req, res) { var contentType = 'Content-Type'; var plain = 'text/plain'; res.setHeader(contentType, plain); assert.ok(!res.headersSent); res.writeHead(200); assert.ok(res.headersSent); res.end('hello world\n'); // This checks that after the headers have been sent, getHeader works // and does not throw an exception (Issue 752) assert.doesNotThrow( function() { assert.equal(plain, res.getHeader(contentType)); } ); }); s.listen(common.PORT, runTest); function runTest() { http.get({ port: common.PORT }, function(response) { response.on('end', function() { s.close(); }); response.resume(); }); } node-v0.10.25~dfsg2/test/simple/test-zlib-zero-byte.js0000644000000000000000000000316712270121457021265 0ustar rootroot// Copyright Joyent, Inc. and other Node contributors. // // Permission is hereby granted, free of charge, to any person obtaining a // copy of this software and associated documentation files (the // "Software"), to deal in the Software without restriction, including // without limitation the rights to use, copy, modify, merge, publish, // distribute, sublicense, and/or sell copies of the Software, and to permit // persons to whom the Software is furnished to do so, subject to the // following conditions: // // The above copyright notice and this permission notice shall be included // in all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS // OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF // MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN // NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, // DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR // OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE // USE OR OTHER DEALINGS IN THE SOFTWARE. var common = require('../common'); var assert = require('assert'); var zlib = require('zlib'); var gz = zlib.Gzip() var emptyBuffer = new Buffer(0); var received = 0; gz.on('data', function(c) { received += c.length; }); var ended = false; gz.on('end', function() { ended = true; }); var finished = false; gz.on('finish', function() { finished = true; }); gz.write(emptyBuffer); gz.end(); process.on('exit', function() { assert.equal(received, 20); assert(ended); assert(finished); console.log('ok'); }); node-v0.10.25~dfsg2/test/simple/test-repl-.save.load.js0000644000000000000000000000573612270121457021305 0ustar rootroot// Copyright Joyent, Inc. and other Node contributors. // // Permission is hereby granted, free of charge, to any person obtaining a // copy of this software and associated documentation files (the // "Software"), to deal in the Software without restriction, including // without limitation the rights to use, copy, modify, merge, publish, // distribute, sublicense, and/or sell copies of the Software, and to permit // persons to whom the Software is furnished to do so, subject to the // following conditions: // // The above copyright notice and this permission notice shall be included // in all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS // OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF // MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN // NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, // DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR // OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE // USE OR OTHER DEALINGS IN THE SOFTWARE. var assert = require('assert'); var util = require('util'); var join = require('path').join; var fs = require('fs'); var common = require('../common'); var repl = require('repl'); // A stream to push an array into a REPL function ArrayStream() { this.run = function(data) { var self = this; data.forEach(function(line) { self.emit('data', line + '\n'); }); } } util.inherits(ArrayStream, require('stream').Stream); ArrayStream.prototype.readable = true; ArrayStream.prototype.writable = true; ArrayStream.prototype.resume = function() {}; ArrayStream.prototype.write = function() {}; var works = [['inner.one'], 'inner.o']; var putIn = new ArrayStream(); var testMe = repl.start('', putIn); var testFile = [ 'var top = function () {', 'var inner = {one:1};' ]; var saveFileName = join(common.tmpDir, 'test.save.js'); // input some data putIn.run(testFile); // save it to a file putIn.run(['.save ' + saveFileName]); // the file should have what I wrote assert.equal(fs.readFileSync(saveFileName, 'utf8'), testFile.join('\n') + '\n'); // make sure that the REPL data is "correct" // so when I load it back I know I'm good testMe.complete('inner.o', function(error, data) { assert.deepEqual(data, works); }); // clear the REPL putIn.run(['.clear']); // Load the file back in putIn.run(['.load ' + saveFileName]); // make sure that the REPL data is "correct" testMe.complete('inner.o', function(error, data) { assert.deepEqual(data, works); }); // clear the REPL putIn.run(['.clear']); var loadFile = join(common.tmpDir, 'file.does.not.exist'); // shold not break putIn.write = function(data) { // make sure I get a failed to load message and not some crazy error assert.equal(data, 'Failed to load:' + loadFile + '\n'); // eat me to avoid work putIn.write = function() {}; }; putIn.run(['.load ' + loadFile]); //TODO how do I do a failed .save test? node-v0.10.25~dfsg2/test/simple/test-stream2-readable-legacy-drain.js0000644000000000000000000000412312270121457024047 0ustar rootroot// Copyright Joyent, Inc. and other Node contributors. // // Permission is hereby granted, free of charge, to any person obtaining a // copy of this software and associated documentation files (the // "Software"), to deal in the Software without restriction, including // without limitation the rights to use, copy, modify, merge, publish, // distribute, sublicense, and/or sell copies of the Software, and to permit // persons to whom the Software is furnished to do so, subject to the // following conditions: // // The above copyright notice and this permission notice shall be included // in all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS // OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF // MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN // NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, // DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR // OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE // USE OR OTHER DEALINGS IN THE SOFTWARE. var common = require('../common'); var assert = require('assert'); var Stream = require('stream'); var Readable = Stream.Readable; var r = new Readable(); var N = 256; var reads = 0; r._read = function(n) { return r.push(++reads === N ? null : new Buffer(1)); }; var rended = false; r.on('end', function() { rended = true; }); var w = new Stream(); w.writable = true; var writes = 0; var buffered = 0; w.write = function(c) { writes += c.length; buffered += c.length; process.nextTick(drain); return false; }; function drain() { assert(buffered <= 2); buffered = 0; w.emit('drain'); } var wended = false; w.end = function() { wended = true; }; // Just for kicks, let's mess with the drain count. // This verifies that even if it gets negative in the // pipe() cleanup function, we'll still function properly. r.on('readable', function() { w.emit('drain'); }); r.pipe(w); process.on('exit', function() { assert(rended); assert(wended); console.error('ok'); }); node-v0.10.25~dfsg2/test/simple/test-http-zero-length-write.js0000644000000000000000000000510012270121457022737 0ustar rootroot// Copyright Joyent, Inc. and other Node contributors. // // Permission is hereby granted, free of charge, to any person obtaining a // copy of this software and associated documentation files (the // "Software"), to deal in the Software without restriction, including // without limitation the rights to use, copy, modify, merge, publish, // distribute, sublicense, and/or sell copies of the Software, and to permit // persons to whom the Software is furnished to do so, subject to the // following conditions: // // The above copyright notice and this permission notice shall be included // in all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS // OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF // MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN // NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, // DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR // OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE // USE OR OTHER DEALINGS IN THE SOFTWARE. var common = require('../common'); var assert = require('assert'); var http = require('http'); var Stream = require('stream'); function getSrc() { // An old-style readable stream. // The Readable class prevents this behavior. var src = new Stream(); // start out paused, just so we don't miss anything yet. var paused = false; src.pause = function() { paused = true; }; src.resume = function() { paused = false; }; var chunks = [ '', 'asdf', '', 'foo', '', 'bar', '' ]; var interval = setInterval(function() { if (paused) return var chunk = chunks.shift(); if (chunk !== undefined) { src.emit('data', chunk); } else { src.emit('end'); clearInterval(interval); } }, 1); return src; } var expect = 'asdffoobar'; var server = http.createServer(function(req, res) { var actual = ''; req.setEncoding('utf8'); req.on('data', function(c) { actual += c; }); req.on('end', function() { assert.equal(actual, expect); getSrc().pipe(res); }); server.close(); }); server.listen(common.PORT, function() { var req = http.request({ port: common.PORT, method: 'POST' }); var actual = ''; req.on('response', function(res) { res.setEncoding('utf8'); res.on('data', function(c) { actual += c; }); res.on('end', function() { assert.equal(actual, expect); }); }); getSrc().pipe(req); }); process.on('exit', function(c) { if (!c) console.log('ok'); }); node-v0.10.25~dfsg2/test/simple/test-fs-write-file-buffer.js0000644000000000000000000000472312270121457022332 0ustar rootroot// Copyright Joyent, Inc. and other Node contributors. // // Permission is hereby granted, free of charge, to any person obtaining a // copy of this software and associated documentation files (the // "Software"), to deal in the Software without restriction, including // without limitation the rights to use, copy, modify, merge, publish, // distribute, sublicense, and/or sell copies of the Software, and to permit // persons to whom the Software is furnished to do so, subject to the // following conditions: // // The above copyright notice and this permission notice shall be included // in all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS // OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF // MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN // NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, // DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR // OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE // USE OR OTHER DEALINGS IN THE SOFTWARE. var common = require('../common'); var join = require('path').join; var util = require('util'); var fs = require('fs'); var data = [ '/9j/4AAQSkZJRgABAQAAAQABAAD/2wBDAAUDBAQEAwUEBAQFBQUGBwwIBwcH', 'Bw8LCwkMEQ8SEhEPERETFhwXExQaFRERGCEYGh0dHx8fExciJCIeJBweHx7/', '2wBDAQUFBQcGBw4ICA4eFBEUHh4eHh4eHh4eHh4eHh4eHh4eHh4eHh4eHh4e', 'Hh4eHh4eHh4eHh4eHh4eHh4eHh4eHh7/wAARCAAQABADASIAAhEBAxEB/8QA', 'HwAAAQUBAQEBAQEAAAAAAAAAAAECAwQFBgcICQoL/8QAtRAAAgEDAwIEAwUF', 'BAQAAAF9AQIDAAQRBRIhMUEGE1FhByJxFDKBkaEII0KxwRVS0fAkM2JyggkK', 'FhcYGRolJicoKSo0NTY3ODk6Q0RFRkdISUpTVFVWV1hZWmNkZWZnaGlqc3R1', 'dnd4eXqDhIWGh4iJipKTlJWWl5iZmqKjpKWmp6ipqrKztLW2t7i5usLDxMXG', 'x8jJytLT1NXW19jZ2uHi4+Tl5ufo6erx8vP09fb3+Pn6/8QAHwEAAwEBAQEB', 'AQEBAQAAAAAAAAECAwQFBgcICQoL/8QAtREAAgECBAQDBAcFBAQAAQJ3AAEC', 'AxEEBSExBhJBUQdhcRMiMoEIFEKRobHBCSMzUvAVYnLRChYkNOEl8RcYGRom', 'JygpKjU2Nzg5OkNERUZHSElKU1RVVldYWVpjZGVmZ2hpanN0dXZ3eHl6goOE', 'hYaHiImKkpOUlZaXmJmaoqOkpaanqKmqsrO0tba3uLm6wsPExcbHyMnK0tPU', '1dbX2Nna4uPk5ebn6Onq8vP09fb3+Pn6/9oADAMBAAIRAxEAPwDhfBUFl/wk', 'OmPqKJJZw3aiZFBw4z93jnkkc9u9dj8XLfSI/EBt7DTo7ea2Ox5YXVo5FC7g', 'Tjq24nJPXNVtO0KATRvNHCIg3zoWJWQHqp+o4pun+EtJ0zxBq8mnLJa2d1L5', '0NvnKRjJBUE5PAx3NYxxUY0pRtvYHSc5Ka2X9d7H/9k=']; data = data.join('\n'); var buf = new Buffer(data, 'base64'); fs.writeFileSync(join(common.tmpDir, 'test.jpg'), buf); util.log('Done!'); node-v0.10.25~dfsg2/test/simple/test-http-should-keep-alive.js0000644000000000000000000000532212270121457022675 0ustar rootroot// Copyright Joyent, Inc. and other Node contributors. // // Permission is hereby granted, free of charge, to any person obtaining a // copy of this software and associated documentation files (the // "Software"), to deal in the Software without restriction, including // without limitation the rights to use, copy, modify, merge, publish, // distribute, sublicense, and/or sell copies of the Software, and to permit // persons to whom the Software is furnished to do so, subject to the // following conditions: // // The above copyright notice and this permission notice shall be included // in all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS // OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF // MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN // NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, // DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR // OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE // USE OR OTHER DEALINGS IN THE SOFTWARE. var common = require('../common'); var assert = require('assert'); var http = require('http'); var net = require('net'); var SERVER_RESPONSES = [ 'HTTP/1.0 200 ok\r\nContent-Length: 0\r\n\r\n', 'HTTP/1.0 200 ok\r\nContent-Length: 0\r\nConnection: keep-alive\r\n\r\n', 'HTTP/1.0 200 ok\r\nContent-Length: 0\r\nConnection: close\r\n\r\n', 'HTTP/1.1 200 ok\r\nContent-Length: 0\r\n\r\n', 'HTTP/1.1 200 ok\r\nContent-Length: 0\r\nConnection: keep-alive\r\n\r\n', 'HTTP/1.1 200 ok\r\nContent-Length: 0\r\nConnection: close\r\n\r\n' ]; var SHOULD_KEEP_ALIVE = [ false, // HTTP/1.0, default true, // HTTP/1.0, Connection: keep-alive false, // HTTP/1.0, Connection: close true, // HTTP/1.1, default true, // HTTP/1.1, Connection: keep-alive false // HTTP/1.1, Connection: close ]; var requests = 0; var responses = 0; var server = net.createServer(function(socket) { socket.write(SERVER_RESPONSES[requests]); ++requests; }).listen(common.PORT, function() { function makeRequest() { var req = http.get({port: common.PORT}, function(res) { assert.equal(req.shouldKeepAlive, SHOULD_KEEP_ALIVE[responses], SERVER_RESPONSES[responses] + ' should ' + (SHOULD_KEEP_ALIVE[responses] ? '' : 'not ') + 'Keep-Alive'); ++responses; if (responses < SHOULD_KEEP_ALIVE.length) { makeRequest(); } else { server.close(); } res.resume(); }); } makeRequest(); }); process.on('exit', function() { assert.equal(requests, SERVER_RESPONSES.length); assert.equal(responses, SHOULD_KEEP_ALIVE.length); }); node-v0.10.25~dfsg2/test/simple/test-net-dns-error.js0000644000000000000000000000331512270121457021101 0ustar rootroot// Copyright Joyent, Inc. and other Node contributors. // // Permission is hereby granted, free of charge, to any person obtaining a // copy of this software and associated documentation files (the // "Software"), to deal in the Software without restriction, including // without limitation the rights to use, copy, modify, merge, publish, // distribute, sublicense, and/or sell copies of the Software, and to permit // persons to whom the Software is furnished to do so, subject to the // following conditions: // // The above copyright notice and this permission notice shall be included // in all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS // OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF // MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN // NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, // DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR // OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE // USE OR OTHER DEALINGS IN THE SOFTWARE. var common = require('../common'); var assert = require('assert'); var net = require('net'); var expected_bad_connections = 1; var actual_bad_connections = 0; var host = '********'; host += host; host += host; host += host; host += host; host += host; function do_not_call() { throw new Error('This function should not have been called.'); } var socket = net.connect(42, host, do_not_call); socket.on('error', function(err) { assert.equal(err.code, 'ENOTFOUND'); actual_bad_connections++; }); process.on('exit', function() { assert.equal(actual_bad_connections, expected_bad_connections); }); node-v0.10.25~dfsg2/test/simple/test-http-abort-stream-end.js0000644000000000000000000000364212270121457022526 0ustar rootroot// Copyright Joyent, Inc. and other Node contributors. // // Permission is hereby granted, free of charge, to any person obtaining a // copy of this software and associated documentation files (the // "Software"), to deal in the Software without restriction, including // without limitation the rights to use, copy, modify, merge, publish, // distribute, sublicense, and/or sell copies of the Software, and to permit // persons to whom the Software is furnished to do so, subject to the // following conditions: // // The above copyright notice and this permission notice shall be included // in all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS // OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF // MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN // NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, // DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR // OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE // USE OR OTHER DEALINGS IN THE SOFTWARE. var common = require('../common'); var assert = require('assert'); var http = require('http'); var maxSize = 1024; var size = 0; var s = http.createServer(function(req, res) { this.close(); res.writeHead(200, {'Content-Type': 'text/plain'}); for (var i = 0; i < maxSize; i++) { res.write('x' + i); } res.end(); }); var aborted = false; s.listen(common.PORT, function() { var req = http.get('http://localhost:' + common.PORT, function(res) { res.on('data', function(chunk) { size += chunk.length; assert(!aborted, 'got data after abort'); if (size > maxSize) { aborted = true; req.abort(); size = maxSize; } }); }); req.end(); }); process.on('exit', function() { assert(aborted); assert.equal(size, maxSize); console.log('ok'); }); node-v0.10.25~dfsg2/test/simple/test-child-process-fork.js0000644000000000000000000000363212270121457022102 0ustar rootroot// Copyright Joyent, Inc. and other Node contributors. // // Permission is hereby granted, free of charge, to any person obtaining a // copy of this software and associated documentation files (the // "Software"), to deal in the Software without restriction, including // without limitation the rights to use, copy, modify, merge, publish, // distribute, sublicense, and/or sell copies of the Software, and to permit // persons to whom the Software is furnished to do so, subject to the // following conditions: // // The above copyright notice and this permission notice shall be included // in all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS // OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF // MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN // NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, // DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR // OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE // USE OR OTHER DEALINGS IN THE SOFTWARE. var assert = require('assert'); var common = require('../common'); var fork = require('child_process').fork; var args = ['foo', 'bar']; var n = fork(common.fixturesDir + '/child-process-spawn-node.js', args); assert.deepEqual(args, ['foo', 'bar']); var messageCount = 0; n.on('message', function(m) { console.log('PARENT got message:', m); assert.ok(m.foo); messageCount++; }); // https://github.com/joyent/node/issues/2355 - JSON.stringify(undefined) // returns "undefined" but JSON.parse() cannot parse that... assert.throws(function() { n.send(undefined); }, TypeError); assert.throws(function() { n.send(); }, TypeError); n.send({ hello: 'world' }); var childExitCode = -1; n.on('exit', function(c) { childExitCode = c; }); process.on('exit', function() { assert.ok(childExitCode == 0); }); node-v0.10.25~dfsg2/test/simple/test-http-expect-continue.js0000644000000000000000000000572412270121457022477 0ustar rootroot// Copyright Joyent, Inc. and other Node contributors. // // Permission is hereby granted, free of charge, to any person obtaining a // copy of this software and associated documentation files (the // "Software"), to deal in the Software without restriction, including // without limitation the rights to use, copy, modify, merge, publish, // distribute, sublicense, and/or sell copies of the Software, and to permit // persons to whom the Software is furnished to do so, subject to the // following conditions: // // The above copyright notice and this permission notice shall be included // in all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS // OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF // MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN // NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, // DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR // OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE // USE OR OTHER DEALINGS IN THE SOFTWARE. var common = require('../common'); var assert = require('assert'); var http = require('http'); var outstanding_reqs = 0; var test_req_body = 'some stuff...\n'; var test_res_body = 'other stuff!\n'; var sent_continue = false; var got_continue = false; function handler(req, res) { assert.equal(sent_continue, true, 'Full response sent before 100 Continue'); common.debug('Server sending full response...'); res.writeHead(200, { 'Content-Type' : 'text/plain', 'ABCD' : '1' }); res.end(test_res_body); } var server = http.createServer(handler); server.on('checkContinue', function(req, res) { common.debug('Server got Expect: 100-continue...'); res.writeContinue(); sent_continue = true; setTimeout(function() { handler(req, res); }, 100); }); server.listen(common.PORT); server.on('listening', function() { var req = http.request({ port: common.PORT, method: 'POST', path: '/world', headers: { 'Expect': '100-continue' } }); common.debug('Client sending request...'); outstanding_reqs++; var body = ''; req.on('continue', function() { common.debug('Client got 100 Continue...'); got_continue = true; req.end(test_req_body); }); req.on('response', function(res) { assert.equal(got_continue, true, 'Full response received before 100 Continue'); assert.equal(200, res.statusCode, 'Final status code was ' + res.statusCode + ', not 200.'); res.setEncoding('utf8'); res.on('data', function(chunk) { body += chunk; }); res.on('end', function() { common.debug('Got full response.'); assert.equal(body, test_res_body, 'Response body doesn\'t match.'); assert.ok('abcd' in res.headers, 'Response headers missing.'); outstanding_reqs--; if (outstanding_reqs == 0) { server.close(); process.exit(); } }); }); }); node-v0.10.25~dfsg2/test/simple/test-tty-stdout-end.js0000644000000000000000000000273412270121457021312 0ustar rootroot// Copyright Joyent, Inc. and other Node contributors. // // Permission is hereby granted, free of charge, to any person obtaining a // copy of this software and associated documentation files (the // "Software"), to deal in the Software without restriction, including // without limitation the rights to use, copy, modify, merge, publish, // distribute, sublicense, and/or sell copies of the Software, and to permit // persons to whom the Software is furnished to do so, subject to the // following conditions: // // The above copyright notice and this permission notice shall be included // in all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS // OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF // MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN // NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, // DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR // OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE // USE OR OTHER DEALINGS IN THE SOFTWARE. // Can't test this when 'make test' doesn't assign a tty to the stdout. var common = require('../common'); var assert = require('assert'); var exceptionCaught = false; try { process.stdout.end(); } catch (e) { exceptionCaught = true; assert.ok(common.isError(e)); assert.equal('process.stdout cannot be closed.', e.message); } assert.ok(exceptionCaught); node-v0.10.25~dfsg2/test/simple/test-crypto-verify-failure.js0000644000000000000000000000453612270121457022657 0ustar rootroot// Copyright Joyent, Inc. and other Node contributors. // // Permission is hereby granted, free of charge, to any person obtaining a // copy of this software and associated documentation files (the // "Software"), to deal in the Software without restriction, including // without limitation the rights to use, copy, modify, merge, publish, // distribute, sublicense, and/or sell copies of the Software, and to permit // persons to whom the Software is furnished to do so, subject to the // following conditions: // // The above copyright notice and this permission notice shall be included // in all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS // OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF // MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN // NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, // DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR // OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE // USE OR OTHER DEALINGS IN THE SOFTWARE. var common = require('../common'); var assert = require('assert'); try { var crypto = require('crypto'); var tls = require('tls'); } catch (e) { console.log('Not compiled with OPENSSL support.'); process.exit(); } crypto.DEFAULT_ENCODING = 'buffer'; var fs = require('fs'); var certPem = fs.readFileSync(common.fixturesDir + '/test_cert.pem', 'ascii'); var options = { key: fs.readFileSync(common.fixturesDir + '/keys/agent1-key.pem'), cert: fs.readFileSync(common.fixturesDir + '/keys/agent1-cert.pem') }; var canSend = true; var server = tls.Server(options, function(socket) { process.nextTick(function() { console.log('sending'); socket.destroy(); verify(); }); }); var client; function verify() { console.log('verify'); var verified = crypto.createVerify('RSA-SHA1') .update('Test') .verify(certPem, 'asdfasdfas', 'base64'); } server.listen(common.PORT, function() { client = tls.connect({ port: common.PORT, rejectUnauthorized: false }, function() { verify(); }).on('data', function(data) { console.log(data); }).on('error', function(err) { throw err; }).on('close', function() { server.close(); }).resume(); }); server.unref(); node-v0.10.25~dfsg2/test/simple/test-http-unix-socket.js0000644000000000000000000000461012270121457021627 0ustar rootroot// Copyright Joyent, Inc. and other Node contributors. // // Permission is hereby granted, free of charge, to any person obtaining a // copy of this software and associated documentation files (the // "Software"), to deal in the Software without restriction, including // without limitation the rights to use, copy, modify, merge, publish, // distribute, sublicense, and/or sell copies of the Software, and to permit // persons to whom the Software is furnished to do so, subject to the // following conditions: // // The above copyright notice and this permission notice shall be included // in all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS // OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF // MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN // NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, // DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR // OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE // USE OR OTHER DEALINGS IN THE SOFTWARE. var common = require('../common'); var assert = require('assert'); var fs = require('fs'); var http = require('http'); var status_ok = false; // status code == 200? var headers_ok = false; var body_ok = false; var server = http.createServer(function(req, res) { res.writeHead(200, { 'Content-Type': 'text/plain', 'Connection': 'close' }); res.write('hello '); res.write('world\n'); res.end(); }); server.listen(common.PIPE, function() { var options = { socketPath: common.PIPE, path: '/' }; var req = http.get(options, function(res) { assert.equal(res.statusCode, 200); status_ok = true; assert.equal(res.headers['content-type'], 'text/plain'); headers_ok = true; res.body = ''; res.setEncoding('utf8'); res.on('data', function(chunk) { res.body += chunk; }); res.on('end', function() { assert.equal(res.body, 'hello world\n'); body_ok = true; server.close(); }); }); req.on('error', function(e) { console.log(e.stack); process.exit(1); }); req.end(); }); process.on('exit', function() { assert.ok(status_ok); assert.ok(headers_ok); assert.ok(body_ok); // Double close should throw. Follows net_legacy behaviour. assert.throws(function() { server.close(); }); }); node-v0.10.25~dfsg2/test/simple/test-child-process-detached.js0000644000000000000000000000331212270121457022675 0ustar rootroot// Copyright Joyent, Inc. and other Node contributors. // // Permission is hereby granted, free of charge, to any person obtaining a // copy of this software and associated documentation files (the // "Software"), to deal in the Software without restriction, including // without limitation the rights to use, copy, modify, merge, publish, // distribute, sublicense, and/or sell copies of the Software, and to permit // persons to whom the Software is furnished to do so, subject to the // following conditions: // // The above copyright notice and this permission notice shall be included // in all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS // OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF // MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN // NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, // DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR // OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE // USE OR OTHER DEALINGS IN THE SOFTWARE. var common = require('../common'); var assert = require('assert'); var path = require('path'); var spawn = require('child_process').spawn; var childPath = path.join(__dirname, '..', 'fixtures', 'parent-process-nonpersistent.js'); var persistentPid = -1; var child = spawn(process.execPath, [ childPath ]); child.stdout.on('data', function (data) { persistentPid = parseInt(data, 10); }); process.on('exit', function () { assert(persistentPid !== -1); assert.throws(function () { process.kill(child.pid); }); assert.doesNotThrow(function () { process.kill(persistentPid); }); }); node-v0.10.25~dfsg2/test/simple/test-setproctitle.js0000644000000000000000000000413712270121457021126 0ustar rootroot// Copyright Joyent, Inc. and other Node contributors. // // Permission is hereby granted, free of charge, to any person obtaining a // copy of this software and associated documentation files (the // "Software"), to deal in the Software without restriction, including // without limitation the rights to use, copy, modify, merge, publish, // distribute, sublicense, and/or sell copies of the Software, and to permit // persons to whom the Software is furnished to do so, subject to the // following conditions: // // The above copyright notice and this permission notice shall be included // in all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS // OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF // MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN // NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, // DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR // OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE // USE OR OTHER DEALINGS IN THE SOFTWARE. // Original test written by Jakub Lekstan // FIXME add sunos support if ('linux freebsd darwin'.indexOf(process.platform) === -1) { console.error('Skipping test, platform not supported.'); process.exit(); } var common = require('../common'); var assert = require('assert'); var exec = require('child_process').exec; // The title shouldn't be too long; libuv's uv_set_process_title() out of // security considerations no longer overwrites envp, only argv, so the // maximum title length is possibly quite short. var title = 'testme'; assert.notEqual(process.title, title); process.title = title; assert.equal(process.title, title); exec('ps -p ' + process.pid + ' -o args=', function(error, stdout, stderr) { assert.equal(error, null); assert.equal(stderr, ''); // freebsd always add ' (procname)' to the process title if (process.platform === 'freebsd') title += ' (node)'; // omitting trailing whitespace and \n assert.equal(stdout.replace(/\s+$/, ''), title); }); node-v0.10.25~dfsg2/test/simple/test-vm-create-context-circular-reference.js0000644000000000000000000000253312270121457025506 0ustar rootroot// Copyright Joyent, Inc. and other Node contributors. // // Permission is hereby granted, free of charge, to any person obtaining a // copy of this software and associated documentation files (the // "Software"), to deal in the Software without restriction, including // without limitation the rights to use, copy, modify, merge, publish, // distribute, sublicense, and/or sell copies of the Software, and to permit // persons to whom the Software is furnished to do so, subject to the // following conditions: // // The above copyright notice and this permission notice shall be included // in all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS // OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF // MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN // NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, // DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR // OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE // USE OR OTHER DEALINGS IN THE SOFTWARE. var common = require('../common'); var assert = require('assert'); var vm = require('vm'); var sbx = {}; sbx.window = sbx; sbx = vm.createContext(sbx); sbx.test = 123; assert.equal(sbx.window.window.window.window.window.test, 123); node-v0.10.25~dfsg2/test/simple/test-tcp-wrap-listen.js0000644000000000000000000000631712270121457021440 0ustar rootroot// Copyright Joyent, Inc. and other Node contributors. // // Permission is hereby granted, free of charge, to any person obtaining a // copy of this software and associated documentation files (the // "Software"), to deal in the Software without restriction, including // without limitation the rights to use, copy, modify, merge, publish, // distribute, sublicense, and/or sell copies of the Software, and to permit // persons to whom the Software is furnished to do so, subject to the // following conditions: // // The above copyright notice and this permission notice shall be included // in all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS // OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF // MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN // NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, // DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR // OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE // USE OR OTHER DEALINGS IN THE SOFTWARE. var common = require('../common'); var assert = require('assert'); var TCP = process.binding('tcp_wrap').TCP; var server = new TCP(); var r = server.bind('0.0.0.0', common.PORT); assert.equal(0, r); server.listen(128); var slice, sliceCount = 0, eofCount = 0; var writeCount = 0; var recvCount = 0; server.onconnection = function(client) { assert.equal(0, client.writeQueueSize); console.log('got connection'); function maybeCloseClient() { if (client.pendingWrites.length == 0 && client.gotEOF) { console.log('close client'); client.close(); } } client.readStart(); client.pendingWrites = []; client.onread = function(buffer, offset, length) { if (buffer) { assert.ok(length > 0); assert.equal(0, client.writeQueueSize); var req = client.writeBuffer(buffer.slice(offset, offset + length)); client.pendingWrites.push(req); console.log('client.writeQueueSize: ' + client.writeQueueSize); // 11 bytes should flush assert.equal(0, client.writeQueueSize); req.oncomplete = function(status, client_, req_) { assert.equal(req, client.pendingWrites.shift()); // Check parameters. assert.equal(0, status); assert.equal(client, client_); assert.equal(req, req_); console.log('client.writeQueueSize: ' + client.writeQueueSize); assert.equal(0, client.writeQueueSize); writeCount++; console.log('write ' + writeCount); maybeCloseClient(); }; sliceCount++; } else { console.log('eof'); client.gotEOF = true; server.close(); eofCount++; maybeCloseClient(); } }; }; var net = require('net'); var c = net.createConnection(common.PORT); c.on('connect', function() { c.end('hello world'); }); c.setEncoding('utf8'); c.on('data', function(d) { assert.equal('hello world', d); recvCount++; }); c.on('close', function() { console.error('client closed'); }); process.on('exit', function() { assert.equal(1, sliceCount); assert.equal(1, eofCount); assert.equal(1, writeCount); assert.equal(1, recvCount); }); node-v0.10.25~dfsg2/test/simple/test-http-upgrade-client.js0000644000000000000000000000476312270121457022272 0ustar rootroot// Copyright Joyent, Inc. and other Node contributors. // // Permission is hereby granted, free of charge, to any person obtaining a // copy of this software and associated documentation files (the // "Software"), to deal in the Software without restriction, including // without limitation the rights to use, copy, modify, merge, publish, // distribute, sublicense, and/or sell copies of the Software, and to permit // persons to whom the Software is furnished to do so, subject to the // following conditions: // // The above copyright notice and this permission notice shall be included // in all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS // OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF // MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN // NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, // DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR // OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE // USE OR OTHER DEALINGS IN THE SOFTWARE. // Verify that the 'upgrade' header causes an 'upgrade' event to be emitted to // the HTTP client. This test uses a raw TCP server to better control server // behavior. var common = require('../common'); var assert = require('assert'); var http = require('http'); var net = require('net'); // Create a TCP server var srv = net.createServer(function(c) { var data = ''; c.on('data', function(d) { data += d.toString('utf8'); c.write('HTTP/1.1 101\r\n'); c.write('hello: world\r\n'); c.write('connection: upgrade\r\n'); c.write('upgrade: websocket\r\n'); c.write('\r\n'); c.write('nurtzo'); }); c.on('end', function() { c.end(); }); }); var gotUpgrade = false; srv.listen(common.PORT, '127.0.0.1', function() { var req = http.get({ port: common.PORT }); req.on('upgrade', function(res, socket, upgradeHead) { // XXX: This test isn't fantastic, as it assumes that the entire response // from the server will arrive in a single data callback assert.equal(upgradeHead, 'nurtzo'); console.log(res.headers); var expectedHeaders = {'hello': 'world', 'connection': 'upgrade', 'upgrade': 'websocket' }; assert.deepEqual(expectedHeaders, res.headers); socket.end(); srv.close(); gotUpgrade = true; }); }); process.on('exit', function() { assert.ok(gotUpgrade); }); node-v0.10.25~dfsg2/test/simple/test-http-parser-free.js0000644000000000000000000000352012270121457021570 0ustar rootroot// Copyright Joyent, Inc. and other Node contributors. // // Permission is hereby granted, free of charge, to any person obtaining a // copy of this software and associated documentation files (the // "Software"), to deal in the Software without restriction, including // without limitation the rights to use, copy, modify, merge, publish, // distribute, sublicense, and/or sell copies of the Software, and to permit // persons to whom the Software is furnished to do so, subject to the // following conditions: // // The above copyright notice and this permission notice shall be included // in all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS // OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF // MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN // NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, // DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR // OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE // USE OR OTHER DEALINGS IN THE SOFTWARE. var common = require('../common'); var assert = require('assert'); var http = require('http'); var N = 100; var responses = 0; var server = http.createServer(function(req, res) { res.end('Hello'); }); server.listen(common.PORT, function() { http.globalAgent.maxSockets = 1; var parser; for (var i = 0; i < N; ++i) { (function makeRequest(i) { var req = http.get({port: common.PORT}, function(res) { if (!parser) { parser = req.parser; } else { assert.strictEqual(req.parser, parser); } if (++responses === N) { server.close(); } res.resume(); }); })(i); } }); process.on('exit', function() { assert.equal(responses, N); }); node-v0.10.25~dfsg2/test/simple/test-http-server-multiheaders.js0000644000000000000000000000550312270121457023352 0ustar rootroot// Copyright Joyent, Inc. and other Node contributors. // // Permission is hereby granted, free of charge, to any person obtaining a // copy of this software and associated documentation files (the // "Software"), to deal in the Software without restriction, including // without limitation the rights to use, copy, modify, merge, publish, // distribute, sublicense, and/or sell copies of the Software, and to permit // persons to whom the Software is furnished to do so, subject to the // following conditions: // // The above copyright notice and this permission notice shall be included // in all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS // OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF // MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN // NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, // DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR // OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE // USE OR OTHER DEALINGS IN THE SOFTWARE. // Verify that the HTTP server implementation handles multiple instances // of the same header as per RFC2616: joining the handful of fields by ', ' // that support it, and dropping duplicates for other fields. var common = require('../common'); var assert = require('assert'); var http = require('http'); var srv = http.createServer(function(req, res) { assert.equal(req.headers.accept, 'abc, def, ghijklmnopqrst'); assert.equal(req.headers.host, 'foo'); assert.equal(req.headers['www-authenticate'], 'foo, bar, baz'); assert.equal(req.headers['proxy-authenticate'], 'foo, bar, baz'); assert.equal(req.headers['x-foo'], 'bingo'); assert.equal(req.headers['x-bar'], 'banjo, bango'); assert.equal(req.headers['sec-websocket-protocol'], 'chat, share'); assert.equal(req.headers['sec-websocket-extensions'], 'foo; 1, bar; 2, baz'); res.writeHead(200, {'Content-Type' : 'text/plain'}); res.end('EOF'); srv.close(); }); srv.listen(common.PORT, function() { http.get({ host: 'localhost', port: common.PORT, path: '/', headers: [ ['accept', 'abc'], ['accept', 'def'], ['Accept', 'ghijklmnopqrst'], ['host', 'foo'], ['Host', 'bar'], ['hOst', 'baz'], ['www-authenticate', 'foo'], ['WWW-Authenticate', 'bar'], ['WWW-AUTHENTICATE', 'baz'], ['proxy-authenticate','foo'], ['Proxy-Authenticate','bar'], ['PROXY-AUTHENTICATE','baz'], ['x-foo', 'bingo'], ['x-bar', 'banjo'], ['x-bar', 'bango'], ['sec-websocket-protocol', 'chat'], ['sec-websocket-protocol', 'share'], ['sec-websocket-extensions', 'foo; 1'], ['sec-websocket-extensions', 'bar; 2'], ['sec-websocket-extensions', 'baz'] ] }); }); node-v0.10.25~dfsg2/test/simple/test-stream2-push.js0000644000000000000000000000625512270121457020742 0ustar rootroot// Copyright Joyent, Inc. and other Node contributors. // // Permission is hereby granted, free of charge, to any person obtaining a // copy of this software and associated documentation files (the // "Software"), to deal in the Software without restriction, including // without limitation the rights to use, copy, modify, merge, publish, // distribute, sublicense, and/or sell copies of the Software, and to permit // persons to whom the Software is furnished to do so, subject to the // following conditions: // // The above copyright notice and this permission notice shall be included // in all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS // OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF // MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN // NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, // DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR // OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE // USE OR OTHER DEALINGS IN THE SOFTWARE. var common = require('../common.js'); var stream = require('stream'); var Readable = stream.Readable; var Writable = stream.Writable; var assert = require('assert'); var util = require('util'); var EE = require('events').EventEmitter; // a mock thing a bit like the net.Socket/tcp_wrap.handle interaction var stream = new Readable({ highWaterMark: 16, encoding: 'utf8' }); var source = new EE; stream._read = function() { console.error('stream._read'); readStart(); }; var ended = false; stream.on('end', function() { ended = true; }); source.on('data', function(chunk) { var ret = stream.push(chunk); console.error('data', stream._readableState.length); if (!ret) readStop(); }); source.on('end', function() { stream.push(null); }); var reading = false; function readStart() { console.error('readStart'); reading = true; } function readStop() { console.error('readStop'); reading = false; process.nextTick(function() { var r = stream.read(); if (r !== null) writer.write(r); }); } var writer = new Writable({ decodeStrings: false }); var written = []; var expectWritten = [ 'asdfgasdfgasdfgasdfg', 'asdfgasdfgasdfgasdfg', 'asdfgasdfgasdfgasdfg', 'asdfgasdfgasdfgasdfg', 'asdfgasdfgasdfgasdfg', 'asdfgasdfgasdfgasdfg' ]; writer._write = function(chunk, encoding, cb) { console.error('WRITE %s', chunk); written.push(chunk); process.nextTick(cb); }; writer.on('finish', finish); // now emit some chunks. var chunk = "asdfg"; var set = 0; readStart(); data(); function data() { assert(reading); source.emit('data', chunk); assert(reading); source.emit('data', chunk); assert(reading); source.emit('data', chunk); assert(reading); source.emit('data', chunk); assert(!reading); if (set++ < 5) setTimeout(data, 10); else end(); } function finish() { console.error('finish'); assert.deepEqual(written, expectWritten); console.log('ok'); } function end() { source.emit('end'); assert(!reading); writer.end(stream.read()); setTimeout(function() { assert(ended); }); } node-v0.10.25~dfsg2/test/simple/test-timers-zero-timeout.js0000644000000000000000000000360212270121457022345 0ustar rootroot// Copyright Joyent, Inc. and other Node contributors. // // Permission is hereby granted, free of charge, to any person obtaining a // copy of this software and associated documentation files (the // "Software"), to deal in the Software without restriction, including // without limitation the rights to use, copy, modify, merge, publish, // distribute, sublicense, and/or sell copies of the Software, and to permit // persons to whom the Software is furnished to do so, subject to the // following conditions: // // The above copyright notice and this permission notice shall be included // in all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS // OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF // MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN // NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, // DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR // OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE // USE OR OTHER DEALINGS IN THE SOFTWARE. var common = require('../common'); var assert = require('assert'); // https://github.com/joyent/node/issues/2079 - zero timeout drops extra args (function() { var ncalled = 0; setTimeout(f, 0, 'foo', 'bar', 'baz'); var timer = setTimeout(function() {}, 0); function f(a, b, c) { assert.equal(a, 'foo'); assert.equal(b, 'bar'); assert.equal(c, 'baz'); ncalled++; } process.on('exit', function() { assert.equal(ncalled, 1); }); })(); (function() { var ncalled = 0; var iv = setInterval(f, 0, 'foo', 'bar', 'baz'); function f(a, b, c) { assert.equal(a, 'foo'); assert.equal(b, 'bar'); assert.equal(c, 'baz'); if (++ncalled == 3) clearTimeout(iv); } process.on('exit', function() { assert.equal(ncalled, 3); }); })(); node-v0.10.25~dfsg2/test/simple/test-os.js0000644000000000000000000000617212270121457017027 0ustar rootroot// Copyright Joyent, Inc. and other Node contributors. // // Permission is hereby granted, free of charge, to any person obtaining a // copy of this software and associated documentation files (the // "Software"), to deal in the Software without restriction, including // without limitation the rights to use, copy, modify, merge, publish, // distribute, sublicense, and/or sell copies of the Software, and to permit // persons to whom the Software is furnished to do so, subject to the // following conditions: // // The above copyright notice and this permission notice shall be included // in all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS // OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF // MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN // NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, // DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR // OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE // USE OR OTHER DEALINGS IN THE SOFTWARE. var common = require('../common'); var assert = require('assert'); var os = require('os'); process.env.TMPDIR = '/tmpdir'; process.env.TMP = '/tmp'; process.env.TEMP = '/temp'; var t = ( process.platform === 'win32' ? 'c:\\windows\\temp' : '/tmp' ); assert.equal(os.tmpdir(), '/tmpdir'); process.env.TMPDIR = ''; assert.equal(os.tmpdir(), '/tmp'); process.env.TMP = ''; assert.equal(os.tmpdir(), '/temp'); process.env.TEMP = ''; assert.equal(os.tmpdir(), t); var endianness = os.endianness(); console.log('endianness = %s', endianness); assert.ok(/[BL]E/.test(endianness)); var hostname = os.hostname(); console.log('hostname = %s', hostname); assert.ok(hostname.length > 0); var uptime = os.uptime(); console.log('uptime = %d', uptime); assert.ok(uptime > 0); var cpus = os.cpus(); console.log('cpus = ', cpus); assert.ok(cpus.length > 0); var type = os.type(); console.log('type = ', type); assert.ok(type.length > 0); var release = os.release(); console.log('release = ', release); assert.ok(release.length > 0); var platform = os.platform(); console.log('platform = ', platform); assert.ok(platform.length > 0); var arch = os.arch(); console.log('arch = ', arch); assert.ok(arch.length > 0); if (process.platform != 'sunos') { // not implemeneted yet assert.ok(os.loadavg().length > 0); assert.ok(os.freemem() > 0); assert.ok(os.totalmem() > 0); } var interfaces = os.networkInterfaces(); console.error(interfaces); switch (platform) { case 'linux': var filter = function(e) { return e.address == '127.0.0.1'; }; var actual = interfaces.lo.filter(filter); var expected = [{ address: '127.0.0.1', family: 'IPv4', internal: true }]; assert.deepEqual(actual, expected); break; case 'win32': var filter = function(e) { return e.address == '127.0.0.1'; }; var actual = interfaces['Loopback Pseudo-Interface 1'].filter(filter); var expected = [{ address: '127.0.0.1', family: 'IPv4', internal: true }]; assert.deepEqual(actual, expected); break; } var EOL = os.EOL; assert.ok(EOL.length > 0); node-v0.10.25~dfsg2/test/simple/test-process-exit-recursive.js0000644000000000000000000000265112270121457023036 0ustar rootroot// Copyright Joyent, Inc. and other Node contributors. // // Permission is hereby granted, free of charge, to any person obtaining a // copy of this software and associated documentation files (the // "Software"), to deal in the Software without restriction, including // without limitation the rights to use, copy, modify, merge, publish, // distribute, sublicense, and/or sell copies of the Software, and to permit // persons to whom the Software is furnished to do so, subject to the // following conditions: // // The above copyright notice and this permission notice shall be included // in all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS // OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF // MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN // NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, // DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR // OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE // USE OR OTHER DEALINGS IN THE SOFTWARE. var assert = require('assert'); // recursively calling .exit() should not overflow the call stack var nexits = 0; process.on('exit', function(code) { assert.equal(nexits++, 0); assert.equal(code, 1); // now override the exit code of 1 with 0 so that the test passes process.exit(); }); process.exit(1); node-v0.10.25~dfsg2/test/simple/test-pump-file2tcp-noexist.js0000644000000000000000000000456012270121457022563 0ustar rootroot// Copyright Joyent, Inc. and other Node contributors. // // Permission is hereby granted, free of charge, to any person obtaining a // copy of this software and associated documentation files (the // "Software"), to deal in the Software without restriction, including // without limitation the rights to use, copy, modify, merge, publish, // distribute, sublicense, and/or sell copies of the Software, and to permit // persons to whom the Software is furnished to do so, subject to the // following conditions: // // The above copyright notice and this permission notice shall be included // in all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS // OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF // MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN // NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, // DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR // OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE // USE OR OTHER DEALINGS IN THE SOFTWARE. var common = require('../common'); var assert = require('assert'); var net = require('net'); var fs = require('fs'); var util = require('util'); var path = require('path'); var fn = path.join(common.fixturesDir, 'does_not_exist.txt'); var got_error = false; var conn_closed = false; var server = net.createServer(function(stream) { common.error('pump!'); util.pump(fs.createReadStream(fn), stream, function(err) { common.error('util.pump\'s callback fired'); if (err) { got_error = true; } else { common.debug('util.pump\'s callback fired with no error'); common.debug('this shouldn\'t happen as the file doesn\'t exist...'); assert.equal(true, false); } server.close(); }); }); server.listen(common.PORT, function() { var conn = net.createConnection(common.PORT); conn.setEncoding('utf8'); conn.on('data', function(chunk) { common.error('recv data! nchars = ' + chunk.length); buffer += chunk; }); conn.on('end', function() { conn.end(); }); conn.on('close', function() { common.error('client connection close'); conn_closed = true; }); }); var buffer = ''; process.on('exit', function() { assert.equal(true, got_error); assert.equal(true, conn_closed); console.log('exiting'); }); node-v0.10.25~dfsg2/test/simple/test-event-emitter-add-listeners.js0000644000000000000000000000416612270121457023733 0ustar rootroot// Copyright Joyent, Inc. and other Node contributors. // // Permission is hereby granted, free of charge, to any person obtaining a // copy of this software and associated documentation files (the // "Software"), to deal in the Software without restriction, including // without limitation the rights to use, copy, modify, merge, publish, // distribute, sublicense, and/or sell copies of the Software, and to permit // persons to whom the Software is furnished to do so, subject to the // following conditions: // // The above copyright notice and this permission notice shall be included // in all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS // OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF // MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN // NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, // DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR // OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE // USE OR OTHER DEALINGS IN THE SOFTWARE. var common = require('../common'); var assert = require('assert'); var events = require('events'); var e = new events.EventEmitter(); var events_new_listener_emited = []; var listeners_new_listener_emited = []; var times_hello_emited = 0; // sanity check assert.equal(e.addListener, e.on); e.on('newListener', function(event, listener) { console.log('newListener: ' + event); events_new_listener_emited.push(event); listeners_new_listener_emited.push(listener); }); function hello(a, b) { console.log('hello'); times_hello_emited += 1; assert.equal('a', a); assert.equal('b', b); } e.on('hello', hello); var foo = function() {}; e.once('foo', foo); console.log('start'); e.emit('hello', 'a', 'b'); // just make sure that this doesn't throw: var f = new events.EventEmitter(); f.setMaxListeners(0); process.on('exit', function() { assert.deepEqual(['hello', 'foo'], events_new_listener_emited); assert.deepEqual([hello, foo], listeners_new_listener_emited); assert.equal(1, times_hello_emited); }); node-v0.10.25~dfsg2/test/simple/test-fs-truncate-GH-6233.js0000644000000000000000000000345612270121457021532 0ustar rootroot// Copyright Joyent, Inc. and other Node contributors. // // Permission is hereby granted, free of charge, to any person obtaining a // copy of this software and associated documentation files (the // "Software"), to deal in the Software without restriction, including // without limitation the rights to use, copy, modify, merge, publish, // distribute, sublicense, and/or sell copies of the Software, and to permit // persons to whom the Software is furnished to do so, subject to the // following conditions: // // The above copyright notice and this permission notice shall be included // in all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS // OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF // MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN // NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, // DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR // OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE // USE OR OTHER DEALINGS IN THE SOFTWARE. var common = require('../common'); var assert = require('assert'); var fs = require('fs'); var filename = common.tmpDir + '/truncate-file.txt'; // Synchronous test. (function() { fs.writeFileSync(filename, '0123456789'); assert.equal(fs.readFileSync(filename).toString(), '0123456789'); fs.truncateSync(filename, 5); assert.equal(fs.readFileSync(filename).toString(), '01234'); })(); // Asynchronous test. (function() { fs.writeFileSync(filename, '0123456789'); assert.equal(fs.readFileSync(filename).toString(), '0123456789'); fs.truncate(filename, 5, common.mustCall(function(err) { if (err) throw err; assert.equal(fs.readFileSync(filename).toString(), '01234'); })); })(); node-v0.10.25~dfsg2/test/simple/test-net-GH-5504.js0000644000000000000000000000720012270121457020054 0ustar rootroot// Copyright Joyent, Inc. and other Node contributors. // // Permission is hereby granted, free of charge, to any person obtaining a // copy of this software and associated documentation files (the // "Software"), to deal in the Software without restriction, including // without limitation the rights to use, copy, modify, merge, publish, // distribute, sublicense, and/or sell copies of the Software, and to permit // persons to whom the Software is furnished to do so, subject to the // following conditions: // // The above copyright notice and this permission notice shall be included // in all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS // OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF // MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN // NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, // DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR // OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE // USE OR OTHER DEALINGS IN THE SOFTWARE. var common = require('../common'); var assert = require('assert'); // this test only fails with CentOS 6.3 using kernel version 2.6.32 // On other linuxes and darwin, the `read` call gets an ECONNRESET in // that case. On sunos, the `write` call fails with EPIPE. // // However, old CentOS will occasionally send an EOF instead of a // ECONNRESET or EPIPE when the client has been destroyed abruptly. // // Make sure we don't keep trying to write or read more in that case. switch (process.argv[2]) { case 'server': return server(); case 'client': return client(); case undefined: return parent(); default: throw new Error('wtf'); } function server() { var net = require('net'); var content = new Buffer(64 * 1024 * 1024); content.fill('#'); net.createServer(function(socket) { this.close(); socket.on('end', function() { console.error('end'); }); socket.on('_socketEnd', function() { console.error('_socketEnd'); }); socket.write(content); }).listen(3000, function() { console.log('listening'); }); } function client() { var net = require('net'); var client = net.connect({ host: 'localhost', port: 3000 }, function() { client.destroy(); }); } function parent() { var spawn = require('child_process').spawn; var node = process.execPath; var assert = require('assert'); var serverExited = false; var clientExited = false; var serverListened = false; var opt = { env: { NODE_DEBUG: 'net' } }; process.on('exit', function() { assert(serverExited); assert(clientExited); assert(serverListened); console.log('ok'); }); setTimeout(function() { if (s) s.kill(); if (c) c.kill(); setTimeout(function() { throw new Error('hang'); }); }, 1000).unref(); var s = spawn(node, [__filename, 'server'], opt); var c; wrap(s.stderr, process.stderr, 'SERVER 2>'); wrap(s.stdout, process.stdout, 'SERVER 1>'); s.on('exit', function(c) { console.error('server exited', c); serverExited = true; }); s.stdout.once('data', function() { serverListened = true; c = spawn(node, [__filename, 'client']); wrap(c.stderr, process.stderr, 'CLIENT 2>'); wrap(c.stdout, process.stdout, 'CLIENT 1>'); c.on('exit', function(c) { console.error('client exited', c); clientExited = true; }); }); function wrap(inp, out, w) { inp.setEncoding('utf8'); inp.on('data', function(c) { c = c.trim(); if (!c) return; out.write(w + c.split('\n').join('\n' + w) + '\n'); }); } } node-v0.10.25~dfsg2/test/simple/test-stdin-from-file.js0000644000000000000000000000552312270121457021404 0ustar rootroot// Copyright Joyent, Inc. and other Node contributors. // // Permission is hereby granted, free of charge, to any person obtaining a // copy of this software and associated documentation files (the // "Software"), to deal in the Software without restriction, including // without limitation the rights to use, copy, modify, merge, publish, // distribute, sublicense, and/or sell copies of the Software, and to permit // persons to whom the Software is furnished to do so, subject to the // following conditions: // // The above copyright notice and this permission notice shall be included // in all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS // OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF // MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN // NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, // DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR // OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE // USE OR OTHER DEALINGS IN THE SOFTWARE. var common = require('../common'); var assert = require('assert'); var join = require('path').join; var childProccess = require('child_process'); var fs = require('fs'); var stdoutScript = join(common.fixturesDir, 'echo.js'); var tmpFile = join(common.fixturesDir, 'stdin.txt'); var cmd = '"' + process.argv[0] + '" "' + stdoutScript + '" < "' + tmpFile + '"'; var string = 'abc\nümlaut.\nsomething else\n' + '南越国是前203年至前111年存在于岭南地区的一个国家,国都位于番禺,' + '疆域包括今天中国的广东、广西两省区的大部份地区,福建省、湖南、贵州、' + '云南的一小部份地区和越南的北部。南越国是秦朝灭亡后,' + '由南海郡尉赵佗于前203年起兵兼并桂林郡和象郡后建立。前196年和前179年,' + '南越国曾先后两次名义上臣属于西汉,成为西汉的“外臣”。前112年,' + '南越国末代君主赵建德与西汉发生战争,被汉武帝于前111年所灭。南越国共存在93年,' + '历经五代君主。南越国是岭南地区的第一个有记载的政权国家,' + '采用封建制和郡县制并存的制度,' + '它的建立保证了秦末乱世岭南地区社会秩序的稳定,' + '有效的改善了岭南地区落后的政治、##济现状。\n'; console.log(cmd + '\n\n'); try { fs.unlinkSync(tmpFile); } catch (e) {} fs.writeFileSync(tmpFile, string); childProccess.exec(cmd, function(err, stdout, stderr) { fs.unlinkSync(tmpFile); if (err) throw err; console.log(stdout); assert.equal(stdout, 'hello world\r\n' + string); assert.equal('', stderr); }); node-v0.10.25~dfsg2/test/simple/test-http-incoming-pipelined-socket-destroy.js0000644000000000000000000000467112270121457026114 0ustar rootroot// Copyright Joyent, Inc. and other Node contributors. // // Permission is hereby granted, free of charge, to any person obtaining a // copy of this software and associated documentation files (the // "Software"), to deal in the Software without restriction, including // without limitation the rights to use, copy, modify, merge, publish, // distribute, sublicense, and/or sell copies of the Software, and to permit // persons to whom the Software is furnished to do so, subject to the // following conditions: // // The above copyright notice and this permission notice shall be included // in all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS // OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF // MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN // NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, // DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR // OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE // USE OR OTHER DEALINGS IN THE SOFTWARE. var common = require('../common'); var assert = require('assert'); var http = require('http'); var net = require('net'); // Set up some timing issues where sockets can be destroyed // via either the req or res. var server = http.createServer(function(req, res) { switch (req.url) { case '/1': return setTimeout(function() { req.socket.destroy(); }); case '/2': return process.nextTick(function() { res.destroy(); }); // in one case, actually send a response in 2 chunks case '/3': res.write('hello '); return setTimeout(function() { res.end('world!'); }); default: return res.destroy(); } }); // Make a bunch of requests pipelined on the same socket function generator() { var reqs = [ 3, 1, 2, 3, 4, 1, 2, 3, 4, 1, 2, 3, 4 ]; return reqs.map(function(r) { return 'GET /' + r + ' HTTP/1.1\r\n' + 'Host: localhost:' + common.PORT + '\r\n' + '\r\n' + '\r\n' }).join(''); } server.listen(common.PORT, function() { var client = net.connect({ port: common.PORT }); // immediately write the pipelined requests. // Some of these will not have a socket to destroy! client.write(generator(), function() { server.close(); }); }); process.on('exit', function(c) { if (!c) console.log('ok'); }); node-v0.10.25~dfsg2/test/simple/test-child-process-buffering.js0000644000000000000000000000401612270121457023105 0ustar rootroot// Copyright Joyent, Inc. and other Node contributors. // // Permission is hereby granted, free of charge, to any person obtaining a // copy of this software and associated documentation files (the // "Software"), to deal in the Software without restriction, including // without limitation the rights to use, copy, modify, merge, publish, // distribute, sublicense, and/or sell copies of the Software, and to permit // persons to whom the Software is furnished to do so, subject to the // following conditions: // // The above copyright notice and this permission notice shall be included // in all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS // OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF // MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN // NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, // DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR // OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE // USE OR OTHER DEALINGS IN THE SOFTWARE. var common = require('../common'); var assert = require('assert'); var spawn = require('child_process').spawn; var pwd_called = false; var childClosed = false; var childExited = false; function pwd(callback) { var output = ''; var child = common.spawnPwd(); child.stdout.setEncoding('utf8'); child.stdout.on('data', function(s) { console.log('stdout: ' + JSON.stringify(s)); output += s; }); child.on('exit', function(c) { console.log('exit: ' + c); assert.equal(0, c); childExited = true; }); child.on('close', function () { callback(output); pwd_called = true; childClosed = true; }); } pwd(function(result) { console.dir(result); assert.equal(true, result.length > 1); assert.equal('\n', result[result.length - 1]); }); process.on('exit', function() { assert.equal(true, pwd_called); assert.equal(true, childExited); assert.equal(true, childClosed); }); node-v0.10.25~dfsg2/test/simple/test-stream2-readable-from-list.js0000644000000000000000000000631712270121457023433 0ustar rootroot// Copyright Joyent, Inc. and other Node contributors. // // Permission is hereby granted, free of charge, to any person obtaining a // copy of this software and associated documentation files (the // "Software"), to deal in the Software without restriction, including // without limitation the rights to use, copy, modify, merge, publish, // distribute, sublicense, and/or sell copies of the Software, and to permit // persons to whom the Software is furnished to do so, subject to the // following conditions: // // The above copyright notice and this permission notice shall be included // in all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS // OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF // MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN // NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, // DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR // OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE // USE OR OTHER DEALINGS IN THE SOFTWARE. var assert = require('assert'); var common = require('../common.js'); var fromList = require('_stream_readable')._fromList; // tiny node-tap lookalike. var tests = []; var count = 0; function test(name, fn) { count++; tests.push([name, fn]); } function run() { var next = tests.shift(); if (!next) return console.error('ok'); var name = next[0]; var fn = next[1]; console.log('# %s', name); fn({ same: assert.deepEqual, equal: assert.equal, end: function () { count--; run(); } }); } // ensure all tests have run process.on("exit", function () { assert.equal(count, 0); }); process.nextTick(run); test('buffers', function(t) { // have a length var len = 16; var list = [ new Buffer('foog'), new Buffer('bark'), new Buffer('bazy'), new Buffer('kuel') ]; // read more than the first element. var ret = fromList(6, { buffer: list, length: 16 }); t.equal(ret.toString(), 'foogba'); // read exactly the first element. ret = fromList(2, { buffer: list, length: 10 }); t.equal(ret.toString(), 'rk'); // read less than the first element. ret = fromList(2, { buffer: list, length: 8 }); t.equal(ret.toString(), 'ba'); // read more than we have. ret = fromList(100, { buffer: list, length: 6 }); t.equal(ret.toString(), 'zykuel'); // all consumed. t.same(list, []); t.end(); }); test('strings', function(t) { // have a length var len = 16; var list = [ 'foog', 'bark', 'bazy', 'kuel' ]; // read more than the first element. var ret = fromList(6, { buffer: list, length: 16, decoder: true }); t.equal(ret, 'foogba'); // read exactly the first element. ret = fromList(2, { buffer: list, length: 10, decoder: true }); t.equal(ret, 'rk'); // read less than the first element. ret = fromList(2, { buffer: list, length: 8, decoder: true }); t.equal(ret, 'ba'); // read more than we have. ret = fromList(100, { buffer: list, length: 6, decoder: true }); t.equal(ret, 'zykuel'); // all consumed. t.same(list, []); t.end(); }); node-v0.10.25~dfsg2/test/simple/test-http-request-end.js0000644000000000000000000000354512270121457021620 0ustar rootroot// Copyright Joyent, Inc. and other Node contributors. // // Permission is hereby granted, free of charge, to any person obtaining a // copy of this software and associated documentation files (the // "Software"), to deal in the Software without restriction, including // without limitation the rights to use, copy, modify, merge, publish, // distribute, sublicense, and/or sell copies of the Software, and to permit // persons to whom the Software is furnished to do so, subject to the // following conditions: // // The above copyright notice and this permission notice shall be included // in all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS // OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF // MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN // NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, // DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR // OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE // USE OR OTHER DEALINGS IN THE SOFTWARE. var common = require('../common'); var assert = require('assert'); var http = require('http'); var expected = 'Post Body For Test'; var result = ''; var server = http.Server(function(req, res) { req.setEncoding('utf8'); req.on('data', function(chunk) { result += chunk; }); req.on('end', function() { server.close(); }); res.writeHead(200); res.end('hello world\n'); }); server.listen(common.PORT, function() { http.request({ port: common.PORT, path: '/', method: 'POST' }, function(res) { console.log(res.statusCode); res.resume(); }).on('error', function(e) { console.log(e.message); process.exit(1); }).end(expected); }); process.on('exit', function() { assert.equal(expected, result); }); node-v0.10.25~dfsg2/test/simple/test-http-exceptions.js0000644000000000000000000000341212270121457021536 0ustar rootroot// Copyright Joyent, Inc. and other Node contributors. // // Permission is hereby granted, free of charge, to any person obtaining a // copy of this software and associated documentation files (the // "Software"), to deal in the Software without restriction, including // without limitation the rights to use, copy, modify, merge, publish, // distribute, sublicense, and/or sell copies of the Software, and to permit // persons to whom the Software is furnished to do so, subject to the // following conditions: // // The above copyright notice and this permission notice shall be included // in all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS // OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF // MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN // NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, // DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR // OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE // USE OR OTHER DEALINGS IN THE SOFTWARE. var common = require('../common'); var assert = require('assert'); var http = require('http'); var server = http.createServer(function(req, res) { intentionally_not_defined(); res.writeHead(200, {'Content-Type': 'text/plain'}); res.write('Thank you, come again.'); res.end(); }); server.listen(common.PORT, function() { var req; for (var i = 0; i < 4; i += 1) { req = http.get({ port: common.PORT, path: '/busy/' + i }); } }); var exception_count = 0; process.on('uncaughtException', function(err) { console.log('Caught an exception: ' + err); if (err.name === 'AssertionError') throw err; if (++exception_count == 4) process.exit(0); }); node-v0.10.25~dfsg2/test/simple/test-child-process-set-blocking.js0000644000000000000000000000275312270121457023525 0ustar rootroot// Copyright Joyent, Inc. and other Node contributors. // // Permission is hereby granted, free of charge, to any person obtaining a // copy of this software and associated documentation files (the // "Software"), to deal in the Software without restriction, including // without limitation the rights to use, copy, modify, merge, publish, // distribute, sublicense, and/or sell copies of the Software, and to permit // persons to whom the Software is furnished to do so, subject to the // following conditions: // // The above copyright notice and this permission notice shall be included // in all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS // OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF // MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN // NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, // DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR // OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE // USE OR OTHER DEALINGS IN THE SOFTWARE. var common = require('../common'); var assert = require('assert'); var ch = require('child_process'); var SIZE = 100000; var childGone = false; var cp = ch.spawn('python', ['-c', 'print ' + SIZE + ' * "C"'], { customFds: [0, 1, 2] }); cp.on('exit', function(code) { childGone = true; assert.equal(0, code); }); process.on('exit', function() { assert.ok(childGone); }); node-v0.10.25~dfsg2/test/simple/test-net-remote-address-port.js0000644000000000000000000000412012270121457023061 0ustar rootroot// Copyright Joyent, Inc. and other Node contributors. // // Permission is hereby granted, free of charge, to any person obtaining a // copy of this software and associated documentation files (the // "Software"), to deal in the Software without restriction, including // without limitation the rights to use, copy, modify, merge, publish, // distribute, sublicense, and/or sell copies of the Software, and to permit // persons to whom the Software is furnished to do so, subject to the // following conditions: // // The above copyright notice and this permission notice shall be included // in all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS // OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF // MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN // NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, // DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR // OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE // USE OR OTHER DEALINGS IN THE SOFTWARE. var common = require('../common'); var assert = require('assert'); var net = require('net'); var conns = 0, conns_closed = 0; var server = net.createServer(function(socket) { conns++; assert.equal('127.0.0.1', socket.remoteAddress); assert.ok(socket.remotePort); assert.notEqual(socket.remotePort, common.PORT); socket.on('end', function() { if (++conns_closed == 2) server.close(); }); socket.resume(); }); server.listen(common.PORT, 'localhost', function() { var client = net.createConnection(common.PORT, 'localhost'); var client2 = net.createConnection(common.PORT); client.on('connect', function() { assert.equal('127.0.0.1', client.remoteAddress); assert.equal(common.PORT, client.remotePort); client.end(); }); client2.on('connect', function() { assert.equal('127.0.0.1', client2.remoteAddress); assert.equal(common.PORT, client2.remotePort); client2.end(); }); }); process.on('exit', function() { assert.equal(2, conns); }); node-v0.10.25~dfsg2/test/simple/test-http-destroyed-socket-write.js0000644000000000000000000000744612270121457024010 0ustar rootroot// Copyright Joyent, Inc. and other Node contributors. // // Permission is hereby granted, free of charge, to any person obtaining a // copy of this software and associated documentation files (the // "Software"), to deal in the Software without restriction, including // without limitation the rights to use, copy, modify, merge, publish, // distribute, sublicense, and/or sell copies of the Software, and to permit // persons to whom the Software is furnished to do so, subject to the // following conditions: // // The above copyright notice and this permission notice shall be included // in all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS // OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF // MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN // NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, // DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR // OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE // USE OR OTHER DEALINGS IN THE SOFTWARE. var common = require('../common'); var assert = require('assert'); // Fix the memory explosion that happens when writing to a http request // where the server has destroyed the socket on us between a successful // first request, and a subsequent request that reuses the socket. // // This test should not be ported to v0.10 and higher, because the // problem is fixed by not ignoring ECONNRESET in the first place. var http = require('http'); var net = require('net'); var server = http.createServer(function(req, res) { // simulate a server that is in the process of crashing or something // it only crashes after the first request, but before the second, // which reuses the connection. res.end('hallo wereld\n', function() { setTimeout(function() { req.connection.destroy(); }, 100); }); }); var gotFirstResponse = false; var gotFirstData = false; var gotFirstEnd = false; server.listen(common.PORT, function() { var gotFirstResponse = false; var first = http.request({ port: common.PORT, path: '/' }); first.on('response', function(res) { gotFirstResponse = true; res.on('data', function(chunk) { gotFirstData = true; }); res.on('end', function() { gotFirstEnd = true; }) }); first.end(); second(); function second() { var sec = http.request({ port: common.PORT, path: '/', method: 'POST' }); var timer = setTimeout(write, 200); var writes = 0; var sawFalseWrite; function write() { if (++writes === 64) { clearTimeout(timer); sec.end(); test(); } else { timer = setTimeout(write); var writeRet = sec.write(new Buffer('hello')); // Once we find out that the connection is destroyed, every // write() returns false if (sawFalseWrite) assert.equal(writeRet, false); else sawFalseWrite = writeRet === false; } } assert.equal(first.connection, sec.connection, 'should reuse connection'); sec.on('response', function(res) { res.on('data', function(chunk) { console.error('second saw data: ' + chunk); }); res.on('end', function() { console.error('second saw end'); }); }); function test() { server.close(); assert(sec.connection.destroyed); if (sec.output.length || sec.outputEncodings.length) console.error('bad happened', sec.output, sec.outputEncodings); assert.equal(sec.output.length, 0); assert.equal(sec.outputEncodings, 0); assert(sawFalseWrite); assert(gotFirstResponse); assert(gotFirstData); assert(gotFirstEnd); console.log('ok'); } } }); node-v0.10.25~dfsg2/test/simple/test-repl-tab-complete.js0000644000000000000000000001273112270121457021720 0ustar rootroot// Copyright Joyent, Inc. and other Node contributors. // // Permission is hereby granted, free of charge, to any person obtaining a // copy of this software and associated documentation files (the // "Software"), to deal in the Software without restriction, including // without limitation the rights to use, copy, modify, merge, publish, // distribute, sublicense, and/or sell copies of the Software, and to permit // persons to whom the Software is furnished to do so, subject to the // following conditions: // // The above copyright notice and this permission notice shall be included // in all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS // OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF // MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN // NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, // DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR // OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE // USE OR OTHER DEALINGS IN THE SOFTWARE. var common = require('../common'); var assert = require('assert'); var util = require('util'); var repl = require('repl'); // A stream to push an array into a REPL function ArrayStream() { this.run = function(data) { var self = this; data.forEach(function(line) { self.emit('data', line + '\n'); }); } } util.inherits(ArrayStream, require('stream').Stream); ArrayStream.prototype.readable = true; ArrayStream.prototype.writable = true; ArrayStream.prototype.resume = function() {}; ArrayStream.prototype.write = function() {}; var works = [['inner.one'], 'inner.o']; var doesNotBreak = [[], 'inner.o']; var putIn = new ArrayStream(); var testMe = repl.start('', putIn); // Tab Complete will not break in an object literal putIn.run(['.clear']); putIn.run([ 'var inner = {', 'one:1' ]); testMe.complete('inner.o', function(error, data) { assert.deepEqual(data, doesNotBreak); }); testMe.complete('console.lo', function(error, data) { assert.deepEqual(data, [['console.log'], 'console.lo']); }); // Tab Complete will return globaly scoped variables putIn.run(['};']); testMe.complete('inner.o', function(error, data) { assert.deepEqual(data, works); }); putIn.run(['.clear']); // Tab Complete will not break in an ternary operator with () putIn.run([ 'var inner = ( true ' , '?', '{one: 1} : ' ]); testMe.complete('inner.o', function(error, data) { assert.deepEqual(data, doesNotBreak); }); putIn.run(['.clear']); // Tab Complete will return a simple local variable putIn.run([ 'var top = function () {', 'var inner = {one:1};' ]); testMe.complete('inner.o', function(error, data) { assert.deepEqual(data, works); }); // When you close the function scope tab complete will not return the // locally scoped variable putIn.run(['};']); testMe.complete('inner.o', function(error, data) { assert.deepEqual(data, doesNotBreak); }); putIn.run(['.clear']); // Tab Complete will return a complex local variable putIn.run([ 'var top = function () {', 'var inner = {', ' one:1', '};' ]); testMe.complete('inner.o', function(error, data) { assert.deepEqual(data, works); }); putIn.run(['.clear']); // Tab Complete will return a complex local variable even if the function // has parameters putIn.run([ 'var top = function (one, two) {', 'var inner = {', ' one:1', '};' ]); testMe.complete('inner.o', function(error, data) { assert.deepEqual(data, works); }); putIn.run(['.clear']); // Tab Complete will return a complex local variable even if the // scope is nested inside an immediately executed function putIn.run([ 'var top = function () {', '(function test () {', 'var inner = {', ' one:1', '};' ]); testMe.complete('inner.o', function(error, data) { assert.deepEqual(data, works); }); putIn.run(['.clear']); // currently does not work, but should not break note the inner function // def has the params and { on a separate line putIn.run([ 'var top = function () {', 'r = function test (', ' one, two) {', 'var inner = {', ' one:1', '};' ]); testMe.complete('inner.o', function(error, data) { assert.deepEqual(data, doesNotBreak); }); putIn.run(['.clear']); // currently does not work, but should not break, not the { putIn.run([ 'var top = function () {', 'r = function test ()', '{', 'var inner = {', ' one:1', '};' ]); testMe.complete('inner.o', function(error, data) { assert.deepEqual(data, doesNotBreak); }); putIn.run(['.clear']); // currently does not work, but should not break putIn.run([ 'var top = function () {', 'r = function test (', ')', '{', 'var inner = {', ' one:1', '};' ]); testMe.complete('inner.o', function(error, data) { assert.deepEqual(data, doesNotBreak); }); putIn.run(['.clear']); // make sure tab completion works on non-Objects putIn.run([ 'var str = "test";' ]); testMe.complete('str.len', function(error, data) { assert.deepEqual(data, [['str.length'], 'str.len']); }); putIn.run(['.clear']); // tab completion should not break on spaces var spaceTimeout = setTimeout(function() { throw new Error('timeout'); }, 1000); testMe.complete(' ', function(error, data) { assert.deepEqual(data, [[],undefined]); clearTimeout(spaceTimeout); }); // tab completion should pick up the global "toString" object, and // any other properties up the "global" object's prototype chain testMe.complete('toSt', function(error, data) { assert.deepEqual(data, [['toString'], 'toSt']); }); node-v0.10.25~dfsg2/test/simple/test-child-process-stdin.js0000644000000000000000000000463012270121457022261 0ustar rootroot// Copyright Joyent, Inc. and other Node contributors. // // Permission is hereby granted, free of charge, to any person obtaining a // copy of this software and associated documentation files (the // "Software"), to deal in the Software without restriction, including // without limitation the rights to use, copy, modify, merge, publish, // distribute, sublicense, and/or sell copies of the Software, and to permit // persons to whom the Software is furnished to do so, subject to the // following conditions: // // The above copyright notice and this permission notice shall be included // in all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS // OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF // MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN // NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, // DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR // OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE // USE OR OTHER DEALINGS IN THE SOFTWARE. var common = require('../common'); var assert = require('assert'); var spawn = require('child_process').spawn; var is_windows = process.platform === 'win32'; var cat = spawn(is_windows ? 'more' : 'cat'); cat.stdin.write('hello'); cat.stdin.write(' '); cat.stdin.write('world'); assert.ok(cat.stdin.writable); assert.ok(!cat.stdin.readable); cat.stdin.end(); var response = ''; var exitStatus = -1; var closed = false; var gotStdoutEOF = false; cat.stdout.setEncoding('utf8'); cat.stdout.on('data', function(chunk) { console.log('stdout: ' + chunk); response += chunk; }); cat.stdout.on('end', function() { gotStdoutEOF = true; }); var gotStderrEOF = false; cat.stderr.on('data', function(chunk) { // shouldn't get any stderr output assert.ok(false); }); cat.stderr.on('end', function(chunk) { gotStderrEOF = true; }); cat.on('exit', function(status) { console.log('exit event'); exitStatus = status; }); cat.on('close', function () { closed = true; if (is_windows) { assert.equal('hello world\r\n', response); } else { assert.equal('hello world', response); } }); process.on('exit', function() { assert.equal(0, exitStatus); assert(closed); if (is_windows) { assert.equal('hello world\r\n', response); } else { assert.equal('hello world', response); } }); node-v0.10.25~dfsg2/test/simple/test-dgram-send-bad-arguments.js0000644000000000000000000000365512270121457023161 0ustar rootroot// Copyright Joyent, Inc. and other Node contributors. // // Permission is hereby granted, free of charge, to any person obtaining a // copy of this software and associated documentation files (the // "Software"), to deal in the Software without restriction, including // without limitation the rights to use, copy, modify, merge, publish, // distribute, sublicense, and/or sell copies of the Software, and to permit // persons to whom the Software is furnished to do so, subject to the // following conditions: // // The above copyright notice and this permission notice shall be included // in all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS // OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF // MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN // NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, // DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR // OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE // USE OR OTHER DEALINGS IN THE SOFTWARE. var common = require('../common'); var assert = require('assert'); var dgram = require('dgram'); var buf = Buffer('test'); var host = '127.0.0.1'; var sock = dgram.createSocket('udp4'); assert.throws(function() { sock.send(); }, TypeError); // First argument should be a buffer. assert.throws(function() { sock.send(buf, -1, 1, 1, host); }, RangeError); assert.throws(function() { sock.send(buf, 1, -1, 1, host); }, RangeError); assert.throws(function() { sock.send(buf, 1, 1, -1, host); }, RangeError); assert.throws(function() { sock.send(buf, 5, 1, 1, host); }, RangeError); assert.throws(function() { sock.send(buf, 1, 5, 1, host); }, RangeError); assert.throws(function() { sock.send(buf, 1, 1, 0, host); }, RangeError); assert.throws(function() { sock.send(buf, 1, 1, 65536, host); }, RangeError); node-v0.10.25~dfsg2/test/simple/test-dgram-broadcast-multi-process.js0000644000000000000000000001623312270121457024243 0ustar rootroot// Copyright Joyent, Inc. and other Node contributors. // // Permission is hereby granted, free of charge, to any person obtaining a // copy of this software and associated documentation files (the // "Software"), to deal in the Software without restriction, including // without limitation the rights to use, copy, modify, merge, publish, // distribute, sublicense, and/or sell copies of the Software, and to permit // persons to whom the Software is furnished to do so, subject to the // following conditions: // // The above copyright notice and this permission notice shall be included // in all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS // OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF // MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN // NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, // DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR // OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE // USE OR OTHER DEALINGS IN THE SOFTWARE. var common = require('../common'), assert = require('assert'), dgram = require('dgram'), util = require('util'), networkInterfaces = require('os').networkInterfaces(), Buffer = require('buffer').Buffer, fork = require('child_process').fork, LOCAL_BROADCAST_HOST = '255.255.255.255', TIMEOUT = 5000, messages = [ new Buffer('First message to send'), new Buffer('Second message to send'), new Buffer('Third message to send'), new Buffer('Fourth message to send') ]; // take the first non-internal interface as the address for binding get_bindAddress: for (var name in networkInterfaces) { var interfaces = networkInterfaces[name]; for(var i = 0; i < interfaces.length; i++) { var localInterface = interfaces[i]; if (!localInterface.internal && localInterface.family === 'IPv4') { var bindAddress = localInterface.address; break get_bindAddress; } } } assert.ok(bindAddress); if (process.argv[2] !== 'child') { var workers = {}, listeners = 3, listening = 0, dead = 0, i = 0, done = 0, timer = null; //exit the test if it doesn't succeed within TIMEOUT timer = setTimeout(function() { console.error('[PARENT] Responses were not received within %d ms.', TIMEOUT); console.error('[PARENT] Fail'); killChildren(workers); process.exit(1); }, TIMEOUT); //launch child processes for (var x = 0; x < listeners; x++) { (function() { var worker = fork(process.argv[1], ['child']); workers[worker.pid] = worker; worker.messagesReceived = []; //handle the death of workers worker.on('exit', function(code, signal) { // don't consider this the true death if the worker // has finished successfully // or if the exit code is 0 if (worker.isDone || code == 0) { return; } dead += 1; console.error('[PARENT] Worker %d died. %d dead of %d', worker.pid, dead, listeners); if (dead === listeners) { console.error('[PARENT] All workers have died.'); console.error('[PARENT] Fail'); killChildren(workers); process.exit(1); } }); worker.on('message', function(msg) { if (msg.listening) { listening += 1; if (listening === listeners) { //all child process are listening, so start sending sendSocket.sendNext(); } } else if (msg.message) { worker.messagesReceived.push(msg.message); if (worker.messagesReceived.length === messages.length) { done += 1; worker.isDone = true; console.error('[PARENT] %d received %d messages total.', worker.pid, worker.messagesReceived.length); } if (done === listeners) { console.error('[PARENT] All workers have received the ' + 'required number of ' + 'messages. Will now compare.'); Object.keys(workers).forEach(function(pid) { var worker = workers[pid]; var count = 0; worker.messagesReceived.forEach(function(buf) { for (var i = 0; i < messages.length; ++i) { if (buf.toString() === messages[i].toString()) { count++; break; } } }); console.error('[PARENT] %d received %d matching messges.', worker.pid, count); assert.equal(count, messages.length, 'A worker received an invalid multicast message'); }); clearTimeout(timer); console.error('[PARENT] Success'); killChildren(workers); } } }); })(x); } var sendSocket = dgram.createSocket('udp4'); // bind the address explicitly for sending // INADDR_BROADCAST to only one interface sendSocket.bind(common.PORT, bindAddress); sendSocket.on('listening', function () { sendSocket.setBroadcast(true); }); sendSocket.on('close', function() { console.error('[PARENT] sendSocket closed'); }); sendSocket.sendNext = function() { var buf = messages[i++]; if (!buf) { try { sendSocket.close(); } catch (e) {} return; } sendSocket.send(buf, 0, buf.length, common.PORT, LOCAL_BROADCAST_HOST, function(err) { if (err) throw err; console.error('[PARENT] sent %s to %s:%s', util.inspect(buf.toString()), LOCAL_BROADCAST_HOST, common.PORT); process.nextTick(sendSocket.sendNext); }); }; function killChildren(children) { Object.keys(children).forEach(function(key) { var child = children[key]; child.kill(); }); } } if (process.argv[2] === 'child') { var receivedMessages = []; var listenSocket = dgram.createSocket('udp4'); listenSocket.on('message', function(buf, rinfo) { // receive udp messages only sent from parent if (rinfo.address !== bindAddress) return; console.error('[CHILD] %s received %s from %j', process.pid, util.inspect(buf.toString()), rinfo); receivedMessages.push(buf); process.send({ message: buf.toString() }); if (receivedMessages.length == messages.length) { process.nextTick(function() { listenSocket.close(); }); } }); listenSocket.on('close', function() { //HACK: Wait to exit the process to ensure that the parent //process has had time to receive all messages via process.send() //This may be indicitave of some other issue. setTimeout(function() { process.exit(); }, 1000); }); listenSocket.on('listening', function() { process.send({ listening: true }); }); listenSocket.bind(common.PORT); } node-v0.10.25~dfsg2/test/simple/test-http-client-abort.js0000644000000000000000000000521512270121457021743 0ustar rootroot// Copyright Joyent, Inc. and other Node contributors. // // Permission is hereby granted, free of charge, to any person obtaining a // copy of this software and associated documentation files (the // "Software"), to deal in the Software without restriction, including // without limitation the rights to use, copy, modify, merge, publish, // distribute, sublicense, and/or sell copies of the Software, and to permit // persons to whom the Software is furnished to do so, subject to the // following conditions: // // The above copyright notice and this permission notice shall be included // in all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS // OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF // MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN // NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, // DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR // OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE // USE OR OTHER DEALINGS IN THE SOFTWARE. var common = require('../common'); var assert = require('assert'); var http = require('http'); var clientAborts = 0; var server = http.Server(function(req, res) { console.log('Got connection'); res.writeHead(200); res.write('Working on it...'); // I would expect an error event from req or res that the client aborted // before completing the HTTP request / response cycle, or maybe a new // event like "aborted" or something. req.on('aborted', function() { clientAborts++; console.log('Got abort ' + clientAborts); if (clientAborts === N) { console.log('All aborts detected, you win.'); server.close(); } }); // since there is already clientError, maybe that would be appropriate, // since "error" is magical req.on('clientError', function() { console.log('Got clientError'); }); }); var responses = 0; var N = http.Agent.defaultMaxSockets - 1; var requests = []; server.listen(common.PORT, function() { console.log('Server listening.'); for (var i = 0; i < N; i++) { console.log('Making client ' + i); var options = { port: common.PORT, path: '/?id=' + i }; var req = http.get(options, function(res) { console.log('Client response code ' + res.statusCode); if (++responses == N) { console.log('All clients connected, destroying.'); requests.forEach(function(outReq) { console.log('abort'); outReq.abort(); }); } }); requests.push(req); } }); process.on('exit', function() { assert.equal(N, clientAborts); }); node-v0.10.25~dfsg2/test/simple/test-dgram-bind-default-address.js0000644000000000000000000000326512270121457023457 0ustar rootroot// Copyright Joyent, Inc. and other Node contributors. // // Permission is hereby granted, free of charge, to any person obtaining a // copy of this software and associated documentation files (the // "Software"), to deal in the Software without restriction, including // without limitation the rights to use, copy, modify, merge, publish, // distribute, sublicense, and/or sell copies of the Software, and to permit // persons to whom the Software is furnished to do so, subject to the // following conditions: // // The above copyright notice and this permission notice shall be included // in all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS // OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF // MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN // NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, // DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR // OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE // USE OR OTHER DEALINGS IN THE SOFTWARE. var common = require('../common'); var assert = require('assert'); var dgram = require('dgram'); dgram.createSocket('udp4').bind(common.PORT + 0, common.mustCall(function() { assert.equal(this.address().port, common.PORT + 0); assert.equal(this.address().address, '0.0.0.0'); this.close(); })); dgram.createSocket('udp6').bind(common.PORT + 1, common.mustCall(function() { assert.equal(this.address().port, common.PORT + 1); var address = this.address().address; if (address === '::ffff:0.0.0.0') address = '::'; assert.equal(address, '::'); this.close(); })); node-v0.10.25~dfsg2/test/simple/test-fs-utimes.js0000644000000000000000000001132112270121457020312 0ustar rootroot// Copyright Joyent, Inc. and other Node contributors. // // Permission is hereby granted, free of charge, to any person obtaining a // copy of this software and associated documentation files (the // "Software"), to deal in the Software without restriction, including // without limitation the rights to use, copy, modify, merge, publish, // distribute, sublicense, and/or sell copies of the Software, and to permit // persons to whom the Software is furnished to do so, subject to the // following conditions: // // The above copyright notice and this permission notice shall be included // in all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS // OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF // MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN // NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, // DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR // OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE // USE OR OTHER DEALINGS IN THE SOFTWARE. var common = require('../common'); var assert = require('assert'); var util = require('util'); var fs = require('fs'); var is_windows = process.platform === 'win32'; var tests_ok = 0; var tests_run = 0; function stat_resource(resource) { if (typeof resource == 'string') { return fs.statSync(resource); } else { // ensure mtime has been written to disk fs.fsyncSync(resource); return fs.fstatSync(resource); } } function check_mtime(resource, mtime) { var mtime = fs._toUnixTimestamp(mtime); var stats = stat_resource(resource); var real_mtime = fs._toUnixTimestamp(stats.mtime); // check up to single-second precision // sub-second precision is OS and fs dependant return Math.floor(mtime) == Math.floor(real_mtime); } function expect_errno(syscall, resource, err, errno) { if (err && (err.code === errno || err.code === 'ENOSYS')) { tests_ok++; } else { console.log('FAILED:', arguments.callee.name, util.inspect(arguments)); } } function expect_ok(syscall, resource, err, atime, mtime) { if (!err && check_mtime(resource, mtime) || err && err.code === 'ENOSYS') { tests_ok++; } else { console.log('FAILED:', arguments.callee.name, util.inspect(arguments)); } } // the tests assume that __filename belongs to the user running the tests // this should be a fairly safe assumption; testing against a temp file // would be even better though (node doesn't have such functionality yet) function runTest(atime, mtime, callback) { var fd, err; // // test synchronized code paths, these functions throw on failure // function syncTests() { fs.utimesSync(__filename, atime, mtime); expect_ok('utimesSync', __filename, undefined, atime, mtime); tests_run++; // some systems don't have futimes // if there's an error, it should be ENOSYS try { tests_run++; fs.futimesSync(fd, atime, mtime); expect_ok('futimesSync', fd, undefined, atime, mtime); } catch (ex) { expect_errno('futimesSync', fd, ex, 'ENOSYS'); } var err; err = undefined; try { fs.utimesSync('foobarbaz', atime, mtime); } catch (ex) { err = ex; } expect_errno('utimesSync', 'foobarbaz', err, 'ENOENT'); tests_run++; err = undefined; try { fs.futimesSync(-1, atime, mtime); } catch (ex) { err = ex; } expect_errno('futimesSync', -1, err, 'EBADF'); tests_run++; } // // test async code paths // fs.utimes(__filename, atime, mtime, function(err) { expect_ok('utimes', __filename, err, atime, mtime); fs.utimes('foobarbaz', atime, mtime, function(err) { expect_errno('utimes', 'foobarbaz', err, 'ENOENT'); // don't close this fd if (is_windows) { fd = fs.openSync(__filename, 'r+'); } else { fd = fs.openSync(__filename, 'r'); } fs.futimes(fd, atime, mtime, function(err) { expect_ok('futimes', fd, err, atime, mtime); fs.futimes(-1, atime, mtime, function(err) { expect_errno('futimes', -1, err, 'EBADF'); syncTests(); callback(); }); tests_run++; }); tests_run++; }); tests_run++; }); tests_run++; } var stats = fs.statSync(__filename); runTest(new Date('1982-09-10 13:37'), new Date('1982-09-10 13:37'), function() { runTest(new Date(), new Date(), function() { runTest(123456.789, 123456.789, function() { runTest(stats.mtime, stats.mtime, function() { // done }); }); }); }); process.on('exit', function() { console.log('Tests run / ok:', tests_run, '/', tests_ok); assert.equal(tests_ok, tests_run); }); node-v0.10.25~dfsg2/test/simple/test-c-ares.js0000644000000000000000000000407212270121457017555 0ustar rootroot// Copyright Joyent, Inc. and other Node contributors. // // Permission is hereby granted, free of charge, to any person obtaining a // copy of this software and associated documentation files (the // "Software"), to deal in the Software without restriction, including // without limitation the rights to use, copy, modify, merge, publish, // distribute, sublicense, and/or sell copies of the Software, and to permit // persons to whom the Software is furnished to do so, subject to the // following conditions: // // The above copyright notice and this permission notice shall be included // in all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS // OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF // MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN // NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, // DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR // OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE // USE OR OTHER DEALINGS IN THE SOFTWARE. var common = require('../common'); var assert = require('assert'); var dns = require('dns'); // Try resolution without callback dns.lookup(null, function(error, result, addressType) { assert.equal(null, result); assert.equal(4, addressType); }); dns.lookup('127.0.0.1', function(error, result, addressType) { assert.equal('127.0.0.1', result); assert.equal(4, addressType); }); dns.lookup('::1', function(error, result, addressType) { assert.equal('::1', result); assert.equal(6, addressType); }); // Try calling resolve with an unsupported type. assert.throws(function() { dns.resolve('www.google.com', 'HI'); }, /Unknown type/); // Windows doesn't usually have an entry for localhost 127.0.0.1 in // C:\Windows\System32\drivers\etc\hosts // so we disable this test on Windows. if (process.platform != 'win32') { dns.resolve('127.0.0.1', 'PTR', function(error, domains) { if (error) throw error; assert.ok(Array.isArray(domains)); }); } node-v0.10.25~dfsg2/test/simple/test-punycode.js0000644000000000000000000002023512270121457020230 0ustar rootroot// Copyright Joyent, Inc. and other Node contributors. // // Permission is hereby granted, free of charge, to any person obtaining a // copy of this software and associated documentation files (the // "Software"), to deal in the Software without restriction, including // without limitation the rights to use, copy, modify, merge, publish, // distribute, sublicense, and/or sell copies of the Software, and to permit // persons to whom the Software is furnished to do so, subject to the // following conditions: // // The above copyright notice and this permission notice shall be included // in all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS // OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF // MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN // NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, // DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR // OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE // USE OR OTHER DEALINGS IN THE SOFTWARE. // Copyright (C) 2011 by Ben Noordhuis // // Permission is hereby granted, free of charge, to any person obtaining a copy // of this software and associated documentation files (the "Software"), to deal // in the Software without restriction, including without limitation the rights // to use, copy, modify, merge, publish, distribute, sublicense, and/or sell // copies of the Software, and to permit persons to whom the Software is // furnished to do so, subject to the following conditions: // // The above copyright notice and this permission notice shall be included in // all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN // THE SOFTWARE. var common = require('../common'); var punycode = require('punycode'); var assert = require('assert'); assert.equal(punycode.encode('ü'), 'tda'); assert.equal(punycode.encode('Goethe'), 'Goethe-'); assert.equal(punycode.encode('Bücher'), 'Bcher-kva'); assert.equal(punycode.encode( 'Willst du die Blüthe des frühen, die Früchte des späteren Jahres'), 'Willst du die Blthe des frhen, die Frchte des spteren Jahres-x9e96lkal'); assert.equal(punycode.encode('日本語'), 'wgv71a119e'); assert.equal(punycode.decode('tda'), 'ü'); assert.equal(punycode.decode('Goethe-'), 'Goethe'); assert.equal(punycode.decode('Bcher-kva'), 'Bücher'); assert.equal(punycode.decode( 'Willst du die Blthe des frhen, die Frchte des spteren Jahres-x9e96lkal'), 'Willst du die Blüthe des frühen, die Früchte des späteren Jahres'); assert.equal(punycode.decode('wgv71a119e'), '日本語'); // http://tools.ietf.org/html/rfc3492#section-7.1 var tests = { // (A) Arabic (Egyptian) 'egbpdaj6bu4bxfgehfvwxn': '\u0644\u064A\u0647\u0645\u0627\u0628\u062A\u0643\u0644\u0645\u0648' + '\u0634\u0639\u0631\u0628\u064A\u061F', // (B) Chinese (simplified) 'ihqwcrb4cv8a8dqg056pqjye': '\u4ED6\u4EEC\u4E3A\u4EC0\u4E48\u4E0D\u8BF4\u4E2D\u6587', // (C) Chinese (traditional) 'ihqwctvzc91f659drss3x8bo0yb': '\u4ED6\u5011\u7232\u4EC0\u9EBD\u4E0D\u8AAA\u4E2D\u6587', // (D) Czech: Proprostnemluvesky 'Proprostnemluvesky-uyb24dma41a': '\u0050\u0072\u006F\u010D\u0070\u0072\u006F\u0073\u0074\u011B\u006E' + '\u0065\u006D\u006C\u0075\u0076\u00ED\u010D\u0065\u0073\u006B\u0079', // (E) Hebrew '4dbcagdahymbxekheh6e0a7fei0b': '\u05DC\u05DE\u05D4\u05D4\u05DD\u05E4\u05E9\u05D5\u05D8\u05DC\u05D0' + '\u05DE\u05D3\u05D1\u05E8\u05D9\u05DD\u05E2\u05D1\u05E8\u05D9\u05EA', // (F) Hindi (Devanagari) 'i1baa7eci9glrd9b2ae1bj0hfcgg6iyaf8o0a1dig0cd': '\u092F\u0939\u0932\u094B\u0917\u0939\u093F\u0928\u094D\u0926\u0940' + '\u0915\u094D\u092F\u094B\u0902\u0928\u0939\u0940\u0902\u092C\u094B' + '\u0932\u0938\u0915\u0924\u0947\u0939\u0948\u0902', // (G) Japanese (kanji and hiragana) 'n8jok5ay5dzabd5bym9f0cm5685rrjetr6pdxa': '\u306A\u305C\u307F\u3093\u306A\u65E5\u672C\u8A9E\u3092\u8A71\u3057' + '\u3066\u304F\u308C\u306A\u3044\u306E\u304B', // (H) Korean (Hangul syllables) '989aomsvi5e83db1d2a355cv1e0vak1dwrv93d5xbh15a0dt30a5jpsd879ccm6fea98c': '\uC138\uACC4\uC758\uBAA8\uB4E0\uC0AC\uB78C\uB4E4\uC774\uD55C\uAD6D' + '\uC5B4\uB97C\uC774\uD574\uD55C\uB2E4\uBA74\uC5BC\uB9C8\uB098\uC88B' + '\uC744\uAE4C', // (I) Russian (Cyrillic) /* XXX disabled, fails - possibly a bug in the RFC 'b1abfaaepdrnnbgefbaDotcwatmq2g4l': '\u043F\u043E\u0447\u0435\u043C\u0443\u0436\u0435\u043E\u043D\u0438' + '\u043D\u0435\u0433\u043E\u0432\u043E\u0440\u044F\u0442\u043F\u043E' + '\u0440\u0443\u0441\u0441\u043A\u0438', */ // (J) Spanish: PorqunopuedensimplementehablarenEspaol 'PorqunopuedensimplementehablarenEspaol-fmd56a': '\u0050\u006F\u0072\u0071\u0075\u00E9\u006E\u006F\u0070\u0075\u0065' + '\u0064\u0065\u006E\u0073\u0069\u006D\u0070\u006C\u0065\u006D\u0065' + '\u006E\u0074\u0065\u0068\u0061\u0062\u006C\u0061\u0072\u0065\u006E' + '\u0045\u0073\u0070\u0061\u00F1\u006F\u006C', // (K) Vietnamese: Tisaohkhngth // chnitingVit 'TisaohkhngthchnitingVit-kjcr8268qyxafd2f1b9g': '\u0054\u1EA1\u0069\u0073\u0061\u006F\u0068\u1ECD\u006B\u0068\u00F4' + '\u006E\u0067\u0074\u0068\u1EC3\u0063\u0068\u1EC9\u006E\u00F3\u0069' + '\u0074\u0069\u1EBF\u006E\u0067\u0056\u0069\u1EC7\u0074', // (L) 3B '3B-ww4c5e180e575a65lsy2b': '\u0033\u5E74\u0042\u7D44\u91D1\u516B\u5148\u751F', // (M) -with-SUPER-MONKEYS '-with-SUPER-MONKEYS-pc58ag80a8qai00g7n9n': '\u5B89\u5BA4\u5948\u7F8E\u6075\u002D\u0077\u0069\u0074\u0068\u002D' + '\u0053\u0055\u0050\u0045\u0052\u002D\u004D\u004F\u004E\u004B\u0045' + '\u0059\u0053', // (N) Hello-Another-Way- 'Hello-Another-Way--fc4qua05auwb3674vfr0b': '\u0048\u0065\u006C\u006C\u006F\u002D\u0041\u006E\u006F\u0074\u0068' + '\u0065\u0072\u002D\u0057\u0061\u0079\u002D\u305D\u308C\u305E\u308C' + '\u306E\u5834\u6240', // (O) 2 '2-u9tlzr9756bt3uc0v': '\u3072\u3068\u3064\u5C4B\u6839\u306E\u4E0B\u0032', // (P) MajiKoi5 'MajiKoi5-783gue6qz075azm5e': '\u004D\u0061\u006A\u0069\u3067\u004B\u006F\u0069\u3059\u308B\u0035' + '\u79D2\u524D', // (Q) de 'de-jg4avhby1noc0d': '\u30D1\u30D5\u30A3\u30FC\u0064\u0065\u30EB\u30F3\u30D0', // (R) 'd9juau41awczczp': '\u305D\u306E\u30B9\u30D4\u30FC\u30C9\u3067', // (S) -> $1.00 <- '-> $1.00 <--': '\u002D\u003E\u0020\u0024\u0031\u002E\u0030\u0030\u0020\u003C\u002D' }; var errors = 0; for (var encoded in tests) { var decoded = tests[encoded]; try { assert.equal(punycode.encode(decoded), encoded); } catch (e) { console.error('FAIL: expected %j, got %j', e.expected, e.actual); errors++; } try { assert.equal(punycode.decode(encoded), decoded); } catch (e) { console.error('FAIL: expected %j, got %j', e.expected, e.actual); errors++; } } // BMP code point assert.equal(punycode.ucs2.encode([0x61]), 'a'); // supplementary code point (surrogate pair) assert.equal(punycode.ucs2.encode([0x1D306]), '\uD834\uDF06'); // high surrogate assert.equal(punycode.ucs2.encode([0xD800]), '\uD800'); // high surrogate followed by non-surrogates assert.equal(punycode.ucs2.encode([0xD800, 0x61, 0x62]), '\uD800ab'); // low surrogate assert.equal(punycode.ucs2.encode([0xDC00]), '\uDC00'); // low surrogate followed by non-surrogates assert.equal(punycode.ucs2.encode([0xDC00, 0x61, 0x62]), '\uDC00ab'); assert.equal(errors, 0); node-v0.10.25~dfsg2/test/simple/test-cluster-worker-exit.js0000644000000000000000000001167512270121457022351 0ustar rootroot// Copyright Joyent, Inc. and other Node contributors. // // Permission is hereby granted, free of charge, to any person obtaining a // copy of this software and associated documentation files (the // "Software"), to deal in the Software without restriction, including // without limitation the rights to use, copy, modify, merge, publish, // distribute, sublicense, and/or sell copies of the Software, and to permit // persons to whom the Software is furnished to do so, subject to the // following conditions: // // The above copyright notice and this permission notice shall be included // in all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS // OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF // MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN // NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, // DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR // OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE // USE OR OTHER DEALINGS IN THE SOFTWARE. // test-cluster-worker-exit.js // verifies that, when a child process exits (by calling `process.exit(code)`) // - the parent receives the proper events in the proper order, no duplicates // - the exitCode and signalCode are correct in the 'exit' event // - the worker.suicide flag, and worker.state are correct // - the worker process actually goes away var common = require('../common'); var assert = require('assert'); var cluster = require('cluster'); var EXIT_CODE = 42; if (cluster.isWorker) { var http = require('http'); var server = http.Server(function() { }); server.once('listening', function() { process.exit(EXIT_CODE); }); server.listen(common.PORT, '127.0.0.1'); } else if (cluster.isMaster) { var expected_results = { cluster_emitDisconnect: [1, "the cluster did not emit 'disconnect'"], cluster_emitExit: [1, "the cluster did not emit 'exit'"], cluster_exitCode: [EXIT_CODE, 'the cluster exited w/ incorrect exitCode'], cluster_signalCode: [null, 'the cluster exited w/ incorrect signalCode'], worker_emitDisconnect: [1, "the worker did not emit 'disconnect'"], worker_emitExit: [1, "the worker did not emit 'exit'"], worker_state: ['disconnected', 'the worker state is incorrect'], worker_suicideMode: [false, 'the worker.suicide flag is incorrect'], worker_died: [true, 'the worker is still running'], worker_exitCode: [EXIT_CODE, 'the worker exited w/ incorrect exitCode'], worker_signalCode: [null, 'the worker exited w/ incorrect signalCode'] }; var results = { cluster_emitDisconnect: 0, cluster_emitExit: 0, worker_emitDisconnect: 0, worker_emitExit: 0 }; // start worker var worker = cluster.fork(); worker.once('listening', function() { // the worker is up and running... }); // Check cluster events cluster.on('disconnect', function() { results.cluster_emitDisconnect += 1; }); cluster.on('exit', function(worker) { results.cluster_exitCode = worker.process.exitCode; results.cluster_signalCode = worker.process.signalCode; results.cluster_emitExit += 1; assert.ok(results.cluster_emitDisconnect, "cluster: 'exit' event before 'disconnect' event"); }); // Check worker eventes and properties worker.on('disconnect', function() { results.worker_emitDisconnect += 1; results.worker_suicideMode = worker.suicide; results.worker_state = worker.state; }); // Check that the worker died worker.once('exit', function(exitCode, signalCode) { results.worker_exitCode = exitCode; results.worker_signalCode = signalCode; results.worker_emitExit += 1; results.worker_died = !alive(worker.process.pid); assert.ok(results.worker_emitDisconnect, "worker: 'exit' event before 'disconnect' event"); process.nextTick(function() { finish_test(); }); }); var finish_test = function() { try { checkResults(expected_results, results); } catch (exc) { console.error('FAIL: ' + exc.message); if (exc.name != 'AssertionError') { console.trace(exc); } process.exit(1); return; } process.exit(0); }; } // some helper functions ... function checkResults(expected_results, results) { for (var k in expected_results) { var actual = results[k], expected = expected_results[k]; if (typeof expected === 'function') { expected(r[k]); } else { var msg = (expected[1] || '') + (' [expected: ' + expected[0] + ' / actual: ' + actual + ']'); if (expected && expected.length) { assert.equal(actual, expected[0], msg); } else { assert.equal(actual, expected, msg); } } } } function alive(pid) { try { process.kill(pid, 'SIGCONT'); return true; } catch (e) { return false; } } node-v0.10.25~dfsg2/test/simple/test-http-many-keep-alive-connections.js0000644000000000000000000000412312270121457024661 0ustar rootroot// Copyright Joyent, Inc. and other Node contributors. // // Permission is hereby granted, free of charge, to any person obtaining a // copy of this software and associated documentation files (the // "Software"), to deal in the Software without restriction, including // without limitation the rights to use, copy, modify, merge, publish, // distribute, sublicense, and/or sell copies of the Software, and to permit // persons to whom the Software is furnished to do so, subject to the // following conditions: // // The above copyright notice and this permission notice shall be included // in all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS // OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF // MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN // NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, // DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR // OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE // USE OR OTHER DEALINGS IN THE SOFTWARE. var common = require('../common'); var assert = require('assert'); var http = require('http'); var expected = 10000; var responses = 0; var requests = 0; var connection; var server = http.Server(function(req, res) { requests++; assert.equal(req.connection, connection); res.writeHead(200); res.end('hello world\n'); }); server.once('connection', function(c) { connection = c; }); server.listen(common.PORT, function() { var callee = arguments.callee; var request = http.get({ port: common.PORT, path: '/', headers: { 'Connection': 'Keep-alive' } }, function(res) { res.on('end', function() { if (++responses < expected) { callee(); } else { server.close(); } }); res.resume(); }).on('error', function(e) { console.log(e.message); process.exit(1); }); request.agent.maxSockets = 1; }); process.on('exit', function() { assert.equal(expected, responses); assert.equal(expected, requests); }); node-v0.10.25~dfsg2/test/simple/test-http-allow-req-after-204-res.js0000644000000000000000000000427312270121457023457 0ustar rootroot// Copyright Joyent, Inc. and other Node contributors. // // Permission is hereby granted, free of charge, to any person obtaining a // copy of this software and associated documentation files (the // "Software"), to deal in the Software without restriction, including // without limitation the rights to use, copy, modify, merge, publish, // distribute, sublicense, and/or sell copies of the Software, and to permit // persons to whom the Software is furnished to do so, subject to the // following conditions: // // The above copyright notice and this permission notice shall be included // in all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS // OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF // MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN // NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, // DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR // OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE // USE OR OTHER DEALINGS IN THE SOFTWARE. var common = require('../common'); var http = require('http'); var assert = require('assert'); // first 204 or 304 works, subsequent anything fails var codes = [204, 200]; // Methods don't really matter, but we put in something realistic. var methods = ['DELETE', 'DELETE']; var server = http.createServer(function(req, res) { var code = codes.shift(); assert.equal('number', typeof code); assert.ok(code > 0); console.error('writing %d response', code); res.writeHead(code, {}); res.end(); }); function nextRequest() { var method = methods.shift(); console.error('writing request: %s', method); var request = http.request({ port: common.PORT, method: method, path: '/' }, function(response) { response.on('end', function() { if (methods.length == 0) { console.error('close server'); server.close(); } else { // throws error: nextRequest(); // works just fine: //process.nextTick(nextRequest); } }); response.resume(); }); request.end(); } server.listen(common.PORT, nextRequest); node-v0.10.25~dfsg2/test/simple/test-tls-ondata.js0000644000000000000000000000377312270121457020460 0ustar rootroot// Copyright Joyent, Inc. and other Node contributors. // // Permission is hereby granted, free of charge, to any person obtaining a // copy of this software and associated documentation files (the // "Software"), to deal in the Software without restriction, including // without limitation the rights to use, copy, modify, merge, publish, // distribute, sublicense, and/or sell copies of the Software, and to permit // persons to whom the Software is furnished to do so, subject to the // following conditions: // // The above copyright notice and this permission notice shall be included // in all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS // OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF // MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN // NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, // DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR // OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE // USE OR OTHER DEALINGS IN THE SOFTWARE. var common = require('../common'); var assert = require('assert'); var tls = require('tls'); var fs = require('fs'); var options = { key: fs.readFileSync(common.fixturesDir + '/keys/agent1-key.pem'), cert: fs.readFileSync(common.fixturesDir + '/keys/agent1-cert.pem') }; var server = tls.Server(options, function(socket) { socket.end('hello world'); }); server.listen(common.PORT, function() { var client = tls.connect({ port: common.PORT, rejectUnauthorized: false }); // test that setting the `ondata` function *prevents* data from // being pushed to the streams2 interface of the socket client.ondata = function (buf, start, length) { var b = buf.slice(start, length); process.nextTick(function () { var b2 = client.read(); if (b2) { assert.notEqual(b.toString(), b2.toString()); } client.destroy(); server.close(); }); }; }); node-v0.10.25~dfsg2/test/simple/test-net-isip.js0000644000000000000000000000553312270121457020136 0ustar rootroot// Copyright Joyent, Inc. and other Node contributors. // // Permission is hereby granted, free of charge, to any person obtaining a // copy of this software and associated documentation files (the // "Software"), to deal in the Software without restriction, including // without limitation the rights to use, copy, modify, merge, publish, // distribute, sublicense, and/or sell copies of the Software, and to permit // persons to whom the Software is furnished to do so, subject to the // following conditions: // // The above copyright notice and this permission notice shall be included // in all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS // OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF // MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN // NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, // DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR // OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE // USE OR OTHER DEALINGS IN THE SOFTWARE. var common = require('../common'); var assert = require('assert'); var net = require('net'); assert.equal(net.isIP('127.0.0.1'), 4); assert.equal(net.isIP('x127.0.0.1'), 0); assert.equal(net.isIP('example.com'), 0); assert.equal(net.isIP('0000:0000:0000:0000:0000:0000:0000:0000'), 6); assert.equal(net.isIP('0000:0000:0000:0000:0000:0000:0000:0000::0000'), 0); assert.equal(net.isIP('1050:0:0:0:5:600:300c:326b'), 6); assert.equal(net.isIP('2001:252:0:1::2008:6'), 6); assert.equal(net.isIP('2001:dead:beef:1::2008:6'), 6); assert.equal(net.isIP('2001::'), 6); assert.equal(net.isIP('2001:dead::'), 6); assert.equal(net.isIP('2001:dead:beef::'), 6); assert.equal(net.isIP('2001:dead:beef:1::'), 6); assert.equal(net.isIP('ffff:ffff:ffff:ffff:ffff:ffff:ffff:ffff'), 6); assert.equal(net.isIP(':2001:252:0:1::2008:6:'), 0); assert.equal(net.isIP(':2001:252:0:1::2008:6'), 0); assert.equal(net.isIP('2001:252:0:1::2008:6:'), 0); assert.equal(net.isIP('2001:252::1::2008:6'), 0); assert.equal(net.isIP('::2001:252:1:2008:6'), 6); assert.equal(net.isIP('::2001:252:1:1.1.1.1'), 6); assert.equal(net.isIP('::2001:252:1:255.255.255.255'), 6); assert.equal(net.isIP('::2001:252:1:255.255.255.255.76'), 0); assert.equal(net.isIP('::anything'), 0); assert.equal(net.isIP('::1'), 6); assert.equal(net.isIP('::'), 6); assert.equal(net.isIP('0000:0000:0000:0000:0000:0000:12345:0000'), 0); assert.equal(net.isIP('0'), 0); assert.equal(net.isIP(), 0); assert.equal(net.isIP(""), 0); assert.equal(net.isIPv4('127.0.0.1'), true); assert.equal(net.isIPv4('example.com'), false); assert.equal(net.isIPv4('2001:252:0:1::2008:6'), false); assert.equal(net.isIPv6('127.0.0.1'), false); assert.equal(net.isIPv6('example.com'), false); assert.equal(net.isIPv6('2001:252:0:1::2008:6'), true); node-v0.10.25~dfsg2/test/simple/test-cluster-worker-death.js0000644000000000000000000000325512270121457022460 0ustar rootroot// Copyright Joyent, Inc. and other Node contributors. // // Permission is hereby granted, free of charge, to any person obtaining a // copy of this software and associated documentation files (the // "Software"), to deal in the Software without restriction, including // without limitation the rights to use, copy, modify, merge, publish, // distribute, sublicense, and/or sell copies of the Software, and to permit // persons to whom the Software is furnished to do so, subject to the // following conditions: // // The above copyright notice and this permission notice shall be included // in all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS // OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF // MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN // NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, // DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR // OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE // USE OR OTHER DEALINGS IN THE SOFTWARE. var common = require('../common'); var assert = require('assert'); var cluster = require('cluster'); if (!cluster.isMaster) { process.exit(42); } else { var seenExit = 0; var seenDeath = 0; var worker = cluster.fork(); worker.on('exit', function(exitCode, signalCode) { assert.equal(exitCode, 42); assert.equal(signalCode, null); seenExit++; }); cluster.on('exit', function(worker_) { assert.equal(worker_, worker); seenDeath++; }); process.on('exit', function() { assert.equal(seenExit, 1); assert.equal(seenDeath, 1); }); } node-v0.10.25~dfsg2/test/simple/test-assert.js0000644000000000000000000002251012270121457017701 0ustar rootroot// Copyright Joyent, Inc. and other Node contributors. // // Permission is hereby granted, free of charge, to any person obtaining a // copy of this software and associated documentation files (the // "Software"), to deal in the Software without restriction, including // without limitation the rights to use, copy, modify, merge, publish, // distribute, sublicense, and/or sell copies of the Software, and to permit // persons to whom the Software is furnished to do so, subject to the // following conditions: // // The above copyright notice and this permission notice shall be included // in all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS // OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF // MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN // NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, // DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR // OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE // USE OR OTHER DEALINGS IN THE SOFTWARE. var common = require('../common'); var assert = require('assert'); var a = require('assert'); function makeBlock(f) { var args = Array.prototype.slice.call(arguments, 1); return function() { return f.apply(this, args); }; } assert.ok(common.indirectInstanceOf(a.AssertionError.prototype, Error), 'a.AssertionError instanceof Error'); assert.throws(makeBlock(a, false), a.AssertionError, 'ok(false)'); assert.doesNotThrow(makeBlock(a, true), a.AssertionError, 'ok(true)'); assert.doesNotThrow(makeBlock(a, 'test', 'ok(\'test\')')); assert.throws(makeBlock(a.ok, false), a.AssertionError, 'ok(false)'); assert.doesNotThrow(makeBlock(a.ok, true), a.AssertionError, 'ok(true)'); assert.doesNotThrow(makeBlock(a.ok, 'test'), 'ok(\'test\')'); assert.throws(makeBlock(a.equal, true, false), a.AssertionError, 'equal'); assert.doesNotThrow(makeBlock(a.equal, null, null), 'equal'); assert.doesNotThrow(makeBlock(a.equal, undefined, undefined), 'equal'); assert.doesNotThrow(makeBlock(a.equal, null, undefined), 'equal'); assert.doesNotThrow(makeBlock(a.equal, true, true), 'equal'); assert.doesNotThrow(makeBlock(a.equal, 2, '2'), 'equal'); assert.doesNotThrow(makeBlock(a.notEqual, true, false), 'notEqual'); assert.throws(makeBlock(a.notEqual, true, true), a.AssertionError, 'notEqual'); assert.throws(makeBlock(a.strictEqual, 2, '2'), a.AssertionError, 'strictEqual'); assert.throws(makeBlock(a.strictEqual, null, undefined), a.AssertionError, 'strictEqual'); assert.doesNotThrow(makeBlock(a.notStrictEqual, 2, '2'), 'notStrictEqual'); // deepEquals joy! // 7.2 assert.doesNotThrow(makeBlock(a.deepEqual, new Date(2000, 3, 14), new Date(2000, 3, 14)), 'deepEqual date'); assert.throws(makeBlock(a.deepEqual, new Date(), new Date(2000, 3, 14)), a.AssertionError, 'deepEqual date'); // 7.3 assert.doesNotThrow(makeBlock(a.deepEqual, /a/, /a/)); assert.doesNotThrow(makeBlock(a.deepEqual, /a/g, /a/g)); assert.doesNotThrow(makeBlock(a.deepEqual, /a/i, /a/i)); assert.doesNotThrow(makeBlock(a.deepEqual, /a/m, /a/m)); assert.doesNotThrow(makeBlock(a.deepEqual, /a/igm, /a/igm)); assert.throws(makeBlock(a.deepEqual, /ab/, /a/)); assert.throws(makeBlock(a.deepEqual, /a/g, /a/)); assert.throws(makeBlock(a.deepEqual, /a/i, /a/)); assert.throws(makeBlock(a.deepEqual, /a/m, /a/)); assert.throws(makeBlock(a.deepEqual, /a/igm, /a/im)); var re1 = /a/; re1.lastIndex = 3; assert.throws(makeBlock(a.deepEqual, re1, /a/)); // 7.4 assert.doesNotThrow(makeBlock(a.deepEqual, 4, '4'), 'deepEqual == check'); assert.doesNotThrow(makeBlock(a.deepEqual, true, 1), 'deepEqual == check'); assert.throws(makeBlock(a.deepEqual, 4, '5'), a.AssertionError, 'deepEqual == check'); // 7.5 // having the same number of owned properties && the same set of keys assert.doesNotThrow(makeBlock(a.deepEqual, {a: 4}, {a: 4})); assert.doesNotThrow(makeBlock(a.deepEqual, {a: 4, b: '2'}, {a: 4, b: '2'})); assert.doesNotThrow(makeBlock(a.deepEqual, [4], ['4'])); assert.throws(makeBlock(a.deepEqual, {a: 4}, {a: 4, b: true}), a.AssertionError); assert.doesNotThrow(makeBlock(a.deepEqual, ['a'], {0: 'a'})); //(although not necessarily the same order), assert.doesNotThrow(makeBlock(a.deepEqual, {a: 4, b: '1'}, {b: '1', a: 4})); var a1 = [1, 2, 3]; var a2 = [1, 2, 3]; a1.a = 'test'; a1.b = true; a2.b = true; a2.a = 'test'; assert.throws(makeBlock(a.deepEqual, Object.keys(a1), Object.keys(a2)), a.AssertionError); assert.doesNotThrow(makeBlock(a.deepEqual, a1, a2)); // having an identical prototype property var nbRoot = { toString: function() { return this.first + ' ' + this.last; } }; function nameBuilder(first, last) { this.first = first; this.last = last; return this; } nameBuilder.prototype = nbRoot; function nameBuilder2(first, last) { this.first = first; this.last = last; return this; } nameBuilder2.prototype = nbRoot; var nb1 = new nameBuilder('Ryan', 'Dahl'); var nb2 = new nameBuilder2('Ryan', 'Dahl'); assert.doesNotThrow(makeBlock(a.deepEqual, nb1, nb2)); nameBuilder2.prototype = Object; nb2 = new nameBuilder2('Ryan', 'Dahl'); assert.throws(makeBlock(a.deepEqual, nb1, nb2), a.AssertionError); // String literal + object blew up my implementation... assert.throws(makeBlock(a.deepEqual, 'a', {}), a.AssertionError); // Testing the throwing function thrower(errorConstructor) { throw new errorConstructor('test'); } var aethrow = makeBlock(thrower, a.AssertionError); aethrow = makeBlock(thrower, a.AssertionError); // the basic calls work assert.throws(makeBlock(thrower, a.AssertionError), a.AssertionError, 'message'); assert.throws(makeBlock(thrower, a.AssertionError), a.AssertionError); assert.throws(makeBlock(thrower, a.AssertionError)); // if not passing an error, catch all. assert.throws(makeBlock(thrower, TypeError)); // when passing a type, only catch errors of the appropriate type var threw = false; try { a.throws(makeBlock(thrower, TypeError), a.AssertionError); } catch (e) { threw = true; assert.ok(e instanceof TypeError, 'type'); } assert.equal(true, threw, 'a.throws with an explicit error is eating extra errors', a.AssertionError); threw = false; // doesNotThrow should pass through all errors try { a.doesNotThrow(makeBlock(thrower, TypeError), a.AssertionError); } catch (e) { threw = true; assert.ok(e instanceof TypeError); } assert.equal(true, threw, 'a.doesNotThrow with an explicit error is eating extra errors'); // key difference is that throwing our correct error makes an assertion error try { a.doesNotThrow(makeBlock(thrower, TypeError), TypeError); } catch (e) { threw = true; assert.ok(e instanceof a.AssertionError); } assert.equal(true, threw, 'a.doesNotThrow is not catching type matching errors'); assert.throws(function() {assert.ifError(new Error('test error'))}); assert.doesNotThrow(function() {assert.ifError(null)}); assert.doesNotThrow(function() {assert.ifError()}); // make sure that validating using constructor really works threw = false; try { assert.throws( function() { throw ({}); }, Array ); } catch (e) { threw = true; } assert.ok(threw, 'wrong constructor validation'); // use a RegExp to validate error message a.throws(makeBlock(thrower, TypeError), /test/); // use a fn to validate error object a.throws(makeBlock(thrower, TypeError), function(err) { if ((err instanceof TypeError) && /test/.test(err)) { return true; } }); // GH-207. Make sure deepEqual doesn't loop forever on circular refs var b = {}; b.b = b; var c = {}; c.b = c; var gotError = false; try { assert.deepEqual(b, c); } catch (e) { gotError = true; } console.log('All OK'); assert.ok(gotError); // #217 function testAssertionMessage(actual, expected) { try { assert.equal(actual, ''); } catch (e) { assert.equal(e.toString(), ['AssertionError:', expected, '==', '""'].join(' ')); } } testAssertionMessage(undefined, '"undefined"'); testAssertionMessage(null, 'null'); testAssertionMessage(true, 'true'); testAssertionMessage(false, 'false'); testAssertionMessage(0, '0'); testAssertionMessage(100, '100'); testAssertionMessage(NaN, '"NaN"'); testAssertionMessage(Infinity, '"Infinity"'); testAssertionMessage(-Infinity, '"-Infinity"'); testAssertionMessage('', '""'); testAssertionMessage('foo', '"foo"'); testAssertionMessage([], '[]'); testAssertionMessage([1, 2, 3], '[1,2,3]'); testAssertionMessage(/a/, '"/a/"'); testAssertionMessage(/abc/gim, '"/abc/gim"'); testAssertionMessage(function f() {}, '"function f() {}"'); testAssertionMessage({}, '{}'); testAssertionMessage({a: undefined, b: null}, '{"a":"undefined","b":null}'); testAssertionMessage({a: NaN, b: Infinity, c: -Infinity}, '{"a":"NaN","b":"Infinity","c":"-Infinity"}'); // #2893 try { assert.throws(function () { assert.ifError(null); }); } catch (e) { threw = true; assert.equal(e.message, 'Missing expected exception..'); } assert.ok(threw); // #5292 try { assert.equal(1, 2); } catch (e) { assert.equal(e.toString().split('\n')[0], 'AssertionError: 1 == 2') } try { assert.equal(1, 2, 'oh no'); } catch (e) { assert.equal(e.toString().split('\n')[0], 'AssertionError: oh no') } node-v0.10.25~dfsg2/test/simple/test-http-malformed-request.js0000644000000000000000000000376512270121457023024 0ustar rootroot// Copyright Joyent, Inc. and other Node contributors. // // Permission is hereby granted, free of charge, to any person obtaining a // copy of this software and associated documentation files (the // "Software"), to deal in the Software without restriction, including // without limitation the rights to use, copy, modify, merge, publish, // distribute, sublicense, and/or sell copies of the Software, and to permit // persons to whom the Software is furnished to do so, subject to the // following conditions: // // The above copyright notice and this permission notice shall be included // in all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS // OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF // MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN // NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, // DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR // OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE // USE OR OTHER DEALINGS IN THE SOFTWARE. var common = require('../common'); var assert = require('assert'); var net = require('net'); var http = require('http'); var url = require('url'); // Make sure no exceptions are thrown when receiving malformed HTTP // requests. var nrequests_completed = 0; var nrequests_expected = 1; var server = http.createServer(function(req, res) { console.log('req: ' + JSON.stringify(url.parse(req.url))); res.writeHead(200, {'Content-Type': 'text/plain'}); res.write('Hello World'); res.end(); if (++nrequests_completed == nrequests_expected) server.close(); }); server.listen(common.PORT); server.on('listening', function() { var c = net.createConnection(common.PORT); c.on('connect', function() { c.write('GET /hello?foo=%99bar HTTP/1.1\r\n\r\n'); c.end(); }); // TODO add more! }); process.on('exit', function() { assert.equal(nrequests_expected, nrequests_completed); }); node-v0.10.25~dfsg2/test/simple/test-https-simple.js0000644000000000000000000000465512270121457021043 0ustar rootroot// Copyright Joyent, Inc. and other Node contributors. // // Permission is hereby granted, free of charge, to any person obtaining a // copy of this software and associated documentation files (the // "Software"), to deal in the Software without restriction, including // without limitation the rights to use, copy, modify, merge, publish, // distribute, sublicense, and/or sell copies of the Software, and to permit // persons to whom the Software is furnished to do so, subject to the // following conditions: // // The above copyright notice and this permission notice shall be included // in all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS // OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF // MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN // NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, // DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR // OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE // USE OR OTHER DEALINGS IN THE SOFTWARE. if (!process.versions.openssl) { console.error('Skipping because node compiled without OpenSSL.'); process.exit(0); } var common = require('../common'); var assert = require('assert'); var fs = require('fs'); var exec = require('child_process').exec; var https = require('https'); var options = { key: fs.readFileSync(common.fixturesDir + '/keys/agent1-key.pem'), cert: fs.readFileSync(common.fixturesDir + '/keys/agent1-cert.pem') }; var reqCount = 0; var body = 'hello world\n'; var server = https.createServer(options, function(req, res) { reqCount++; console.log('got request'); res.writeHead(200, { 'content-type': 'text/plain' }); res.end(body); }); server.listen(common.PORT, function() { var cmd = 'curl --insecure https://127.0.0.1:' + common.PORT + '/'; console.error('executing %j', cmd); exec(cmd, function(err, stdout, stderr) { if (err) throw err; common.error(common.inspect(stdout)); assert.equal(body, stdout); // Do the same thing now without --insecure // The connection should not be accepted. var cmd = 'curl https://127.0.0.1:' + common.PORT + '/'; console.error('executing %j', cmd); exec(cmd, function(err, stdout, stderr) { assert.ok(err); server.close(); }); }); }); process.on('exit', function() { assert.equal(1, reqCount); }); node-v0.10.25~dfsg2/test/simple/path.js0000644000000000000000000000273712270121457016370 0ustar rootroot// Copyright Joyent, Inc. and other Node contributors. // // Permission is hereby granted, free of charge, to any person obtaining a // copy of this software and associated documentation files (the // "Software"), to deal in the Software without restriction, including // without limitation the rights to use, copy, modify, merge, publish, // distribute, sublicense, and/or sell copies of the Software, and to permit // persons to whom the Software is furnished to do so, subject to the // following conditions: // // The above copyright notice and this permission notice shall be included // in all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS // OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF // MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN // NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, // DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR // OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE // USE OR OTHER DEALINGS IN THE SOFTWARE. // This is actually more a fixture than a test. It is used to make var common = require('../common'); // sure that require('./path') and require('path') do different things. // It has to be in the same directory as the test 'test-module-loading.js' // and it has to have the same name as an internal module. exports.path_func = function() { return 'path_func'; }; node-v0.10.25~dfsg2/test/simple/test-http-localaddress-bind-error.js0000644000000000000000000000401312270121457024054 0ustar rootroot// Copyright Joyent, Inc. and other Node contributors. // // Permission is hereby granted, free of charge, to any person obtaining a // copy of this software and associated documentation files (the // "Software"), to deal in the Software without restriction, including // without limitation the rights to use, copy, modify, merge, publish, // distribute, sublicense, and/or sell copies of the Software, and to permit // persons to whom the Software is furnished to do so, subject to the // following conditions: // // The above copyright notice and this permission notice shall be included // in all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS // OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF // MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN // NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, // DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR // OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE // USE OR OTHER DEALINGS IN THE SOFTWARE. var common = require('../common'); var assert = require('assert'); var http = require('http'); var invalidLocalAddress = '1.2.3.4'; var gotError = false; var server = http.createServer(function(req, res) { console.log("Connect from: " + req.connection.remoteAddress); req.on('end', function() { res.writeHead(200, { 'Content-Type': 'text/plain' }); res.end('You are from: ' + req.connection.remoteAddress); }); req.resume(); }); server.listen(common.PORT, "127.0.0.1", function() { var req = http.request({ host: 'localhost', port: common.PORT, path: '/', method: 'GET', localAddress: invalidLocalAddress }, function(res) { assert.fail('unexpectedly got response from server'); }).on('error', function(e) { console.log('client got error: ' + e.message); gotError = true; server.close(); }).end(); }); process.on('exit', function() { assert.ok(gotError); }); node-v0.10.25~dfsg2/test/simple/test-http-client-timeout-with-data.js0000644000000000000000000000407512270121457024205 0ustar rootroot// Copyright Joyent, Inc. and other Node contributors. // // Permission is hereby granted, free of charge, to any person obtaining a // copy of this software and associated documentation files (the // "Software"), to deal in the Software without restriction, including // without limitation the rights to use, copy, modify, merge, publish, // distribute, sublicense, and/or sell copies of the Software, and to permit // persons to whom the Software is furnished to do so, subject to the // following conditions: // // The above copyright notice and this permission notice shall be included // in all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS // OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF // MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN // NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, // DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR // OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE // USE OR OTHER DEALINGS IN THE SOFTWARE. var common = require('../common'); var assert = require('assert'); var http = require('http'); var ntimeouts = 0; var nchunks = 0; process.on('exit', function() { assert.equal(ntimeouts, 1); assert.equal(nchunks, 2); }); var options = { method: 'GET', port: common.PORT, host: '127.0.0.1', path: '/' }; var server = http.createServer(function(req, res) { res.writeHead(200, {'Content-Length':'2'}); res.write('*'); setTimeout(function() { res.end('*') }, 100); }); server.listen(options.port, options.host, function() { var req = http.request(options, onresponse); req.end(); function onresponse(res) { req.setTimeout(50, function() { assert.equal(nchunks, 1); // should have received the first chunk by now ntimeouts++; }); res.on('data', function(data) { assert.equal('' + data, '*'); nchunks++; }); res.on('end', function() { assert.equal(nchunks, 2); server.close(); }); } }); node-v0.10.25~dfsg2/test/simple/test-http-blank-header.js0000644000000000000000000000420412270121457021672 0ustar rootroot// Copyright Joyent, Inc. and other Node contributors. // // Permission is hereby granted, free of charge, to any person obtaining a // copy of this software and associated documentation files (the // "Software"), to deal in the Software without restriction, including // without limitation the rights to use, copy, modify, merge, publish, // distribute, sublicense, and/or sell copies of the Software, and to permit // persons to whom the Software is furnished to do so, subject to the // following conditions: // // The above copyright notice and this permission notice shall be included // in all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS // OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF // MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN // NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, // DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR // OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE // USE OR OTHER DEALINGS IN THE SOFTWARE. var common = require('../common'); var assert = require('assert'); var http = require('http'); var net = require('net'); var gotReq = false; var server = http.createServer(function(req, res) { common.error('got req'); gotReq = true; assert.equal('GET', req.method); assert.equal('/blah', req.url); assert.deepEqual({ host: 'mapdevel.trolologames.ru:443', origin: 'http://mapdevel.trolologames.ru', cookie: '' }, req.headers); }); server.listen(common.PORT, function() { var c = net.createConnection(common.PORT); c.on('connect', function() { common.error('client wrote message'); c.write('GET /blah HTTP/1.1\r\n' + 'Host: mapdevel.trolologames.ru:443\r\n' + 'Cookie:\r\n' + 'Origin: http://mapdevel.trolologames.ru\r\n' + '\r\n\r\nhello world' ); }); c.on('end', function() { c.end(); }); c.on('close', function() { common.error('client close'); server.close(); }); }); process.on('exit', function() { assert.ok(gotReq); }); node-v0.10.25~dfsg2/test/simple/test-http-proxy.js0000644000000000000000000000651012270121457020540 0ustar rootroot// Copyright Joyent, Inc. and other Node contributors. // // Permission is hereby granted, free of charge, to any person obtaining a // copy of this software and associated documentation files (the // "Software"), to deal in the Software without restriction, including // without limitation the rights to use, copy, modify, merge, publish, // distribute, sublicense, and/or sell copies of the Software, and to permit // persons to whom the Software is furnished to do so, subject to the // following conditions: // // The above copyright notice and this permission notice shall be included // in all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS // OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF // MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN // NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, // DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR // OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE // USE OR OTHER DEALINGS IN THE SOFTWARE. var common = require('../common'); var assert = require('assert'); var http = require('http'); var url = require('url'); var PROXY_PORT = common.PORT; var BACKEND_PORT = common.PORT + 1; var cookies = [ 'session_token=; path=/; expires=Sun, 15-Sep-2030 13:48:52 GMT', 'prefers_open_id=; path=/; expires=Thu, 01-Jan-1970 00:00:00 GMT' ]; var headers = {'content-type': 'text/plain', 'set-cookie': cookies, 'hello': 'world' }; var backend = http.createServer(function(req, res) { common.debug('backend request'); res.writeHead(200, headers); res.write('hello world\n'); res.end(); }); var proxy = http.createServer(function(req, res) { common.debug('proxy req headers: ' + JSON.stringify(req.headers)); var proxy_req = http.get({ port: BACKEND_PORT, path: url.parse(req.url).pathname }, function(proxy_res) { common.debug('proxy res headers: ' + JSON.stringify(proxy_res.headers)); assert.equal('world', proxy_res.headers['hello']); assert.equal('text/plain', proxy_res.headers['content-type']); assert.deepEqual(cookies, proxy_res.headers['set-cookie']); res.writeHead(proxy_res.statusCode, proxy_res.headers); proxy_res.on('data', function(chunk) { res.write(chunk); }); proxy_res.on('end', function() { res.end(); common.debug('proxy res'); }); }); }); var body = ''; var nlistening = 0; function startReq() { nlistening++; if (nlistening < 2) return; var client = http.get({ port: PROXY_PORT, path: '/test' }, function(res) { common.debug('got res'); assert.equal(200, res.statusCode); assert.equal('world', res.headers['hello']); assert.equal('text/plain', res.headers['content-type']); assert.deepEqual(cookies, res.headers['set-cookie']); res.setEncoding('utf8'); res.on('data', function(chunk) { body += chunk; }); res.on('end', function() { proxy.close(); backend.close(); common.debug('closed both'); }); }); common.debug('client req'); } common.debug('listen proxy'); proxy.listen(PROXY_PORT, startReq); common.debug('listen backend'); backend.listen(BACKEND_PORT, startReq); process.on('exit', function() { assert.equal(body, 'hello world\n'); }); node-v0.10.25~dfsg2/test/simple/test-net-eaddrinuse.js0000644000000000000000000000275712270121457021322 0ustar rootroot// Copyright Joyent, Inc. and other Node contributors. // // Permission is hereby granted, free of charge, to any person obtaining a // copy of this software and associated documentation files (the // "Software"), to deal in the Software without restriction, including // without limitation the rights to use, copy, modify, merge, publish, // distribute, sublicense, and/or sell copies of the Software, and to permit // persons to whom the Software is furnished to do so, subject to the // following conditions: // // The above copyright notice and this permission notice shall be included // in all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS // OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF // MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN // NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, // DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR // OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE // USE OR OTHER DEALINGS IN THE SOFTWARE. var common = require('../common'); var assert = require('assert'); var net = require('net'); var server1 = net.createServer(function(socket) { }); var server2 = net.createServer(function(socket) { }); server1.listen(common.PORT); server2.on('error', function(error) { assert.equal(true, error.message.indexOf('EADDRINUSE') >= 0); server1.close(); }); server2.listen(common.PORT); node-v0.10.25~dfsg2/test/simple/test-http-legacy.js0000644000000000000000000000637512270121457020634 0ustar rootroot// Copyright Joyent, Inc. and other Node contributors. // // Permission is hereby granted, free of charge, to any person obtaining a // copy of this software and associated documentation files (the // "Software"), to deal in the Software without restriction, including // without limitation the rights to use, copy, modify, merge, publish, // distribute, sublicense, and/or sell copies of the Software, and to permit // persons to whom the Software is furnished to do so, subject to the // following conditions: // // The above copyright notice and this permission notice shall be included // in all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS // OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF // MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN // NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, // DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR // OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE // USE OR OTHER DEALINGS IN THE SOFTWARE. var common = require('../common'); var assert = require('assert'); var http = require('http'); var url = require('url'); function p(x) { common.error(common.inspect(x)); } var responses_sent = 0; var responses_recvd = 0; var body0 = ''; var body1 = ''; var server = http.createServer(function(req, res) { if (responses_sent == 0) { assert.equal('GET', req.method); assert.equal('/hello', url.parse(req.url).pathname); console.dir(req.headers); assert.equal(true, 'accept' in req.headers); assert.equal('*/*', req.headers['accept']); assert.equal(true, 'foo' in req.headers); assert.equal('bar', req.headers['foo']); } if (responses_sent == 1) { assert.equal('POST', req.method); assert.equal('/world', url.parse(req.url).pathname); this.close(); } req.on('end', function() { res.writeHead(200, {'Content-Type': 'text/plain'}); res.write('The path was ' + url.parse(req.url).pathname); res.end(); responses_sent += 1; }); req.resume(); //assert.equal('127.0.0.1', res.connection.remoteAddress); }); server.listen(common.PORT, function() { var client = http.createClient(common.PORT); var req = client.request('/hello', {'Accept': '*/*', 'Foo': 'bar'}); setTimeout(function() { req.end(); }, 100); req.on('response', function(res) { assert.equal(200, res.statusCode); responses_recvd += 1; res.setEncoding('utf8'); res.on('data', function(chunk) { body0 += chunk; }); common.debug('Got /hello response'); }); setTimeout(function() { var req = client.request('POST', '/world'); req.end(); req.on('response', function(res) { assert.equal(200, res.statusCode); responses_recvd += 1; res.setEncoding('utf8'); res.on('data', function(chunk) { body1 += chunk; }); common.debug('Got /world response'); }); }, 1); }); process.on('exit', function() { common.debug('responses_recvd: ' + responses_recvd); assert.equal(2, responses_recvd); common.debug('responses_sent: ' + responses_sent); assert.equal(2, responses_sent); assert.equal('The path was /hello', body0); assert.equal('The path was /world', body1); }); node-v0.10.25~dfsg2/test/simple/test-tls-hello-parser-failure.js0000644000000000000000000000376512270121457023235 0ustar rootroot// Copyright Joyent, Inc. and other Node contributors. // // Permission is hereby granted, free of charge, to any person obtaining a // copy of this software and associated documentation files (the // "Software"), to deal in the Software without restriction, including // without limitation the rights to use, copy, modify, merge, publish, // distribute, sublicense, and/or sell copies of the Software, and to permit // persons to whom the Software is furnished to do so, subject to the // following conditions: // // The above copyright notice and this permission notice shall be included // in all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS // OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF // MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN // NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, // DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR // OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE // USE OR OTHER DEALINGS IN THE SOFTWARE. var common = require('../common'); var tls = require('tls'); var net = require('net'); var fs = require('fs'); var assert = require('assert'); var options = { key: fs.readFileSync(common.fixturesDir + '/test_key.pem'), cert: fs.readFileSync(common.fixturesDir + '/test_cert.pem') }; var bonkers = new Buffer(1024 * 1024); bonkers.fill(42); var server = tls.createServer(options, function(c) { }).listen(common.PORT, function() { var client = net.connect(common.PORT, function() { client.write(bonkers); }); var once = false; var writeAgain = setTimeout(function() { client.write(bonkers); }); client.on('error', function(err) { if (!once) { clearTimeout(writeAgain); once = true; client.destroy(); server.close(); } }); client.on('close', function (hadError) { assert.strictEqual(hadError, true, 'Client never errored'); }); }); node-v0.10.25~dfsg2/test/simple/test-stream-pipe-cleanup.js0000644000000000000000000000714212270121457022257 0ustar rootroot// Copyright Joyent, Inc. and other Node contributors. // // Permission is hereby granted, free of charge, to any person obtaining a // copy of this software and associated documentation files (the // "Software"), to deal in the Software without restriction, including // without limitation the rights to use, copy, modify, merge, publish, // distribute, sublicense, and/or sell copies of the Software, and to permit // persons to whom the Software is furnished to do so, subject to the // following conditions: // // The above copyright notice and this permission notice shall be included // in all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS // OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF // MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN // NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, // DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR // OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE // USE OR OTHER DEALINGS IN THE SOFTWARE. // This test asserts that Stream.prototype.pipe does not leave listeners // hanging on the source or dest. var common = require('../common'); var stream = require('stream'); var assert = require('assert'); var util = require('util'); function Writable() { this.writable = true; this.endCalls = 0; stream.Stream.call(this); } util.inherits(Writable, stream.Stream); Writable.prototype.end = function() { this.endCalls++; }; Writable.prototype.destroy = function() { this.endCalls++; }; function Readable() { this.readable = true; stream.Stream.call(this); } util.inherits(Readable, stream.Stream); function Duplex() { this.readable = true; Writable.call(this); } util.inherits(Duplex, Writable); var i = 0; var limit = 100; var w = new Writable(); var r; for (i = 0; i < limit; i++) { r = new Readable(); r.pipe(w); r.emit('end'); } assert.equal(0, r.listeners('end').length); assert.equal(limit, w.endCalls); w.endCalls = 0; for (i = 0; i < limit; i++) { r = new Readable(); r.pipe(w); r.emit('close'); } assert.equal(0, r.listeners('close').length); assert.equal(limit, w.endCalls); w.endCalls = 0; r = new Readable(); for (i = 0; i < limit; i++) { w = new Writable(); r.pipe(w); w.emit('close'); } assert.equal(0, w.listeners('close').length); r = new Readable(); w = new Writable(); var d = new Duplex(); r.pipe(d); // pipeline A d.pipe(w); // pipeline B assert.equal(r.listeners('end').length, 2); // A.onend, A.cleanup assert.equal(r.listeners('close').length, 2); // A.onclose, A.cleanup assert.equal(d.listeners('end').length, 2); // B.onend, B.cleanup assert.equal(d.listeners('close').length, 3); // A.cleanup, B.onclose, B.cleanup assert.equal(w.listeners('end').length, 0); assert.equal(w.listeners('close').length, 1); // B.cleanup r.emit('end'); assert.equal(d.endCalls, 1); assert.equal(w.endCalls, 0); assert.equal(r.listeners('end').length, 0); assert.equal(r.listeners('close').length, 0); assert.equal(d.listeners('end').length, 2); // B.onend, B.cleanup assert.equal(d.listeners('close').length, 2); // B.onclose, B.cleanup assert.equal(w.listeners('end').length, 0); assert.equal(w.listeners('close').length, 1); // B.cleanup d.emit('end'); assert.equal(d.endCalls, 1); assert.equal(w.endCalls, 1); assert.equal(r.listeners('end').length, 0); assert.equal(r.listeners('close').length, 0); assert.equal(d.listeners('end').length, 0); assert.equal(d.listeners('close').length, 0); assert.equal(w.listeners('end').length, 0); assert.equal(w.listeners('close').length, 0); node-v0.10.25~dfsg2/test/simple/test-eval.js0000644000000000000000000000336012270121457017331 0ustar rootroot// Copyright Joyent, Inc. and other Node contributors. // // Permission is hereby granted, free of charge, to any person obtaining a // copy of this software and associated documentation files (the // "Software"), to deal in the Software without restriction, including // without limitation the rights to use, copy, modify, merge, publish, // distribute, sublicense, and/or sell copies of the Software, and to permit // persons to whom the Software is furnished to do so, subject to the // following conditions: // // The above copyright notice and this permission notice shall be included // in all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS // OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF // MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN // NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, // DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR // OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE // USE OR OTHER DEALINGS IN THE SOFTWARE. require('../common'); var util = require('util'); var assert = require('assert'); var exec = require('child_process').exec; var success_count = 0; var error_count = 0; var cmd = [process.execPath, '-e', '"console.error(process.argv)"', 'foo', 'bar'].join(' '); var expected = util.format([process.execPath, 'foo', 'bar']) + '\n'; var child = exec(cmd, function(err, stdout, stderr) { if (err) { console.log(err.toString()); ++error_count; return; } assert.equal(stderr, expected); ++success_count; }); process.on('exit', function() { assert.equal(1, success_count); assert.equal(0, error_count); }); node-v0.10.25~dfsg2/test/simple/test-cluster-eaccess.js0000644000000000000000000000406612270121457021473 0ustar rootroot// Copyright Joyent, Inc. and other Node contributors. // // Permission is hereby granted, free of charge, to any person obtaining a // copy of this software and associated documentation files (the // "Software"), to deal in the Software without restriction, including // without limitation the rights to use, copy, modify, merge, publish, // distribute, sublicense, and/or sell copies of the Software, and to permit // persons to whom the Software is furnished to do so, subject to the // following conditions: // // The above copyright notice and this permission notice shall be included // in all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS // OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF // MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN // NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, // DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR // OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE // USE OR OTHER DEALINGS IN THE SOFTWARE. var common = require('../common'); var assert = require('assert'); var cluster = require('cluster'); var path = require('path'); var fs = require('fs'); var net = require('net'); var socketPath = path.join(common.fixturesDir, 'socket-path'); if (cluster.isMaster) { var worker = cluster.fork(); var gotError = 0; worker.on('message', function(err) { gotError++; console.log(err); if (process.platform === 'win32') assert.strictEqual('EACCES', err.code); else assert.strictEqual('EADDRINUSE', err.code); worker.disconnect(); }); process.on('exit', function() { console.log('master exited'); try { fs.unlinkSync(socketPath); } catch (e) { } assert.equal(gotError, 1); }); } else { fs.writeFileSync(socketPath, 'some contents'); var server = net.createServer().listen(socketPath, function() { console.log('here'); }); server.on('error', function(err) { process.send(err); }); } node-v0.10.25~dfsg2/test/simple/test-tls-connect.js0000644000000000000000000000477212270121457020643 0ustar rootroot// Copyright Joyent, Inc. and other Node contributors. // // Permission is hereby granted, free of charge, to any person obtaining a // copy of this software and associated documentation files (the // "Software"), to deal in the Software without restriction, including // without limitation the rights to use, copy, modify, merge, publish, // distribute, sublicense, and/or sell copies of the Software, and to permit // persons to whom the Software is furnished to do so, subject to the // following conditions: // // The above copyright notice and this permission notice shall be included // in all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS // OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF // MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN // NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, // DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR // OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE // USE OR OTHER DEALINGS IN THE SOFTWARE. if (!process.versions.openssl) { console.error('Skipping because node compiled without OpenSSL.'); process.exit(0); } var common = require('../common'); var assert = require('assert'); var fs = require('fs'); var tls = require('tls'); var path = require('path'); // https://github.com/joyent/node/issues/1218 // uncatchable exception on TLS connection error (function() { var cert = fs.readFileSync(path.join(common.fixturesDir, 'test_cert.pem')); var key = fs.readFileSync(path.join(common.fixturesDir, 'test_key.pem')); var errorEmitted = false; process.on('exit', function() { assert.ok(errorEmitted); }); var conn = tls.connect({cert: cert, key: key, port: common.PORT}, function() { assert.ok(false); // callback should never be executed }); conn.on('error', function() { errorEmitted = true; }); })(); // SSL_accept/SSL_connect error handling (function() { var cert = fs.readFileSync(path.join(common.fixturesDir, 'test_cert.pem')); var key = fs.readFileSync(path.join(common.fixturesDir, 'test_key.pem')); var errorEmitted = false; process.on('exit', function() { assert.ok(errorEmitted); }); var conn = tls.connect({ cert: cert, key: key, port: common.PORT, ciphers: 'rick-128-roll' }, function() { assert.ok(false); // callback should never be executed }); conn.on('error', function() { errorEmitted = true; }); })(); node-v0.10.25~dfsg2/test/simple/test-zlib-write-after-flush.js0000644000000000000000000000343112270121457022707 0ustar rootroot// Copyright Joyent, Inc. and other Node contributors. // // Permission is hereby granted, free of charge, to any person obtaining a // copy of this software and associated documentation files (the // "Software"), to deal in the Software without restriction, including // without limitation the rights to use, copy, modify, merge, publish, // distribute, sublicense, and/or sell copies of the Software, and to permit // persons to whom the Software is furnished to do so, subject to the // following conditions: // // The above copyright notice and this permission notice shall be included // in all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS // OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF // MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN // NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, // DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR // OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE // USE OR OTHER DEALINGS IN THE SOFTWARE. var common = require('../common'); var assert = require('assert'); var zlib = require('zlib'); var fs = require('fs'); var gzip = zlib.createGzip(); var gunz = zlib.createUnzip(); gzip.pipe(gunz); var output = ''; var input = 'A line of data\n'; gunz.setEncoding('utf8'); gunz.on('data', function(c) { output += c; }); process.on('exit', function() { assert.equal(output, input); // Make sure that the flush flag was set back to normal assert.equal(gzip._flushFlag, zlib.Z_NO_FLUSH); console.log('ok'); }); // make sure that flush/write doesn't trigger an assert failure gzip.flush(); write(); function write() { gzip.write(input); gzip.end(); gunz.read(0); } node-v0.10.25~dfsg2/test/simple/test-http-agent.js0000644000000000000000000000374612270121457020465 0ustar rootroot// Copyright Joyent, Inc. and other Node contributors. // // Permission is hereby granted, free of charge, to any person obtaining a // copy of this software and associated documentation files (the // "Software"), to deal in the Software without restriction, including // without limitation the rights to use, copy, modify, merge, publish, // distribute, sublicense, and/or sell copies of the Software, and to permit // persons to whom the Software is furnished to do so, subject to the // following conditions: // // The above copyright notice and this permission notice shall be included // in all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS // OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF // MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN // NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, // DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR // OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE // USE OR OTHER DEALINGS IN THE SOFTWARE. var common = require('../common'); var assert = require('assert'); var http = require('http'); var server = http.Server(function(req, res) { res.writeHead(200); res.end('hello world\n'); }); var responses = 0; var N = 10; var M = 10; server.listen(common.PORT, function() { for (var i = 0; i < N; i++) { setTimeout(function() { for (var j = 0; j < M; j++) { http.get({ port: common.PORT, path: '/' }, function(res) { console.log('%d %d', responses, res.statusCode); if (++responses == N * M) { console.error('Received all responses, closing server'); server.close(); } res.resume(); }).on('error', function(e) { console.log('Error!', e); process.exit(1); }); } }, i); } }); process.on('exit', function() { assert.equal(N * M, responses); }); node-v0.10.25~dfsg2/test/simple/test-readline-set-raw-mode.js0000644000000000000000000000513712270121457022473 0ustar rootroot// Copyright Joyent, Inc. and other Node contributors. // // Permission is hereby granted, free of charge, to any person obtaining a // copy of this software and associated documentation files (the // "Software"), to deal in the Software without restriction, including // without limitation the rights to use, copy, modify, merge, publish, // distribute, sublicense, and/or sell copies of the Software, and to permit // persons to whom the Software is furnished to do so, subject to the // following conditions: // // The above copyright notice and this permission notice shall be included // in all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS // OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF // MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN // NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, // DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR // OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE // USE OR OTHER DEALINGS IN THE SOFTWARE. var assert = require('assert'); var readline = require('readline'); var Stream = require('stream'); var stream = new Stream(); var expectedRawMode = true; var rawModeCalled = false; var resumeCalled = false; var pauseCalled = false; stream.setRawMode = function(mode) { rawModeCalled = true; assert.equal(mode, expectedRawMode); }; stream.resume = function() { resumeCalled = true; }; stream.pause = function() { pauseCalled = true; }; // when the "readline" starts in "terminal" mode, // then setRawMode(true) should be called var rli = readline.createInterface({ input: stream, output: stream, terminal: true }); assert(rli.terminal) assert(rawModeCalled); assert(resumeCalled); assert(!pauseCalled); // pause() should call *not* call setRawMode() rawModeCalled = false; resumeCalled = false; pauseCalled = false; rli.pause(); assert(!rawModeCalled); assert(!resumeCalled); assert(pauseCalled); // resume() should *not* call setRawMode() rawModeCalled = false; resumeCalled = false; pauseCalled = false; rli.resume(); assert(!rawModeCalled); assert(resumeCalled); assert(!pauseCalled); // close() should call setRawMode(false) expectedRawMode = false; rawModeCalled = false; resumeCalled = false; pauseCalled = false; rli.close(); assert(rawModeCalled); assert(!resumeCalled); assert(pauseCalled); assert.deepEqual(stream.listeners('end'), []); assert.deepEqual(stream.listeners('keypress'), []); // one data listener for the keypress events. assert.equal(stream.listeners('data').length, 1); node-v0.10.25~dfsg2/test/simple/test-tls-fast-writing.js0000644000000000000000000000471212270121457021622 0ustar rootroot// Copyright Joyent, Inc. and other Node contributors. // // Permission is hereby granted, free of charge, to any person obtaining a // copy of this software and associated documentation files (the // "Software"), to deal in the Software without restriction, including // without limitation the rights to use, copy, modify, merge, publish, // distribute, sublicense, and/or sell copies of the Software, and to permit // persons to whom the Software is furnished to do so, subject to the // following conditions: // // The above copyright notice and this permission notice shall be included // in all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS // OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF // MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN // NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, // DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR // OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE // USE OR OTHER DEALINGS IN THE SOFTWARE. var common = require('../common'); var assert = require('assert'); var tls = require('tls'); var fs = require('fs'); var PORT = common.PORT; var dir = common.fixturesDir; var options = { key: fs.readFileSync(dir + '/test_key.pem'), cert: fs.readFileSync(dir + '/test_cert.pem'), ca: [ fs.readFileSync(dir + '/test_ca.pem') ] }; var server = tls.createServer(options, onconnection); var gotChunk = false; var gotDrain = false; var timer = setTimeout(function() { console.log('not ok - timed out'); process.exit(1); }, 500); function onconnection(conn) { conn.on('data', function(c) { if (!gotChunk) { gotChunk = true; console.log('ok - got chunk'); } // just some basic sanity checks. assert(c.length); assert(Buffer.isBuffer(c)); if (gotDrain) process.exit(0); }); } server.listen(PORT, function() { var chunk = new Buffer(1024); chunk.fill('x'); var opt = { port: PORT, rejectUnauthorized: false }; var conn = tls.connect(opt, function() { conn.on('drain', ondrain); write(); }); function ondrain() { if (!gotDrain) { gotDrain = true; console.log('ok - got drain'); } if (gotChunk) process.exit(0); write(); } function write() { // this needs to return false eventually while (false !== conn.write(chunk)); } }); node-v0.10.25~dfsg2/test/simple/test-script-static-new.js0000644000000000000000000000415112270121457021761 0ustar rootroot// Copyright Joyent, Inc. and other Node contributors. // // Permission is hereby granted, free of charge, to any person obtaining a // copy of this software and associated documentation files (the // "Software"), to deal in the Software without restriction, including // without limitation the rights to use, copy, modify, merge, publish, // distribute, sublicense, and/or sell copies of the Software, and to permit // persons to whom the Software is furnished to do so, subject to the // following conditions: // // The above copyright notice and this permission notice shall be included // in all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS // OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF // MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN // NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, // DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR // OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE // USE OR OTHER DEALINGS IN THE SOFTWARE. var common = require('../common'); var assert = require('assert'); var Script = require('vm').Script; common.globalCheck = false; common.debug('run a string'); var result = Script.runInNewContext('\'passed\';'); assert.equal('passed', result); common.debug('thrown error'); assert.throws(function() { Script.runInNewContext('throw new Error(\'test\');'); }); hello = 5; Script.runInNewContext('hello = 2'); assert.equal(5, hello); common.debug('pass values in and out'); code = 'foo = 1;' + 'bar = 2;' + 'if (baz !== 3) throw new Error(\'test fail\');'; foo = 2; obj = { foo: 0, baz: 3 }; var baz = Script.runInNewContext(code, obj); assert.equal(1, obj.foo); assert.equal(2, obj.bar); assert.equal(2, foo); common.debug('call a function by reference'); function changeFoo() { foo = 100 } Script.runInNewContext('f()', { f: changeFoo }); assert.equal(foo, 100); common.debug('modify an object by reference'); var f = { a: 1 }; Script.runInNewContext('f.a = 2', { f: f }); assert.equal(f.a, 2); node-v0.10.25~dfsg2/test/simple/test-regress-GH-1726.js0000644000000000000000000000416212270121457020746 0ustar rootroot// Copyright Joyent, Inc. and other Node contributors. // // Permission is hereby granted, free of charge, to any person obtaining a // copy of this software and associated documentation files (the // 'Software'), to deal in the Software without restriction, including // without limitation the rights to use, copy, modify, merge, publish, // distribute, sublicense, and/or sell copies of the Software, and to permit // persons to whom the Software is furnished to do so, subject to the // following conditions: // // The above copyright notice and this permission notice shall be included // in all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED 'AS IS', WITHOUT WARRANTY OF ANY KIND, EXPRESS // OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF // MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN // NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, // DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR // OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE // USE OR OTHER DEALINGS IN THE SOFTWARE. // Open a chain of five Node processes each a child of the next. The final // process exits immediately. Each process in the chain is instructed to // exit when its child exits. // https://github.com/joyent/node/issues/1726 var common = require('../common'); var assert = require('assert'); var ch = require('child_process'); var gen = +(process.argv[2] || 0); var maxGen = 5; if (gen === maxGen) { console.error('hit maxGen, exiting', maxGen); return; } var child = ch.spawn(process.execPath, [__filename, gen + 1], { customFds: [0, -1, 2] }); assert.ok(!child.stdin); assert.ok(child.stdout); assert.ok(!child.stderr); console.error('gen=%d, pid=%d', gen, process.pid); /* var timer = setTimeout(function () { throw new Error('timeout! gen='+gen); }, 1000); */ child.on('exit', function(code) { console.error('exit %d from gen %d', code, gen + 1); //clearTimeout(timer); }); child.stdout.pipe(process.stdout); child.stdout.on('close', function() { console.error('child.stdout close gen=%d', gen); }); node-v0.10.25~dfsg2/test/simple/test-net-bytes-stats.js0000644000000000000000000000461012270121457021447 0ustar rootroot// Copyright Joyent, Inc. and other Node contributors. // // Permission is hereby granted, free of charge, to any person obtaining a // copy of this software and associated documentation files (the // "Software"), to deal in the Software without restriction, including // without limitation the rights to use, copy, modify, merge, publish, // distribute, sublicense, and/or sell copies of the Software, and to permit // persons to whom the Software is furnished to do so, subject to the // following conditions: // // The above copyright notice and this permission notice shall be included // in all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS // OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF // MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN // NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, // DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR // OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE // USE OR OTHER DEALINGS IN THE SOFTWARE. var common = require('../common'); var assert = require('assert'); var net = require('net'); var tcpPort = common.PORT; var bytesRead = 0; var bytesWritten = 0; var count = 0; var tcp = net.Server(function(s) { console.log('tcp server connection'); // trigger old mode. s.resume(); s.on('end', function() { bytesRead += s.bytesRead; console.log('tcp socket disconnect #' + count); }); }); tcp.listen(common.PORT, function doTest() { console.error('listening'); var socket = net.createConnection(tcpPort); socket.on('connect', function() { count++; console.error('CLIENT connect #%d', count); socket.write('foo', function() { console.error('CLIENT: write cb'); socket.end('bar'); }); }); socket.on('finish', function() { bytesWritten += socket.bytesWritten; console.error('CLIENT end event #%d', count); }); socket.on('close', function() { console.error('CLIENT close event #%d', count); console.log('Bytes read: ' + bytesRead); console.log('Bytes written: ' + bytesWritten); if (count < 2) { console.error('RECONNECTING'); socket.connect(tcpPort); } else { tcp.close(); } }); }); process.on('exit', function() { assert.equal(bytesRead, 12); assert.equal(bytesWritten, 12); }); node-v0.10.25~dfsg2/test/simple/test-child-process-exec-error.js0000644000000000000000000000317512270121457023216 0ustar rootroot// Copyright Joyent, Inc. and other Node contributors. // // Permission is hereby granted, free of charge, to any person obtaining a // copy of this software and associated documentation files (the // "Software"), to deal in the Software without restriction, including // without limitation the rights to use, copy, modify, merge, publish, // distribute, sublicense, and/or sell copies of the Software, and to permit // persons to whom the Software is furnished to do so, subject to the // following conditions: // // The above copyright notice and this permission notice shall be included // in all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS // OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF // MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN // NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, // DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR // OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE // USE OR OTHER DEALINGS IN THE SOFTWARE. var common = require('../common'); var assert = require('assert'); var child_process = require('child_process'); function test(fun, code) { var errors = 0; fun('does-not-exist', function(err) { assert.equal(err.code, code); errors++; }); process.on('exit', function() { assert.equal(errors, 1); }); } if (process.platform === 'win32') { test(child_process.exec, 1); // exit code of cmd.exe } else { test(child_process.exec, 127); // exit code of /bin/sh } test(child_process.execFile, 'ENOENT'); node-v0.10.25~dfsg2/test/simple/test-tls-over-http-tunnel.js0000644000000000000000000001224712270121457022441 0ustar rootroot// Copyright Joyent, Inc. and other Node contributors. // // Permission is hereby granted, free of charge, to any person obtaining a // copy of this software and associated documentation files (the // "Software"), to deal in the Software without restriction, including // without limitation the rights to use, copy, modify, merge, publish, // distribute, sublicense, and/or sell copies of the Software, and to permit // persons to whom the Software is furnished to do so, subject to the // following conditions: // // The above copyright notice and this permission notice shall be included // in all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS // OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF // MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN // NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, // DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR // OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE // USE OR OTHER DEALINGS IN THE SOFTWARE. if (!process.versions.openssl) { console.error('Skipping because node compiled without OpenSSL.'); process.exit(0); } var common = require('../common'); var assert = require('assert'); var fs = require('fs'); var net = require('net'); var http = require('http'); var https = require('https'); var proxyPort = common.PORT + 1; var gotRequest = false; var key = fs.readFileSync(common.fixturesDir + '/keys/agent1-key.pem'); var cert = fs.readFileSync(common.fixturesDir + '/keys/agent1-cert.pem'); var options = { key: key, cert: cert }; var server = https.createServer(options, function(req, res) { console.log('SERVER: got request'); res.writeHead(200, { 'content-type': 'text/plain' }); console.log('SERVER: sending response'); res.end('hello world\n'); }); var proxy = net.createServer(function(clientSocket) { console.log('PROXY: got a client connection'); var serverSocket = null; clientSocket.on('data', function(chunk) { if (!serverSocket) { // Verify the CONNECT request assert.equal('CONNECT localhost:' + common.PORT + ' HTTP/1.1\r\n' + 'Proxy-Connections: keep-alive\r\n' + 'Host: localhost:' + proxyPort + '\r\n\r\n', chunk); console.log('PROXY: got CONNECT request'); console.log('PROXY: creating a tunnel'); // create the tunnel serverSocket = net.connect(common.PORT, function() { console.log('PROXY: replying to client CONNECT request'); // Send the response clientSocket.write('HTTP/1.1 200 OK\r\nProxy-Connections: keep' + '-alive\r\nConnections: keep-alive\r\nVia: ' + 'localhost:' + proxyPort + '\r\n\r\n'); }); serverSocket.on('data', function(chunk) { clientSocket.write(chunk); }); serverSocket.on('end', function() { clientSocket.destroy(); }); } else { serverSocket.write(chunk); } }); clientSocket.on('end', function() { serverSocket.destroy(); }); }); server.listen(common.PORT); proxy.listen(proxyPort, function() { console.log('CLIENT: Making CONNECT request'); var req = http.request({ port: proxyPort, method: 'CONNECT', path: 'localhost:' + common.PORT, headers: { 'Proxy-Connections': 'keep-alive' } }); req.useChunkedEncodingByDefault = false; // for v0.6 req.on('response', onResponse); // for v0.6 req.on('upgrade', onUpgrade); // for v0.6 req.on('connect', onConnect); // for v0.7 or later req.end(); function onResponse(res) { // Very hacky. This is necessary to avoid http-parser leaks. res.upgrade = true; } function onUpgrade(res, socket, head) { // Hacky. process.nextTick(function() { onConnect(res, socket, head); }); } function onConnect(res, socket, header) { assert.equal(200, res.statusCode); console.log('CLIENT: got CONNECT response'); // detach the socket socket.removeAllListeners('data'); socket.removeAllListeners('close'); socket.removeAllListeners('error'); socket.removeAllListeners('drain'); socket.removeAllListeners('end'); socket.ondata = null; socket.onend = null; socket.ondrain = null; console.log('CLIENT: Making HTTPS request'); https.get({ path: '/foo', key: key, cert: cert, socket: socket, // reuse the socket agent: false, rejectUnauthorized: false }, function(res) { assert.equal(200, res.statusCode); res.on('data', function(chunk) { assert.equal('hello world\n', chunk); console.log('CLIENT: got HTTPS response'); gotRequest = true; }); res.on('end', function() { proxy.close(); server.close(); }); }).on('error', function(er) { // We're ok with getting ECONNRESET in this test, but it's // timing-dependent, and thus unreliable. Any other errors // are just failures, though. if (er.code !== 'ECONNRESET') throw er; }).end(); } }); process.on('exit', function() { assert.ok(gotRequest); }); node-v0.10.25~dfsg2/test/simple/test-child-process-fork-ref2.js0000644000000000000000000000324512270121457022736 0ustar rootroot// Copyright Joyent, Inc. and other Node contributors. // // Permission is hereby granted, free of charge, to any person obtaining a // copy of this software and associated documentation files (the // "Software"), to deal in the Software without restriction, including // without limitation the rights to use, copy, modify, merge, publish, // distribute, sublicense, and/or sell copies of the Software, and to permit // persons to whom the Software is furnished to do so, subject to the // following conditions: // // The above copyright notice and this permission notice shall be included // in all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS // OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF // MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN // NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, // DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR // OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE // USE OR OTHER DEALINGS IN THE SOFTWARE. var common = require('../common'); var assert = require('assert'); var fork = require('child_process').fork; if (process.argv[2] === 'child') { console.log('child -> call disconnect'); process.disconnect(); setTimeout(function() { console.log('child -> will this keep it alive?'); process.on('message', function () { }); }, 400); } else { var child = fork(__filename, ['child']); child.on('disconnect', function () { console.log('parent -> disconnect'); }); child.once('exit', function () { console.log('parent -> exit'); }); } node-v0.10.25~dfsg2/test/simple/test-stream2-httpclient-response-end.js0000644000000000000000000000357012270121457024536 0ustar rootroot// Copyright Joyent, Inc. and other Node contributors. // // Permission is hereby granted, free of charge, to any person obtaining a // copy of this software and associated documentation files (the // "Software"), to deal in the Software without restriction, including // without limitation the rights to use, copy, modify, merge, publish, // distribute, sublicense, and/or sell copies of the Software, and to permit // persons to whom the Software is furnished to do so, subject to the // following conditions: // // The above copyright notice and this permission notice shall be included // in all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS // OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF // MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN // NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, // DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR // OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE // USE OR OTHER DEALINGS IN THE SOFTWARE. var common = require('../common.js'); var assert = require('assert'); var http = require('http'); var msg = 'Hello'; var readable_event = false; var end_event = false; var server = http.createServer(function(req, res) { res.writeHead(200, {'Content-Type': 'text/plain'}); res.end(msg); }).listen(common.PORT, function() { http.get({port: common.PORT}, function(res) { var data = ''; res.on('readable', function() { console.log('readable event'); readable_event = true; data += res.read(); }); res.on('end', function() { console.log('end event'); end_event = true; assert.strictEqual(msg, data); server.close(); }); }); }); process.on('exit', function() { assert(readable_event); assert(end_event); }); node-v0.10.25~dfsg2/test/simple/test-http-write-empty-string.js0000644000000000000000000000357412270121457023160 0ustar rootroot// Copyright Joyent, Inc. and other Node contributors. // // Permission is hereby granted, free of charge, to any person obtaining a // copy of this software and associated documentation files (the // "Software"), to deal in the Software without restriction, including // without limitation the rights to use, copy, modify, merge, publish, // distribute, sublicense, and/or sell copies of the Software, and to permit // persons to whom the Software is furnished to do so, subject to the // following conditions: // // The above copyright notice and this permission notice shall be included // in all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS // OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF // MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN // NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, // DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR // OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE // USE OR OTHER DEALINGS IN THE SOFTWARE. var common = require('../common'); var assert = require('assert'); var http = require('http'); var server = http.createServer(function(request, response) { console.log('responding to ' + request.url); response.writeHead(200, {'Content-Type': 'text/plain'}); response.write('1\n'); response.write(''); response.write('2\n'); response.write(''); response.end('3\n'); this.close(); }); var response = ''; process.on('exit', function() { assert.equal('1\n2\n3\n', response); }); server.listen(common.PORT, function() { http.get({ port: common.PORT }, function(res) { assert.equal(200, res.statusCode); res.setEncoding('ascii'); res.on('data', function(chunk) { response += chunk; }); common.error('Got /hello response'); }); }); node-v0.10.25~dfsg2/test/simple/test-fs-write-buffer.js0000644000000000000000000000362512270121457021415 0ustar rootroot// Copyright Joyent, Inc. and other Node contributors. // // Permission is hereby granted, free of charge, to any person obtaining a // copy of this software and associated documentation files (the // "Software"), to deal in the Software without restriction, including // without limitation the rights to use, copy, modify, merge, publish, // distribute, sublicense, and/or sell copies of the Software, and to permit // persons to whom the Software is furnished to do so, subject to the // following conditions: // // The above copyright notice and this permission notice shall be included // in all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS // OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF // MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN // NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, // DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR // OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE // USE OR OTHER DEALINGS IN THE SOFTWARE. var common = require('../common'); var assert = require('assert'); var path = require('path'), Buffer = require('buffer').Buffer, fs = require('fs'), filename = path.join(common.tmpDir, 'write.txt'), expected = new Buffer('hello'), openCalled = 0, writeCalled = 0; fs.open(filename, 'w', 0644, function(err, fd) { openCalled++; if (err) throw err; fs.write(fd, expected, 0, expected.length, null, function(err, written) { writeCalled++; if (err) throw err; assert.equal(expected.length, written); fs.closeSync(fd); var found = fs.readFileSync(filename, 'utf8'); assert.deepEqual(expected.toString(), found); fs.unlinkSync(filename); }); }); process.on('exit', function() { assert.equal(1, openCalled); assert.equal(1, writeCalled); }); node-v0.10.25~dfsg2/test/simple/test-console.js0000644000000000000000000000435212270121457020046 0ustar rootroot// Copyright Joyent, Inc. and other Node contributors. // // Permission is hereby granted, free of charge, to any person obtaining a // copy of this software and associated documentation files (the // "Software"), to deal in the Software without restriction, including // without limitation the rights to use, copy, modify, merge, publish, // distribute, sublicense, and/or sell copies of the Software, and to permit // persons to whom the Software is furnished to do so, subject to the // following conditions: // // The above copyright notice and this permission notice shall be included // in all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS // OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF // MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN // NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, // DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR // OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE // USE OR OTHER DEALINGS IN THE SOFTWARE. var common = require('../common'); var assert = require('assert'); assert.ok(process.stdout.writable); assert.ok(process.stderr.writable); // Support legacy API assert.equal('number', typeof process.stdout.fd); assert.equal('number', typeof process.stderr.fd); var stdout_write = global.process.stdout.write; var strings = []; global.process.stdout.write = function(string) { strings.push(string); }; console.log('foo'); console.log('foo', 'bar'); console.log('%s %s', 'foo', 'bar', 'hop'); console.log({slashes: '\\\\'}); console._stderr = process.stdout; console.trace('This is a %j %d', { formatted: 'trace' }, 10, 'foo'); global.process.stdout.write = stdout_write; assert.equal('foo\n', strings.shift()); assert.equal('foo bar\n', strings.shift()); assert.equal('foo bar hop\n', strings.shift()); assert.equal("{ slashes: '\\\\\\\\' }\n", strings.shift()); assert.equal('Trace: This is a {"formatted":"trace"} 10 foo', strings.shift().split('\n').shift()); assert.throws(function () { console.timeEnd('no such label'); }); assert.doesNotThrow(function () { console.time('label'); console.timeEnd('label'); }); node-v0.10.25~dfsg2/test/simple/test-cluster-dgram-1.js0000644000000000000000000000633212270121457021313 0ustar rootroot// Copyright Joyent, Inc. and other Node contributors. // // Permission is hereby granted, free of charge, to any person obtaining a // copy of this software and associated documentation files (the // "Software"), to deal in the Software without restriction, including // without limitation the rights to use, copy, modify, merge, publish, // distribute, sublicense, and/or sell copies of the Software, and to permit // persons to whom the Software is furnished to do so, subject to the // following conditions: // // The above copyright notice and this permission notice shall be included // in all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS // OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF // MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN // NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, // DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR // OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE // USE OR OTHER DEALINGS IN THE SOFTWARE. var NUM_WORKERS = 4; var PACKETS_PER_WORKER = 10; var assert = require('assert'); var cluster = require('cluster'); var common = require('../common'); var dgram = require('dgram'); if (process.platform === 'win32') { console.warn("dgram clustering is currently not supported on windows."); process.exit(0); } if (cluster.isMaster) master(); else worker(); function master() { var listening = 0; // Fork 4 workers. for (var i = 0; i < NUM_WORKERS; i++) cluster.fork(); // Wait until all workers are listening. cluster.on('listening', function() { if (++listening < NUM_WORKERS) return; // Start sending messages. var buf = new Buffer('hello world'); var socket = dgram.createSocket('udp4'); var sent = 0; doSend(); function doSend() { socket.send(buf, 0, buf.length, common.PORT, '127.0.0.1', afterSend); } function afterSend() { sent++; if (sent < NUM_WORKERS * PACKETS_PER_WORKER) { doSend(); } else { console.log('master sent %d packets', sent); socket.close(); } } }); // Set up event handlers for every worker. Each worker sends a message when // it has received the expected number of packets. After that it disconnects. for (var key in cluster.workers) { if (cluster.workers.hasOwnProperty(key)) setupWorker(cluster.workers[key]); } function setupWorker(worker) { var received = 0; worker.on('message', function(msg) { received = msg.received; console.log('worker %d received %d packets', worker.id, received); }); worker.on('disconnect', function() { assert(received === PACKETS_PER_WORKER); console.log('worker %d disconnected', worker.id); }); } } function worker() { var received = 0; // Create udp socket and start listening. var socket = dgram.createSocket('udp4'); socket.on('message', function(data, info) { received++; // Every 10 messages, notify the master. if (received == PACKETS_PER_WORKER) { process.send({received: received}); process.disconnect(); } }); socket.bind(common.PORT); } node-v0.10.25~dfsg2/test/simple/test-dgram-udp4.js0000644000000000000000000000571712270121457020356 0ustar rootroot// Copyright Joyent, Inc. and other Node contributors. // // Permission is hereby granted, free of charge, to any person obtaining a // copy of this software and associated documentation files (the // "Software"), to deal in the Software without restriction, including // without limitation the rights to use, copy, modify, merge, publish, // distribute, sublicense, and/or sell copies of the Software, and to permit // persons to whom the Software is furnished to do so, subject to the // following conditions: // // The above copyright notice and this permission notice shall be included // in all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS // OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF // MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN // NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, // DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR // OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE // USE OR OTHER DEALINGS IN THE SOFTWARE. var common = require('../common'); var assert = require('assert'); var Buffer = require('buffer').Buffer, fs = require('fs'), dgram = require('dgram'), server, client, server_port = 20989, message_to_send = new Buffer('A message to send'), timer; server = dgram.createSocket('udp4'); server.on('message', function(msg, rinfo) { console.log('server got: ' + msg + ' from ' + rinfo.address + ':' + rinfo.port); assert.strictEqual(rinfo.address, '127.0.0.1'); assert.strictEqual(msg.toString(), message_to_send.toString()); server.send(msg, 0, msg.length, rinfo.port, rinfo.address); }); server.on('listening', function() { var address = server.address(); console.log('server is listening on ' + address.address + ':' + address.port); client = dgram.createSocket('udp4'); client.on('message', function(msg, rinfo) { console.log('client got: ' + msg + ' from ' + rinfo.address + ':' + address.port); assert.strictEqual(rinfo.address, '127.0.0.1'); assert.strictEqual(rinfo.port, server_port); assert.strictEqual(msg.toString(), message_to_send.toString()); client.close(); server.close(); }); client.send(message_to_send, 0, message_to_send.length, server_port, 'localhost', function(err, bytes) { if (err) { console.log('Caught error in client send.'); throw err; } console.log('client wrote ' + bytes + ' bytes.'); assert.strictEqual(bytes, message_to_send.length); }); client.on('close', function() { if (server.fd === null) { clearTimeout(timer); } }); }); server.on('close', function() { if (client.fd === null) { clearTimeout(timer); } }); server.bind(server_port); timer = setTimeout(function() { throw new Error('Timeout'); }, 200); node-v0.10.25~dfsg2/test/simple/test-tls-timeout-server.js0000644000000000000000000000350712270121457022177 0ustar rootroot// Copyright Joyent, Inc. and other Node contributors. // // Permission is hereby granted, free of charge, to any person obtaining a // copy of this software and associated documentation files (the // "Software"), to deal in the Software without restriction, including // without limitation the rights to use, copy, modify, merge, publish, // distribute, sublicense, and/or sell copies of the Software, and to permit // persons to whom the Software is furnished to do so, subject to the // following conditions: // // The above copyright notice and this permission notice shall be included // in all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS // OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF // MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN // NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, // DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR // OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE // USE OR OTHER DEALINGS IN THE SOFTWARE. if (!process.versions.openssl) process.exit(); var common = require('../common'); var assert = require('assert'); var net = require('net'); var tls = require('tls'); var fs = require('fs'); var clientErrors = 0; process.on('exit', function() { assert.equal(clientErrors, 1); }); var options = { key: fs.readFileSync(common.fixturesDir + '/keys/agent1-key.pem'), cert: fs.readFileSync(common.fixturesDir + '/keys/agent1-cert.pem'), handshakeTimeout: 50 }; var server = tls.createServer(options, assert.fail); server.on('clientError', function(err, conn) { conn.destroy(); server.close(); clientErrors++; }); server.listen(common.PORT, function() { net.connect({ host: '127.0.0.1', port: common.PORT }); }); node-v0.10.25~dfsg2/test/simple/test-http.js0000644000000000000000000000650312270121457017363 0ustar rootroot// Copyright Joyent, Inc. and other Node contributors. // // Permission is hereby granted, free of charge, to any person obtaining a // copy of this software and associated documentation files (the // "Software"), to deal in the Software without restriction, including // without limitation the rights to use, copy, modify, merge, publish, // distribute, sublicense, and/or sell copies of the Software, and to permit // persons to whom the Software is furnished to do so, subject to the // following conditions: // // The above copyright notice and this permission notice shall be included // in all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS // OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF // MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN // NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, // DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR // OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE // USE OR OTHER DEALINGS IN THE SOFTWARE. var common = require('../common'); var assert = require('assert'); var http = require('http'); var url = require('url'); function p(x) { common.error(common.inspect(x)); } var responses_sent = 0; var responses_recvd = 0; var body0 = ''; var body1 = ''; var server = http.Server(function(req, res) { if (responses_sent == 0) { assert.equal('GET', req.method); assert.equal('/hello', url.parse(req.url).pathname); console.dir(req.headers); assert.equal(true, 'accept' in req.headers); assert.equal('*/*', req.headers['accept']); assert.equal(true, 'foo' in req.headers); assert.equal('bar', req.headers['foo']); } if (responses_sent == 1) { assert.equal('POST', req.method); assert.equal('/world', url.parse(req.url).pathname); this.close(); } req.on('end', function() { res.writeHead(200, {'Content-Type': 'text/plain'}); res.write('The path was ' + url.parse(req.url).pathname); res.end(); responses_sent += 1; }); req.resume(); //assert.equal('127.0.0.1', res.connection.remoteAddress); }); server.listen(common.PORT); server.on('listening', function() { var agent = new http.Agent({ port: common.PORT, maxSockets: 1 }); http.get({ port: common.PORT, path: '/hello', headers: {'Accept': '*/*', 'Foo': 'bar'}, agent: agent }, function(res) { assert.equal(200, res.statusCode); responses_recvd += 1; res.setEncoding('utf8'); res.on('data', function(chunk) { body0 += chunk; }); common.debug('Got /hello response'); }); setTimeout(function() { var req = http.request({ port: common.PORT, method: 'POST', path: '/world', agent: agent }, function(res) { assert.equal(200, res.statusCode); responses_recvd += 1; res.setEncoding('utf8'); res.on('data', function(chunk) { body1 += chunk; }); common.debug('Got /world response'); }); req.end(); }, 1); }); process.on('exit', function() { common.debug('responses_recvd: ' + responses_recvd); assert.equal(2, responses_recvd); common.debug('responses_sent: ' + responses_sent); assert.equal(2, responses_sent); assert.equal('The path was /hello', body0); assert.equal('The path was /world', body1); }); node-v0.10.25~dfsg2/test/simple/test-http-client-pipe-end.js0000644000000000000000000000352212270121457022334 0ustar rootroot// Copyright Joyent, Inc. and other Node contributors. // // Permission is hereby granted, free of charge, to any person obtaining a // copy of this software and associated documentation files (the // "Software"), to deal in the Software without restriction, including // without limitation the rights to use, copy, modify, merge, publish, // distribute, sublicense, and/or sell copies of the Software, and to permit // persons to whom the Software is furnished to do so, subject to the // following conditions: // // The above copyright notice and this permission notice shall be included // in all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS // OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF // MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN // NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, // DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR // OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE // USE OR OTHER DEALINGS IN THE SOFTWARE. // see https://github.com/joyent/node/issues/3257 var common = require('../common'); var assert = require('assert'); var http = require('http'); var server = http.createServer(function(req, res) { req.resume(); req.once('end', function() { res.writeHead(200); res.end(); server.close(); }); }); server.listen(common.PIPE, function() { var req = http.request({ socketPath: common.PIPE, headers: {'Content-Length':'1'}, method: 'POST', path: '/' }); req.write('.'); sched(function() { req.end() }, 5); }); // schedule a callback after `ticks` event loop ticks function sched(cb, ticks) { function fn() { if (--ticks) setImmediate(fn); else cb(); } setImmediate(fn); } node-v0.10.25~dfsg2/test/simple/test-http-client-race-2.js0000644000000000000000000000733112270121457021706 0ustar rootroot// Copyright Joyent, Inc. and other Node contributors. // // Permission is hereby granted, free of charge, to any person obtaining a // copy of this software and associated documentation files (the // "Software"), to deal in the Software without restriction, including // without limitation the rights to use, copy, modify, merge, publish, // distribute, sublicense, and/or sell copies of the Software, and to permit // persons to whom the Software is furnished to do so, subject to the // following conditions: // // The above copyright notice and this permission notice shall be included // in all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS // OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF // MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN // NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, // DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR // OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE // USE OR OTHER DEALINGS IN THE SOFTWARE. var common = require('../common'); var assert = require('assert'); var http = require('http'); var url = require('url'); // // Slight variation on test-http-client-race to test for another race // condition involving the parsers FreeList used internally by http.Client. // var body1_s = '1111111111111111'; var body2_s = '22222'; var body3_s = '3333333333333333333'; var server = http.createServer(function(req, res) { var pathname = url.parse(req.url).pathname; var body; switch (pathname) { case '/1': body = body1_s; break; case '/2': body = body2_s; break; default: body = body3_s; } res.writeHead(200, {'Content-Type': 'text/plain', 'Content-Length': body.length}); res.end(body); }); server.listen(common.PORT); var body1 = ''; var body2 = ''; var body3 = ''; server.on('listening', function() { var client = http.createClient(common.PORT); // // Client #1 is assigned Parser #1 // var req1 = client.request('/1'); req1.end(); req1.on('response', function(res1) { res1.setEncoding('utf8'); res1.on('data', function(chunk) { body1 += chunk; }); res1.on('end', function() { // // Delay execution a little to allow the 'close' event to be processed // (required to trigger this bug!) // setTimeout(function() { // // The bug would introduce itself here: Client #2 would be allocated the // parser that previously belonged to Client #1. But we're not finished // with Client #1 yet! // var client2 = http.createClient(common.PORT); // // At this point, the bug would manifest itself and crash because the // internal state of the parser was no longer valid for use by Client #1 // var req2 = client.request('/2'); req2.end(); req2.on('response', function(res2) { res2.setEncoding('utf8'); res2.on('data', function(chunk) { body2 += chunk; }); res2.on('end', function() { // // Just to be really sure we've covered all our bases, execute a // request using client2. // var req3 = client2.request('/3'); req3.end(); req3.on('response', function(res3) { res3.setEncoding('utf8'); res3.on('data', function(chunk) { body3 += chunk }); res3.on('end', function() { server.close(); }); }); }); }); }, 500); }); }); }); process.on('exit', function() { assert.equal(body1_s, body1); assert.equal(body2_s, body2); assert.equal(body3_s, body3); }); node-v0.10.25~dfsg2/test/simple/test-stdin-child-proc.js0000644000000000000000000000274412270121457021552 0ustar rootroot// Copyright Joyent, Inc. and other Node contributors. // // Permission is hereby granted, free of charge, to any person obtaining a // copy of this software and associated documentation files (the // "Software"), to deal in the Software without restriction, including // without limitation the rights to use, copy, modify, merge, publish, // distribute, sublicense, and/or sell copies of the Software, and to permit // persons to whom the Software is furnished to do so, subject to the // following conditions: // // The above copyright notice and this permission notice shall be included // in all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS // OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF // MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN // NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, // DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR // OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE // USE OR OTHER DEALINGS IN THE SOFTWARE. // This tests that pausing and resuming stdin does not hang and timeout // when done in a child process. See test/simple/test-stdin-pause-resume.js var common = require('../common'); var child_process = require('child_process'); var path = require('path'); child_process.spawn(process.execPath, [path.resolve(__dirname, 'test-stdin-pause-resume.js')]); node-v0.10.25~dfsg2/test/simple/test-http-pipe-fs.js0000644000000000000000000000431412270121457020722 0ustar rootroot// Copyright Joyent, Inc. and other Node contributors. // // Permission is hereby granted, free of charge, to any person obtaining a // copy of this software and associated documentation files (the // "Software"), to deal in the Software without restriction, including // without limitation the rights to use, copy, modify, merge, publish, // distribute, sublicense, and/or sell copies of the Software, and to permit // persons to whom the Software is furnished to do so, subject to the // following conditions: // // The above copyright notice and this permission notice shall be included // in all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS // OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF // MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN // NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, // DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR // OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE // USE OR OTHER DEALINGS IN THE SOFTWARE. var common = require('../common'); var assert = require('assert'); var http = require('http'); var fs = require('fs'); var path = require('path'); var file = path.join(common.tmpDir, 'http-pipe-fs-test.txt'); var requests = 0; var server = http.createServer(function(req, res) { ++requests; var stream = fs.createWriteStream(file); req.pipe(stream); stream.on('close', function() { res.writeHead(200); res.end(); }); }).listen(common.PORT, function() { http.globalAgent.maxSockets = 1; for (var i = 0; i < 2; ++i) { (function(i) { var req = http.request({ port: common.PORT, method: 'POST', headers: { 'Content-Length': 5 } }, function(res) { res.on('end', function() { common.debug('res' + i + ' end'); if (i === 2) { server.close(); } }); res.resume(); }); req.on('socket', function(s) { common.debug('req' + i + ' start'); }); req.end('12345'); }(i + 1)); } }); process.on('exit', function() { assert.equal(requests, 2); }); node-v0.10.25~dfsg2/test/simple/test-util.js0000644000000000000000000000704212270121457017360 0ustar rootroot// Copyright Joyent, Inc. and other Node contributors. // // Permission is hereby granted, free of charge, to any person obtaining a // copy of this software and associated documentation files (the // "Software"), to deal in the Software without restriction, including // without limitation the rights to use, copy, modify, merge, publish, // distribute, sublicense, and/or sell copies of the Software, and to permit // persons to whom the Software is furnished to do so, subject to the // following conditions: // // The above copyright notice and this permission notice shall be included // in all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS // OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF // MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN // NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, // DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR // OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE // USE OR OTHER DEALINGS IN THE SOFTWARE. var common = require('../common'); var assert = require('assert'); var util = require('util'); var context = require('vm').runInNewContext; // isArray assert.equal(true, util.isArray([])); assert.equal(true, util.isArray(Array())); assert.equal(true, util.isArray(new Array())); assert.equal(true, util.isArray(new Array(5))); assert.equal(true, util.isArray(new Array('with', 'some', 'entries'))); assert.equal(true, util.isArray(context('Array')())); assert.equal(false, util.isArray({})); assert.equal(false, util.isArray({ push: function() {} })); assert.equal(false, util.isArray(/regexp/)); assert.equal(false, util.isArray(new Error)); assert.equal(false, util.isArray(Object.create(Array.prototype))); // isRegExp assert.equal(true, util.isRegExp(/regexp/)); assert.equal(true, util.isRegExp(RegExp())); assert.equal(true, util.isRegExp(new RegExp())); assert.equal(true, util.isRegExp(context('RegExp')())); assert.equal(false, util.isRegExp({})); assert.equal(false, util.isRegExp([])); assert.equal(false, util.isRegExp(new Date())); assert.equal(false, util.isRegExp(Object.create(RegExp.prototype))); // isDate assert.equal(true, util.isDate(new Date())); assert.equal(true, util.isDate(new Date(0))); assert.equal(true, util.isDate(new (context('Date')))); assert.equal(false, util.isDate(Date())); assert.equal(false, util.isDate({})); assert.equal(false, util.isDate([])); assert.equal(false, util.isDate(new Error)); assert.equal(false, util.isDate(Object.create(Date.prototype))); // isError assert.equal(true, util.isError(new Error)); assert.equal(true, util.isError(new TypeError)); assert.equal(true, util.isError(new SyntaxError)); assert.equal(true, util.isError(new (context('Error')))); assert.equal(true, util.isError(new (context('TypeError')))); assert.equal(true, util.isError(new (context('SyntaxError')))); assert.equal(false, util.isError({})); assert.equal(false, util.isError({ name: 'Error', message: '' })); assert.equal(false, util.isError([])); assert.equal(false, util.isError(Object.create(Error.prototype))); // _extend assert.deepEqual(util._extend({a:1}), {a:1}); assert.deepEqual(util._extend({a:1}, []), {a:1}); assert.deepEqual(util._extend({a:1}, null), {a:1}); assert.deepEqual(util._extend({a:1}, true), {a:1}); assert.deepEqual(util._extend({a:1}, false), {a:1}); assert.deepEqual(util._extend({a:1}, {b:2}), {a:1, b:2}); assert.deepEqual(util._extend({a:1, b:2}, {b:3}), {a:1, b:3}); node-v0.10.25~dfsg2/test/simple/test-stdout-close-catch.js0000644000000000000000000000372712270121457022116 0ustar rootroot// Copyright Joyent, Inc. and other Node contributors. // // Permission is hereby granted, free of charge, to any person obtaining a // copy of this software and associated documentation files (the // "Software"), to deal in the Software without restriction, including // without limitation the rights to use, copy, modify, merge, publish, // distribute, sublicense, and/or sell copies of the Software, and to permit // persons to whom the Software is furnished to do so, subject to the // following conditions: // // The above copyright notice and this permission notice shall be included // in all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS // OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF // MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN // NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, // DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR // OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE // USE OR OTHER DEALINGS IN THE SOFTWARE. var common = require('../common'); var assert = require('assert'); var path = require('path'); var child_process = require('child_process'); var fs = require('fs'); var testScript = path.join(common.fixturesDir, 'catch-stdout-error.js'); var cmd = JSON.stringify(process.execPath) + ' ' + JSON.stringify(testScript) + ' | ' + JSON.stringify(process.execPath) + ' ' + '-pe "process.exit(1);"'; var child = child_process.exec(cmd); var output = ''; var outputExpect = { 'code': 'EPIPE', 'errno': 'EPIPE', 'syscall': 'write' }; child.stderr.on('data', function(c) { output += c; }); child.on('close', function(code) { try { output = JSON.parse(output); } catch (er) { console.error(output); process.exit(1); } assert.deepEqual(output, outputExpect); console.log('ok'); }); node-v0.10.25~dfsg2/test/simple/test-http-url.parse-auth-with-header-in-request.js0000644000000000000000000000364512270121457026530 0ustar rootroot// Copyright Joyent, Inc. and other Node contributors. // // Permission is hereby granted, free of charge, to any person obtaining a // copy of this software and associated documentation files (the // "Software"), to deal in the Software without restriction, including // without limitation the rights to use, copy, modify, merge, publish, // distribute, sublicense, and/or sell copies of the Software, and to permit // persons to whom the Software is furnished to do so, subject to the // following conditions: // // The above copyright notice and this permission notice shall be included // in all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS // OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF // MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN // NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, // DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR // OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE // USE OR OTHER DEALINGS IN THE SOFTWARE. var common = require('../common'); var assert = require('assert'); var http = require('http'); var url = require('url'); var testURL = url.parse('http://asdf:qwer@localhost:' + common.PORT); // the test here is if you set a specific authorization header in the // request we should not override that with basic auth testURL.headers = { Authorization: 'NoAuthForYOU' }; function check(request) { // the correct authorization header is be passed assert.strictEqual(request.headers.authorization, 'NoAuthForYOU'); } var server = http.createServer(function(request, response) { // run the check function check.call(this, request, response); response.writeHead(200, {}); response.end('ok'); server.close(); }); server.listen(common.PORT, function() { // make the request http.request(testURL).end(); }); node-v0.10.25~dfsg2/test/simple/test-tls-client-abort.js0000644000000000000000000000337012270121457021566 0ustar rootroot// Copyright Joyent, Inc. and other Node contributors. // // Permission is hereby granted, free of charge, to any person obtaining a // copy of this software and associated documentation files (the // "Software"), to deal in the Software without restriction, including // without limitation the rights to use, copy, modify, merge, publish, // distribute, sublicense, and/or sell copies of the Software, and to permit // persons to whom the Software is furnished to do so, subject to the // following conditions: // // The above copyright notice and this permission notice shall be included // in all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS // OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF // MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN // NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, // DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR // OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE // USE OR OTHER DEALINGS IN THE SOFTWARE. if (!process.versions.openssl) { console.error('Skipping because node compiled without OpenSSL.'); process.exit(0); } var common = require('../common'); var assert = require('assert'); var fs = require('fs'); var tls = require('tls'); var path = require('path'); var cert = fs.readFileSync(path.join(common.fixturesDir, 'test_cert.pem')); var key = fs.readFileSync(path.join(common.fixturesDir, 'test_key.pem')); var conn = tls.connect({cert: cert, key: key, port: common.PORT}, function() { assert.ok(false); // callback should never be executed }); conn.on('error', function() { }); assert.doesNotThrow(function() { conn.destroy(); }); node-v0.10.25~dfsg2/test/simple/test-net-connect-options.js0000644000000000000000000000401012270121457022301 0ustar rootroot// Copyright Joyent, Inc. and other Node contributors. // // Permission is hereby granted, free of charge, to any person obtaining a // copy of this software and associated documentation files (the // "Software"), to deal in the Software without restriction, including // without limitation the rights to use, copy, modify, merge, publish, // distribute, sublicense, and/or sell copies of the Software, and to permit // persons to whom the Software is furnished to do so, subject to the // following conditions: // // The above copyright notice and this permission notice shall be included // in all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS // OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF // MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN // NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, // DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR // OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE // USE OR OTHER DEALINGS IN THE SOFTWARE. var common = require('../common'); var assert = require('assert'); var net = require('net'); var serverGotEnd = false; var clientGotEnd = false; var server = net.createServer({allowHalfOpen: true}, function(socket) { socket.resume(); socket.on('end', function() { serverGotEnd = true; }); socket.end(); }); server.listen(common.PORT, function() { var client = net.connect({ host: '127.0.0.1', port: common.PORT, allowHalfOpen: true }, function() { console.error('client connect cb'); client.resume(); client.on('end', function() { clientGotEnd = true; setTimeout(function() { assert(client.writable); client.end(); }, 10); }); client.on('close', function() { server.close(); }); }); }); process.on('exit', function() { console.error('exit', serverGotEnd, clientGotEnd); assert(serverGotEnd); assert(clientGotEnd); }); node-v0.10.25~dfsg2/test/simple/test-cluster-dgram-2.js0000644000000000000000000000466412270121457021322 0ustar rootroot// Copyright Joyent, Inc. and other Node contributors. // // Permission is hereby granted, free of charge, to any person obtaining a // copy of this software and associated documentation files (the // "Software"), to deal in the Software without restriction, including // without limitation the rights to use, copy, modify, merge, publish, // distribute, sublicense, and/or sell copies of the Software, and to permit // persons to whom the Software is furnished to do so, subject to the // following condonitions: // // The above copyright notice and this permission notice shall be included // in all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS // OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF // MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN // NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, // DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR // OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE // USE OR OTHER DEALINGS IN THE SOFTWARE. var NUM_WORKERS = 4; var PACKETS_PER_WORKER = 10; var assert = require('assert'); var cluster = require('cluster'); var common = require('../common'); var dgram = require('dgram'); if (process.platform === 'win32') { console.warn("dgram clustering is currently not supported on windows."); process.exit(0); } if (cluster.isMaster) master(); else worker(); function master() { var i; var received = 0; // Start listening on a socket. var socket = dgram.createSocket('udp4'); socket.bind(common.PORT); // Disconnect workers when the expected number of messages have been // received. socket.on('message', function(data, info) { received++; if (received == PACKETS_PER_WORKER * NUM_WORKERS) { console.log('master received %d packets', received); // Close the socket. socket.close(); // Disconnect all workers. cluster.disconnect(); } }); // Fork workers. for (var i = 0; i < NUM_WORKERS; i++) cluster.fork(); } function worker() { // Create udp socket and send packets to master. var socket = dgram.createSocket('udp4'); var buf = new Buffer('hello world'); for (var i = 0; i < PACKETS_PER_WORKER; i++) socket.send(buf, 0, buf.length, common.PORT, '127.0.0.1'); console.log('worker %d sent %d packets', cluster.worker.id, PACKETS_PER_WORKER); } node-v0.10.25~dfsg2/test/simple/test-http-parser-bad-ref.js0000644000000000000000000000333612270121457022154 0ustar rootroot// Run this program with valgrind or efence with --expose_gc to expose the // problem. // Flags: --expose_gc var common = require('../common'); var assert = require('assert'); var HTTPParser = process.binding('http_parser').HTTPParser; var headersComplete = 0; var messagesComplete = 0; function flushPool() { new Buffer(Buffer.poolSize - 1); gc(); } function demoBug(part1, part2) { flushPool(); var parser = new HTTPParser('REQUEST'); parser.headers = []; parser.url = ''; parser.onHeaders = function(headers, url) { parser.headers = parser.headers.concat(headers); parser.url += url; }; parser.onHeadersComplete = function(info) { headersComplete++; console.log('url', info.url); }; parser.onBody = function(b, start, len) { }; parser.onMessageComplete = function() { messagesComplete++; }; // We use a function to eliminate references to the Buffer b // We want b to be GCed. The parser will hold a bad reference to it. (function() { var b = Buffer(part1); flushPool(); console.log('parse the first part of the message'); parser.execute(b, 0, b.length); })(); flushPool(); (function() { var b = Buffer(part2); console.log('parse the second part of the message'); parser.execute(b, 0, b.length); parser.finish(); })(); flushPool(); } demoBug('POST /1', '/22 HTTP/1.1\r\n' + 'Content-Type: text/plain\r\n' + 'Content-Length: 4\r\n\r\n' + 'pong'); demoBug('POST /1/22 HTTP/1.1\r\n' + 'Content-Type: tex', 't/plain\r\n' + 'Content-Length: 4\r\n\r\n' + 'pong'); process.on('exit', function() { assert.equal(2, headersComplete); assert.equal(2, messagesComplete); console.log('done!'); }); node-v0.10.25~dfsg2/test/simple/test-net-socket-timeout.js0000644000000000000000000000314212270121457022140 0ustar rootroot// Copyright Joyent, Inc. and other Node contributors. // // Permission is hereby granted, free of charge, to any person obtaining a // copy of this software and associated documentation files (the // "Software"), to deal in the Software without restriction, including // without limitation the rights to use, copy, modify, merge, publish, // distribute, sublicense, and/or sell copies of the Software, and to permit // persons to whom the Software is furnished to do so, subject to the // following conditions: // // The above copyright notice and this permission notice shall be included // in all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS // OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF // MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN // NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, // DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR // OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE // USE OR OTHER DEALINGS IN THE SOFTWARE. var common = require('../common'); var net = require('net'); var assert = require('assert'); var timedout = false; var server = net.Server(); server.listen(common.PORT, function() { var socket = net.createConnection(common.PORT); socket.setTimeout(100, function() { timedout = true; socket.destroy(); server.close(); clearTimeout(timer); }); var timer = setTimeout(function() { process.exit(1); }, 200); }); process.on('exit', function() { assert.ok(timedout); }); node-v0.10.25~dfsg2/test/simple/test-regress-GH-3739.js0000644000000000000000000000367112270121457020760 0ustar rootroot// Copyright Joyent, Inc. and other Node contributors. // // Permission is hereby granted, free of charge, to any person obtaining a // copy of this software and associated documentation files (the // "Software"), to deal in the Software without restriction, including // without limitation the rights to use, copy, modify, merge, publish, // distribute, sublicense, and/or sell copies of the Software, and to permit // persons to whom the Software is furnished to do so, subject to the // following conditions: // // The above copyright notice and this permission notice shall be included // in all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS // OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF // MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN // NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, // DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR // OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE // USE OR OTHER DEALINGS IN THE SOFTWARE. var common = require('../common.js'), assert = require('assert'), fs = require('fs'), path = require('path'); var dir = path.resolve(common.fixturesDir), dirs = []; // Make a long path. for (var i = 0; i < 50; i++) { dir = dir + '/123456790'; try { fs.mkdirSync(dir, '0777'); } catch (e) { if (e.code == 'EEXIST') { // Ignore; } else { cleanup(); throw e; } } dirs.push(dir); } // Test existsSync var r = fs.existsSync(dir); if (r !== true) { cleanup(); throw new Error('fs.existsSync returned false'); } // Text exists fs.exists(dir, function(r) { cleanup(); if (r !== true) { throw new Error('fs.exists reported false'); } }); // Remove all created directories function cleanup() { for (var i = dirs.length - 1; i >= 0; i--) { fs.rmdirSync(dirs[i]); } } node-v0.10.25~dfsg2/test/simple/test-stream2-read-sync-stack.js0000644000000000000000000000350012270121457022741 0ustar rootroot// Copyright Joyent, Inc. and other Node contributors. // // Permission is hereby granted, free of charge, to any person obtaining a // copy of this software and associated documentation files (the // "Software"), to deal in the Software without restriction, including // without limitation the rights to use, copy, modify, merge, publish, // distribute, sublicense, and/or sell copies of the Software, and to permit // persons to whom the Software is furnished to do so, subject to the // following conditions: // // The above copyright notice and this permission notice shall be included // in all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS // OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF // MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN // NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, // DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR // OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE // USE OR OTHER DEALINGS IN THE SOFTWARE. var common = require('../common'); var assert = require('assert'); var Readable = require('stream').Readable; var r = new Readable(); var N = 256 * 1024; // Go ahead and allow the pathological case for this test. // Yes, it's an infinite loop, that's the point. process.maxTickDepth = N + 2; var reads = 0; r._read = function(n) { var chunk = reads++ === N ? null : new Buffer(1); r.push(chunk); }; r.on('readable', function onReadable() { if (!(r._readableState.length % 256)) console.error('readable', r._readableState.length); r.read(N * 2); }); var ended = false; r.on('end', function onEnd() { ended = true; }); r.read(0); process.on('exit', function() { assert(ended); console.log('ok'); }); node-v0.10.25~dfsg2/test/simple/test-timers-ordering.js0000644000000000000000000000332612270121457021516 0ustar rootroot// Copyright Joyent, Inc. and other Node contributors. // // Permission is hereby granted, free of charge, to any person obtaining a // copy of this software and associated documentation files (the // "Software"), to deal in the Software without restriction, including // without limitation the rights to use, copy, modify, merge, publish, // distribute, sublicense, and/or sell copies of the Software, and to permit // persons to whom the Software is furnished to do so, subject to the // following conditions: // // The above copyright notice and this permission notice shall be included // in all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS // OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF // MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN // NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, // DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR // OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE // USE OR OTHER DEALINGS IN THE SOFTWARE. var common = require('../common'); var assert = require('assert'); var i; var N = 30; var last_i = 0; var last_ts = 0; var start = Date.now(); var f = function(i) { if (i <= N) { // check order assert.equal(i, last_i + 1, 'order is broken: ' + i + ' != ' + last_i + ' + 1'); last_i = i; // check that this iteration is fired at least 1ms later than the previous var now = Date.now(); console.log(i, now); assert(now >= last_ts + 1, 'current ts ' + now + ' < prev ts ' + last_ts + ' + 1'); last_ts = now; // schedule next iteration setTimeout(f, 1, i + 1); } }; f(1); node-v0.10.25~dfsg2/test/simple/test-dh-padding.js0000644000000000000000000000365712270121457020412 0ustar rootroot// Copyright Joyent, Inc. and other Node contributors. // // Permission is hereby granted, free of charge, to any person obtaining a // copy of this software and associated documentation files (the // "Software"), to deal in the Software without restriction, including // without limitation the rights to use, copy, modify, merge, publish, // distribute, sublicense, and/or sell copies of the Software, and to permit // persons to whom the Software is furnished to do so, subject to the // following conditions: // // The above copyright notice and this permission notice shall be included // in all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS // OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF // MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN // NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, // DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR // OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE // USE OR OTHER DEALINGS IN THE SOFTWARE. var common = require('../common'); var assert = require('assert'); try { var crypto = require('crypto'); } catch (e) { console.log('Not compiled with OPENSSL support.'); process.exit(); } var prime = 'c51f7bf8f0e1cf899243cdf408b1bc7c09c010e33ef7f3fbe5bd5feaf906113b'; var apub = '6fe9f37037d8d017f908378c1ee04fe60e1cd3668bfc5075fac55c2f7153dd84'; var bpub = '31d83e167fdf956c9dae6b980140577a9f8868acbfcbdc19113e58bfb9223abc'; var apriv = '4fbfd4661f9181bbf574537b1a78adf473e8e771eef13c605e963c0f3094b697'; var secret = '25616eed33f1af7975bbd0a8071d98a014f538b243bef90d76c08e81a0b3c500'; var p = crypto.createDiffieHellman(prime, 'hex'); p.setPublicKey(apub, 'hex'); p.setPrivateKey(apriv, 'hex'); assert.equal( p.computeSecret(bpub, 'hex', 'hex'), '0025616eed33f1af7975bbd0a8071d98a014f538b243bef90d76c08e81a0b3c5' ); node-v0.10.25~dfsg2/test/simple/test-http-full-response.js0000644000000000000000000000540412270121457022156 0ustar rootroot// Copyright Joyent, Inc. and other Node contributors. // // Permission is hereby granted, free of charge, to any person obtaining a // copy of this software and associated documentation files (the // "Software"), to deal in the Software without restriction, including // without limitation the rights to use, copy, modify, merge, publish, // distribute, sublicense, and/or sell copies of the Software, and to permit // persons to whom the Software is furnished to do so, subject to the // following conditions: // // The above copyright notice and this permission notice shall be included // in all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS // OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF // MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN // NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, // DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR // OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE // USE OR OTHER DEALINGS IN THE SOFTWARE. var common = require('../common'); var assert = require('assert'); // This test requires the program 'ab' var http = require('http'); var exec = require('child_process').exec; var bodyLength = 12345; var body = ''; for (var i = 0; i < bodyLength; i++) { body += 'c'; } var server = http.createServer(function(req, res) { res.writeHead(200, { 'Content-Length': bodyLength, 'Content-Type': 'text/plain' }); res.end(body); }); var runs = 0; function runAb(opts, callback) { var command = 'ab ' + opts + ' http://127.0.0.1:' + common.PORT + '/'; exec(command, function(err, stdout, stderr) { if (err) { if (/ab|apr/mi.test(stderr)) { console.log('problem spawning ab - skipping test.\n' + stderr); process.reallyExit(0); } process.exit(); return; } var m = /Document Length:\s*(\d+) bytes/mi.exec(stdout); var documentLength = parseInt(m[1]); var m = /Complete requests:\s*(\d+)/mi.exec(stdout); var completeRequests = parseInt(m[1]); var m = /HTML transferred:\s*(\d+) bytes/mi.exec(stdout); var htmlTransfered = parseInt(m[1]); assert.equal(bodyLength, documentLength); assert.equal(completeRequests * documentLength, htmlTransfered); runs++; if (callback) callback(); }); } server.listen(common.PORT, function() { runAb('-c 1 -n 10', function() { console.log('-c 1 -n 10 okay'); runAb('-c 1 -n 100', function() { console.log('-c 1 -n 100 okay'); runAb('-c 1 -n 1000', function() { console.log('-c 1 -n 1000 okay'); server.close(); }); }); }); }); process.on('exit', function() { assert.equal(3, runs); }); node-v0.10.25~dfsg2/test/simple/test-readdir.js0000644000000000000000000000466012270121457020020 0ustar rootroot// Copyright Joyent, Inc. and other Node contributors. // // Permission is hereby granted, free of charge, to any person obtaining a // copy of this software and associated documentation files (the // "Software"), to deal in the Software without restriction, including // without limitation the rights to use, copy, modify, merge, publish, // distribute, sublicense, and/or sell copies of the Software, and to permit // persons to whom the Software is furnished to do so, subject to the // following conditions: // // The above copyright notice and this permission notice shall be included // in all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS // OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF // MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN // NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, // DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR // OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE // USE OR OTHER DEALINGS IN THE SOFTWARE. var common = require('../common'); var assert = require('assert'); var path = require('path'); var fs = require('fs'); var got_error = false, readdirDir = path.join(common.fixturesDir, 'readdir'); var files = ['are', 'dir', 'empty', 'files', 'for', 'just', 'testing.js', 'these']; console.log('readdirSync ' + readdirDir); var f = fs.readdirSync(readdirDir); console.dir(f); assert.deepEqual(files, f.sort()); console.log('readdir ' + readdirDir); fs.readdir(readdirDir, function(err, f) { if (err) { console.log('error'); got_error = true; } else { console.dir(f); assert.deepEqual(files, f.sort()); } }); process.on('exit', function() { assert.equal(false, got_error); console.log('exit'); }); // readdir() on file should throw ENOTDIR // https://github.com/joyent/node/issues/1869 (function() { var has_caught = false; try { fs.readdirSync(__filename); } catch (e) { has_caught = true; assert.equal(e.code, 'ENOTDIR'); } assert(has_caught); })(); (function() { var readdir_cb_called = false; fs.readdir(__filename, function(e) { readdir_cb_called = true; assert.equal(e.code, 'ENOTDIR'); }); process.on('exit', function() { assert(readdir_cb_called); }); })(); node-v0.10.25~dfsg2/test/simple/test-http-curl-chunk-problem.js0000644000000000000000000000535212270121457023073 0ustar rootroot// Copyright Joyent, Inc. and other Node contributors. // // Permission is hereby granted, free of charge, to any person obtaining a // copy of this software and associated documentation files (the // "Software"), to deal in the Software without restriction, including // without limitation the rights to use, copy, modify, merge, publish, // distribute, sublicense, and/or sell copies of the Software, and to permit // persons to whom the Software is furnished to do so, subject to the // following conditions: // // The above copyright notice and this permission notice shall be included // in all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS // OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF // MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN // NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, // DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR // OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE // USE OR OTHER DEALINGS IN THE SOFTWARE. if (!process.versions.openssl) { console.error('Skipping because node compiled without OpenSSL.'); process.exit(0); } // http://groups.google.com/group/nodejs/browse_thread/thread/f66cd3c960406919 var common = require('../common'); var assert = require('assert'); var http = require('http'); var cp = require('child_process'); var fs = require('fs'); var filename = require('path').join(common.tmpDir, 'big'); var count = 0; function maybeMakeRequest() { if (++count < 2) return; console.log('making curl request'); var cmd = 'curl http://127.0.0.1:' + common.PORT + '/ | openssl sha1'; cp.exec(cmd, function(err, stdout, stderr) { if (err) throw err; var hex = stdout.match(/([A-Fa-f0-9]{40})/)[0]; assert.equal('8c206a1a87599f532ce68675536f0b1546900d7a', hex); console.log('got the correct response'); fs.unlink(filename); server.close(); }); } var ddcmd = common.ddCommand(filename, 10240); console.log('dd command: ', ddcmd); cp.exec(ddcmd, function(err, stdout, stderr) { if (err) throw err; maybeMakeRequest(); }); var server = http.createServer(function(req, res) { res.writeHead(200); // Create the subprocess var cat = cp.spawn('cat', [filename]); // Stream the data through to the response as binary chunks cat.stdout.on('data', function(data) { res.write(data); }); // End the response on exit (and log errors) cat.on('exit', function(code) { if (code !== 0) { console.error('subprocess exited with code ' + code); exit(1); } res.end(); }); }); server.listen(common.PORT, maybeMakeRequest); console.log('Server running at http://localhost:8080'); node-v0.10.25~dfsg2/test/simple/test-script-context.js0000644000000000000000000000556212270121457021376 0ustar rootroot// Copyright Joyent, Inc. and other Node contributors. // // Permission is hereby granted, free of charge, to any person obtaining a // copy of this software and associated documentation files (the // "Software"), to deal in the Software without restriction, including // without limitation the rights to use, copy, modify, merge, publish, // distribute, sublicense, and/or sell copies of the Software, and to permit // persons to whom the Software is furnished to do so, subject to the // following conditions: // // The above copyright notice and this permission notice shall be included // in all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS // OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF // MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN // NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, // DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR // OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE // USE OR OTHER DEALINGS IN THE SOFTWARE. var common = require('../common'); var assert = require('assert'); var vm = require('vm'); var Script = vm.Script; var script = new Script('"passed";'); common.debug('run in a new empty context'); var context = script.createContext(); var result = script.runInContext(context); assert.equal('passed', result); common.debug('create a new pre-populated context'); context = script.createContext({'foo': 'bar', 'thing': 'lala'}); assert.equal('bar', context.foo); assert.equal('lala', context.thing); common.debug('test updating context'); script = new Script('foo = 3;'); result = script.runInContext(context); assert.equal(3, context.foo); assert.equal('lala', context.thing); // Issue GH-227: Script.runInNewContext('', null, 'some.js'); // Issue GH-1140: common.debug('test runInContext signature'); var gh1140Exception; try { Script.runInContext('throw new Error()', context, 'expected-filename.js'); } catch (e) { gh1140Exception = e; assert.ok(/expected-filename/.test(e.stack), 'expected appearance of filename in Error stack'); } assert.ok(gh1140Exception, 'expected exception from runInContext signature test'); // GH-558, non-context argument segfaults / raises assertion function isTypeError(o) { return o instanceof TypeError; } ([undefined, null, 0, 0.0, '', {}, []].forEach(function(e) { assert.throws(function() { script.runInContext(e); }, isTypeError); assert.throws(function() { vm.runInContext('', e); }, isTypeError); })); // Issue GH-693: common.debug('test RegExp as argument to assert.throws'); script = vm.createScript('var assert = require(\'assert\'); assert.throws(' + 'function() { throw "hello world"; }, /hello/);', 'some.js'); script.runInNewContext({ require : require }); node-v0.10.25~dfsg2/test/simple/test-fs-symlink.js0000644000000000000000000000573512270121457020506 0ustar rootroot// Copyright Joyent, Inc. and other Node contributors. // // Permission is hereby granted, free of charge, to any person obtaining a // copy of this software and associated documentation files (the // "Software"), to deal in the Software without restriction, including // without limitation the rights to use, copy, modify, merge, publish, // distribute, sublicense, and/or sell copies of the Software, and to permit // persons to whom the Software is furnished to do so, subject to the // following conditions: // // The above copyright notice and this permission notice shall be included // in all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS // OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF // MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN // NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, // DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR // OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE // USE OR OTHER DEALINGS IN THE SOFTWARE. var common = require('../common'); var assert = require('assert'); var path = require('path'); var fs = require('fs'); var exec = require('child_process').exec; var completed = 0; var expected_tests = 2; var is_windows = process.platform === 'win32'; var runtest = function(skip_symlinks) { if (!skip_symlinks) { // test creating and reading symbolic link var linkData = path.join(common.fixturesDir, '/cycles/root.js'); var linkPath = path.join(common.tmpDir, 'symlink1.js'); // Delete previously created link try { fs.unlinkSync(linkPath); } catch (e) {} fs.symlink(linkData, linkPath, function(err) { if (err) throw err; console.log('symlink done'); // todo: fs.lstat? fs.readlink(linkPath, function(err, destination) { if (err) throw err; assert.equal(destination, linkData); completed++; }); }); } // test creating and reading hard link var srcPath = path.join(common.fixturesDir, 'cycles', 'root.js'); var dstPath = path.join(common.tmpDir, 'link1.js'); // Delete previously created link try { fs.unlinkSync(dstPath); } catch (e) {} fs.link(srcPath, dstPath, function(err) { if (err) throw err; console.log('hard link done'); var srcContent = fs.readFileSync(srcPath, 'utf8'); var dstContent = fs.readFileSync(dstPath, 'utf8'); assert.equal(srcContent, dstContent); completed++; }); }; if (is_windows) { // On Windows, creating symlinks requires admin privileges. // We'll only try to run symlink test if we have enough privileges. exec('whoami /priv', function(err, o) { if (err || o.indexOf('SeCreateSymbolicLinkPrivilege') == -1) { expected_tests = 1; runtest(true); } else { runtest(false); } }); } else { runtest(false); } process.on('exit', function() { assert.equal(completed, expected_tests); }); node-v0.10.25~dfsg2/test/simple/test-https-socket-options.js0000644000000000000000000000553512270121457022531 0ustar rootroot// Copyright Joyent, Inc. and other Node contributors. // // Permission is hereby granted, free of charge, to any person obtaining a // copy of this software and associated documentation files (the // "Software"), to deal in the Software without restriction, including // without limitation the rights to use, copy, modify, merge, publish, // distribute, sublicense, and/or sell copies of the Software, and to permit // persons to whom the Software is furnished to do so, subject to the // following conditions: // // The above copyright notice and this permission notice shall be included // in all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS // OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF // MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN // NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, // DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR // OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE // USE OR OTHER DEALINGS IN THE SOFTWARE. if (!process.versions.openssl) { console.error('Skipping because node compiled without OpenSSL.'); process.exit(0); } var common = require('../common'); var assert = require('assert'); var fs = require('fs'); var exec = require('child_process').exec; var http = require('http'); var https = require('https'); var options = { key: fs.readFileSync(common.fixturesDir + '/keys/agent1-key.pem'), cert: fs.readFileSync(common.fixturesDir + '/keys/agent1-cert.pem') }; var body = 'hello world\n'; // Try first with http server var server_http = http.createServer(function(req, res) { console.log('got HTTP request'); res.writeHead(200, { 'content-type': 'text/plain' }); res.end(body); }); server_http.listen(common.PORT, function() { var req = http.request({ port: common.PORT, rejectUnauthorized: false }, function(res) { server_http.close(); res.resume(); }); // These methods should exist on the request and get passed down to the socket req.setNoDelay(true); req.setTimeout(1000, function() { }); req.setSocketKeepAlive(true, 1000); req.end(); }); // Then try https server (requires functions to be mirroed in tls.js's CryptoStream) var server_https = https.createServer(options, function(req, res) { console.log('got HTTPS request'); res.writeHead(200, { 'content-type': 'text/plain' }); res.end(body); }); server_https.listen(common.PORT+1, function() { var req = https.request({ port: common.PORT + 1, rejectUnauthorized: false }, function(res) { server_https.close(); res.resume(); }); // These methods should exist on the request and get passed down to the socket req.setNoDelay(true); req.setTimeout(1000, function() { }); req.setSocketKeepAlive(true, 1000); req.end(); }); node-v0.10.25~dfsg2/test/simple/test-umask.js0000644000000000000000000000322712270121457017524 0ustar rootroot// Copyright Joyent, Inc. and other Node contributors. // // Permission is hereby granted, free of charge, to any person obtaining a // copy of this software and associated documentation files (the // "Software"), to deal in the Software without restriction, including // without limitation the rights to use, copy, modify, merge, publish, // distribute, sublicense, and/or sell copies of the Software, and to permit // persons to whom the Software is furnished to do so, subject to the // following conditions: // // The above copyright notice and this permission notice shall be included // in all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS // OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF // MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN // NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, // DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR // OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE // USE OR OTHER DEALINGS IN THE SOFTWARE. var common = require('../common'); var assert = require('assert'); // Note in Windows one can only set the "user" bits. var mask; if (process.platform == 'win32') { mask = '0600'; } else { mask = '0664'; } var old = process.umask(mask); assert.equal(parseInt(mask, 8), process.umask(old)); // confirm reading the umask does not modify it. // 1. If the test fails, this call will succeed, but the mask will be set to 0 assert.equal(old, process.umask()); // 2. If the test fails, process.umask() will return 0 assert.equal(old, process.umask()); node-v0.10.25~dfsg2/test/simple/test-http-end-throw-socket-handling.js0000644000000000000000000000420312270121457024333 0ustar rootroot// Copyright Joyent, Inc. and other Node contributors. // // Permission is hereby granted, free of charge, to any person obtaining a // copy of this software and associated documentation files (the // "Software"), to deal in the Software without restriction, including // without limitation the rights to use, copy, modify, merge, publish, // distribute, sublicense, and/or sell copies of the Software, and to permit // persons to whom the Software is furnished to do so, subject to the // following conditions: // // The above copyright notice and this permission notice shall be included // in all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS // OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF // MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN // NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, // DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR // OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE // USE OR OTHER DEALINGS IN THE SOFTWARE. var common = require('../common'); var assert = require('assert'); // Make sure that throwing in 'end' handler doesn't lock // up the socket forever. // // This is NOT a good way to handle errors in general, but all // the same, we should not be so brittle and easily broken. var http = require('http'); var n = 0; var server = http.createServer(function(req, res) { if (++n === 10) server.close(); res.end('ok'); }); server.listen(common.PORT, function() { for (var i = 0; i < 10; i++) { var options = { port: common.PORT }; var req = http.request(options, function (res) { res.resume() res.on('end', function() { throw new Error('gleep glorp'); }); }); req.end(); } }); setTimeout(function() { process.removeListener('uncaughtException', catcher); throw new Error('Taking too long!'); }, 1000).unref(); process.on('uncaughtException', catcher); var errors = 0; function catcher() { errors++; } process.on('exit', function() { assert.equal(errors, 10); console.log('ok'); }); node-v0.10.25~dfsg2/test/simple/test-debugger-repl-break-in-module.js0000644000000000000000000000502312270121457024075 0ustar rootroot// Copyright Joyent, Inc. and other Node contributors. // // Permission is hereby granted, free of charge, to any person obtaining a // copy of this software and associated documentation files (the // "Software"), to deal in the Software without restriction, including // without limitation the rights to use, copy, modify, merge, publish, // distribute, sublicense, and/or sell copies of the Software, and to permit // persons to whom the Software is furnished to do so, subject to the // following conditions: // // The above copyright notice and this permission notice shall be included // in all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS // OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF // MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN // NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, // DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR // OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE // USE OR OTHER DEALINGS IN THE SOFTWARE. var repl = require('./helper-debugger-repl.js'); repl.startDebugger('break-in-module/main.js'); // -- SET BREAKPOINT -- // Set breakpoint by file name + line number where the file is not loaded yet repl.addTest('sb("mod.js", 23)', [ /Warning: script 'mod\.js' was not loaded yet\./, /1/, /2/, /3/, /4/, /5/, /6/ ]); // Check escaping of regex characters repl.addTest('sb(")^$*+?}{|][(.js\\\\", 1)', [ /Warning: script '[^']+' was not loaded yet\./, /1/, /2/, /3/, /4/, /5/, /6/ ]); // continue - the breakpoint should be triggered repl.addTest('c', [ /break in .*[\\\/]mod\.js:23/, /21/, /22/, /23/, /24/, /25/ ]); // -- RESTORE BREAKPOINT ON RESTART -- // Restart the application - breakpoint should be restored repl.addTest('restart', [].concat( [ /terminated/ ], repl.handshakeLines, [ /Restoring breakpoint mod.js:23/, /Warning: script 'mod\.js' was not loaded yet\./, /Restoring breakpoint \).*:\d+/, /Warning: script '\)[^']*' was not loaded yet\./ ], repl.initialBreakLines)); // continue - the breakpoint should be triggered repl.addTest('c', [ /break in .*[\\\/]mod\.js:23/, /21/, /22/, /23/, /24/, /25/ ]); // -- CLEAR BREAKPOINT SET IN MODULE TO BE LOADED -- repl.addTest('cb("mod.js", 23)', [ /18/, /./, /./, /./, /./, /./, /./, /./, /26/ ]); repl.addTest('c', [ /break in .*[\\\/]main\.js:4/, /2/, /3/, /4/, /5/, /6/ ]); // -- (END) -- repl.addTest('quit', []); node-v0.10.25~dfsg2/test/simple/test-child-process-stdio-big-write-end.js0000644000000000000000000000442212270121457024714 0ustar rootroot// Copyright Joyent, Inc. and other Node contributors. // // Permission is hereby granted, free of charge, to any person obtaining a // copy of this software and associated documentation files (the // "Software"), to deal in the Software without restriction, including // without limitation the rights to use, copy, modify, merge, publish, // distribute, sublicense, and/or sell copies of the Software, and to permit // persons to whom the Software is furnished to do so, subject to the // following conditions: // // The above copyright notice and this permission notice shall be included // in all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS // OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF // MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN // NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, // DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR // OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE // USE OR OTHER DEALINGS IN THE SOFTWARE. var common = require('../common'); var assert = require('assert'); var BUFSIZE = 1024; switch (process.argv[2]) { case undefined: return parent(); case 'child': return child(); default: throw new Error('wtf?'); } function parent() { var spawn = require('child_process').spawn; var child = spawn(process.execPath, [__filename, 'child']); var sent = 0; var n = ''; child.stdout.setEncoding('ascii'); child.stdout.on('data', function(c) { n += c; }); child.stdout.on('end', function() { assert.equal(+n, sent); console.log('ok'); }); // Write until the buffer fills up. do { var buf = new Buffer(BUFSIZE); buf.fill('.'); sent += BUFSIZE; } while (child.stdin.write(buf)); // then write a bunch more times. for (var i = 0; i < 100; i++) { var buf = new Buffer(BUFSIZE); buf.fill('.'); sent += BUFSIZE; child.stdin.write(buf); } // now end, before it's all flushed. child.stdin.end(); // now we wait... } function child() { var received = 0; process.stdin.on('data', function(c) { received += c.length; }); process.stdin.on('end', function() { console.log(received); }); } node-v0.10.25~dfsg2/test/simple/test-http-dns-error.js0000644000000000000000000000424612270121457021276 0ustar rootroot// Copyright Joyent, Inc. and other Node contributors. // // Permission is hereby granted, free of charge, to any person obtaining a // copy of this software and associated documentation files (the // "Software"), to deal in the Software without restriction, including // without limitation the rights to use, copy, modify, merge, publish, // distribute, sublicense, and/or sell copies of the Software, and to permit // persons to whom the Software is furnished to do so, subject to the // following conditions: // // The above copyright notice and this permission notice shall be included // in all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS // OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF // MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN // NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, // DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR // OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE // USE OR OTHER DEALINGS IN THE SOFTWARE. var common = require('../common'); var assert = require('assert'); var http = require('http'); var https = require('https'); var expected_bad_requests = 0; var actual_bad_requests = 0; var host = '********'; host += host; host += host; host += host; host += host; host += host; function do_not_call() { throw new Error('This function should not have been called.'); } function test(mod) { expected_bad_requests += 2; // Bad host name should not throw an uncatchable exception. // Ensure that there is time to attach an error listener. var req = mod.get({host: host, port: 42}, do_not_call); req.on('error', function(err) { assert.equal(err.code, 'ENOTFOUND'); actual_bad_requests++; }); // http.get() called req.end() for us var req = mod.request({method: 'GET', host: host, port: 42}, do_not_call); req.on('error', function(err) { assert.equal(err.code, 'ENOTFOUND'); actual_bad_requests++; }); req.end(); } test(https); test(http); process.on('exit', function() { assert.equal(actual_bad_requests, expected_bad_requests); }); node-v0.10.25~dfsg2/test/simple/test-fs-stream-double-close.js0000644000000000000000000000401112270121457022650 0ustar rootroot// Copyright Joyent, Inc. and other Node contributors. // // Permission is hereby granted, free of charge, to any person obtaining a // copy of this software and associated documentation files (the // "Software"), to deal in the Software without restriction, including // without limitation the rights to use, copy, modify, merge, publish, // distribute, sublicense, and/or sell copies of the Software, and to permit // persons to whom the Software is furnished to do so, subject to the // following conditions: // // The above copyright notice and this permission notice shall be included // in all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS // OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF // MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN // NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, // DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR // OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE // USE OR OTHER DEALINGS IN THE SOFTWARE. var common = require('../common'); var assert = require('assert'); var fs = require('fs'); test1(fs.createReadStream(__filename)); test2(fs.createReadStream(__filename)); test3(fs.createReadStream(__filename)); test1(fs.createWriteStream(common.tmpDir + '/dummy1')); test2(fs.createWriteStream(common.tmpDir + '/dummy2')); test3(fs.createWriteStream(common.tmpDir + '/dummy3')); function test1(stream) { stream.destroy(); stream.destroy(); } function test2(stream) { stream.destroy(); stream.on('open', function(fd) { stream.destroy(); open_cb_called++; }); process.on('exit', function() { assert.equal(open_cb_called, 1); }); var open_cb_called = 0; } function test3(stream) { stream.on('open', function(fd) { stream.destroy(); stream.destroy(); open_cb_called++; }); process.on('exit', function() { assert.equal(open_cb_called, 1); }); var open_cb_called = 0; } node-v0.10.25~dfsg2/test/simple/test-cluster-basic.js0000644000000000000000000001177012270121457021146 0ustar rootroot// Copyright Joyent, Inc. and other Node contributors. // // Permission is hereby granted, free of charge, to any person obtaining a // copy of this software and associated documentation files (the // "Software"), to deal in the Software without restriction, including // without limitation the rights to use, copy, modify, merge, publish, // distribute, sublicense, and/or sell copies of the Software, and to permit // persons to whom the Software is furnished to do so, subject to the // following conditions: // // The above copyright notice and this permission notice shall be included // in all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS // OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF // MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN // NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, // DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR // OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE // USE OR OTHER DEALINGS IN THE SOFTWARE. var common = require('../common'); var assert = require('assert'); var cluster = require('cluster'); assert.equal('NODE_UNIQUE_ID' in process.env, false, 'NODE_UNIQUE_ID should be removed on startup'); function forEach(obj, fn) { Object.keys(obj).forEach(function(name, index) { fn(obj[name], name, index); }); } if (cluster.isWorker) { var http = require('http'); http.Server(function() { }).listen(common.PORT, '127.0.0.1'); } else if (cluster.isMaster) { var checks = { cluster: { events: { fork: false, online: false, listening: false, exit: false }, equal: { fork: false, online: false, listening: false, exit: false } }, worker: { events: { online: false, listening: false, exit: false }, equal: { online: false, listening: false, exit: false }, states: { none: false, online: false, listening: false, dead: false } } }; var worker; var stateNames = Object.keys(checks.worker.states); //Check events, states, and emit arguments forEach(checks.cluster.events, function(bool, name, index) { //Listen on event cluster.on(name, function(/* worker */) { //Set event checks.cluster.events[name] = true; //Check argument checks.cluster.equal[name] = worker === arguments[0]; //Check state var state = stateNames[index]; checks.worker.states[state] = (state === worker.state); }); }); //Kill worker when listening cluster.on('listening', function() { worker.kill(); }); //Kill process when worker is killed cluster.on('exit', function() { process.exit(0); }); //Create worker worker = cluster.fork(); assert.equal(worker.id, 1); assert.ok(worker instanceof cluster.Worker, 'the worker is not a instance of the Worker constructor'); //Check event forEach(checks.worker.events, function(bool, name, index) { worker.on(name, function() { //Set event checks.worker.events[name] = true; //Check argument checks.worker.equal[name] = (worker === this); switch (name) { case 'exit': assert.equal(arguments[0], worker.process.exitCode); assert.equal(arguments[1], worker.process.signalCode); assert.equal(arguments.length, 2); break; case 'listening': assert.equal(arguments.length, 1); var expect = { address: '127.0.0.1', port: common.PORT, addressType: 4, fd: undefined }; assert.deepEqual(arguments[0], expect); break; default: assert.equal(arguments.length, 0); break; } }); }); //Check all values process.once('exit', function() { //Check cluster events forEach(checks.cluster.events, function(check, name) { assert.ok(check, 'The cluster event "' + name + '" on the cluster ' + 'object did not fire'); }); //Check cluster event arguments forEach(checks.cluster.equal, function(check, name) { assert.ok(check, 'The cluster event "' + name + '" did not emit ' + 'with correct argument'); }); //Check worker states forEach(checks.worker.states, function(check, name) { assert.ok(check, 'The worker state "' + name + '" was not set to true'); }); //Check worker events forEach(checks.worker.events, function(check, name) { assert.ok(check, 'The worker event "' + name + '" on the worker object ' + 'did not fire'); }); //Check worker event arguments forEach(checks.worker.equal, function(check, name) { assert.ok(check, 'The worker event "' + name + '" did not emit with ' + 'corrent argument'); }); }); } node-v0.10.25~dfsg2/test/simple/test-zlib-dictionary.js0000644000000000000000000000632612270121457021512 0ustar rootroot// Copyright Joyent, Inc. and other Node contributors. // // Permission is hereby granted, free of charge, to any person obtaining a // copy of this software and associated documentation files (the // "Software"), to deal in the Software without restriction, including // without limitation the rights to use, copy, modify, merge, publish, // distribute, sublicense, and/or sell copies of the Software, and to permit // persons to whom the Software is furnished to do so, subject to the // following conditions: // // The above copyright notice and this permission notice shall be included // in all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS // OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF // MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN // NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, // DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR // OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE // USE OR OTHER DEALINGS IN THE SOFTWARE. // test compression/decompresion with dictionary var common = require('../common.js'); var assert = require('assert'); var zlib = require('zlib'); var path = require('path'); var spdyDict = new Buffer([ 'optionsgetheadpostputdeletetraceacceptaccept-charsetaccept-encodingaccept-', 'languageauthorizationexpectfromhostif-modified-sinceif-matchif-none-matchi', 'f-rangeif-unmodifiedsincemax-forwardsproxy-authorizationrangerefererteuser', '-agent10010120020120220320420520630030130230330430530630740040140240340440', '5406407408409410411412413414415416417500501502503504505accept-rangesageeta', 'glocationproxy-authenticatepublicretry-afterservervarywarningwww-authentic', 'ateallowcontent-basecontent-encodingcache-controlconnectiondatetrailertran', 'sfer-encodingupgradeviawarningcontent-languagecontent-lengthcontent-locati', 'oncontent-md5content-rangecontent-typeetagexpireslast-modifiedset-cookieMo', 'ndayTuesdayWednesdayThursdayFridaySaturdaySundayJanFebMarAprMayJunJulAugSe', 'pOctNovDecchunkedtext/htmlimage/pngimage/jpgimage/gifapplication/xmlapplic', 'ation/xhtmltext/plainpublicmax-agecharset=iso-8859-1utf-8gzipdeflateHTTP/1', '.1statusversionurl\0' ].join('')); var deflate = zlib.createDeflate({ dictionary: spdyDict }); var input = [ 'HTTP/1.1 200 Ok', 'Server: node.js', 'Content-Length: 0', '' ].join('\r\n'); var called = 0; // // We'll use clean-new inflate stream each time // and .reset() old dirty deflate one // function run(num) { var inflate = zlib.createInflate({ dictionary: spdyDict }); if (num === 2) { deflate.reset(); deflate.removeAllListeners('data'); } // Put data into deflate stream deflate.on('data', function(chunk) { inflate.write(chunk); }); // Get data from inflate stream var output = []; inflate.on('data', function(chunk) { output.push(chunk); }); inflate.on('end', function() { called++; assert.equal(output.join(''), input); if (num < 2) run(num + 1); }); deflate.write(input); deflate.flush(function() { inflate.end(); }); } run(1); process.on('exit', function() { assert.equal(called, 2); }); node-v0.10.25~dfsg2/test/simple/test-tls-server-verify.js0000644000000000000000000001772012270121457022017 0ustar rootroot// Copyright Joyent, Inc. and other Node contributors. // // Permission is hereby granted, free of charge, to any person obtaining a // copy of this software and associated documentation files (the // "Software"), to deal in the Software without restriction, including // without limitation the rights to use, copy, modify, merge, publish, // distribute, sublicense, and/or sell copies of the Software, and to permit // persons to whom the Software is furnished to do so, subject to the // following conditions: // // The above copyright notice and this permission notice shall be included // in all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS // OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF // MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN // NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, // DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR // OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE // USE OR OTHER DEALINGS IN THE SOFTWARE. if (!process.versions.openssl) { console.error('Skipping because node compiled without OpenSSL.'); process.exit(0); } // This is a rather complex test which sets up various TLS servers with node // and connects to them using the 'openssl s_client' command line utility // with various keys. Depending on the certificate authority and other // parameters given to the server, the various clients are // - rejected, // - accepted and "unauthorized", or // - accepted and "authorized". var testCases = [{ title: 'Do not request certs. Everyone is unauthorized.', requestCert: false, rejectUnauthorized: false, CAs: ['ca1-cert'], clients: [{ name: 'agent1', shouldReject: false, shouldAuth: false }, { name: 'agent2', shouldReject: false, shouldAuth: false }, { name: 'agent3', shouldReject: false, shouldAuth: false }, { name: 'nocert', shouldReject: false, shouldAuth: false } ] }, { title: 'Allow both authed and unauthed connections with CA1', requestCert: true, rejectUnauthorized: false, CAs: ['ca1-cert'], clients: [{ name: 'agent1', shouldReject: false, shouldAuth: true }, { name: 'agent2', shouldReject: false, shouldAuth: false }, { name: 'agent3', shouldReject: false, shouldAuth: false }, { name: 'nocert', shouldReject: false, shouldAuth: false } ] }, { title: 'Allow only authed connections with CA1', requestCert: true, rejectUnauthorized: true, CAs: ['ca1-cert'], clients: [{ name: 'agent1', shouldReject: false, shouldAuth: true }, { name: 'agent2', shouldReject: true }, { name: 'agent3', shouldReject: true }, { name: 'nocert', shouldReject: true } ] }, { title: 'Allow only authed connections with CA1 and CA2', requestCert: true, rejectUnauthorized: true, CAs: ['ca1-cert', 'ca2-cert'], clients: [{ name: 'agent1', shouldReject: false, shouldAuth: true }, { name: 'agent2', shouldReject: true }, { name: 'agent3', shouldReject: false, shouldAuth: true }, { name: 'nocert', shouldReject: true } ] }, { title: 'Allow only certs signed by CA2 but not in the CRL', requestCert: true, rejectUnauthorized: true, CAs: ['ca2-cert'], crl: 'ca2-crl', clients: [ { name: 'agent1', shouldReject: true, shouldAuth: false }, { name: 'agent2', shouldReject: true, shouldAuth: false }, { name: 'agent3', shouldReject: false, shouldAuth: true }, // Agent4 has a cert in the CRL. { name: 'agent4', shouldReject: true, shouldAuth: false }, { name: 'nocert', shouldReject: true } ] } ]; var common = require('../common'); var assert = require('assert'); var fs = require('fs'); var tls = require('tls'); var spawn = require('child_process').spawn; function filenamePEM(n) { return require('path').join(common.fixturesDir, 'keys', n + '.pem'); } function loadPEM(n) { return fs.readFileSync(filenamePEM(n)); } var serverKey = loadPEM('agent2-key'); var serverCert = loadPEM('agent2-cert'); function runClient(options, cb) { // Client can connect in three ways: // - Self-signed cert // - Certificate, but not signed by CA. // - Certificate signed by CA. var args = ['s_client', '-connect', '127.0.0.1:' + common.PORT]; console.log(' connecting with', options.name); switch (options.name) { case 'agent1': // Signed by CA1 args.push('-key'); args.push(filenamePEM('agent1-key')); args.push('-cert'); args.push(filenamePEM('agent1-cert')); break; case 'agent2': // Self-signed // This is also the key-cert pair that the server will use. args.push('-key'); args.push(filenamePEM('agent2-key')); args.push('-cert'); args.push(filenamePEM('agent2-cert')); break; case 'agent3': // Signed by CA2 args.push('-key'); args.push(filenamePEM('agent3-key')); args.push('-cert'); args.push(filenamePEM('agent3-cert')); break; case 'agent4': // Signed by CA2 (rejected by ca2-crl) args.push('-key'); args.push(filenamePEM('agent4-key')); args.push('-cert'); args.push(filenamePEM('agent4-cert')); break; case 'nocert': // Do not send certificate break; default: throw new Error('Unknown agent name'); } // To test use: openssl s_client -connect localhost:8000 var client = spawn('openssl', args); var out = ''; var rejected = true; var authed = false; client.stdout.setEncoding('utf8'); client.stdout.on('data', function(d) { out += d; if (/_unauthed/g.test(out)) { console.error(' * unauthed'); client.stdin.end('goodbye\n'); authed = false; rejected = false; } if (/_authed/g.test(out)) { console.error(' * authed'); client.stdin.end('goodbye\n'); authed = true; rejected = false; } }); //client.stdout.pipe(process.stdout); client.on('exit', function(code) { //assert.equal(0, code, options.name + // ": s_client exited with error code " + code); if (options.shouldReject) { assert.equal(true, rejected, options.name + ' NOT rejected, but should have been'); } else { assert.equal(false, rejected, options.name + ' rejected, but should NOT have been'); assert.equal(options.shouldAuth, authed); } cb(); }); } // Run the tests var successfulTests = 0; function runTest(testIndex) { var tcase = testCases[testIndex]; if (!tcase) return; console.error("Running '%s'", tcase.title); var cas = tcase.CAs.map(loadPEM); var crl = tcase.crl ? loadPEM(tcase.crl) : null; var serverOptions = { key: serverKey, cert: serverCert, ca: cas, crl: crl, requestCert: tcase.requestCert, rejectUnauthorized: tcase.rejectUnauthorized }; var connections = 0; var server = tls.Server(serverOptions, function(c) { connections++; if (c.authorized) { console.error('- authed connection: ' + c.getPeerCertificate().subject.CN); c.write('\n_authed\n'); } else { console.error('- unauthed connection: %s', c.authorizationError); c.write('\n_unauthed\n'); } }); function runNextClient(clientIndex) { var options = tcase.clients[clientIndex]; if (options) { runClient(options, function() { runNextClient(clientIndex + 1); }); } else { server.close(); successfulTests++; runTest(testIndex + 1); } } server.listen(common.PORT, function() { if (tcase.debug) { console.error('TLS server running on port ' + common.PORT); } else { runNextClient(0); } }); } runTest(0); process.on('exit', function() { assert.equal(successfulTests, testCases.length); }); node-v0.10.25~dfsg2/test/simple/test-event-emitter-remove-listeners.js0000644000000000000000000000502612270121457024474 0ustar rootroot// Copyright Joyent, Inc. and other Node contributors. // // Permission is hereby granted, free of charge, to any person obtaining a // copy of this software and associated documentation files (the // "Software"), to deal in the Software without restriction, including // without limitation the rights to use, copy, modify, merge, publish, // distribute, sublicense, and/or sell copies of the Software, and to permit // persons to whom the Software is furnished to do so, subject to the // following conditions: // // The above copyright notice and this permission notice shall be included // in all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS // OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF // MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN // NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, // DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR // OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE // USE OR OTHER DEALINGS IN THE SOFTWARE. var common = require('../common'); var assert = require('assert'); var events = require('events'); var count = 0; function listener1() { console.log('listener1'); count++; } function listener2() { console.log('listener2'); count++; } function listener3() { console.log('listener3'); count++; } function remove1() { assert(0); } function remove2() { assert(0); } var e1 = new events.EventEmitter(); e1.on('hello', listener1); e1.on('removeListener', common.mustCall(function(name, cb) { assert.equal(name, 'hello'); assert.equal(cb, listener1); })); e1.removeListener('hello', listener1); assert.deepEqual([], e1.listeners('hello')); var e2 = new events.EventEmitter(); e2.on('hello', listener1); e2.on('removeListener', assert.fail); e2.removeListener('hello', listener2); assert.deepEqual([listener1], e2.listeners('hello')); var e3 = new events.EventEmitter(); e3.on('hello', listener1); e3.on('hello', listener2); e3.on('removeListener', common.mustCall(function(name, cb) { assert.equal(name, 'hello'); assert.equal(cb, listener1); })); e3.removeListener('hello', listener1); assert.deepEqual([listener2], e3.listeners('hello')); var e4 = new events.EventEmitter(); e4.on('removeListener', common.mustCall(function(name, cb) { if (cb !== remove1) return; this.removeListener('quux', remove2); this.emit('quux'); }, 2)); e4.on('quux', remove1); e4.on('quux', remove2); e4.removeListener('quux', remove1); node-v0.10.25~dfsg2/test/simple/test-child-process-fork-dgram.js0000644000000000000000000000575512270121457023202 0ustar rootroot// Copyright Joyent, Inc. and other Node contributors. // // Permission is hereby granted, free of charge, to any person obtaining a // copy of this software and associated documentation files (the // "Software"), to deal in the Software without restriction, including // without limitation the rights to use, copy, modify, merge, publish, // distribute, sublicense, and/or sell copies of the Software, and to permit // persons to whom the Software is furnished to do so, subject to the // following conditions: // // The above copyright notice and this permission notice shall be included // in all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS // OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF // MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN // NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, // DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR // OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE // USE OR OTHER DEALINGS IN THE SOFTWARE. var dgram = require('dgram'); var fork = require('child_process').fork; var assert = require('assert'); var common = require('../common'); if (process.platform === 'win32') { console.error('Sending dgram sockets to child processes not supported'); process.exit(0); } if (process.argv[2] === 'child') { var childCollected = 0; var server; process.on('message', function removeMe(msg, clusterServer) { if (msg === 'server') { server = clusterServer; server.on('message', function () { childCollected += 1; }); } else if (msg === 'stop') { server.close(); process.send(childCollected); process.removeListener('message', removeMe); } }); } else { var server = dgram.createSocket('udp4'); var client = dgram.createSocket('udp4'); var child = fork(__filename, ['child']); var msg = new Buffer('Some bytes'); var parentCollected = 0; var childCollected = 0; server.on('message', function (msg, rinfo) { parentCollected += 1; }); server.on('listening', function () { child.send('server', server); sendMessages(); }); var sendMessages = function () { var wait = 0; var send = 0; var total = 100; var timer = setInterval(function () { send += 1; if (send === total) { clearInterval(timer); } client.send(msg, 0, msg.length, common.PORT, '127.0.0.1', function(err) { if (err) throw err; wait += 1; if (wait === total) { shutdown(); } } ); }, 1); }; var shutdown = function () { child.send('stop'); child.once('message', function (collected) { childCollected = collected; }); server.close(); client.close(); }; server.bind(common.PORT, '127.0.0.1'); process.once('exit', function () { assert(childCollected > 0); assert(parentCollected > 0); }); } node-v0.10.25~dfsg2/test/simple/test-stdio-readable-writable.js0000644000000000000000000000257312270121457023075 0ustar rootroot// Copyright Joyent, Inc. and other Node contributors. // // Permission is hereby granted, free of charge, to any person obtaining a // copy of this software and associated documentation files (the // "Software"), to deal in the Software without restriction, including // without limitation the rights to use, copy, modify, merge, publish, // distribute, sublicense, and/or sell copies of the Software, and to permit // persons to whom the Software is furnished to do so, subject to the // following conditions: // // The above copyright notice and this permission notice shall be included // in all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS // OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF // MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN // NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, // DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR // OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE // USE OR OTHER DEALINGS IN THE SOFTWARE. var common = require('../common'); var assert = require('assert'); assert(process.stdout.writable); assert(!process.stdout.readable); assert(process.stderr.writable); assert(!process.stderr.readable); assert(!process.stdin.writable); assert(process.stdin.readable); node-v0.10.25~dfsg2/test/simple/test-https-client-resume.js0000644000000000000000000000560612270121457022323 0ustar rootroot// Copyright Joyent, Inc. and other Node contributors. // // Permission is hereby granted, free of charge, to any person obtaining a // copy of this software and associated documentation files (the // "Software"), to deal in the Software without restriction, including // without limitation the rights to use, copy, modify, merge, publish, // distribute, sublicense, and/or sell copies of the Software, and to permit // persons to whom the Software is furnished to do so, subject to the // following conditions: // // The above copyright notice and this permission notice shall be included // in all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS // OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF // MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN // NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, // DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR // OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE // USE OR OTHER DEALINGS IN THE SOFTWARE. // Create an ssl server. First connection, validate that not resume. // Cache session and close connection. Use session on second connection. // ASSERT resumption. if (!process.versions.openssl) { console.error('Skipping because node compiled without OpenSSL.'); process.exit(0); } var common = require('../common'); var assert = require('assert'); var https = require('https'); var tls = require('tls'); var fs = require('fs'); var options = { key: fs.readFileSync(common.fixturesDir + '/keys/agent2-key.pem'), cert: fs.readFileSync(common.fixturesDir + '/keys/agent2-cert.pem') }; var connections = 0; // create server var server = https.createServer(options, function(res, res) { res.end('Goodbye'); connections++; }); // start listening server.listen(common.PORT, function() { var session1 = null; var client1 = tls.connect({ port: common.PORT, rejectUnauthorized: false }, function() { console.log('connect1'); assert.ok(!client1.isSessionReused(), 'Session *should not* be reused.'); session1 = client1.getSession(); client1.write('GET / HTTP/1.0\r\n' + 'Server: 127.0.0.1\r\n' + '\r\n'); }); client1.on('close', function() { console.log('close1'); var opts = { port: common.PORT, rejectUnauthorized: false, session: session1 }; var client2 = tls.connect(opts, function() { console.log('connect2'); assert.ok(client2.isSessionReused(), 'Session *should* be reused.'); client2.write('GET / HTTP/1.0\r\n' + 'Server: 127.0.0.1\r\n' + '\r\n'); }); client2.on('close', function() { console.log('close2'); server.close(); }); }); }); process.on('exit', function() { assert.equal(2, connections); }); node-v0.10.25~dfsg2/test/simple/test-fs-readfile-unlink.js0000644000000000000000000000336612270121457022067 0ustar rootroot// Copyright Joyent, Inc. and other Node contributors. // // Permission is hereby granted, free of charge, to any person obtaining a // copy of this software and associated documentation files (the // "Software"), to deal in the Software without restriction, including // without limitation the rights to use, copy, modify, merge, publish, // distribute, sublicense, and/or sell copies of the Software, and to permit // persons to whom the Software is furnished to do so, subject to the // following conditions: // // The above copyright notice and this permission notice shall be included // in all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS // OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF // MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN // NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, // DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR // OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE // USE OR OTHER DEALINGS IN THE SOFTWARE. var assert = require('assert'), common = require('../common'), fs = require('fs'), path = require('path'), dirName = path.resolve(common.fixturesDir, 'test-readfile-unlink'), fileName = path.resolve(dirName, 'test.bin'); var buf = new Buffer(512 * 1024); buf.fill(42); try { fs.mkdirSync(dirName); } catch (e) { // Ignore if the directory already exists. if (e.code != 'EEXIST') throw e; } fs.writeFileSync(fileName, buf); fs.readFile(fileName, function(err, data) { assert.ifError(err); assert(data.length == buf.length); assert.strictEqual(buf[0], 42); fs.unlinkSync(fileName); fs.rmdirSync(dirName); }); node-v0.10.25~dfsg2/test/simple/test-fs-write-stream.js0000644000000000000000000000341112270121457021430 0ustar rootroot// Copyright Joyent, Inc. and other Node contributors. // // Permission is hereby granted, free of charge, to any person obtaining a // copy of this software and associated documentation files (the // "Software"), to deal in the Software without restriction, including // without limitation the rights to use, copy, modify, merge, publish, // distribute, sublicense, and/or sell copies of the Software, and to permit // persons to whom the Software is furnished to do so, subject to the // following conditions: // // The above copyright notice and this permission notice shall be included // in all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS // OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF // MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN // NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, // DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR // OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE // USE OR OTHER DEALINGS IN THE SOFTWARE. var common = require('../common'); var assert = require('assert'); var path = require('path'), fs = require('fs'); var file = path.join(common.tmpDir, 'write.txt'); (function() { var stream = fs.WriteStream(file), _fs_close = fs.close; fs.close = function(fd) { assert.ok(fd, 'fs.close must not be called without an undefined fd.'); fs.close = _fs_close; } stream.destroy(); })(); (function() { var stream = fs.createWriteStream(file); stream.on('drain', function() { assert.fail('\'drain\' event must not be emitted before ' + 'stream.write() has been called at least once.'); }); stream.destroy(); })(); node-v0.10.25~dfsg2/test/simple/test-require-resolve.js0000644000000000000000000000321612270121457021533 0ustar rootroot// Copyright Joyent, Inc. and other Node contributors. // // Permission is hereby granted, free of charge, to any person obtaining a // copy of this software and associated documentation files (the // "Software"), to deal in the Software without restriction, including // without limitation the rights to use, copy, modify, merge, publish, // distribute, sublicense, and/or sell copies of the Software, and to permit // persons to whom the Software is furnished to do so, subject to the // following conditions: // // The above copyright notice and this permission notice shall be included // in all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS // OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF // MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN // NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, // DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR // OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE // USE OR OTHER DEALINGS IN THE SOFTWARE. var common = require('../common'); var fixturesDir = common.fixturesDir; var assert = require('assert'); var path = require('path'); assert.equal(path.join(__dirname, '../fixtures/a.js'), require.resolve('../fixtures/a')); assert.equal(path.join(fixturesDir, 'a.js'), require.resolve(path.join(fixturesDir, 'a'))); assert.equal(path.join(fixturesDir, 'nested-index', 'one', 'index.js'), require.resolve('../fixtures/nested-index/one')); assert.equal('path', require.resolve('path')); console.log('ok'); node-v0.10.25~dfsg2/test/simple/test-debugger-client.js0000644000000000000000000001522612270121457021446 0ustar rootroot// Copyright Joyent, Inc. and other Node contributors. // // Permission is hereby granted, free of charge, to any person obtaining a // copy of this software and associated documentation files (the // "Software"), to deal in the Software without restriction, including // without limitation the rights to use, copy, modify, merge, publish, // distribute, sublicense, and/or sell copies of the Software, and to permit // persons to whom the Software is furnished to do so, subject to the // following conditions: // // The above copyright notice and this permission notice shall be included // in all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS // OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF // MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN // NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, // DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR // OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE // USE OR OTHER DEALINGS IN THE SOFTWARE. process.env.NODE_DEBUGGER_TIMEOUT = 2000; var common = require('../common'); var assert = require('assert'); var debug = require('_debugger'); var debugPort = common.PORT + 1337; debug.port = debugPort; var spawn = require('child_process').spawn; setTimeout(function() { if (nodeProcess) nodeProcess.kill('SIGTERM'); throw new Error('timeout'); }, 10000).unref(); var resCount = 0; var p = new debug.Protocol(); p.onResponse = function(res) { resCount++; }; p.execute('Type: connect\r\n' + 'V8-Version: 3.0.4.1\r\n' + 'Protocol-Version: 1\r\n' + 'Embedding-Host: node v0.3.3-pre\r\n' + 'Content-Length: 0\r\n\r\n'); assert.equal(1, resCount); // Make sure split messages go in. var parts = []; parts.push('Content-Length: 336\r\n'); assert.equal(21, parts[0].length); parts.push('\r\n'); assert.equal(2, parts[1].length); var bodyLength = 0; parts.push('{"seq":12,"type":"event","event":"break","body":' + '{"invocationText":"#'); assert.equal(78, parts[2].length); bodyLength += parts[2].length; parts.push('.[anonymous](req=#, ' + 'res=#)","sourceLine"'); assert.equal(78, parts[3].length); bodyLength += parts[3].length; parts.push(':45,"sourceColumn":4,"sourceLineText":" debugger;",' + '"script":{"id":24,"name":"/home/ryan/projects/node/' + 'benchmark/http_simple.js","lineOffset":0,"columnOffset":0,' + '"lineCount":98}}}'); assert.equal(180, parts[4].length); bodyLength += parts[4].length; assert.equal(336, bodyLength); for (var i = 0; i < parts.length; i++) { p.execute(parts[i]); } assert.equal(2, resCount); // Make sure that if we get backed up, we still manage to get all the // messages var d = 'Content-Length: 466\r\n\r\n' + '{"seq":10,"type":"event","event":"afterCompile","success":true,' + '"body":{"script":{"handle":1,"type":"script","name":"dns.js",' + '"id":34,"lineOffset":0,"columnOffset":0,"lineCount":241,' + '"sourceStart":"(function (module, exports, require) {' + 'var dns = process.binding(\'cares\')' + ';\\nvar ne","sourceLength":6137,"scriptType":2,"compilationType":0,' + '"context":{"ref":0},"text":"dns.js (lines: 241)"}},"refs":' + '[{"handle":0' + ',"type":"context","text":"#"}],"running":true}' + 'Content-Length: 119\r\n\r\n' + '{"seq":11,"type":"event","event":"scriptCollected","success":true,' + '"body":{"script":{"id":26}},"refs":[],"running":true}'; p.execute(d); assert.equal(4, resCount); var expectedConnections = 0; var tests = []; function addTest(cb) { expectedConnections++; tests.push(cb); } addTest(function(client, done) { console.error('requesting version'); client.reqVersion(function(err, v) { assert.ok(!err); console.log('version: %s', v); assert.equal(process.versions.v8, v); done(); }); }); addTest(function(client, done) { console.error('requesting scripts'); client.reqScripts(function(err) { assert.ok(!err); console.error('got %d scripts', Object.keys(client.scripts).length); var foundMainScript = false; for (var k in client.scripts) { var script = client.scripts[k]; if (script && script.name === 'node.js') { foundMainScript = true; break; } } assert.ok(foundMainScript); done(); }); }); addTest(function(client, done) { console.error('eval 2+2'); client.reqEval('2+2', function(err, res) { console.error(res); assert.ok(!err); assert.equal('4', res.text); assert.equal(4, res.value); done(); }); }); var connectCount = 0; var script = 'setTimeout(function () { console.log("blah"); });' + 'setInterval(function () {}, 1000000);'; var nodeProcess; function doTest(cb, done) { var args = ['--debug=' + debugPort, '-e', script]; nodeProcess = spawn(process.execPath, args); nodeProcess.stdout.once('data', function(c) { console.log('>>> new node process: %d', nodeProcess.pid); var failed = true; try { process._debugProcess(nodeProcess.pid); failed = false; } finally { // At least TRY not to leave zombie procs if this fails. if (failed) nodeProcess.kill('SIGTERM'); } console.log('>>> starting debugger session'); }); var didTryConnect = false; nodeProcess.stderr.setEncoding('utf8'); var b = ''; nodeProcess.stderr.on('data', function(data) { console.error('got stderr data %j', data); nodeProcess.stderr.resume(); b += data; if (didTryConnect == false && b.match(/debugger listening on port/)) { didTryConnect = true; setTimeout(function() { // Wait for some data before trying to connect var c = new debug.Client(); console.error('>>> connecting...'); c.connect(debug.port); c.on('break', function(brk) { c.reqContinue(function() {}); }); c.on('ready', function() { connectCount++; console.log('ready!'); cb(c, function() { c.end(); c.on('end', function() { console.error( '>>> killing node process %d\n\n', nodeProcess.pid); nodeProcess.kill(); done(); }); }); }); }); } }); } function run() { var t = tests[0]; if (!t) return; doTest(t, function() { tests.shift(); run(); }); } run(); process.on('exit', function(code) { if (!code) assert.equal(expectedConnections, connectCount); }); node-v0.10.25~dfsg2/test/simple/test-event-emitter-no-error-provided-to-error-event.js0000644000000000000000000000305312270121457027432 0ustar rootroot// Copyright Joyent, Inc. and other Node contributors. // // Permission is hereby granted, free of charge, to any person obtaining a // copy of this software and associated documentation files (the // "Software"), to deal in the Software without restriction, including // without limitation the rights to use, copy, modify, merge, publish, // distribute, sublicense, and/or sell copies of the Software, and to permit // persons to whom the Software is furnished to do so, subject to the // following conditions: // // The above copyright notice and this permission notice shall be included // in all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS // OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF // MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN // NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, // DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR // OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE // USE OR OTHER DEALINGS IN THE SOFTWARE. var common = require('../common'); var assert = require('assert'); var events = require('events'); var domain = require('domain'); var errorCatched = false; var e = new events.EventEmitter(); var d = domain.create(); d.add(e); d.on('error', function (er) { assert(er instanceof TypeError, 'type error created'); errorCatched = true; }); e.emit('error'); process.on('exit', function () { assert(errorCatched, 'error got catched'); }); node-v0.10.25~dfsg2/test/simple/test-net-listen-error.js0000644000000000000000000000277512270121457021624 0ustar rootroot// Copyright Joyent, Inc. and other Node contributors. // // Permission is hereby granted, free of charge, to any person obtaining a // copy of this software and associated documentation files (the // "Software"), to deal in the Software without restriction, including // without limitation the rights to use, copy, modify, merge, publish, // distribute, sublicense, and/or sell copies of the Software, and to permit // persons to whom the Software is furnished to do so, subject to the // following conditions: // // The above copyright notice and this permission notice shall be included // in all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS // OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF // MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN // NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, // DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR // OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE // USE OR OTHER DEALINGS IN THE SOFTWARE. var common = require('../common'); var assert = require('assert'); var net = require('net'); var gotError = false; var server = net.createServer(function(socket) { }); server.listen(1, '1.1.1.1', function() { // EACCESS or EADDRNOTAVAIL assert(false); }); server.on('error', function(error) { common.debug(error); gotError = true; }); process.on('exit', function() { assert(gotError); }); node-v0.10.25~dfsg2/test/simple/test-tls-client-abort2.js0000644000000000000000000000315612270121457021652 0ustar rootroot// Copyright Joyent, Inc. and other Node contributors. // // Permission is hereby granted, free of charge, to any person obtaining a // copy of this software and associated documentation files (the // "Software"), to deal in the Software without restriction, including // without limitation the rights to use, copy, modify, merge, publish, // distribute, sublicense, and/or sell copies of the Software, and to permit // persons to whom the Software is furnished to do so, subject to the // following conditions: // // The above copyright notice and this permission notice shall be included // in all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS // OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF // MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN // NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, // DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR // OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE // USE OR OTHER DEALINGS IN THE SOFTWARE. if (!process.versions.openssl) { console.error('Skipping because node compiled without OpenSSL.'); process.exit(0); } var common = require('../common'); var assert = require('assert'); var tls = require('tls'); var errors = 0; var conn = tls.connect(common.PORT, function() { assert(false); // callback should never be executed }); conn.on('error', function() { ++errors; assert.doesNotThrow(function() { conn.destroy(); }); }); process.on('exit', function() { assert.equal(errors, 1); }); node-v0.10.25~dfsg2/test/simple/test-stream2-pipe-error-once-listener.js0000755000000000000000000000361412270121457024613 0ustar rootroot// Copyright Joyent, Inc. and other Node contributors. // // Permission is hereby granted, free of charge, to any person obtaining a // copy of this software and associated documentation files (the // "Software"), to deal in the Software without restriction, including // without limitation the rights to use, copy, modify, merge, publish, // distribute, sublicense, and/or sell copies of the Software, and to permit // persons to whom the Software is furnished to do so, subject to the // following conditions: // // The above copyright notice and this permission notice shall be included // in all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS // OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF // MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN // NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, // DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR // OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE // USE OR OTHER DEALINGS IN THE SOFTWARE. var common = require('../common.js'); var assert = require('assert'); var util = require('util'); var stream = require('stream'); var Read = function() { stream.Readable.call(this); }; util.inherits(Read, stream.Readable); Read.prototype._read = function(size) { this.push('x'); this.push(null); }; var Write = function() { stream.Writable.call(this); }; util.inherits(Write, stream.Writable); Write.prototype._write = function(buffer, encoding, cb) { this.emit('error', new Error('boom')); this.emit('alldone'); }; var read = new Read(); var write = new Write(); write.once('error', function(err) {}); write.once('alldone', function(err) { console.log('ok'); }); process.on('exit', function(c) { console.error('error thrown even with listener'); }); read.pipe(write); node-v0.10.25~dfsg2/test/simple/test-net-server-listen-remove-callback.js0000644000000000000000000000317512270121457025021 0ustar rootroot// Copyright Joyent, Inc. and other Node contributors. // // Permission is hereby granted, free of charge, to any person obtaining a // copy of this software and associated documentation files (the // "Software"), to deal in the Software without restriction, including // without limitation the rights to use, copy, modify, merge, publish, // distribute, sublicense, and/or sell copies of the Software, and to permit // persons to whom the Software is furnished to do so, subject to the // following conditions: // // The above copyright notice and this permission notice shall be included // in all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS // OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF // MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN // NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, // DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR // OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE // USE OR OTHER DEALINGS IN THE SOFTWARE. var common = require('../common'); var assert = require('assert'); var net = require('net'); // Server should only fire listen callback once var server = net.createServer(); server.on('close', function() { var listeners = server.listeners('listening'); console.log('Closed, listeners:', listeners.length); assert.equal(0, listeners.length); }); server.listen(common.PORT, function() { server.close(); }); server.once('close', function() { server.listen(common.PORT + 1, function() { server.close(); }); }); node-v0.10.25~dfsg2/test/simple/test-http-multi-line-headers.js0000644000000000000000000000374312270121457023054 0ustar rootroot// Copyright Joyent, Inc. and other Node contributors. // // Permission is hereby granted, free of charge, to any person obtaining a // copy of this software and associated documentation files (the // "Software"), to deal in the Software without restriction, including // without limitation the rights to use, copy, modify, merge, publish, // distribute, sublicense, and/or sell copies of the Software, and to permit // persons to whom the Software is furnished to do so, subject to the // following conditions: // // The above copyright notice and this permission notice shall be included // in all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS // OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF // MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN // NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, // DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR // OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE // USE OR OTHER DEALINGS IN THE SOFTWARE. var common = require('../common'); var assert = require('assert'); var http = require('http'); var net = require('net'); var gotResponse = false; var server = net.createServer(function(conn) { var body = 'Yet another node.js server.'; var response = 'HTTP/1.1 200 OK\r\n' + 'Connection: close\r\n' + 'Content-Length: ' + body.length + '\r\n' + 'Content-Type: text/plain;\r\n' + ' x-unix-mode=0600;\r\n' + ' name=\"hello.txt\"\r\n' + '\r\n' + body; conn.end(response); server.close(); }); server.listen(common.PORT, function() { http.get({host: '127.0.0.1', port: common.PORT}, function(res) { assert.equal(res.headers['content-type'], 'text/plain;x-unix-mode=0600;name="hello.txt"'); gotResponse = true; res.destroy(); }); }); process.on('exit', function() { assert.ok(gotResponse); }); node-v0.10.25~dfsg2/test/simple/test-listen-fd-server.js0000644000000000000000000001005712270121457021574 0ustar rootroot// Copyright Joyent, Inc. and other Node contributors. // // Permission is hereby granted, free of charge, to any person obtaining a // copy of this software and associated documentation files (the // "Software"), to deal in the Software without restriction, including // without limitation the rights to use, copy, modify, merge, publish, // distribute, sublicense, and/or sell copies of the Software, and to permit // persons to whom the Software is furnished to do so, subject to the // following conditions: // // The above copyright notice and this permission notice shall be included // in all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS // OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF // MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN // NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, // DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR // OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE // USE OR OTHER DEALINGS IN THE SOFTWARE. var common = require('../common'); var assert = require('assert'); var http = require('http'); var net = require('net'); var PORT = common.PORT; var spawn = require('child_process').spawn; if (process.platform === 'win32') { console.error('This test is disabled on windows.'); return; } switch (process.argv[2]) { case 'child': return child(); case 'parent': return parent(); default: return test(); } // spawn the parent, and listen for it to tell us the pid of the child. // WARNING: This is an example of listening on some arbitrary FD number // that has already been bound elsewhere in advance. However, binding // server handles to stdio fd's is NOT a good or reliable way to do // concurrency in HTTP servers! Use the cluster module, or if you want // a more low-level approach, use child process IPC manually. function test() { var parent = spawn(process.execPath, [__filename, 'parent'], { stdio: [ 0, 'pipe', 2 ] }); var json = ''; parent.stdout.on('data', function(c) { json += c.toString(); if (json.indexOf('\n') !== -1) next(); }); function next() { console.error('output from parent = %s', json); var child = JSON.parse(json); // now make sure that we can request to the child, then kill it. http.get({ server: 'localhost', port: PORT, path: '/', }).on('response', function (res) { var s = ''; res.on('data', function(c) { s += c.toString(); }); res.on('end', function() { // kill the child before we start doing asserts. // it's really annoying when tests leave orphans! process.kill(child.pid, 'SIGKILL'); try { parent.kill(); } catch (e) {} assert.equal(s, 'hello from child\n'); assert.equal(res.statusCode, 200); }); }) } } function child() { // start a server on fd=3 http.createServer(function(req, res) { console.error('request on child'); console.error('%s %s', req.method, req.url, req.headers); res.end('hello from child\n'); }).listen({ fd: 3 }, function() { console.error('child listening on fd=3'); }); } function parent() { var server = net.createServer(function(conn) { console.error('connection on parent'); conn.end('hello from parent\n'); }).listen(PORT, function() { console.error('server listening on %d', PORT); var spawn = require('child_process').spawn; var child = spawn(process.execPath, [__filename, 'child'], { stdio: [ 0, 1, 2, server._handle ] }); console.log('%j\n', { pid: child.pid }); // Now close the parent, so that the child is the only thing // referencing that handle. Note that connections will still // be accepted, because the child has the fd open. server.close(); child.on('exit', function(code) { console.error('child exited', code); }); child.on('close', function() { console.error('child closed'); }); console.error('child spawned'); }); } node-v0.10.25~dfsg2/test/simple/test-child-process-silent.js0000644000000000000000000000662012270121457022437 0ustar rootroot// Copyright Joyent, Inc. and other Node contributors. // // Permission is hereby granted, free of charge, to any person obtaining a // copy of this software and associated documentation files (the // "Software"), to deal in the Software without restriction, including // without limitation the rights to use, copy, modify, merge, publish, // distribute, sublicense, and/or sell copies of the Software, and to permit // persons to whom the Software is furnished to do so, subject to the // following conditions: // // The above copyright notice and this permission notice shall be included // in all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS // OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF // MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN // NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, // DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR // OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE // USE OR OTHER DEALINGS IN THE SOFTWARE. var common = require('../common'); var assert = require('assert'); var childProcess = require('child_process'); // Child pipe test if (process.argv[2] === 'pipetest') { process.stdout.write('stdout message'); process.stderr.write('stderr message'); } else if (process.argv[2] === 'ipctest') { // Child IPC test process.send('message from child'); process.on('message', function() { process.send('got message from master'); }); } else if (process.argv[2] === 'parent') { // Parent | start child pipe test var child = childProcess.fork(process.argv[1], ['pipetest'], {silent: true}); // Allow child process to self terminate child._channel.close(); child._channel = null; child.on('exit', function() { process.exit(0); }); } else { // testcase | start parent && child IPC test // testing: is stderr and stdout piped to parent var args = [process.argv[1], 'parent']; var parent = childProcess.spawn(process.execPath, args); //got any stderr or std data var stdoutData = false; parent.stdout.on('data', function() { stdoutData = true; }); var stderrData = false; parent.stdout.on('data', function() { stderrData = true; }); // testing: do message system work when using silent var child = childProcess.fork(process.argv[1], ['ipctest'], {silent: true}); // Manual pipe so we will get errors child.stderr.pipe(process.stderr, {end: false}); child.stdout.pipe(process.stdout, {end: false}); var childSending = false; var childReciveing = false; child.on('message', function(message) { if (childSending === false) { childSending = (message === 'message from child'); } if (childReciveing === false) { childReciveing = (message === 'got message from master'); } if (childReciveing === true) { child.kill(); } }); child.send('message to child'); // Check all values process.on('exit', function() { // clean up child.kill(); parent.kill(); // Check std(out|err) pipes assert.ok(!stdoutData, 'The stdout socket was piped to parent'); assert.ok(!stderrData, 'The stderr socket was piped to parent'); // Check message system assert.ok(childSending, 'The child was able to send a message'); assert.ok(childReciveing, 'The child was able to receive a message'); }); } node-v0.10.25~dfsg2/test/simple/test-stream-push-strings.js0000644000000000000000000000421012270121457022334 0ustar rootroot// Copyright Joyent, Inc. and other Node contributors. // // Permission is hereby granted, free of charge, to any person obtaining a // copy of this software and associated documentation files (the // "Software"), to deal in the Software without restriction, including // without limitation the rights to use, copy, modify, merge, publish, // distribute, sublicense, and/or sell copies of the Software, and to permit // persons to whom the Software is furnished to do so, subject to the // following conditions: // // The above copyright notice and this permission notice shall be included // in all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS // OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF // MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN // NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, // DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR // OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE // USE OR OTHER DEALINGS IN THE SOFTWARE. var common = require('../common'); var assert = require('assert'); var Readable = require('stream').Readable; var util = require('util'); util.inherits(MyStream, Readable); function MyStream(options) { Readable.call(this, options); this._chunks = 3; } MyStream.prototype._read = function(n) { switch (this._chunks--) { case 0: return this.push(null); case 1: return setTimeout(function() { this.push('last chunk'); }.bind(this), 100); case 2: return this.push('second to last chunk'); case 3: return process.nextTick(function() { this.push('first chunk'); }.bind(this)); default: throw new Error('?'); } }; var ms = new MyStream(); var results = []; ms.on('readable', function() { var chunk; while (null !== (chunk = ms.read())) results.push(chunk + ''); }); var expect = [ 'first chunksecond to last chunk', 'last chunk' ]; process.on('exit', function() { assert.equal(ms._chunks, -1); assert.deepEqual(results, expect); console.log('ok'); }); node-v0.10.25~dfsg2/test/simple/test-pipe-head.js0000644000000000000000000000321012270121457020230 0ustar rootroot// Copyright Joyent, Inc. and other Node contributors. // // Permission is hereby granted, free of charge, to any person obtaining a // copy of this software and associated documentation files (the // "Software"), to deal in the Software without restriction, including // without limitation the rights to use, copy, modify, merge, publish, // distribute, sublicense, and/or sell copies of the Software, and to permit // persons to whom the Software is furnished to do so, subject to the // following conditions: // // The above copyright notice and this permission notice shall be included // in all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS // OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF // MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN // NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, // DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR // OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE // USE OR OTHER DEALINGS IN THE SOFTWARE. var common = require('../common'); var assert = require('assert'); var exec = require('child_process').exec; var join = require('path').join; var nodePath = process.argv[0]; var script = join(common.fixturesDir, 'print-10-lines.js'); var cmd = '"' + nodePath + '" "' + script + '" | head -2'; var finished = false; exec(cmd, function(err, stdout, stderr) { if (err) throw err; var lines = stdout.split('\n'); assert.equal(3, lines.length); finished = true; }); process.on('exit', function() { assert.ok(finished); }); node-v0.10.25~dfsg2/test/simple/test-zlib-invalid-input.js0000644000000000000000000000454512270121457022131 0ustar rootroot// Copyright Joyent, Inc. and other Node contributors. // // Permission is hereby granted, free of charge, to any person obtaining a // copy of this software and associated documentation files (the // "Software"), to deal in the Software without restriction, including // without limitation the rights to use, copy, modify, merge, publish, // distribute, sublicense, and/or sell copies of the Software, and to permit // persons to whom the Software is furnished to do so, subject to the // following conditions: // // The above copyright notice and this permission notice shall be included // in all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS // OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF // MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN // NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, // DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR // OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE // USE OR OTHER DEALINGS IN THE SOFTWARE. // test uncompressing invalid input var common = require('../common.js'), assert = require('assert'), zlib = require('zlib'); var nonStringInputs = [1, true, {a: 1}, ['a']]; console.error('Doing the non-strings'); nonStringInputs.forEach(function(input) { // zlib.gunzip should not throw an error when called with bad input. assert.doesNotThrow(function() { zlib.gunzip(input, function(err, buffer) { // zlib.gunzip should pass the error to the callback. assert.ok(err); }); }); }); console.error('Doing the unzips'); // zlib.Unzip classes need to get valid data, or else they'll throw. var unzips = [ zlib.Unzip(), zlib.Gunzip(), zlib.Inflate(), zlib.InflateRaw() ]; var hadError = []; unzips.forEach(function (uz, i) { console.error('Error for '+uz.constructor.name); uz.on('error', function(er) { console.error('Error event', er); hadError[i] = true; }); uz.on('end', function(er) { throw new Error('end event should not be emitted '+uz.constructor.name); }); // this will trigger error event uz.write('this is not valid compressed data.'); }); process.on('exit', function() { assert.deepEqual(hadError, [true, true, true, true], 'expect 4 errors'); }); node-v0.10.25~dfsg2/test/simple/test-stream2-readable-empty-buffer-no-eof.js0000644000000000000000000000663712270121457025312 0ustar rootroot// Copyright Joyent, Inc. and other Node contributors. // // Permission is hereby granted, free of charge, to any person obtaining a // copy of this software and associated documentation files (the // "Software"), to deal in the Software without restriction, including // without limitation the rights to use, copy, modify, merge, publish, // distribute, sublicense, and/or sell copies of the Software, and to permit // persons to whom the Software is furnished to do so, subject to the // following conditions: // // The above copyright notice and this permission notice shall be included // in all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS // OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF // MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN // NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, // DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR // OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE // USE OR OTHER DEALINGS IN THE SOFTWARE. var common = require('../common'); var assert = require('assert'); var Readable = require('stream').Readable; test1(); test2(); function test1() { var r = new Readable(); // should not end when we get a Buffer(0) or '' as the _read result // that just means that there is *temporarily* no data, but to go // ahead and try again later. // // note that this is very unusual. it only works for crypto streams // because the other side of the stream will call read(0) to cycle // data through openssl. that's why we set the timeouts to call // r.read(0) again later, otherwise there is no more work being done // and the process just exits. var buf = new Buffer(5); buf.fill('x'); var reads = 5; r._read = function(n) { switch (reads--) { case 0: return r.push(null); // EOF case 1: return r.push(buf); case 2: setTimeout(r.read.bind(r, 0), 10); return r.push(new Buffer(0)); // Not-EOF! case 3: setTimeout(r.read.bind(r, 0), 10); return process.nextTick(function() { return r.push(new Buffer(0)); }); case 4: setTimeout(r.read.bind(r, 0), 10); return setTimeout(function() { return r.push(new Buffer(0)); }); case 5: return setTimeout(function() { return r.push(buf); }); default: throw new Error('unreachable'); } }; var results = []; function flow() { var chunk; while (null !== (chunk = r.read())) results.push(chunk + ''); } r.on('readable', flow); r.on('end', function() { results.push('EOF'); }); flow(); process.on('exit', function() { assert.deepEqual(results, [ 'xxxxx', 'xxxxx', 'EOF' ]); console.log('ok'); }); } function test2() { var r = new Readable({ encoding: 'base64' }); var reads = 5; r._read = function(n) { if (!reads--) return r.push(null); // EOF else return r.push(new Buffer('x')); }; var results = []; function flow() { var chunk; while (null !== (chunk = r.read())) results.push(chunk + ''); } r.on('readable', flow); r.on('end', function() { results.push('EOF'); }); flow(); process.on('exit', function() { assert.deepEqual(results, [ 'eHh4', 'eHg=', 'EOF' ]); console.log('ok'); }); } node-v0.10.25~dfsg2/test/simple/test-tls-sni-server-client.js0000644000000000000000000000665512270121457022565 0ustar rootroot// Copyright Joyent, Inc. and other Node contributors. // // Permission is hereby granted, free of charge, to any person obtaining a // copy of this software and associated documentation files (the // "Software"), to deal in the Software without restriction, including // without limitation the rights to use, copy, modify, merge, publish, // distribute, sublicense, and/or sell copies of the Software, and to permit // persons to whom the Software is furnished to do so, subject to the // following conditions: // // The above copyright notice and this permission notice shall be included // in all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS // OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF // MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN // NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, // DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR // OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE // USE OR OTHER DEALINGS IN THE SOFTWARE. if (!process.features.tls_sni) { console.error('Skipping because node compiled without OpenSSL or ' + 'with old OpenSSL version.'); process.exit(0); } var common = require('../common'), assert = require('assert'), fs = require('fs'), tls = require('tls'); function filenamePEM(n) { return require('path').join(common.fixturesDir, 'keys', n + '.pem'); } function loadPEM(n) { return fs.readFileSync(filenamePEM(n)); } var serverOptions = { key: loadPEM('agent2-key'), cert: loadPEM('agent2-cert') }; var SNIContexts = { 'a.example.com': { key: loadPEM('agent1-key'), cert: loadPEM('agent1-cert') }, 'asterisk.test.com': { key: loadPEM('agent3-key'), cert: loadPEM('agent3-cert') } }; var serverPort = common.PORT; var clientsOptions = [{ port: serverPort, key: loadPEM('agent1-key'), cert: loadPEM('agent1-cert'), ca: [loadPEM('ca1-cert')], servername: 'a.example.com', rejectUnauthorized: false },{ port: serverPort, key: loadPEM('agent2-key'), cert: loadPEM('agent2-cert'), ca: [loadPEM('ca2-cert')], servername: 'b.test.com', rejectUnauthorized: false },{ port: serverPort, key: loadPEM('agent3-key'), cert: loadPEM('agent3-cert'), ca: [loadPEM('ca1-cert')], servername: 'c.wrong.com', rejectUnauthorized: false }]; var serverResults = [], clientResults = []; var server = tls.createServer(serverOptions, function(c) { serverResults.push(c.servername); }); server.addContext('a.example.com', SNIContexts['a.example.com']); server.addContext('*.test.com', SNIContexts['asterisk.test.com']); server.listen(serverPort, startTest); function startTest() { function connectClient(options, callback) { var client = tls.connect(options, function() { clientResults.push( client.authorizationError && /Hostname\/IP doesn't/.test(client.authorizationError)); client.destroy(); callback(); }); }; connectClient(clientsOptions[0], function() { connectClient(clientsOptions[1], function() { connectClient(clientsOptions[2], function() { server.close(); }); }); }); } process.on('exit', function() { assert.deepEqual(serverResults, ['a.example.com', 'b.test.com', 'c.wrong.com']); assert.deepEqual(clientResults, [true, true, false]); }); node-v0.10.25~dfsg2/test/simple/test-domain-timers.js0000644000000000000000000000371312270121457021154 0ustar rootroot// Copyright Joyent, Inc. and other Node contributors. // // Permission is hereby granted, free of charge, to any person obtaining a // copy of this software and associated documentation files (the // "Software"), to deal in the Software without restriction, including // without limitation the rights to use, copy, modify, merge, publish, // distribute, sublicense, and/or sell copies of the Software, and to permit // persons to whom the Software is furnished to do so, subject to the // following conditions: // // The above copyright notice and this permission notice shall be included // in all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS // OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF // MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN // NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, // DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR // OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE // USE OR OTHER DEALINGS IN THE SOFTWARE. var domain = require('domain'); var assert = require('assert'); var common = require('../common.js'); var timeout_err, timeout, immediate_err; var timeoutd = domain.create(); timeoutd.on('error', function(e) { timeout_err = e; clearTimeout(timeout); }); timeoutd.run(function() { setTimeout(function() { throw new Error('Timeout UNREFd'); }).unref(); }); var immediated = domain.create(); immediated.on('error', function(e) { immediate_err = e; }); immediated.run(function() { setImmediate(function() { throw new Error('Immediate Error'); }); }); timeout = setTimeout(function() {}, 10 * 1000); process.on('exit', function() { assert.equal(timeout_err.message, 'Timeout UNREFd', 'Domain should catch timer error'); assert.equal(immediate_err.message, 'Immediate Error', 'Domain should catch immediate error'); }); node-v0.10.25~dfsg2/test/simple/test-mkdir-rmdir.js0000644000000000000000000000421612270121457020624 0ustar rootroot// Copyright Joyent, Inc. and other Node contributors. // // Permission is hereby granted, free of charge, to any person obtaining a // copy of this software and associated documentation files (the // "Software"), to deal in the Software without restriction, including // without limitation the rights to use, copy, modify, merge, publish, // distribute, sublicense, and/or sell copies of the Software, and to permit // persons to whom the Software is furnished to do so, subject to the // following conditions: // // The above copyright notice and this permission notice shall be included // in all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS // OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF // MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN // NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, // DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR // OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE // USE OR OTHER DEALINGS IN THE SOFTWARE. var common = require('../common'); var assert = require('assert'); var path = require('path'); var fs = require('fs'); var dirname = path.dirname(__filename); var d = path.join(common.tmpDir, 'dir'); var mkdir_error = false; var rmdir_error = false; fs.mkdir(d, 0666, function(err) { if (err) { console.log('mkdir error: ' + err.message); mkdir_error = true; } else { fs.mkdir(d, 0666, function(err) { console.log('expect EEXIST error: ', err); assert.ok(err.message.match(/^EEXIST/), 'got EEXIST message'); assert.equal(err.code, 'EEXIST', 'got EEXIST code'); assert.equal(err.path, d, 'got proper path for EEXIST'); console.log('mkdir okay!'); fs.rmdir(d, function(err) { if (err) { console.log('rmdir error: ' + err.message); rmdir_error = true; } else { console.log('rmdir okay!'); } }); }); } }); process.on('exit', function() { assert.equal(false, mkdir_error); assert.equal(false, rmdir_error); console.log('exit'); }); node-v0.10.25~dfsg2/test/simple/test-script-new.js0000644000000000000000000000533212270121457020476 0ustar rootroot// Copyright Joyent, Inc. and other Node contributors. // // Permission is hereby granted, free of charge, to any person obtaining a // copy of this software and associated documentation files (the // "Software"), to deal in the Software without restriction, including // without limitation the rights to use, copy, modify, merge, publish, // distribute, sublicense, and/or sell copies of the Software, and to permit // persons to whom the Software is furnished to do so, subject to the // following conditions: // // The above copyright notice and this permission notice shall be included // in all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS // OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF // MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN // NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, // DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR // OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE // USE OR OTHER DEALINGS IN THE SOFTWARE. var common = require('../common'); var assert = require('assert'); var Script = require('vm').Script; common.globalCheck = false; common.debug('run a string'); var script = new Script('\'passed\';'); common.debug('script created'); var result1 = script.runInNewContext(); var result2 = script.runInNewContext(); assert.equal('passed', result1); assert.equal('passed', result2); common.debug('thrown error'); script = new Script('throw new Error(\'test\');'); assert.throws(function() { script.runInNewContext(); }); common.debug('undefined reference'); var error; script = new Script('foo.bar = 5;'); try { script.runInNewContext(); } catch (e) { error = e; } assert.ok(error); assert.ok(error.message.indexOf('not defined') >= 0); common.debug('error.message: ' + error.message); hello = 5; script = new Script('hello = 2'); script.runInNewContext(); assert.equal(5, hello); common.debug('pass values in and out'); code = 'foo = 1;' + 'bar = 2;' + 'if (baz !== 3) throw new Error(\'test fail\');'; foo = 2; obj = { foo: 0, baz: 3 }; script = new Script(code); var baz = script.runInNewContext(obj); assert.equal(1, obj.foo); assert.equal(2, obj.bar); assert.equal(2, foo); common.debug('call a function by reference'); script = new Script('f()'); function changeFoo() { foo = 100 } script.runInNewContext({ f: changeFoo }); assert.equal(foo, 100); common.debug('modify an object by reference'); script = new Script('f.a = 2'); var f = { a: 1 }; script.runInNewContext({ f: f }); assert.equal(f.a, 2); common.debug('invalid this'); assert.throws(function() { script.runInNewContext.call('\'hello\';'); }); node-v0.10.25~dfsg2/test/simple/test-fs-readfile-pipe.js0000644000000000000000000000407212270121457021517 0ustar rootroot// Copyright Joyent, Inc. and other Node contributors. // // Permission is hereby granted, free of charge, to any person obtaining a // copy of this software and associated documentation files (the // "Software"), to deal in the Software without restriction, including // without limitation the rights to use, copy, modify, merge, publish, // distribute, sublicense, and/or sell copies of the Software, and to permit // persons to whom the Software is furnished to do so, subject to the // following conditions: // // The above copyright notice and this permission notice shall be included // in all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS // OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF // MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN // NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, // DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR // OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE // USE OR OTHER DEALINGS IN THE SOFTWARE. var common = require('../common'); var assert = require('assert'); // simulate `cat readfile.js | node readfile.js` // TODO: Have some way to make this work on windows. if (process.platform === 'win32') { console.error('No /dev/stdin on windows. Skipping test.'); process.exit(); } var fs = require('fs'); var dataExpected = fs.readFileSync(__filename, 'utf8'); if (process.argv[2] === 'child') { fs.readFile('/dev/stdin', function(er, data) { if (er) throw er; process.stdout.write(data); }); return; } var exec = require('child_process').exec; var f = JSON.stringify(__filename); var node = JSON.stringify(process.execPath); var cmd = 'cat ' + f + ' | ' + node + ' ' + f + ' child'; exec(cmd, function(err, stdout, stderr) { if (err) console.error(err); assert(!err, 'it exits normally'); assert(stdout === dataExpected, 'it reads the file and outputs it'); assert(stderr === '', 'it does not write to stderr'); console.log('ok'); }); node-v0.10.25~dfsg2/test/simple/test-fs-write-sync.js0000644000000000000000000000313012270121457021107 0ustar rootroot// Copyright Joyent, Inc. and other Node contributors. // // Permission is hereby granted, free of charge, to any person obtaining a // copy of this software and associated documentation files (the // "Software"), to deal in the Software without restriction, including // without limitation the rights to use, copy, modify, merge, publish, // distribute, sublicense, and/or sell copies of the Software, and to permit // persons to whom the Software is furnished to do so, subject to the // following conditions: // // The above copyright notice and this permission notice shall be included // in all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS // OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF // MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN // NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, // DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR // OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE // USE OR OTHER DEALINGS IN THE SOFTWARE. var common = require('../common'); var assert = require('assert'); var path = require('path'); var fs = require('fs'); var fn = path.join(common.tmpDir, 'write.txt'); var foo = 'foo'; var fd = fs.openSync(fn, 'w'); var written = fs.writeSync(fd, ''); assert.strictEqual(0, written); fs.writeSync(fd, foo); var bar = 'bár'; written = fs.writeSync(fd, new Buffer(bar), 0, Buffer.byteLength(bar)); assert.ok(written > 3); fs.closeSync(fd); assert.equal(fs.readFileSync(fn), 'foobár'); node-v0.10.25~dfsg2/test/simple/test-net-after-close.js0000644000000000000000000000350212270121457021370 0ustar rootroot// Copyright Joyent, Inc. and other Node contributors. // // Permission is hereby granted, free of charge, to any person obtaining a // copy of this software and associated documentation files (the // "Software"), to deal in the Software without restriction, including // without limitation the rights to use, copy, modify, merge, publish, // distribute, sublicense, and/or sell copies of the Software, and to permit // persons to whom the Software is furnished to do so, subject to the // following conditions: // // The above copyright notice and this permission notice shall be included // in all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS // OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF // MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN // NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, // DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR // OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE // USE OR OTHER DEALINGS IN THE SOFTWARE. var common = require('../common'); var assert = require('assert'); var net = require('net'); var closed = false; var server = net.createServer(function(s) { console.error('SERVER: got connection'); s.end(); }); server.listen(common.PORT, function() { var c = net.createConnection(common.PORT); c.on('close', function() { console.error('connection closed'); assert.strictEqual(c._handle, null); closed = true; assert.doesNotThrow(function() { c.setNoDelay(); c.setKeepAlive(); c.bufferSize; c.pause(); c.resume(); c.address(); c.remoteAddress; c.remotePort; }); server.close(); }); }); process.on('exit', function() { assert(closed); }); node-v0.10.25~dfsg2/test/simple/test-vm-create-context-accessors.js0000644000000000000000000000312112270121457023725 0ustar rootroot// Copyright Joyent, Inc. and other Node contributors. // // Permission is hereby granted, free of charge, to any person obtaining a // copy of this software and associated documentation files (the // "Software"), to deal in the Software without restriction, including // without limitation the rights to use, copy, modify, merge, publish, // distribute, sublicense, and/or sell copies of the Software, and to permit // persons to whom the Software is furnished to do so, subject to the // following conditions: // // The above copyright notice and this permission notice shall be included // in all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS // OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF // MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN // NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, // DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR // OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE // USE OR OTHER DEALINGS IN THE SOFTWARE. var common = require('../common'); var assert = require('assert'); var vm = require('vm'); var ctx = {}; Object.defineProperty(ctx, 'getter', { get: function() { return 'ok'; } }); var val; Object.defineProperty(ctx, 'setter', { set: function(_val) { val = _val; }, get: function() { return 'ok=' + val; } }); ctx = vm.createContext(ctx); var result = vm.runInContext('setter = "test";[getter,setter]', ctx); assert.deepEqual(result, ['ok', 'ok=test']); node-v0.10.25~dfsg2/test/simple/test-fs-open-flags.js0000644000000000000000000000554012270121457021045 0ustar rootroot// Copyright Joyent, Inc. and other Node contributors. // // Permission is hereby granted, free of charge, to any person obtaining a // copy of this software and associated documentation files (the // "Software"), to deal in the Software without restriction, including // without limitation the rights to use, copy, modify, merge, publish, // distribute, sublicense, and/or sell copies of the Software, and to permit // persons to whom the Software is furnished to do so, subject to the // following conditions: // // The above copyright notice and this permission notice shall be included // in all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS // OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF // MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN // NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, // DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR // OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE // USE OR OTHER DEALINGS IN THE SOFTWARE. var common = require('../common'); var assert = require('assert'); var constants = require('constants'); var fs = require('fs'); var O_APPEND = constants.O_APPEND || 0; var O_CREAT = constants.O_CREAT || 0; var O_DIRECTORY = constants.O_DIRECTORY || 0; var O_EXCL = constants.O_EXCL || 0; var O_NOCTTY = constants.O_NOCTTY || 0; var O_NOFOLLOW = constants.O_NOFOLLOW || 0; var O_RDONLY = constants.O_RDONLY || 0; var O_RDWR = constants.O_RDWR || 0; var O_SYMLINK = constants.O_SYMLINK || 0; var O_SYNC = constants.O_SYNC || 0; var O_TRUNC = constants.O_TRUNC || 0; var O_WRONLY = constants.O_WRONLY || 0; assert.equal(fs._stringToFlags('r'), O_RDONLY); assert.equal(fs._stringToFlags('r+'), O_RDWR); assert.equal(fs._stringToFlags('w'), O_TRUNC | O_CREAT | O_WRONLY); assert.equal(fs._stringToFlags('w+'), O_TRUNC | O_CREAT | O_RDWR); assert.equal(fs._stringToFlags('a'), O_APPEND | O_CREAT | O_WRONLY); assert.equal(fs._stringToFlags('a+'), O_APPEND | O_CREAT | O_RDWR); assert.equal(fs._stringToFlags('wx'), O_TRUNC | O_CREAT | O_WRONLY | O_EXCL); assert.equal(fs._stringToFlags('xw'), O_TRUNC | O_CREAT | O_WRONLY | O_EXCL); assert.equal(fs._stringToFlags('wx+'), O_TRUNC | O_CREAT | O_RDWR | O_EXCL); assert.equal(fs._stringToFlags('xw+'), O_TRUNC | O_CREAT | O_RDWR | O_EXCL); assert.equal(fs._stringToFlags('ax'), O_APPEND | O_CREAT | O_WRONLY | O_EXCL); assert.equal(fs._stringToFlags('xa'), O_APPEND | O_CREAT | O_WRONLY | O_EXCL); assert.equal(fs._stringToFlags('ax+'), O_APPEND | O_CREAT | O_RDWR | O_EXCL); assert.equal(fs._stringToFlags('xa+'), O_APPEND | O_CREAT | O_RDWR | O_EXCL); ('+ +a +r +w rw wa war raw r++ a++ w++' + 'x +x x+ rx rx+ wxx wax xwx xxx').split(' ').forEach(function(flags) { assert.throws(function() { fs._stringToFlags(flags); }); }); node-v0.10.25~dfsg2/test/simple/test-dgram-multicast-setTTL.js0000644000000000000000000000316212270121457022654 0ustar rootroot// Copyright Joyent, Inc. and other Node contributors. // // Permission is hereby granted, free of charge, to any person obtaining a // copy of this software and associated documentation files (the // "Software"), to deal in the Software without restriction, including // without limitation the rights to use, copy, modify, merge, publish, // distribute, sublicense, and/or sell copies of the Software, and to permit // persons to whom the Software is furnished to do so, subject to the // following conditions: // // The above copyright notice and this permission notice shall be included // in all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS // OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF // MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN // NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, // DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR // OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE // USE OR OTHER DEALINGS IN THE SOFTWARE. var common = require('../common'), assert = require('assert'), dgram = require('dgram'), thrown = false, socket = dgram.createSocket('udp4'); socket.bind(common.PORT); socket.on('listening', function () { socket.setMulticastTTL(16); //Try to set an invalid TTL (valid ttl is > 0 and < 256) try { socket.setMulticastTTL(1000); } catch (e) { thrown = true; } assert(thrown, 'Setting an invalid multicast TTL should throw some error'); //close the socket socket.close(); }); node-v0.10.25~dfsg2/test/simple/test-fs-readfile-zero-byte-liar.js0000644000000000000000000000354612270121457023434 0ustar rootroot// Copyright Joyent, Inc. and other Node contributors. // // Permission is hereby granted, free of charge, to any person obtaining a // copy of this software and associated documentation files (the // "Software"), to deal in the Software without restriction, including // without limitation the rights to use, copy, modify, merge, publish, // distribute, sublicense, and/or sell copies of the Software, and to permit // persons to whom the Software is furnished to do so, subject to the // following conditions: // // The above copyright notice and this permission notice shall be included // in all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS // OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF // MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN // NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, // DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR // OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE // USE OR OTHER DEALINGS IN THE SOFTWARE. var common = require('../common'); var assert = require('assert'); var fs = require('fs'); var dataExpected = fs.readFileSync(__filename, 'utf8'); // sometimes stat returns size=0, but it's a lie. fs._fstat = fs.fstat; fs._fstatSync = fs.fstatSync; fs.fstat = function(fd, cb) { fs._fstat(fd, function(er, st) { if (er) return cb(er); st.size = 0; return cb(er, st); }); }; fs.fstatSync = function(fd) { var st = fs._fstatSync; st.size = 0; return st; }; var d = fs.readFileSync(__filename, 'utf8'); assert.equal(d, dataExpected); var called = false; fs.readFile(__filename, 'utf8', function (er, d) { assert.equal(d, dataExpected); called = true; }); process.on('exit', function() { assert(called); console.log("ok"); }); node-v0.10.25~dfsg2/test/simple/test-regress-GH-5927.js0000644000000000000000000000303712270121457020755 0ustar rootroot// Copyright Joyent, Inc. and other Node contributors. // // Permission is hereby granted, free of charge, to any person obtaining a // copy of this software and associated documentation files (the // "Software"), to deal in the Software without restriction, including // without limitation the rights to use, copy, modify, merge, publish, // distribute, sublicense, and/or sell copies of the Software, and to permit // persons to whom the Software is furnished to do so, subject to the // following conditions: // // The above copyright notice and this permission notice shall be included // in all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS // OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF // MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN // NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, // DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR // OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE // USE OR OTHER DEALINGS IN THE SOFTWARE. var assert = require('assert'); var readline = require('readline'); var rl = readline.createInterface(process.stdin, process.stdout); rl.resume(); var hasPaused = false; var origPause = rl.pause; rl.pause = function() { hasPaused = true; origPause.apply(this, arguments); } var origSetRawMode = rl._setRawMode; rl._setRawMode = function(mode) { assert.ok(hasPaused); origSetRawMode.apply(this, arguments); } rl.close(); node-v0.10.25~dfsg2/test/simple/test-cluster-bind-twice-v2.js0000644000000000000000000000730512270121457022436 0ustar rootroot// Copyright Joyent, Inc. and other Node contributors. // // Permission is hereby granted, free of charge, to any person obtaining a // copy of this software and associated documentation files (the // "Software"), to deal in the Software without restriction, including // without limitation the rights to use, copy, modify, merge, publish, // distribute, sublicense, and/or sell copies of the Software, and to permit // persons to whom the Software is furnished to do so, subject to the // following conditions: // // The above copyright notice and this permission notice shall be included // in all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS // OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF // MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN // NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, // DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR // OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE // USE OR OTHER DEALINGS IN THE SOFTWARE. // This test starts two clustered HTTP servers on the same port. It expects the // first cluster to succeed and the second cluster to fail with EADDRINUSE. // // The test may seem complex but most of it is plumbing that routes messages // from the child processes back to the supervisor. As a tree it looks something // like this: // // // / \ // // / \ // // // The first worker starts a server on a fixed port and fires a ready message // that is routed to the second worker. When it tries to bind, it expects to // see an EADDRINUSE error. // // See https://github.com/joyent/node/issues/2721 for more details. var common = require('../common'); var assert = require('assert'); var cluster = require('cluster'); var fork = require('child_process').fork; var http = require('http'); var id = process.argv[2]; if (!id) { var a = fork(__filename, ['one']); var b = fork(__filename, ['two']); a.on('exit', function(c) { if (c) throw new Error('A exited with ' + c); }); b.on('exit', function(c) { if (c) throw new Error('B exited with ' + c); }); a.on('message', function(m) { if (typeof m === 'object') return; assert.equal(m, 'READY'); b.send('START'); }); var ok = false; b.on('message', function(m) { if (typeof m === 'object') return; // ignore system messages assert.equal(m, 'EADDRINUSE'); a.kill(); b.kill(); ok = true; }); process.on('exit', function() { a.kill(); b.kill(); assert(ok); }); } else if (id === 'one') { if (cluster.isMaster) return startWorker(); http.createServer(assert.fail).listen(common.PORT, function() { process.send('READY'); }); } else if (id === 'two') { if (cluster.isMaster) return startWorker(); var ok = false; process.on('SIGTERM', process.exit); process.on('exit', function() { assert(ok); }); process.on('message', function(m) { if (typeof m === 'object') return; // ignore system messages assert.equal(m, 'START'); var server = http.createServer(assert.fail); server.listen(common.PORT, assert.fail); server.on('error', function(e) { assert.equal(e.code, 'EADDRINUSE'); process.send(e.code); ok = true; }); }); } else { assert(0); // bad command line argument } function startWorker() { var worker = cluster.fork(); worker.on('message', process.send.bind(process)); process.on('message', worker.send.bind(worker)); process.on('SIGTERM', function() { worker.destroy(); process.exit(); }); } node-v0.10.25~dfsg2/test/simple/test-utf8-scripts.js0000644000000000000000000000247312270121457020761 0ustar rootroot// Copyright Joyent, Inc. and other Node contributors. // // Permission is hereby granted, free of charge, to any person obtaining a // copy of this software and associated documentation files (the // "Software"), to deal in the Software without restriction, including // without limitation the rights to use, copy, modify, merge, publish, // distribute, sublicense, and/or sell copies of the Software, and to permit // persons to whom the Software is furnished to do so, subject to the // following conditions: // // The above copyright notice and this permission notice shall be included // in all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS // OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF // MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN // NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, // DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR // OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE // USE OR OTHER DEALINGS IN THE SOFTWARE. var common = require('../common'); var assert = require('assert'); // üäö console.log('Σὲ γνωρίζω ἀπὸ τὴν κόψη'); assert.equal(true, /Hellö Wörld/.test('Hellö Wörld')); node-v0.10.25~dfsg2/test/simple/test-net-server-close.js0000644000000000000000000000401612270121457021576 0ustar rootroot// Copyright Joyent, Inc. and other Node contributors. // // Permission is hereby granted, free of charge, to any person obtaining a // copy of this software and associated documentation files (the // "Software"), to deal in the Software without restriction, including // without limitation the rights to use, copy, modify, merge, publish, // distribute, sublicense, and/or sell copies of the Software, and to permit // persons to whom the Software is furnished to do so, subject to the // following conditions: // // The above copyright notice and this permission notice shall be included // in all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS // OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF // MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN // NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, // DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR // OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE // USE OR OTHER DEALINGS IN THE SOFTWARE. var common = require('../common'); var assert = require('assert'); var net = require('net'); var events = []; var sockets = []; process.on('exit', function() { assert.equal(server.connections, 0); assert.equal(events.length, 3); // Expect to see one server event and two client events. The order of the // events is undefined because they arrive on the same event loop tick. assert.equal(events.join(' ').match(/server/g).length, 1); assert.equal(events.join(' ').match(/client/g).length, 2); }); var server = net.createServer(function(c) { c.on('close', function() { events.push('client'); }); sockets.push(c); if (sockets.length === 2) { server.close(); sockets.forEach(function(c) { c.destroy() }); } }); server.on('close', function() { events.push('server'); }); server.listen(common.PORT, function() { net.createConnection(common.PORT); net.createConnection(common.PORT); }); node-v0.10.25~dfsg2/test/simple/test-script-this.js0000644000000000000000000000411612270121457020653 0ustar rootroot// Copyright Joyent, Inc. and other Node contributors. // // Permission is hereby granted, free of charge, to any person obtaining a // copy of this software and associated documentation files (the // "Software"), to deal in the Software without restriction, including // without limitation the rights to use, copy, modify, merge, publish, // distribute, sublicense, and/or sell copies of the Software, and to permit // persons to whom the Software is furnished to do so, subject to the // following conditions: // // The above copyright notice and this permission notice shall be included // in all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS // OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF // MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN // NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, // DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR // OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE // USE OR OTHER DEALINGS IN THE SOFTWARE. var common = require('../common'); var assert = require('assert'); var Script = require('vm').Script; common.globalCheck = false; common.debug('run a string'); var script = new Script('\'passed\';'); var result = script.runInThisContext(script); assert.equal('passed', result); common.debug('thrown error'); script = new Script('throw new Error(\'test\');'); assert.throws(function() { script.runInThisContext(script); }); hello = 5; script = new Script('hello = 2'); script.runInThisContext(script); assert.equal(2, hello); common.debug('pass values'); code = 'foo = 1;' + 'bar = 2;' + 'if (typeof baz !== \'undefined\') throw new Error(\'test fail\');'; foo = 2; obj = { foo: 0, baz: 3 }; script = new Script(code); script.runInThisContext(script); assert.equal(0, obj.foo); assert.equal(2, bar); assert.equal(1, foo); common.debug('call a function'); f = function() { foo = 100 }; script = new Script('f()'); script.runInThisContext(script); assert.equal(100, foo); node-v0.10.25~dfsg2/test/simple/test-process-getgroups.js0000644000000000000000000000347212270121457022101 0ustar rootroot// Copyright Joyent, Inc. and other Node contributors. // // Permission is hereby granted, free of charge, to any person obtaining a // copy of this software and associated documentation files (the // "Software"), to deal in the Software without restriction, including // without limitation the rights to use, copy, modify, merge, publish, // distribute, sublicense, and/or sell copies of the Software, and to permit // persons to whom the Software is furnished to do so, subject to the // following conditions: // // The above copyright notice and this permission notice shall be included // in all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS // OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF // MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN // NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, // DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR // OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE // USE OR OTHER DEALINGS IN THE SOFTWARE. var common = require('../common'); var assert = require('assert'); var exec = require('child_process').exec; if (process.platform === 'darwin') { console.log('Skipping. Output of `id -G` is unreliable on Darwin.'); return; } if (typeof process.getgroups === 'function') { var groups = process.getgroups(); assert(Array.isArray(groups)); assert(groups.length > 0); exec('id -G', function(err, stdout) { if (err) throw err; var real_groups = stdout.match(/\d+/g).map(Number); assert.equal(groups.length, real_groups.length); check(groups, real_groups); check(real_groups, groups); }); } function check(a, b) { for (var i = 0; i < a.length; ++i) assert(b.indexOf(a[i]) !== -1); } node-v0.10.25~dfsg2/test/simple/test-tls-invalid-key.js0000644000000000000000000000417412270121457021422 0ustar rootroot// Copyright Joyent, Inc. and other Node contributors. // // Permission is hereby granted, free of charge, to any person obtaining a // copy of this software and associated documentation files (the // "Software"), to deal in the Software without restriction, including // without limitation the rights to use, copy, modify, merge, publish, // distribute, sublicense, and/or sell copies of the Software, and to permit // persons to whom the Software is furnished to do so, subject to the // following conditions: // // The above copyright notice and this permission notice shall be included // in all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS // OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF // MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN // NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, // DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR // OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE // USE OR OTHER DEALINGS IN THE SOFTWARE. if (!process.versions.openssl) { console.error('Skipping because node compiled without OpenSSL.'); process.exit(0); } var common = require('../common'); var assert = require('assert'); var tls = require('tls'); var fs = require('fs'); var path = require('path'); var options = { key: fs.readFileSync(path.join(common.fixturesDir, 'keys/agent1-key.pem')), cert: fs.readFileSync(path.join(common.fixturesDir, 'test_cert.pem')) }; var serverErrorHappened = false; var clientErrorHappened = false; var server = tls.Server(options, function(socket) { assert(false); }); server.on('clientError', function(err) { serverErrorHappened = true; common.debug('Server: ' + err); server.close(); }); server.listen(common.PORT, function() { var client = tls.connect(common.PORT, function() { assert(false); }); client.on('error', function(err) { clientErrorHappened = true; common.debug('Client: ' + err); }); }); process.on('exit', function() { assert(serverErrorHappened); assert(clientErrorHappened); }); node-v0.10.25~dfsg2/test/simple/test-readint.js0000644000000000000000000000712212270121457020030 0ustar rootroot// Copyright Joyent, Inc. and other Node contributors. // // Permission is hereby granted, free of charge, to any person obtaining a // copy of this software and associated documentation files (the // "Software"), to deal in the Software without restriction, including // without limitation the rights to use, copy, modify, merge, publish, // distribute, sublicense, and/or sell copies of the Software, and to permit // persons to whom the Software is furnished to do so, subject to the // following conditions: // // The above copyright notice and this permission notice shall be included // in all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS // OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF // MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN // NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, // DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR // OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE // USE OR OTHER DEALINGS IN THE SOFTWARE. /* * Tests to verify we're reading in signed integers correctly */ var SlowBuffer = process.binding('buffer').SlowBuffer; var common = require('../common'); var ASSERT = require('assert'); /* * Test 8 bit signed integers */ function test8(clazz) { var data = new clazz(4); data[0] = 0x23; ASSERT.equal(0x23, data.readInt8(0)); data[0] = 0xff; ASSERT.equal(-1, data.readInt8(0)); data[0] = 0x87; data[1] = 0xab; data[2] = 0x7c; data[3] = 0xef; ASSERT.equal(-121, data.readInt8(0)); ASSERT.equal(-85, data.readInt8(1)); ASSERT.equal(124, data.readInt8(2)); ASSERT.equal(-17, data.readInt8(3)); } function test16(clazz) { var buffer = new clazz(6); buffer[0] = 0x16; buffer[1] = 0x79; ASSERT.equal(0x1679, buffer.readInt16BE(0)); ASSERT.equal(0x7916, buffer.readInt16LE(0)); buffer[0] = 0xff; buffer[1] = 0x80; ASSERT.equal(-128, buffer.readInt16BE(0)); ASSERT.equal(-32513, buffer.readInt16LE(0)); /* test offset with weenix */ buffer[0] = 0x77; buffer[1] = 0x65; buffer[2] = 0x65; buffer[3] = 0x6e; buffer[4] = 0x69; buffer[5] = 0x78; ASSERT.equal(0x7765, buffer.readInt16BE(0)); ASSERT.equal(0x6565, buffer.readInt16BE(1)); ASSERT.equal(0x656e, buffer.readInt16BE(2)); ASSERT.equal(0x6e69, buffer.readInt16BE(3)); ASSERT.equal(0x6978, buffer.readInt16BE(4)); ASSERT.equal(0x6577, buffer.readInt16LE(0)); ASSERT.equal(0x6565, buffer.readInt16LE(1)); ASSERT.equal(0x6e65, buffer.readInt16LE(2)); ASSERT.equal(0x696e, buffer.readInt16LE(3)); ASSERT.equal(0x7869, buffer.readInt16LE(4)); } function test32(clazz) { var buffer = new clazz(6); buffer[0] = 0x43; buffer[1] = 0x53; buffer[2] = 0x16; buffer[3] = 0x79; ASSERT.equal(0x43531679, buffer.readInt32BE(0)); ASSERT.equal(0x79165343, buffer.readInt32LE(0)); buffer[0] = 0xff; buffer[1] = 0xfe; buffer[2] = 0xef; buffer[3] = 0xfa; ASSERT.equal(-69638, buffer.readInt32BE(0)); ASSERT.equal(-84934913, buffer.readInt32LE(0)); buffer[0] = 0x42; buffer[1] = 0xc3; buffer[2] = 0x95; buffer[3] = 0xa9; buffer[4] = 0x36; buffer[5] = 0x17; ASSERT.equal(0x42c395a9, buffer.readInt32BE(0)); ASSERT.equal(-1013601994, buffer.readInt32BE(1)); ASSERT.equal(-1784072681, buffer.readInt32BE(2)); ASSERT.equal(-1449802942, buffer.readInt32LE(0)); ASSERT.equal(917083587, buffer.readInt32LE(1)); ASSERT.equal(389458325, buffer.readInt32LE(2)); } test8(Buffer); test8(SlowBuffer); test16(Buffer); test16(SlowBuffer); test32(Buffer); test32(SlowBuffer); node-v0.10.25~dfsg2/test/simple/test-process-exit.js0000644000000000000000000000264412270121457021033 0ustar rootroot// Copyright Joyent, Inc. and other Node contributors. // // Permission is hereby granted, free of charge, to any person obtaining a // copy of this software and associated documentation files (the // "Software"), to deal in the Software without restriction, including // without limitation the rights to use, copy, modify, merge, publish, // distribute, sublicense, and/or sell copies of the Software, and to permit // persons to whom the Software is furnished to do so, subject to the // following conditions: // // The above copyright notice and this permission notice shall be included // in all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS // OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF // MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN // NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, // DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR // OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE // USE OR OTHER DEALINGS IN THE SOFTWARE. var common = require('../common'); var assert = require('assert'); // calling .exit() from within "exit" should not overflow the call stack var nexits = 0; process.on('exit', function(code) { assert.equal(nexits++, 0); assert.equal(code, 0); process.exit(); }); // "exit" should be emitted unprovoked node-v0.10.25~dfsg2/test/simple/test-cluster-net-send.js0000644000000000000000000000425312270121457021600 0ustar rootroot// Copyright Joyent, Inc. and other Node contributors. // // Permission is hereby granted, free of charge, to any person obtaining a // copy of this software and associated documentation files (the // "Software"), to deal in the Software without restriction, including // without limitation the rights to use, copy, modify, merge, publish, // distribute, sublicense, and/or sell copies of the Software, and to permit // persons to whom the Software is furnished to do so, subject to the // following conditions: // // The above copyright notice and this permission notice shall be included // in all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS // OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF // MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN // NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, // DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR // OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE // USE OR OTHER DEALINGS IN THE SOFTWARE. var common = require('../common'); var assert = require('assert'); var fork = require('child_process').fork; var net = require('net'); if (process.argv[2] !== 'child') { console.error('[%d] master', process.pid); var worker = fork(__filename, ['child']); var called = false; worker.once('message', function(msg, handle) { assert.equal(msg, 'handle'); assert.ok(handle); worker.send('got'); handle.on('data', function(data) { called = true; assert.equal(data.toString(), 'hello'); worker.kill(); }); }); process.once('exit', function() { assert.ok(called); }); } else { console.error('[%d] worker', process.pid); var server = net.createServer(function(c) { process.once('message', function(msg) { assert.equal(msg, 'got'); c.end('hello'); }); }); server.listen(common.PORT, function() { var socket = net.connect(common.PORT, '127.0.0.1', function() { process.send('handle', socket); }); }); process.on('disconnect', function() { process.exit(); server.close(); }); } node-v0.10.25~dfsg2/test/simple/test-fs-error-messages.js0000644000000000000000000001156512270121457021754 0ustar rootroot// Copyright Joyent, Inc. and other Node contributors. // // Permission is hereby granted, free of charge, to any person obtaining a // copy of this software and associated documentation files (the // "Software"), to deal in the Software without restriction, including // without limitation the rights to use, copy, modify, merge, publish, // distribute, sublicense, and/or sell copies of the Software, and to permit // persons to whom the Software is furnished to do so, subject to the // following conditions: // // The above copyright notice and this permission notice shall be included // in all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS // OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF // MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN // NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, // DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR // OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE // USE OR OTHER DEALINGS IN THE SOFTWARE. var common = require('../common'); var assert = require('assert'); var path = require('path'), fs = require('fs'), fn = path.join(common.fixturesDir, 'non-existent'), existingFile = path.join(common.fixturesDir, 'exit.js'), existingFile2 = path.join(common.fixturesDir, 'create-file.js'), existingDir = path.join(common.fixturesDir, 'empty'), existingDir2 = path.join(common.fixturesDir, 'keys'); // ASYNC_CALL fs.stat(fn, function(err) { assert.equal(fn, err.path); assert.ok(0 <= err.message.indexOf(fn)); }); fs.lstat(fn, function(err) { assert.ok(0 <= err.message.indexOf(fn)); }); fs.readlink(fn, function(err) { assert.ok(0 <= err.message.indexOf(fn)); }); fs.link(fn, 'foo', function(err) { assert.ok(0 <= err.message.indexOf(fn)); }); fs.link(existingFile, existingFile2, function(err) { assert.ok(0 <= err.message.indexOf(existingFile2)); }); fs.unlink(fn, function(err) { assert.ok(0 <= err.message.indexOf(fn)); }); fs.rename(fn, 'foo', function(err) { assert.ok(0 <= err.message.indexOf(fn)); }); fs.rename(existingDir, existingDir2, function(err) { assert.ok(0 <= err.message.indexOf(existingDir2)); }); fs.rmdir(fn, function(err) { assert.ok(0 <= err.message.indexOf(fn)); }); fs.mkdir(existingFile, 0666, function(err) { assert.ok(0 <= err.message.indexOf(existingFile)); }); fs.rmdir(existingFile, function(err) { assert.ok(0 <= err.message.indexOf(existingFile)); }); fs.chmod(fn, 0666, function(err) { assert.ok(0 <= err.message.indexOf(fn)); }); fs.open(fn, 'r', 0666, function(err) { assert.ok(0 <= err.message.indexOf(fn)); }); fs.readFile(fn, function(err) { assert.ok(0 <= err.message.indexOf(fn)); }); // Sync var errors = [], expected = 0; try { ++expected; fs.statSync(fn); } catch (err) { errors.push('stat'); assert.ok(0 <= err.message.indexOf(fn)); } try { ++expected; fs.mkdirSync(existingFile, 0666); } catch (err) { errors.push('mkdir'); assert.ok(0 <= err.message.indexOf(existingFile)); } try { ++expected; fs.chmodSync(fn, 0666); } catch (err) { errors.push('chmod'); assert.ok(0 <= err.message.indexOf(fn)); } try { ++expected; fs.lstatSync(fn); } catch (err) { errors.push('lstat'); assert.ok(0 <= err.message.indexOf(fn)); } try { ++expected; fs.readlinkSync(fn); } catch (err) { errors.push('readlink'); assert.ok(0 <= err.message.indexOf(fn)); } try { ++expected; fs.linkSync(fn, 'foo'); } catch (err) { errors.push('link'); assert.ok(0 <= err.message.indexOf(fn)); } try { ++expected; fs.linkSync(existingFile, existingFile2); } catch (err) { errors.push('link'); assert.ok(0 <= err.message.indexOf(existingFile2)); } try { ++expected; fs.unlinkSync(fn); } catch (err) { errors.push('unlink'); assert.ok(0 <= err.message.indexOf(fn)); } try { ++expected; fs.rmdirSync(fn); } catch (err) { errors.push('rmdir'); assert.ok(0 <= err.message.indexOf(fn)); } try { ++expected; fs.rmdirSync(existingFile); } catch (err) { errors.push('rmdir'); assert.ok(0 <= err.message.indexOf(existingFile)); } try { ++expected; fs.openSync(fn, 'r'); } catch (err) { errors.push('opens'); assert.ok(0 <= err.message.indexOf(fn)); } try { ++expected; fs.renameSync(fn, 'foo'); } catch (err) { errors.push('rename'); assert.ok(0 <= err.message.indexOf(fn)); } try { ++expected; fs.renameSync(existingDir, existingDir2); } catch (err) { errors.push('rename'); assert.ok(0 <= err.message.indexOf(existingDir2)); } try { ++expected; fs.readdirSync(fn); } catch (err) { errors.push('readdir'); assert.ok(0 <= err.message.indexOf(fn)); } process.on('exit', function() { assert.equal(expected, errors.length, 'Test fs sync exceptions raised, got ' + errors.length + ' expected ' + expected); }); node-v0.10.25~dfsg2/test/simple/test-event-emitter-subclass.js0000644000000000000000000000336712270121457023016 0ustar rootroot// Copyright Joyent, Inc. and other Node contributors. // // Permission is hereby granted, free of charge, to any person obtaining a // copy of this software and associated documentation files (the // "Software"), to deal in the Software without restriction, including // without limitation the rights to use, copy, modify, merge, publish, // distribute, sublicense, and/or sell copies of the Software, and to permit // persons to whom the Software is furnished to do so, subject to the // following conditions: // // The above copyright notice and this permission notice shall be included // in all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS // OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF // MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN // NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, // DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR // OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE // USE OR OTHER DEALINGS IN THE SOFTWARE. var common = require('../common'); var assert = require('assert'); var EventEmitter = require('events').EventEmitter; var util = require('util'); util.inherits(MyEE, EventEmitter); function MyEE(cb) { this.once(1, cb); this.emit(1); this.removeAllListeners(); EventEmitter.call(this); } var called = false; var myee = new MyEE(function() { called = true; }); util.inherits(ErrorEE, EventEmitter); function ErrorEE() { this.emit('error', new Error('blerg')); } assert.throws(function() { new ErrorEE(); }, /blerg/); process.on('exit', function() { assert(called); assert.deepEqual(myee._events, {}); console.log('ok'); }); node-v0.10.25~dfsg2/test/simple/test-crypto-random.js0000644000000000000000000000464412270121457021206 0ustar rootroot// Copyright Joyent, Inc. and other Node contributors. // // Permission is hereby granted, free of charge, to any person obtaining a // copy of this software and associated documentation files (the // "Software"), to deal in the Software without restriction, including // without limitation the rights to use, copy, modify, merge, publish, // distribute, sublicense, and/or sell copies of the Software, and to permit // persons to whom the Software is furnished to do so, subject to the // following conditions: // // The above copyright notice and this permission notice shall be included // in all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS // OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF // MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN // NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, // DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR // OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE // USE OR OTHER DEALINGS IN THE SOFTWARE. var common = require('../common'); var assert = require('assert'); try { var crypto = require('crypto'); } catch (e) { console.log('Not compiled with OPENSSL support.'); process.exit(); } crypto.DEFAULT_ENCODING = 'buffer'; // bump, we register a lot of exit listeners process.setMaxListeners(256); [crypto.randomBytes, crypto.pseudoRandomBytes ].forEach(function(f) { [-1, undefined, null, false, true, {}, [] ].forEach(function(value) { assert.throws(function() { f(value); }); assert.throws(function() { f(value, function() {}); }); }); [0, 1, 2, 4, 16, 256, 1024].forEach(function(len) { f(len, checkCall(function(ex, buf) { assert.equal(null, ex); assert.equal(len, buf.length); assert.ok(Buffer.isBuffer(buf)); })); }); }); // assert that the callback is indeed called function checkCall(cb, desc) { var called_ = false; process.on('exit', function() { assert.equal(true, called_, desc || ('callback not called: ' + cb)); }); return function() { return called_ = true, cb.apply(cb, Array.prototype.slice.call(arguments)); }; } // #5126, "FATAL ERROR: v8::Object::SetIndexedPropertiesToExternalArrayData() // length exceeds max acceptable value" assert.throws(function() { crypto.randomBytes(0x3fffffff + 1); }, TypeError); node-v0.10.25~dfsg2/test/simple/test-event-emitter-modify-in-emit.js0000644000000000000000000000506112270121457024017 0ustar rootroot// Copyright Joyent, Inc. and other Node contributors. // // Permission is hereby granted, free of charge, to any person obtaining a // copy of this software and associated documentation files (the // "Software"), to deal in the Software without restriction, including // without limitation the rights to use, copy, modify, merge, publish, // distribute, sublicense, and/or sell copies of the Software, and to permit // persons to whom the Software is furnished to do so, subject to the // following conditions: // // The above copyright notice and this permission notice shall be included // in all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS // OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF // MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN // NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, // DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR // OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE // USE OR OTHER DEALINGS IN THE SOFTWARE. var common = require('../common'); var assert = require('assert'); var events = require('events'); var callbacks_called = []; var e = new events.EventEmitter(); function callback1() { callbacks_called.push('callback1'); e.on('foo', callback2); e.on('foo', callback3); e.removeListener('foo', callback1); } function callback2() { callbacks_called.push('callback2'); e.removeListener('foo', callback2); } function callback3() { callbacks_called.push('callback3'); e.removeListener('foo', callback3); } e.on('foo', callback1); assert.equal(1, e.listeners('foo').length); e.emit('foo'); assert.equal(2, e.listeners('foo').length); assert.deepEqual(['callback1'], callbacks_called); e.emit('foo'); assert.equal(0, e.listeners('foo').length); assert.deepEqual(['callback1', 'callback2', 'callback3'], callbacks_called); e.emit('foo'); assert.equal(0, e.listeners('foo').length); assert.deepEqual(['callback1', 'callback2', 'callback3'], callbacks_called); e.on('foo', callback1); e.on('foo', callback2); assert.equal(2, e.listeners('foo').length); e.removeAllListeners('foo'); assert.equal(0, e.listeners('foo').length); // Verify that removing callbacks while in emit allows emits to propagate to // all listeners callbacks_called = []; e.on('foo', callback2); e.on('foo', callback3); assert.equal(2, e.listeners('foo').length); e.emit('foo'); assert.deepEqual(['callback2', 'callback3'], callbacks_called); assert.equal(0, e.listeners('foo').length); node-v0.10.25~dfsg2/test/simple/test-http-after-connect.js0000644000000000000000000000527512270121457022116 0ustar rootroot// Copyright Joyent, Inc. and other Node contributors. // // Permission is hereby granted, free of charge, to any person obtaining a // copy of this software and associated documentation files (the // "Software"), to deal in the Software without restriction, including // without limitation the rights to use, copy, modify, merge, publish, // distribute, sublicense, and/or sell copies of the Software, and to permit // persons to whom the Software is furnished to do so, subject to the // following conditions: // // The above copyright notice and this permission notice shall be included // in all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS // OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF // MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN // NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, // DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR // OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE // USE OR OTHER DEALINGS IN THE SOFTWARE. var common = require('../common'); var assert = require('assert'); var http = require('http'); var serverConnected = false; var serverRequests = 0; var clientResponses = 0; var server = http.createServer(function(req, res) { common.debug('Server got GET request'); ++serverRequests; res.writeHead(200); res.write(''); setTimeout(function() { res.end(req.url); }, 50); }); server.on('connect', function(req, socket, firstBodyChunk) { common.debug('Server got CONNECT request'); serverConnected = true; socket.write('HTTP/1.1 200 Connection established\r\n\r\n'); socket.on('end', function() { socket.end(); }); }); server.listen(common.PORT, function() { var req = http.request({ port: common.PORT, method: 'CONNECT', path: 'google.com:80' }); req.on('connect', function(res, socket, firstBodyChunk) { common.debug('Client got CONNECT response'); socket.end(); socket.on('end', function() { doRequest(0); doRequest(1); }); }); req.end(); }); function doRequest(i) { var req = http.get({ port: common.PORT, path: '/request' + i }, function(res) { common.debug('Client got GET response'); var data = ''; res.setEncoding('utf8'); res.on('data', function(chunk) { data += chunk; }); res.on('end', function() { assert.equal(data, '/request' + i); ++clientResponses; if (clientResponses === 2) { server.close(); } }); }); } process.on('exit', function() { assert(serverConnected); assert.equal(serverRequests, 2); assert.equal(clientResponses, 2); }); node-v0.10.25~dfsg2/test/simple/test-child-process-fork-net2.js0000644000000000000000000001160212270121457022744 0ustar rootroot// Copyright Joyent, Inc. and other Node contributors. // // Permission is hereby granted, free of charge, to any person obtaining a // copy of this software and associated documentation files (the // "Software"), to deal in the Software without restriction, including // without limitation the rights to use, copy, modify, merge, publish, // distribute, sublicense, and/or sell copies of the Software, and to permit // persons to whom the Software is furnished to do so, subject to the // following conditions: // // The above copyright notice and this permission notice shall be included // in all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS // OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF // MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN // NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, // DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR // OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE // USE OR OTHER DEALINGS IN THE SOFTWARE. var assert = require('assert'); var common = require('../common'); var fork = require('child_process').fork; var net = require('net'); var count = 12; if (process.argv[2] === 'child') { var needEnd = []; var id = process.argv[3]; process.on('message', function(m, socket) { if (!socket) return; console.error('[%d] got socket', id, m); // will call .end('end') or .write('write'); socket[m](m); socket.resume(); socket.on('data', function() { console.error('[%d] socket.data', id, m); }); socket.on('end', function() { console.error('[%d] socket.end', id, m); }); // store the unfinished socket if (m === 'write') { needEnd.push(socket); } socket.on('close', function() { console.error('[%d] socket.close', id, m); }); socket.on('finish', function() { console.error('[%d] socket finished', id, m); }); }); process.on('message', function(m) { if (m !== 'close') return; console.error('[%d] got close message', id); needEnd.forEach(function(endMe, i) { console.error('[%d] ending %d', id, i); endMe.end('end'); }); }); process.on('disconnect', function() { console.error('[%d] process disconnect, ending', id); needEnd.forEach(function(endMe, i) { console.error('[%d] ending %d', id, i); endMe.end('end'); }); }); } else { var child1 = fork(process.argv[1], ['child', '1']); var child2 = fork(process.argv[1], ['child', '2']); var child3 = fork(process.argv[1], ['child', '3']); var server = net.createServer(); var connected = 0, closed = 0; server.on('connection', function(socket) { switch (connected % 6) { case 0: child1.send('end', socket, { track: false }); break; case 1: child1.send('write', socket, { track: true }); break; case 2: child2.send('end', socket, { track: true }); break; case 3: child2.send('write', socket, { track: false }); break; case 4: child3.send('end', socket, { track: false }); break; case 5: child3.send('write', socket, { track: false }); break; } connected += 1; socket.once('close', function() { console.log('[m] socket closed, total %d', ++closed); }); if (connected === count) { closeServer(); } }); var disconnected = 0; server.on('listening', function() { var j = count, client; while (j--) { client = net.connect(common.PORT, '127.0.0.1'); client.on('close', function() { console.error('[m] CLIENT: close event'); disconnected += 1; }); // XXX This resume() should be unnecessary. // a stream high water mark should be enough to keep // consuming the input. client.resume(); } }); var closeEmitted = false; server.on('close', function() { console.error('[m] server close'); closeEmitted = true; child1.kill(); child2.kill(); child3.kill(); }); server.listen(common.PORT, '127.0.0.1'); var timeElasped = 0; var closeServer = function() { console.error('[m] closeServer'); var startTime = Date.now(); server.on('close', function() { console.error('[m] emit(close)'); timeElasped = Date.now() - startTime; }); console.error('[m] calling server.close'); server.close(); setTimeout(function() { assert(!closeEmitted); console.error('[m] sending close to children'); child1.send('close'); child2.send('close'); child3.disconnect(); }, 200); }; process.on('exit', function() { assert.equal(disconnected, count); assert.equal(connected, count); assert.ok(closeEmitted); assert.ok(timeElasped >= 190 && timeElasped <= 1000, 'timeElasped was not between 190 and 1000 ms'); }); } node-v0.10.25~dfsg2/test/simple/test-domain-safe-exit.js0000644000000000000000000000275212270121457021540 0ustar rootroot// Copyright Joyent, Inc. and other Node contributors. // // Permission is hereby granted, free of charge, to any person obtaining a // copy of this software and associated documentation files (the // "Software"), to deal in the Software without restriction, including // without limitation the rights to use, copy, modify, merge, publish, // distribute, sublicense, and/or sell copies of the Software, and to permit // persons to whom the Software is furnished to do so, subject to the // following conditions: // // The above copyright notice and this permission notice shall be included // in all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS // OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF // MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN // NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, // DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR // OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE // USE OR OTHER DEALINGS IN THE SOFTWARE. // Make sure the domain stack doesn't get clobbered by un-matched .exit() var assert = require('assert'); var domain = require('domain'); var a = domain.create(); var b = domain.create(); a.enter(); // push b.enter(); // push assert.deepEqual(domain._stack, [a, b], 'b not pushed'); domain.create().exit(); // no-op assert.deepEqual(domain._stack, [a, b], 'stack mangled!'); node-v0.10.25~dfsg2/test/simple/test-stream-pipe-event.js0000644000000000000000000000315712270121457021753 0ustar rootroot// Copyright Joyent, Inc. and other Node contributors. // // Permission is hereby granted, free of charge, to any person obtaining a // copy of this software and associated documentation files (the // "Software"), to deal in the Software without restriction, including // without limitation the rights to use, copy, modify, merge, publish, // distribute, sublicense, and/or sell copies of the Software, and to permit // persons to whom the Software is furnished to do so, subject to the // following conditions: // // The above copyright notice and this permission notice shall be included // in all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS // OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF // MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN // NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, // DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR // OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE // USE OR OTHER DEALINGS IN THE SOFTWARE. var common = require('../common'); var stream = require('stream'); var assert = require('assert'); var util = require('util'); function Writable() { this.writable = true; stream.Stream.call(this); } util.inherits(Writable, stream.Stream); function Readable() { this.readable = true; stream.Stream.call(this); } util.inherits(Readable, stream.Stream); var passed = false; var w = new Writable(); w.on('pipe', function(src) { passed = true; }); var r = new Readable(); r.pipe(w); assert.ok(passed); node-v0.10.25~dfsg2/test/simple/test-tls-connect-pipe.js0000644000000000000000000000351212270121457021565 0ustar rootroot// Copyright Joyent, Inc. and other Node contributors. // // Permission is hereby granted, free of charge, to any person obtaining a // copy of this software and associated documentation files (the // "Software"), to deal in the Software without restriction, including // without limitation the rights to use, copy, modify, merge, publish, // distribute, sublicense, and/or sell copies of the Software, and to permit // persons to whom the Software is furnished to do so, subject to the // following conditions: // // The above copyright notice and this permission notice shall be included // in all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS // OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF // MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN // NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, // DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR // OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE // USE OR OTHER DEALINGS IN THE SOFTWARE. var common = require('../common'); var assert = require('assert'); var tls = require('tls'); var fs = require('fs'); var clientConnected = 0; var serverConnected = 0; var options = { key: fs.readFileSync(common.fixturesDir + '/keys/agent1-key.pem'), cert: fs.readFileSync(common.fixturesDir + '/keys/agent1-cert.pem') }; var server = tls.Server(options, function(socket) { ++serverConnected; server.close(); }); server.listen(common.PIPE, function() { var options = { rejectUnauthorized: false }; var client = tls.connect(common.PIPE, options, function() { ++clientConnected; client.end(); }); }); process.on('exit', function() { assert.equal(clientConnected, 1); assert.equal(serverConnected, 1); }); node-v0.10.25~dfsg2/test/simple/test-net-write-connect-write.js0000644000000000000000000000330412270121457023075 0ustar rootroot// Copyright Joyent, Inc. and other Node contributors. // // Permission is hereby granted, free of charge, to any person obtaining a // copy of this software and associated documentation files (the // "Software"), to deal in the Software without restriction, including // without limitation the rights to use, copy, modify, merge, publish, // distribute, sublicense, and/or sell copies of the Software, and to permit // persons to whom the Software is furnished to do so, subject to the // following conditions: // // The above copyright notice and this permission notice shall be included // in all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS // OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF // MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN // NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, // DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR // OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE // USE OR OTHER DEALINGS IN THE SOFTWARE. var common = require('../common'); var assert = require('assert'); var net = require('net'); var received = ''; var server = net.createServer(function(socket) { socket.pipe(socket); }).listen(common.PORT, function() { var conn = net.connect(common.PORT); conn.setEncoding('utf8'); conn.write('before'); conn.on('connect', function() { conn.write('after'); }); conn.on('data', function(buf) { received += buf; conn.end(); }); conn.on('end', function() { server.close(); }); }); process.on('exit', function() { assert.equal(received, 'before' + 'after'); }); node-v0.10.25~dfsg2/test/simple/test-child-process-send-utf8.js0000644000000000000000000000274412270121457022761 0ustar rootroot// Copyright Joyent, Inc. and other Node contributors. // // Permission is hereby granted, free of charge, to any person obtaining a // copy of this software and associated documentation files (the // "Software"), to deal in the Software without restriction, including // without limitation the rights to use, copy, modify, merge, publish, // distribute, sublicense, and/or sell copies of the Software, and to permit // persons to whom the Software is furnished to do so, subject to the // following conditions: // // The above copyright notice and this permission notice shall be included // in all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS // OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF // MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN // NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, // DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR // OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE // USE OR OTHER DEALINGS IN THE SOFTWARE. var common = require('../common'); var assert = require('assert'); var fork = require('child_process').fork; var expected = Array(1e5).join('ßßßß'); if (process.argv[2] === 'child') { process.send(expected); } else { var child = fork(process.argv[1], ['child']); child.on('message', common.mustCall(function(actual) { assert.equal(actual, expected); })); } node-v0.10.25~dfsg2/test/simple/test-net-bind-twice.js0000644000000000000000000000317312270121457021215 0ustar rootroot// Copyright Joyent, Inc. and other Node contributors. // // Permission is hereby granted, free of charge, to any person obtaining a // copy of this software and associated documentation files (the // "Software"), to deal in the Software without restriction, including // without limitation the rights to use, copy, modify, merge, publish, // distribute, sublicense, and/or sell copies of the Software, and to permit // persons to whom the Software is furnished to do so, subject to the // following conditions: // // The above copyright notice and this permission notice shall be included // in all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS // OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF // MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN // NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, // DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR // OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE // USE OR OTHER DEALINGS IN THE SOFTWARE. var common = require('../common'); var assert = require('assert'); var net = require('net'); var gotError = false; process.on('exit', function() { assert(gotError); }); function dontCall() { assert(false); } var server1 = net.createServer(dontCall); server1.listen(common.PORT, '127.0.0.1', function() {}); var server2 = net.createServer(dontCall); server2.listen(common.PORT, '127.0.0.1', dontCall); server2.on('error', function(e) { assert.equal(e.code, 'EADDRINUSE'); server1.close(); gotError = true; }); node-v0.10.25~dfsg2/test/simple/test-debugger-repl-utf8.js0000644000000000000000000000244112270121457022011 0ustar rootroot// Copyright Joyent, Inc. and other Node contributors. // // Permission is hereby granted, free of charge, to any person obtaining a // copy of this software and associated documentation files (the // "Software"), to deal in the Software without restriction, including // without limitation the rights to use, copy, modify, merge, publish, // distribute, sublicense, and/or sell copies of the Software, and to permit // persons to whom the Software is furnished to do so, subject to the // following conditions: // // The above copyright notice and this permission notice shall be included // in all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS // OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF // MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN // NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, // DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR // OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE // USE OR OTHER DEALINGS IN THE SOFTWARE. var common = require('../common'); var script = common.fixturesDir + '/breakpoints_utf8.js'; process.env.NODE_DEBUGGER_TEST_SCRIPT = script; require('./test-debugger-repl.js'); node-v0.10.25~dfsg2/test/simple/test-net-server-max-connections.js0000644000000000000000000000611512270121457023600 0ustar rootroot// Copyright Joyent, Inc. and other Node contributors. // // Permission is hereby granted, free of charge, to any person obtaining a // copy of this software and associated documentation files (the // "Software"), to deal in the Software without restriction, including // without limitation the rights to use, copy, modify, merge, publish, // distribute, sublicense, and/or sell copies of the Software, and to permit // persons to whom the Software is furnished to do so, subject to the // following conditions: // // The above copyright notice and this permission notice shall be included // in all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS // OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF // MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN // NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, // DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR // OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE // USE OR OTHER DEALINGS IN THE SOFTWARE. var common = require('../common'); var assert = require('assert'); var net = require('net'); // This test creates 200 connections to a server and sets the server's // maxConnections property to 100. The first 100 connections make it through // and the last 100 connections are rejected. // TODO: test that the server can accept more connections after it reaches // its maximum and some are closed. var N = 200; var count = 0; var closes = 0; var waits = []; var server = net.createServer(function(connection) { console.error('connect %d', count++); connection.write('hello'); waits.push(function() { connection.end(); }); }); server.listen(common.PORT, function() { makeConnection(0); }); server.maxConnections = N / 2; console.error('server.maxConnections = %d', server.maxConnections); function makeConnection(index) { var c = net.createConnection(common.PORT); var gotData = false; c.on('connect', function() { if (index + 1 < N) { makeConnection(index + 1); } }); c.on('end', function() { c.end(); }); c.on('data', function(b) { gotData = true; assert.ok(0 < b.length); }); c.on('error', function(e) { console.error('error %d: %s', index, e); }); c.on('close', function() { console.error('closed %d', index); closes++; if (closes < N / 2) { assert.ok(server.maxConnections <= index, index + ' was one of the first closed connections ' + 'but shouldnt have been'); } if (closes === N / 2) { var cb; console.error('calling wait callback.'); while (cb = waits.shift()) { cb(); } server.close(); } if (index < server.maxConnections) { assert.equal(true, gotData, index + ' didn\'t get data, but should have'); } else { assert.equal(false, gotData, index + ' got data, but shouldn\'t have'); } }); } process.on('exit', function() { assert.equal(N, closes); }); node-v0.10.25~dfsg2/test/simple/test-util-inspect.js0000644000000000000000000001304612270121457021024 0ustar rootroot// Copyright Joyent, Inc. and other Node contributors. // // Permission is hereby granted, free of charge, to any person obtaining a // copy of this software and associated documentation files (the // "Software"), to deal in the Software without restriction, including // without limitation the rights to use, copy, modify, merge, publish, // distribute, sublicense, and/or sell copies of the Software, and to permit // persons to whom the Software is furnished to do so, subject to the // following conditions: // // The above copyright notice and this permission notice shall be included // in all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS // OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF // MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN // NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, // DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR // OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE // USE OR OTHER DEALINGS IN THE SOFTWARE. var common = require('../common'); var assert = require('assert'); var util = require('util'); // test the internal isDate implementation var Date2 = require('vm').runInNewContext('Date'); var d = new Date2(); var orig = util.inspect(d); Date2.prototype.foo = 'bar'; var after = util.inspect(d); assert.equal(orig, after); // test for sparse array var a = ['foo', 'bar', 'baz']; assert.equal(util.inspect(a), '[ \'foo\', \'bar\', \'baz\' ]'); delete a[1]; assert.equal(util.inspect(a), '[ \'foo\', , \'baz\' ]'); assert.equal(util.inspect(a, true), '[ \'foo\', , \'baz\', [length]: 3 ]'); assert.equal(util.inspect(new Array(5)), '[ , , , , ]'); // test for property descriptors var getter = Object.create(null, { a: { get: function() { return 'aaa'; } } }); var setter = Object.create(null, { b: { set: function() {} } }); var getterAndSetter = Object.create(null, { c: { get: function() { return 'ccc'; }, set: function() {} } }); assert.equal(util.inspect(getter, true), '{ [a]: [Getter] }'); assert.equal(util.inspect(setter, true), '{ [b]: [Setter] }'); assert.equal(util.inspect(getterAndSetter, true), '{ [c]: [Getter/Setter] }'); // exceptions should print the error message, not '{}' assert.equal(util.inspect(new Error()), '[Error]'); assert.equal(util.inspect(new Error('FAIL')), '[Error: FAIL]'); assert.equal(util.inspect(new TypeError('FAIL')), '[TypeError: FAIL]'); assert.equal(util.inspect(new SyntaxError('FAIL')), '[SyntaxError: FAIL]'); try { undef(); } catch (e) { assert.equal(util.inspect(e), '[ReferenceError: undef is not defined]'); } var ex = util.inspect(new Error('FAIL'), true); assert.ok(ex.indexOf('[Error: FAIL]') != -1); assert.ok(ex.indexOf('[stack]') != -1); assert.ok(ex.indexOf('[message]') != -1); // GH-1941 // should not throw: assert.equal(util.inspect(Object.create(Date.prototype)), '{}'); // GH-1944 assert.doesNotThrow(function() { var d = new Date(); d.toUTCString = null; util.inspect(d); }); assert.doesNotThrow(function() { var r = /regexp/; r.toString = null; util.inspect(r); }); // bug with user-supplied inspect function returns non-string assert.doesNotThrow(function() { util.inspect([{ inspect: function() { return 123; } }]); }); // GH-2225 var x = { inspect: util.inspect }; assert.ok(util.inspect(x).indexOf('inspect') != -1); // util.inspect.styles and util.inspect.colors function test_color_style(style, input, implicit) { var color_name = util.inspect.styles[style]; var color = ['', '']; if(util.inspect.colors[color_name]) color = util.inspect.colors[color_name]; var without_color = util.inspect(input, false, 0, false); var with_color = util.inspect(input, false, 0, true); var expect = '\u001b[' + color[0] + 'm' + without_color + '\u001b[' + color[1] + 'm'; assert.equal(with_color, expect, 'util.inspect color for style '+style); } test_color_style('special', function(){}); test_color_style('number', 123.456); test_color_style('boolean', true); test_color_style('undefined', undefined); test_color_style('null', null); test_color_style('string', 'test string'); test_color_style('date', new Date); test_color_style('regexp', /regexp/); // an object with "hasOwnProperty" overwritten should not throw assert.doesNotThrow(function() { util.inspect({ hasOwnProperty: null }); }); // new API, accepts an "options" object var subject = { foo: 'bar', hello: 31, a: { b: { c: { d: 0 } } } }; Object.defineProperty(subject, 'hidden', { enumerable: false, value: null }); assert(util.inspect(subject, { showHidden: false }).indexOf('hidden') === -1); assert(util.inspect(subject, { showHidden: true }).indexOf('hidden') !== -1); assert(util.inspect(subject, { colors: false }).indexOf('\u001b[32m') === -1); assert(util.inspect(subject, { colors: true }).indexOf('\u001b[32m') !== -1); assert(util.inspect(subject, { depth: 2 }).indexOf('c: [Object]') !== -1); assert(util.inspect(subject, { depth: 0 }).indexOf('a: [Object]') !== -1); assert(util.inspect(subject, { depth: null }).indexOf('{ d: 0 }') !== -1); // "customInspect" option can enable/disable calling inspect() on objects subject = { inspect: function() { return 123; } }; assert(util.inspect(subject, { customInspect: true }).indexOf('123') !== -1); assert(util.inspect(subject, { customInspect: true }).indexOf('inspect') === -1); assert(util.inspect(subject, { customInspect: false }).indexOf('123') === -1); assert(util.inspect(subject, { customInspect: false }).indexOf('inspect') !== -1); node-v0.10.25~dfsg2/test/simple/test-regress-GH-4015.js0000644000000000000000000000267612270121457020750 0ustar rootroot// Copyright Joyent, Inc. and other Node contributors. // // Permission is hereby granted, free of charge, to any person obtaining a // copy of this software and associated documentation files (the // "Software"), to deal in the Software without restriction, including // without limitation the rights to use, copy, modify, merge, publish, // distribute, sublicense, and/or sell copies of the Software, and to permit // persons to whom the Software is furnished to do so, subject to the // following conditions: // // The above copyright notice and this permission notice shall be included // in all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS // OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF // MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN // NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, // DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR // OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE // USE OR OTHER DEALINGS IN THE SOFTWARE. var common = require('../common'); var assert = require('assert'); var exec = require('child_process').exec; var cmd = process.execPath + ' ' + common.fixturesDir + '/test-regress-GH-4015.js'; exec(cmd, function(err, stdout, stderr) { assert(/RangeError: Maximum call stack size exceeded/.test(stderr)); }); node-v0.10.25~dfsg2/test/simple/test-timers-linked-list.js0000644000000000000000000000562012270121457022123 0ustar rootroot// Copyright Joyent, Inc. and other Node contributors. // // Permission is hereby granted, free of charge, to any person obtaining a // copy of this software and associated documentation files (the // "Software"), to deal in the Software without restriction, including // without limitation the rights to use, copy, modify, merge, publish, // distribute, sublicense, and/or sell copies of the Software, and to permit // persons to whom the Software is furnished to do so, subject to the // following conditions: // // The above copyright notice and this permission notice shall be included // in all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS // OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF // MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN // NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, // DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR // OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE // USE OR OTHER DEALINGS IN THE SOFTWARE. var common = require('../common'); var assert = require('assert'); var L = require('_linklist'); var list = { name: 'list' }; var A = { name: 'A' }; var B = { name: 'B' }; var C = { name: 'C' }; var D = { name: 'D' }; L.init(list); L.init(A); L.init(B); L.init(C); L.init(D); assert.ok(L.isEmpty(list)); assert.equal(null, L.peek(list)); L.append(list, A); // list -> A assert.equal(A, L.peek(list)); L.append(list, B); // list -> A -> B assert.equal(A, L.peek(list)); L.append(list, C); // list -> A -> B -> C assert.equal(A, L.peek(list)); L.append(list, D); // list -> A -> B -> C -> D assert.equal(A, L.peek(list)); var x = L.shift(list); assert.equal(A, x); // list -> B -> C -> D assert.equal(B, L.peek(list)); x = L.shift(list); assert.equal(B, x); // list -> C -> D assert.equal(C, L.peek(list)); // B is already removed, so removing it again shouldn't hurt. L.remove(B); // list -> C -> D assert.equal(C, L.peek(list)); // Put B back on the list L.append(list, B); // list -> C -> D -> B assert.equal(C, L.peek(list)); L.remove(C); // list -> D -> B assert.equal(D, L.peek(list)); L.remove(B); // list -> D assert.equal(D, L.peek(list)); L.remove(D); // list assert.equal(null, L.peek(list)); assert.ok(L.isEmpty(list)); L.append(list, D); // list -> D assert.equal(D, L.peek(list)); L.append(list, C); L.append(list, B); L.append(list, A); // list -> D -> C -> B -> A // Append should REMOVE C from the list and append it to the end. L.append(list, C); // list -> D -> B -> A -> C assert.equal(D, L.shift(list)); // list -> B -> A -> C assert.equal(B, L.peek(list)); assert.equal(B, L.shift(list)); // list -> A -> C assert.equal(A, L.peek(list)); assert.equal(A, L.shift(list)); // list -> C assert.equal(C, L.peek(list)); assert.equal(C, L.shift(list)); // list assert.ok(L.isEmpty(list)); node-v0.10.25~dfsg2/test/simple/test-event-emitter-num-args.js0000644000000000000000000000333612270121457022724 0ustar rootroot// Copyright Joyent, Inc. and other Node contributors. // // Permission is hereby granted, free of charge, to any person obtaining a // copy of this software and associated documentation files (the // "Software"), to deal in the Software without restriction, including // without limitation the rights to use, copy, modify, merge, publish, // distribute, sublicense, and/or sell copies of the Software, and to permit // persons to whom the Software is furnished to do so, subject to the // following conditions: // // The above copyright notice and this permission notice shall be included // in all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS // OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF // MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN // NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, // DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR // OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE // USE OR OTHER DEALINGS IN THE SOFTWARE. var common = require('../common'); var assert = require('assert'); var events = require('events'); var e = new events.EventEmitter(), num_args_emited = []; e.on('numArgs', function() { var numArgs = arguments.length; console.log('numArgs: ' + numArgs); num_args_emited.push(numArgs); }); console.log('start'); e.emit('numArgs'); e.emit('numArgs', null); e.emit('numArgs', null, null); e.emit('numArgs', null, null, null); e.emit('numArgs', null, null, null, null); e.emit('numArgs', null, null, null, null, null); process.on('exit', function() { assert.deepEqual([0, 1, 2, 3, 4, 5], num_args_emited); }); node-v0.10.25~dfsg2/test/simple/test-fs-write.js0000644000000000000000000000533712270121457020150 0ustar rootroot// Copyright Joyent, Inc. and other Node contributors. // // Permission is hereby granted, free of charge, to any person obtaining a // copy of this software and associated documentation files (the // "Software"), to deal in the Software without restriction, including // without limitation the rights to use, copy, modify, merge, publish, // distribute, sublicense, and/or sell copies of the Software, and to permit // persons to whom the Software is furnished to do so, subject to the // following conditions: // // The above copyright notice and this permission notice shall be included // in all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS // OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF // MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN // NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, // DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR // OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE // USE OR OTHER DEALINGS IN THE SOFTWARE. var common = require('../common'); var assert = require('assert'); var path = require('path'); var Buffer = require('buffer').Buffer; var fs = require('fs'); var fn = path.join(common.tmpDir, 'write.txt'); var fn2 = path.join(common.tmpDir, 'write2.txt'); var expected = 'ümlaut.'; var constants = require('constants'); var found, found2; fs.open(fn, 'w', 0644, function(err, fd) { if (err) throw err; console.log('open done'); fs.write(fd, '', 0, 'utf8', function(err, written) { assert.equal(0, written); }); fs.write(fd, expected, 0, 'utf8', function(err, written) { console.log('write done'); if (err) throw err; assert.equal(Buffer.byteLength(expected), written); fs.closeSync(fd); found = fs.readFileSync(fn, 'utf8'); console.log('expected: "%s"', expected); console.log('found: "%s"', found); fs.unlinkSync(fn); }); }); fs.open(fn2, constants.O_CREAT | constants.O_WRONLY | constants.O_TRUNC, 0644, function(err, fd) { if (err) throw err; console.log('open done'); fs.write(fd, '', 0, 'utf8', function(err, written) { assert.equal(0, written); }); fs.write(fd, expected, 0, 'utf8', function(err, written) { console.log('write done'); if (err) throw err; assert.equal(Buffer.byteLength(expected), written); fs.closeSync(fd); found2 = fs.readFileSync(fn2, 'utf8'); console.log('expected: "%s"', expected); console.log('found: "%s"', found2); fs.unlinkSync(fn2); }); }); process.on('exit', function() { assert.equal(expected, found); assert.equal(expected, found2); }); node-v0.10.25~dfsg2/test/simple/test-debug-brk-no-arg.js0000644000000000000000000000272512270121457021431 0ustar rootroot// Copyright Joyent, Inc. and other Node contributors. // // Permission is hereby granted, free of charge, to any person obtaining a // copy of this software and associated documentation files (the // "Software"), to deal in the Software without restriction, including // without limitation the rights to use, copy, modify, merge, publish, // distribute, sublicense, and/or sell copies of the Software, and to permit // persons to whom the Software is furnished to do so, subject to the // following conditions: // // The above copyright notice and this permission notice shall be included // in all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS // OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF // MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN // NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, // DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR // OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE // USE OR OTHER DEALINGS IN THE SOFTWARE. var common = require('../common'); var assert = require('assert'); var spawn = require('child_process').spawn; var child = spawn(process.execPath, ['--debug-brk=' + common.PORT]); child.stderr.once('data', function(c) { console.error('%j', c.toString()); child.stdin.end(); }); child.on('exit', function(c) { assert(c === 0); console.log('ok'); }); node-v0.10.25~dfsg2/test/simple/test-fs-readfile-error.js0000644000000000000000000000436612270121457021721 0ustar rootroot// Copyright Joyent, Inc. and other Node contributors. // // Permission is hereby granted, free of charge, to any person obtaining a // copy of this software and associated documentation files (the // "Software"), to deal in the Software without restriction, including // without limitation the rights to use, copy, modify, merge, publish, // distribute, sublicense, and/or sell copies of the Software, and to permit // persons to whom the Software is furnished to do so, subject to the // following conditions: // // The above copyright notice and this permission notice shall be included // in all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS // OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF // MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN // NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, // DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR // OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE // USE OR OTHER DEALINGS IN THE SOFTWARE. var common = require('../common'); var assert = require('assert'); var exec = require('child_process').exec; var path = require('path'); var callbacks = 0; function test(env, cb) { var filename = path.join(common.fixturesDir, 'test-fs-readfile-error.js'); var execPath = process.execPath + ' --throw-deprecation ' + filename; var options = { env: env || {} }; exec(execPath, options, function(err, stdout, stderr) { assert(err); assert.equal(stdout, ''); assert.notEqual(stderr, ''); cb('' + stderr); }); } test({ NODE_DEBUG: '' }, function(data) { assert(/EISDIR/.test(data)); assert(!/test-fs-readfile-error/.test(data)); callbacks++; }); test({ NODE_DEBUG: 'fs' }, function(data) { assert(/EISDIR/.test(data)); assert(/test-fs-readfile-error/.test(data)); callbacks++; }); process.on('exit', function() { assert.equal(callbacks, 2); }); (function() { console.error('the warnings are normal here.'); // just make sure that this doesn't crash the process. var fs = require('fs'); fs.readFile(__dirname); fs.readdir(__filename); fs.unlink('gee-i-sure-hope-this-file-isnt-important-or-existing'); })(); node-v0.10.25~dfsg2/test/simple/test-fs-write-file-sync.js0000644000000000000000000000547012270121457022035 0ustar rootroot// Copyright Joyent, Inc. and other Node contributors. // // Permission is hereby granted, free of charge, to any person obtaining a // copy of this software and associated documentation files (the // "Software"), to deal in the Software without restriction, including // without limitation the rights to use, copy, modify, merge, publish, // distribute, sublicense, and/or sell copies of the Software, and to permit // persons to whom the Software is furnished to do so, subject to the // following conditions: // // The above copyright notice and this permission notice shall be included // in all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS // OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF // MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN // NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, // DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR // OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE // USE OR OTHER DEALINGS IN THE SOFTWARE. var common = require('../common'); var assert = require('assert'); var path = require('path'); var fs = require('fs'); var isWindows = process.platform === 'win32'; var openCount = 0; var mode; var content; // Need to hijack fs.open/close to make sure that things // get closed once they're opened. fs._openSync = fs.openSync; fs.openSync = openSync; fs._closeSync = fs.closeSync; fs.closeSync = closeSync; // Reset the umask for testing var mask = process.umask(0000); // On Windows chmod is only able to manipulate read-only bit. Test if creating // the file in read-only mode works. if (isWindows) { mode = 0444; } else { mode = 0755; } // Test writeFileSync var file1 = path.join(common.tmpDir, 'testWriteFileSync.txt'); removeFile(file1); fs.writeFileSync(file1, '123', {mode: mode}); content = fs.readFileSync(file1, {encoding: 'utf8'}); assert.equal('123', content); assert.equal(mode, fs.statSync(file1).mode & 0777); removeFile(file1); // Test appendFileSync var file2 = path.join(common.tmpDir, 'testAppendFileSync.txt'); removeFile(file2); fs.appendFileSync(file2, 'abc', {mode: mode}); content = fs.readFileSync(file2, {encoding: 'utf8'}); assert.equal('abc', content); assert.equal(mode, fs.statSync(file2).mode & mode); removeFile(file2); // Verify that all opened files were closed. assert.equal(0, openCount); // Removes a file if it exists. function removeFile(file) { try { if (isWindows) fs.chmodSync(file, 0666); fs.unlinkSync(file); } catch (err) { if (err && err.code !== 'ENOENT') throw err; } } function openSync() { openCount++; return fs._openSync.apply(fs, arguments); } function closeSync() { openCount--; return fs._closeSync.apply(fs, arguments); } node-v0.10.25~dfsg2/test/simple/test-next-tick-error-spin.js0000644000000000000000000000420612270121457022406 0ustar rootroot// Copyright Joyent, Inc. and other Node contributors. // // Permission is hereby granted, free of charge, to any person obtaining a // copy of this software and associated documentation files (the // "Software"), to deal in the Software without restriction, including // without limitation the rights to use, copy, modify, merge, publish, // distribute, sublicense, and/or sell copies of the Software, and to permit // persons to whom the Software is furnished to do so, subject to the // following conditions: // // The above copyright notice and this permission notice shall be included // in all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS // OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF // MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN // NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, // DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR // OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE // USE OR OTHER DEALINGS IN THE SOFTWARE. var common = require('../common'); var assert = require('assert'); if (process.argv[2] !== 'child') { var spawn = require('child_process').spawn; var child = spawn(process.execPath, [__filename, 'child'], { stdio: 'pipe'//'inherit' }); var timer = setTimeout(function() { throw new Error('child is hung'); }, 500); child.on('exit', function(code) { console.error('ok'); assert(!code); clearTimeout(timer); }); } else { var domain = require('domain'); var d = domain.create(); process.maxTickDepth = 10; // in the error handler, we trigger several MakeCallback events d.on('error', function(e) { console.log('a') console.log('b') console.log('c') console.log('d') console.log('e') f(); }); function f() { process.nextTick(function() { d.run(function() { throw(new Error('x')); }); }); } f(); setTimeout(function () { console.error('broke in!'); //process.stdout.close(); //process.stderr.close(); process.exit(0); }); } node-v0.10.25~dfsg2/test/simple/test-tcp-wrap-connect.js0000644000000000000000000000442312270121457021567 0ustar rootroot// Copyright Joyent, Inc. and other Node contributors. // // Permission is hereby granted, free of charge, to any person obtaining a // copy of this software and associated documentation files (the // "Software"), to deal in the Software without restriction, including // without limitation the rights to use, copy, modify, merge, publish, // distribute, sublicense, and/or sell copies of the Software, and to permit // persons to whom the Software is furnished to do so, subject to the // following conditions: // // The above copyright notice and this permission notice shall be included // in all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS // OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF // MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN // NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, // DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR // OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE // USE OR OTHER DEALINGS IN THE SOFTWARE. var common = require('../common'); var assert = require('assert'); var TCP = process.binding('tcp_wrap').TCP; function makeConnection() { var client = new TCP(); var req = client.connect('127.0.0.1', common.PORT); req.oncomplete = function(status, client_, req_) { assert.equal(0, status); assert.equal(client, client_); assert.equal(req, req_); console.log('connected'); var shutdownReq = client.shutdown(); shutdownReq.oncomplete = function(status, client_, req_) { console.log('shutdown complete'); assert.equal(0, status); assert.equal(client, client_); assert.equal(shutdownReq, req_); shutdownCount++; client.close(); }; }; } ///// var connectCount = 0; var endCount = 0; var shutdownCount = 0; var server = require('net').Server(function(s) { console.log('got connection'); connectCount++; s.resume(); s.on('end', function() { console.log('got eof'); endCount++; s.destroy(); server.close(); }); }); server.listen(common.PORT, makeConnection); process.on('exit', function() { assert.equal(1, shutdownCount); assert.equal(1, connectCount); assert.equal(1, endCount); }); node-v0.10.25~dfsg2/test/simple/test-fs-read-buffer.js0000644000000000000000000000361712270121457021177 0ustar rootroot// Copyright Joyent, Inc. and other Node contributors. // // Permission is hereby granted, free of charge, to any person obtaining a // copy of this software and associated documentation files (the // "Software"), to deal in the Software without restriction, including // without limitation the rights to use, copy, modify, merge, publish, // distribute, sublicense, and/or sell copies of the Software, and to permit // persons to whom the Software is furnished to do so, subject to the // following conditions: // // The above copyright notice and this permission notice shall be included // in all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS // OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF // MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN // NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, // DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR // OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE // USE OR OTHER DEALINGS IN THE SOFTWARE. var common = require('../common'); var assert = require('assert'); var path = require('path'), Buffer = require('buffer').Buffer, fs = require('fs'), filepath = path.join(common.fixturesDir, 'x.txt'), fd = fs.openSync(filepath, 'r'), expected = 'xyz\n', bufferAsync = new Buffer(expected.length), bufferSync = new Buffer(expected.length), readCalled = 0; fs.read(fd, bufferAsync, 0, expected.length, 0, function(err, bytesRead) { readCalled++; assert.equal(bytesRead, expected.length); assert.deepEqual(bufferAsync, new Buffer(expected)); }); var r = fs.readSync(fd, bufferSync, 0, expected.length, 0); assert.deepEqual(bufferSync, new Buffer(expected)); assert.equal(r, expected.length); process.on('exit', function() { assert.equal(readCalled, 1); }); node-v0.10.25~dfsg2/test/simple/test-http-head-response-has-no-body-end.js0000644000000000000000000000371512270121457025002 0ustar rootroot// Copyright Joyent, Inc. and other Node contributors. // // Permission is hereby granted, free of charge, to any person obtaining a // copy of this software and associated documentation files (the // "Software"), to deal in the Software without restriction, including // without limitation the rights to use, copy, modify, merge, publish, // distribute, sublicense, and/or sell copies of the Software, and to permit // persons to whom the Software is furnished to do so, subject to the // following conditions: // // The above copyright notice and this permission notice shall be included // in all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS // OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF // MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN // NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, // DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR // OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE // USE OR OTHER DEALINGS IN THE SOFTWARE. var common = require('../common'); var assert = require('assert'); var http = require('http'); // This test is to make sure that when the HTTP server // responds to a HEAD request with data to res.end, // it does not send any body. var server = http.createServer(function(req, res) { res.writeHead(200); res.end('FAIL'); // broken: sends FAIL from hot path. }); server.listen(common.PORT); var responseComplete = false; server.on('listening', function() { var req = http.request({ port: common.PORT, method: 'HEAD', path: '/' }, function(res) { common.error('response'); res.on('end', function() { common.error('response end'); server.close(); responseComplete = true; }); res.resume(); }); common.error('req'); req.end(); }); process.on('exit', function() { assert.ok(responseComplete); }); node-v0.10.25~dfsg2/test/simple/test-child-process-exit-code.js0000644000000000000000000000355312270121457023024 0ustar rootroot// Copyright Joyent, Inc. and other Node contributors. // // Permission is hereby granted, free of charge, to any person obtaining a // copy of this software and associated documentation files (the // "Software"), to deal in the Software without restriction, including // without limitation the rights to use, copy, modify, merge, publish, // distribute, sublicense, and/or sell copies of the Software, and to permit // persons to whom the Software is furnished to do so, subject to the // following conditions: // // The above copyright notice and this permission notice shall be included // in all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS // OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF // MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN // NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, // DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR // OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE // USE OR OTHER DEALINGS IN THE SOFTWARE. var common = require('../common'); var assert = require('assert'); var spawn = require('child_process').spawn; var path = require('path'); var exits = 0; var exitScript = path.join(common.fixturesDir, 'exit.js'); var exitChild = spawn(process.argv[0], [exitScript, 23]); exitChild.on('exit', function(code, signal) { assert.strictEqual(code, 23); assert.strictEqual(signal, null); exits++; }); var errorScript = path.join(common.fixturesDir, 'child_process_should_emit_error.js'); var errorChild = spawn(process.argv[0], [errorScript]); errorChild.on('exit', function(code, signal) { assert.ok(code !== 0); assert.strictEqual(signal, null); exits++; }); process.on('exit', function() { assert.equal(2, exits); }); node-v0.10.25~dfsg2/test/simple/test-dgram-regress-4496.js0000644000000000000000000000277412270121457021560 0ustar rootroot// Copyright Joyent, Inc. and other Node contributors. // // Permission is hereby granted, free of charge, to any person obtaining a // copy of this software and associated documentation files (the // "Software"), to deal in the Software without restriction, including // without limitation the rights to use, copy, modify, merge, publish, // distribute, sublicense, and/or sell copies of the Software, and to permit // persons to whom the Software is furnished to do so, subject to the // following conditions: // // The above copyright notice and this permission notice shall be included // in all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS // OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF // MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN // NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, // DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR // OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE // USE OR OTHER DEALINGS IN THE SOFTWARE. // Remove this test once we support sending strings. var common = require('../common'); var assert = require('assert'); var dgram = require('dgram'); // Should throw but not crash. var socket = dgram.createSocket('udp4'); assert.throws(function() { socket.send('BAM', 0, 1, 1, 'host') }, TypeError); assert.throws(function() { socket.sendto('BAM', 0, 1, 1, 'host') }, TypeError); socket.close(); node-v0.10.25~dfsg2/test/simple/test-tls-zero-clear-in.js0000644000000000000000000000430012270121457021644 0ustar rootroot// Copyright Joyent, Inc. and other Node contributors. // // Permission is hereby granted, free of charge, to any person obtaining a // copy of this software and associated documentation files (the // "Software"), to deal in the Software without restriction, including // without limitation the rights to use, copy, modify, merge, publish, // distribute, sublicense, and/or sell copies of the Software, and to permit // persons to whom the Software is furnished to do so, subject to the // following conditions: // // The above copyright notice and this permission notice shall be included // in all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS // OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF // MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN // NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, // DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR // OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE // USE OR OTHER DEALINGS IN THE SOFTWARE. if (!process.versions.openssl) { console.error('Skipping because node compiled without OpenSSL.'); process.exit(0); } var common = require('../common'); var assert = require('assert'); var fs = require('fs'); var tls = require('tls'); var path = require('path'); var cert = fs.readFileSync(path.join(common.fixturesDir, 'test_cert.pem')); var key = fs.readFileSync(path.join(common.fixturesDir, 'test_key.pem')); var errorEmitted = false; var server = tls.createServer({ cert: cert, key: key }, function(c) { // Nop setTimeout(function() { c.destroy(); server.close(); }, 20); }).listen(common.PORT, function() { var conn = tls.connect({ cert: cert, key: key, rejectUnauthorized: false, port: common.PORT }, function() { setTimeout(function() { conn.destroy(); }, 20); }); // SSL_write() call's return value, when called 0 bytes, should not be // treated as error. conn.end(''); conn.on('error', function(err) { console.log(err); errorEmitted = true; }); }); process.on('exit', function() { assert.ok(!errorEmitted); }); node-v0.10.25~dfsg2/test/simple/test-http-chunked-304.js0000644000000000000000000000440412270121457021304 0ustar rootroot// Copyright Joyent, Inc. and other Node contributors. // // Permission is hereby granted, free of charge, to any person obtaining a // copy of this software and associated documentation files (the // "Software"), to deal in the Software without restriction, including // without limitation the rights to use, copy, modify, merge, publish, // distribute, sublicense, and/or sell copies of the Software, and to permit // persons to whom the Software is furnished to do so, subject to the // following conditions: // // The above copyright notice and this permission notice shall be included // in all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS // OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF // MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN // NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, // DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR // OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE // USE OR OTHER DEALINGS IN THE SOFTWARE. var common = require('../common'); var assert = require('assert'); var http = require('http'); var net = require('net'); // RFC 2616, section 10.2.5: // // The 204 response MUST NOT contain a message-body, and thus is always // terminated by the first empty line after the header fields. // // Likewise for 304 responses. Verify that no empty chunk is sent when // the user explicitly sets a Transfer-Encoding header. test(204, function() { test(304); }); function test(statusCode, next) { var server = http.createServer(function(req, res) { res.writeHead(statusCode, { 'Transfer-Encoding': 'chunked' }); res.end(); server.close(); }); server.listen(common.PORT, function() { var conn = net.createConnection(common.PORT, function() { conn.write('GET / HTTP/1.1\r\n\r\n'); var resp = ''; conn.setEncoding('utf8'); conn.on('data', function(data) { resp += data; }); conn.on('end', common.mustCall(function() { assert.equal(/^Connection: close\r\n$/m.test(resp), true); assert.equal(/^0\r\n$/m.test(resp), false); if (next) process.nextTick(next); })); }); }); } node-v0.10.25~dfsg2/test/simple/test-fs-non-number-arguments-throw.js0000644000000000000000000000152412270121457024234 0ustar rootrootvar assert = require('assert'), fs = require('fs'), saneEmitter, sanity = 'ire(\'assert\')'; saneEmitter = fs.createReadStream(__filename, { start: 17, end: 29 }); assert.throws(function () { fs.createReadStream(__filename, { start: "17", end: 29 }); }, "start as string didn't throw an error for createReadStream"); assert.throws(function () { fs.createReadStream(__filename, { start: 17, end: "29" }); }, "end as string didn't throw an error"); assert.throws(function () { fs.createWriteStream(__filename, { start: "17" }); }, "start as string didn't throw an error for createWriteStream"); saneEmitter.on('data', function (data) { // a sanity check when using numbers instead of strings assert.strictEqual(sanity, data.toString('utf8'), 'read ' + data.toString('utf8') + ' instead of ' + sanity); }); node-v0.10.25~dfsg2/test/simple/test-fs-truncate.js0000644000000000000000000000742212270121457020640 0ustar rootroot// Copyright Joyent, Inc. and other Node contributors. // // Permission is hereby granted, free of charge, to any person obtaining a // copy of this software and associated documentation files (the // "Software"), to deal in the Software without restriction, including // without limitation the rights to use, copy, modify, merge, publish, // distribute, sublicense, and/or sell copies of the Software, and to permit // persons to whom the Software is furnished to do so, subject to the // following conditions: // // The above copyright notice and this permission notice shall be included // in all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS // OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF // MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN // NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, // DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR // OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE // USE OR OTHER DEALINGS IN THE SOFTWARE. var common = require('../common'); var assert = require('assert'); var path = require('path'); var fs = require('fs'); var tmp = common.tmpDir; var filename = path.resolve(tmp, 'truncate-file.txt'); var data = new Buffer(1024 * 16); data.fill('x'); var stat; // truncateSync fs.writeFileSync(filename, data); stat = fs.statSync(filename); assert.equal(stat.size, 1024 * 16); fs.truncateSync(filename, 1024); stat = fs.statSync(filename); assert.equal(stat.size, 1024); fs.truncateSync(filename); stat = fs.statSync(filename); assert.equal(stat.size, 0); // ftruncateSync fs.writeFileSync(filename, data); var fd = fs.openSync(filename, 'r+'); stat = fs.statSync(filename); assert.equal(stat.size, 1024 * 16); fs.ftruncateSync(fd, 1024); stat = fs.statSync(filename); assert.equal(stat.size, 1024); fs.ftruncateSync(fd); stat = fs.statSync(filename); assert.equal(stat.size, 0); fs.closeSync(fd); // async tests var success = 0; testTruncate(function(er) { if (er) throw er; success++; testFtruncate(function(er) { if (er) throw er; success++; }); }); process.on('exit', function() { assert.equal(success, 2); console.log('ok'); }); function testTruncate(cb) { fs.writeFile(filename, data, function(er) { if (er) return cb(er); fs.stat(filename, function(er, stat) { if (er) return cb(er); assert.equal(stat.size, 1024 * 16); fs.truncate(filename, 1024, function(er) { if (er) return cb(er); fs.stat(filename, function(er, stat) { if (er) return cb(er); assert.equal(stat.size, 1024); fs.truncate(filename, function(er) { if (er) return cb(er); fs.stat(filename, function(er, stat) { if (er) return cb(er); assert.equal(stat.size, 0); cb(); }); }); }); }); }); }); } function testFtruncate(cb) { fs.writeFile(filename, data, function(er) { if (er) return cb(er); fs.stat(filename, function(er, stat) { if (er) return cb(er); assert.equal(stat.size, 1024 * 16); fs.open(filename, 'w', function(er, fd) { if (er) return cb(er); fs.ftruncate(fd, 1024, function(er) { if (er) return cb(er); fs.stat(filename, function(er, stat) { if (er) return cb(er); assert.equal(stat.size, 1024); fs.ftruncate(fd, function(er) { if (er) return cb(er); fs.stat(filename, function(er, stat) { if (er) return cb(er); assert.equal(stat.size, 0); fs.close(fd, cb); }); }); }); }); }); }); }); } node-v0.10.25~dfsg2/test/simple/test-tls-client-destroy-soon.js0000644000000000000000000000453712270121457023132 0ustar rootroot// Copyright Joyent, Inc. and other Node contributors. // // Permission is hereby granted, free of charge, to any person obtaining a // copy of this software and associated documentation files (the // "Software"), to deal in the Software without restriction, including // without limitation the rights to use, copy, modify, merge, publish, // distribute, sublicense, and/or sell copies of the Software, and to permit // persons to whom the Software is furnished to do so, subject to the // following conditions: // // The above copyright notice and this permission notice shall be included // in all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS // OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF // MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN // NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, // DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR // OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE // USE OR OTHER DEALINGS IN THE SOFTWARE. // Create an ssl server. First connection, validate that not resume. // Cache session and close connection. Use session on second connection. // ASSERT resumption. if (!process.versions.openssl) { console.error('Skipping because node compiled without OpenSSL.'); process.exit(0); } var common = require('../common'); var assert = require('assert'); var tls = require('tls'); var fs = require('fs'); var options = { key: fs.readFileSync(common.fixturesDir + '/keys/agent2-key.pem'), cert: fs.readFileSync(common.fixturesDir + '/keys/agent2-cert.pem') }; var big = new Buffer(2 * 1024 * 1024); var connections = 0; var bytesRead = 0; big.fill('Y'); // create server var server = tls.createServer(options, function(socket) { socket.end(big); socket.destroySoon(); connections++; }); // start listening server.listen(common.PORT, function() { var client = tls.connect({ port: common.PORT, rejectUnauthorized: false }, function() { client.on('readable', function() { var d = client.read(); if (d) bytesRead += d.length; }); client.on('end', function() { server.close(); }); }); }); process.on('exit', function() { assert.equal(1, connections); assert.equal(big.length, bytesRead); }); node-v0.10.25~dfsg2/test/simple/test-http-upgrade-agent.js0000644000000000000000000000550612270121457022106 0ustar rootroot// Copyright Joyent, Inc. and other Node contributors. // // Permission is hereby granted, free of charge, to any person obtaining a // copy of this software and associated documentation files (the // "Software"), to deal in the Software without restriction, including // without limitation the rights to use, copy, modify, merge, publish, // distribute, sublicense, and/or sell copies of the Software, and to permit // persons to whom the Software is furnished to do so, subject to the // following conditions: // // The above copyright notice and this permission notice shall be included // in all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS // OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF // MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN // NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, // DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR // OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE // USE OR OTHER DEALINGS IN THE SOFTWARE. // Verify that the 'upgrade' header causes an 'upgrade' event to be emitted to // the HTTP client. This test uses a raw TCP server to better control server // behavior. var common = require('../common'); var assert = require('assert'); var http = require('http'); var net = require('net'); // Create a TCP server var srv = net.createServer(function(c) { var data = ''; c.on('data', function(d) { data += d.toString('utf8'); c.write('HTTP/1.1 101\r\n'); c.write('hello: world\r\n'); c.write('connection: upgrade\r\n'); c.write('upgrade: websocket\r\n'); c.write('\r\n'); c.write('nurtzo'); }); c.on('end', function() { c.end(); }); }); var gotUpgrade = false; srv.listen(common.PORT, '127.0.0.1', function() { var options = { port: common.PORT, host: '127.0.0.1', headers: { 'upgrade': 'websocket' } }; var name = options.host + ':' + options.port; var req = http.request(options); req.end(); req.on('upgrade', function(res, socket, upgradeHead) { // XXX: This test isn't fantastic, as it assumes that the entire response // from the server will arrive in a single data callback assert.equal(upgradeHead, 'nurtzo'); console.log(res.headers); var expectedHeaders = { 'hello': 'world', 'connection': 'upgrade', 'upgrade': 'websocket' }; assert.deepEqual(expectedHeaders, res.headers); // Make sure this request got removed from the pool. assert(!http.globalAgent.sockets.hasOwnProperty(name)); req.on('close', function() { socket.end(); srv.close(); gotUpgrade = true; }); }); }); process.on('exit', function() { assert.ok(gotUpgrade); }); node-v0.10.25~dfsg2/test/simple/test-domain-crypto.js0000644000000000000000000000307412270121457021171 0ustar rootroot// Copyright Joyent, Inc. and other Node contributors. // // Permission is hereby granted, free of charge, to any person obtaining a // copy of this software and associated documentation files (the // "Software"), to deal in the Software without restriction, including // without limitation the rights to use, copy, modify, merge, publish, // distribute, sublicense, and/or sell copies of the Software, and to permit // persons to whom the Software is furnished to do so, subject to the // following conditions: // // The above copyright notice and this permission notice shall be included // in all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS // OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF // MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN // NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, // DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR // OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE // USE OR OTHER DEALINGS IN THE SOFTWARE. try { var crypto = require('crypto'); } catch (e) { console.log('Not compiled with OPENSSL support.'); process.exit(); } // the missing var keyword is intentional domain = require('domain'); // should not throw a 'TypeError: undefined is not a function' exception crypto.randomBytes(8); crypto.randomBytes(8, function() {}); crypto.pseudoRandomBytes(8); crypto.pseudoRandomBytes(8, function() {}); crypto.pbkdf2('password', 'salt', 8, 8, function() {}); node-v0.10.25~dfsg2/test/simple/test-event-emitter-set-max-listeners-side-effects.js0000644000000000000000000000251412270121457027113 0ustar rootroot// Copyright Joyent, Inc. and other Node contributors. // // Permission is hereby granted, free of charge, to any person obtaining a // copy of this software and associated documentation files (the // "Software"), to deal in the Software without restriction, including // without limitation the rights to use, copy, modify, merge, publish, // distribute, sublicense, and/or sell copies of the Software, and to permit // persons to whom the Software is furnished to do so, subject to the // following conditions: // // The above copyright notice and this permission notice shall be included // in all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS // OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF // MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN // NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, // DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR // OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE // USE OR OTHER DEALINGS IN THE SOFTWARE. var common = require('../common'); var assert = require('assert'); var events = require('events'); var e = new events.EventEmitter; assert.deepEqual(e._events, {}); e.setMaxListeners(5); assert.deepEqual(e._events, {}); node-v0.10.25~dfsg2/test/simple/test-querystring.js0000644000000000000000000001630412270121457021000 0ustar rootroot// Copyright Joyent, Inc. and other Node contributors. // // Permission is hereby granted, free of charge, to any person obtaining a // copy of this software and associated documentation files (the // "Software"), to deal in the Software without restriction, including // without limitation the rights to use, copy, modify, merge, publish, // distribute, sublicense, and/or sell copies of the Software, and to permit // persons to whom the Software is furnished to do so, subject to the // following conditions: // // The above copyright notice and this permission notice shall be included // in all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS // OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF // MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN // NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, // DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR // OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE // USE OR OTHER DEALINGS IN THE SOFTWARE. var common = require('../common'); var assert = require('assert'); // test using assert var qs = require('querystring'); // folding block, commented to pass gjslint // {{{ // [ wonkyQS, canonicalQS, obj ] var qsTestCases = [ ['foo=918854443121279438895193', 'foo=918854443121279438895193', {'foo': '918854443121279438895193'}], ['foo=bar', 'foo=bar', {'foo': 'bar'}], ['foo=bar&foo=quux', 'foo=bar&foo=quux', {'foo': ['bar', 'quux']}], ['foo=1&bar=2', 'foo=1&bar=2', {'foo': '1', 'bar': '2'}], ['my+weird+field=q1%212%22%27w%245%267%2Fz8%29%3F', 'my%20weird%20field=q1!2%22\'w%245%267%2Fz8)%3F', {'my weird field': 'q1!2"\'w$5&7/z8)?' }], ['foo%3Dbaz=bar', 'foo%3Dbaz=bar', {'foo=baz': 'bar'}], ['foo=baz=bar', 'foo=baz%3Dbar', {'foo': 'baz=bar'}], ['str=foo&arr=1&arr=2&arr=3&somenull=&undef=', 'str=foo&arr=1&arr=2&arr=3&somenull=&undef=', { 'str': 'foo', 'arr': ['1', '2', '3'], 'somenull': '', 'undef': ''}], [' foo = bar ', '%20foo%20=%20bar%20', {' foo ': ' bar '}], ['foo=%zx', 'foo=%25zx', {'foo': '%zx'}], ['foo=%EF%BF%BD', 'foo=%EF%BF%BD', {'foo': '\ufffd' }], // See: https://github.com/joyent/node/issues/1707 ['hasOwnProperty=x&toString=foo&valueOf=bar&__defineGetter__=baz', 'hasOwnProperty=x&toString=foo&valueOf=bar&__defineGetter__=baz', { hasOwnProperty: 'x', toString: 'foo', valueOf: 'bar', __defineGetter__: 'baz' }], // See: https://github.com/joyent/node/issues/3058 ['foo&bar=baz', 'foo=&bar=baz', { foo: '', bar: 'baz' }] ]; // [ wonkyQS, canonicalQS, obj ] var qsColonTestCases = [ ['foo:bar', 'foo:bar', {'foo': 'bar'}], ['foo:bar;foo:quux', 'foo:bar;foo:quux', {'foo': ['bar', 'quux']}], ['foo:1&bar:2;baz:quux', 'foo:1%26bar%3A2;baz:quux', {'foo': '1&bar:2', 'baz': 'quux'}], ['foo%3Abaz:bar', 'foo%3Abaz:bar', {'foo:baz': 'bar'}], ['foo:baz:bar', 'foo:baz%3Abar', {'foo': 'baz:bar'}] ]; // [wonkyObj, qs, canonicalObj] var extendedFunction = function() {}; extendedFunction.prototype = {a: 'b'}; var qsWeirdObjects = [ [{regexp: /./g}, 'regexp=', {'regexp': ''}], [{regexp: new RegExp('.', 'g')}, 'regexp=', {'regexp': ''}], [{fn: function() {}}, 'fn=', {'fn': ''}], [{fn: new Function('')}, 'fn=', {'fn': ''}], [{math: Math}, 'math=', {'math': ''}], [{e: extendedFunction}, 'e=', {'e': ''}], [{d: new Date()}, 'd=', {'d': ''}], [{d: Date}, 'd=', {'d': ''}], [{f: new Boolean(false), t: new Boolean(true)}, 'f=&t=', {'f': '', 't': ''}], [{f: false, t: true}, 'f=false&t=true', {'f': 'false', 't': 'true'}], [{n: null}, 'n=', {'n': ''}], [{nan: NaN}, 'nan=', {'nan': ''}], [{inf: Infinity}, 'inf=', {'inf': ''}] ]; // }}} var Script = require('vm').Script; var foreignObject = Script.runInContext('({"foo": ["bar", "baz"]})', Script.createContext()); var qsNoMungeTestCases = [ ['', {}], ['foo=bar&foo=baz', {'foo': ['bar', 'baz']}], ['foo=bar&foo=baz', foreignObject], ['blah=burp', {'blah': 'burp'}], ['gragh=1&gragh=3&goo=2', {'gragh': ['1', '3'], 'goo': '2'}], ['frappucino=muffin&goat%5B%5D=scone&pond=moose', {'frappucino': 'muffin', 'goat[]': 'scone', 'pond': 'moose'}], ['trololol=yes&lololo=no', {'trololol': 'yes', 'lololo': 'no'}] ]; assert.strictEqual('918854443121279438895193', qs.parse('id=918854443121279438895193').id); // test that the canonical qs is parsed properly. qsTestCases.forEach(function(testCase) { assert.deepEqual(testCase[2], qs.parse(testCase[0])); }); // test that the colon test cases can do the same qsColonTestCases.forEach(function(testCase) { assert.deepEqual(testCase[2], qs.parse(testCase[0], ';', ':')); }); // test the weird objects, that they get parsed properly qsWeirdObjects.forEach(function(testCase) { assert.deepEqual(testCase[2], qs.parse(testCase[1])); }); qsNoMungeTestCases.forEach(function(testCase) { assert.deepEqual(testCase[0], qs.stringify(testCase[1], '&', '=', false)); }); // test the nested qs-in-qs case (function() { var f = qs.parse('a=b&q=x%3Dy%26y%3Dz'); f.q = qs.parse(f.q); assert.deepEqual(f, { a: 'b', q: { x: 'y', y: 'z' } }); })(); // nested in colon (function() { var f = qs.parse('a:b;q:x%3Ay%3By%3Az', ';', ':'); f.q = qs.parse(f.q, ';', ':'); assert.deepEqual(f, { a: 'b', q: { x: 'y', y: 'z' } }); })(); // now test stringifying // basic qsTestCases.forEach(function(testCase) { assert.equal(testCase[1], qs.stringify(testCase[2])); }); qsColonTestCases.forEach(function(testCase) { assert.equal(testCase[1], qs.stringify(testCase[2], ';', ':')); }); qsWeirdObjects.forEach(function(testCase) { assert.equal(testCase[1], qs.stringify(testCase[0])); }); // nested var f = qs.stringify({ a: 'b', q: qs.stringify({ x: 'y', y: 'z' }) }); assert.equal(f, 'a=b&q=x%3Dy%26y%3Dz'); assert.doesNotThrow(function() { qs.parse(undefined); }); // nested in colon var f = qs.stringify({ a: 'b', q: qs.stringify({ x: 'y', y: 'z' }, ';', ':') }, ';', ':'); assert.equal(f, 'a:b;q:x%3Ay%3By%3Az'); assert.deepEqual({}, qs.parse()); // Test limiting assert.equal( Object.keys(qs.parse('a=1&b=1&c=1', null, null, { maxKeys: 1 })).length, 1); // Test removing limit function testUnlimitedKeys() { var query = {}, url; for (var i = 0; i < 2000; i++) query[i] = i; url = qs.stringify(query); assert.equal( Object.keys(qs.parse(url, null, null, { maxKeys: 0 })).length, 2000); } testUnlimitedKeys(); var b = qs.unescapeBuffer('%d3%f2Ug%1f6v%24%5e%98%cb' + '%0d%ac%a2%2f%9d%eb%d8%a2%e6'); // assert.equal(0xd3, b[0]); assert.equal(0xf2, b[1]); assert.equal(0x55, b[2]); assert.equal(0x67, b[3]); assert.equal(0x1f, b[4]); assert.equal(0x36, b[5]); assert.equal(0x76, b[6]); assert.equal(0x24, b[7]); assert.equal(0x5e, b[8]); assert.equal(0x98, b[9]); assert.equal(0xcb, b[10]); assert.equal(0x0d, b[11]); assert.equal(0xac, b[12]); assert.equal(0xa2, b[13]); assert.equal(0x2f, b[14]); assert.equal(0x9d, b[15]); assert.equal(0xeb, b[16]); assert.equal(0xd8, b[17]); assert.equal(0xa2, b[18]); assert.equal(0xe6, b[19]); node-v0.10.25~dfsg2/test/simple/test-cluster-http-pipe.js0000644000000000000000000000416712270121457022001 0ustar rootroot// Copyright Joyent, Inc. and other Node contributors. // // Permission is hereby granted, free of charge, to any person obtaining a // copy of this software and associated documentation files (the // "Software"), to deal in the Software without restriction, including // without limitation the rights to use, copy, modify, merge, publish, // distribute, sublicense, and/or sell copies of the Software, and to permit // persons to whom the Software is furnished to do so, subject to the // following conditions: // // The above copyright notice and this permission notice shall be included // in all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS // OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF // MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN // NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, // DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR // OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE // USE OR OTHER DEALINGS IN THE SOFTWARE. // It is not possible to send pipe handles over the IPC pipe on Windows. if (process.platform === 'win32') { process.exit(0); } var common = require('../common'); var assert = require('assert'); var cluster = require('cluster'); var http = require('http'); if (cluster.isMaster) { var ok = false; var worker = cluster.fork(); worker.on('message', function(msg) { assert.equal(msg, 'DONE'); ok = true; }); worker.on('exit', function() { process.exit(); }); process.on('exit', function() { assert(ok); }); return; } http.createServer(function(req, res) { assert.equal(req.connection.remoteAddress, undefined); assert.equal(req.connection.localAddress, undefined); // TODO common.PIPE? res.writeHead(200); res.end('OK'); }).listen(common.PIPE, function() { var self = this; http.get({ socketPath: common.PIPE, path: '/' }, function(res) { res.resume(); res.on('end', function(err) { if (err) throw err; process.send('DONE'); process.exit(); }); }); }); node-v0.10.25~dfsg2/test/simple/test-http-client-parse-error.js0000644000000000000000000000404512270121457023075 0ustar rootroot// Copyright Joyent, Inc. and other Node contributors. // // Permission is hereby granted, free of charge, to any person obtaining a // copy of this software and associated documentation files (the // "Software"), to deal in the Software without restriction, including // without limitation the rights to use, copy, modify, merge, publish, // distribute, sublicense, and/or sell copies of the Software, and to permit // persons to whom the Software is furnished to do so, subject to the // following conditions: // // The above copyright notice and this permission notice shall be included // in all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS // OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF // MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN // NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, // DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR // OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE // USE OR OTHER DEALINGS IN THE SOFTWARE. var common = require('../common'); var assert = require('assert'); var http = require('http'); var net = require('net'); var connects = 0; var parseErrors = 0; // Create a TCP server net.createServer(function(c) { console.log('connection'); if (++connects === 1) { c.end('HTTP/1.1 302 Object Moved\r\nContent-Length: 0\r\n\r\nhi world'); } else { c.end('bad http - should trigger parse error\r\n'); this.close(); } }).listen(common.PORT, '127.0.0.1', function() { for (var i = 0; i < 2; i++) { http.request({ host: '127.0.0.1', port: common.PORT, method: 'GET', path: '/' }).on('error', function(e) { console.log('got error from client'); assert.ok(e.message.indexOf('Parse Error') >= 0); assert.equal(e.code, 'HPE_INVALID_CONSTANT'); parseErrors++; }).end(); } }); process.on('exit', function() { assert.equal(connects, 2); assert.equal(parseErrors, 2); }); node-v0.10.25~dfsg2/test/simple/test-net-connect-immediate-finish.js0000644000000000000000000000270312270121457024031 0ustar rootroot// Copyright Joyent, Inc. and other Node contributors. // // Permission is hereby granted, free of charge, to any person obtaining a // copy of this software and associated documentation files (the // "Software"), to deal in the Software without restriction, including // without limitation the rights to use, copy, modify, merge, publish, // distribute, sublicense, and/or sell copies of the Software, and to permit // persons to whom the Software is furnished to do so, subject to the // following conditions: // // The above copyright notice and this permission notice shall be included // in all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS // OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF // MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN // NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, // DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR // OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE // USE OR OTHER DEALINGS IN THE SOFTWARE. var common = require('../common'); var assert = require('assert'); var net = require('net'); var gotError = false; var client = net.connect({ host: 'no.way.you.will.resolve.this', port: common.PORT }); client.once('error', function(err) { gotError = true; }); client.end(); process.on('exit', function() { assert(gotError); }); node-v0.10.25~dfsg2/test/simple/test-domain-nested.js0000644000000000000000000000314112270121457021126 0ustar rootroot// Copyright Joyent, Inc. and other Node contributors. // // Permission is hereby granted, free of charge, to any person obtaining a // copy of this software and associated documentation files (the // "Software"), to deal in the Software without restriction, including // without limitation the rights to use, copy, modify, merge, publish, // distribute, sublicense, and/or sell copies of the Software, and to permit // persons to whom the Software is furnished to do so, subject to the // following conditions: // // The above copyright notice and this permission notice shall be included // in all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS // OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF // MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN // NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, // DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR // OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE // USE OR OTHER DEALINGS IN THE SOFTWARE. // Make sure that the nested domains don't cause the domain stack to grow var assert = require('assert'); var domain = require('domain'); process.on('exit', function(c) { assert.equal(domain._stack.length, 0); }); domain.create().run(function() { domain.create().run(function() { domain.create().run(function() { domain.create().on("error", function(e) { // Don't need to do anything here }).run(function() { throw new Error("died") }) }) }) }) node-v0.10.25~dfsg2/test/simple/test-sigint-infinite-loop.js0000644000000000000000000000411412270121457022447 0ustar rootroot// Copyright Joyent, Inc. and other Node contributors. // // Permission is hereby granted, free of charge, to any person obtaining a // copy of this software and associated documentation files (the // "Software"), to deal in the Software without restriction, including // without limitation the rights to use, copy, modify, merge, publish, // distribute, sublicense, and/or sell copies of the Software, and to permit // persons to whom the Software is furnished to do so, subject to the // following conditions: // // The above copyright notice and this permission notice shall be included // in all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS // OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF // MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN // NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, // DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR // OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE // USE OR OTHER DEALINGS IN THE SOFTWARE. // This test is to assert that we can SIGINT a script which loops forever. // Ref(http): // groups.google.com/group/nodejs-dev/browse_thread/thread/e20f2f8df0296d3f var common = require('../common'); var assert = require('assert'); var spawn = require('child_process').spawn; console.log('start'); var c = spawn(process.execPath, ['-e', 'while(true) { console.log("hi"); }']); var sentKill = false; var gotChildExit = true; c.stdout.on('data', function(s) { // Prevent race condition: // Wait for the first bit of output from the child process // so that we're sure that it's in the V8 event loop and not // just in the startup phase of execution. if (!sentKill) { c.kill('SIGINT'); console.log('SIGINT infinite-loop.js'); sentKill = true; } }); c.on('exit', function(code) { assert.ok(code !== 0); console.log('killed infinite-loop.js'); gotChildExit = true; }); process.on('exit', function() { assert.ok(sentKill); assert.ok(gotChildExit); }); node-v0.10.25~dfsg2/test/simple/test-stdin-pipe-resume.js0000644000000000000000000000352712270121457021761 0ustar rootroot// Copyright Joyent, Inc. and other Node contributors. // // Permission is hereby granted, free of charge, to any person obtaining a // copy of this software and associated documentation files (the // "Software"), to deal in the Software without restriction, including // without limitation the rights to use, copy, modify, merge, publish, // distribute, sublicense, and/or sell copies of the Software, and to permit // persons to whom the Software is furnished to do so, subject to the // following conditions: // // The above copyright notice and this permission notice shall be included // in all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS // OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF // MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN // NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, // DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR // OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE // USE OR OTHER DEALINGS IN THE SOFTWARE. // This tests that piping stdin will cause it to resume() as well. var common = require('../common'); var assert = require('assert'); if (process.argv[2] === 'child') { process.stdin.pipe(process.stdout); } else { var spawn = require('child_process').spawn; var buffers = []; var child = spawn(process.execPath, [__filename, 'child']); child.stdout.on('data', function(c) { buffers.push(c); }); child.stdout.on('close', function() { var b = Buffer.concat(buffers).toString(); assert.equal(b, 'Hello, world\n'); console.log('ok'); }); child.stdin.write('Hel'); child.stdin.write('lo,'); child.stdin.write(' wo'); setTimeout(function() { child.stdin.write('rld\n'); child.stdin.end(); }, 10); } node-v0.10.25~dfsg2/test/simple/test-writeint.js0000644000000000000000000001275412270121457020256 0ustar rootroot// Copyright Joyent, Inc. and other Node contributors. // // Permission is hereby granted, free of charge, to any person obtaining a // copy of this software and associated documentation files (the // "Software"), to deal in the Software without restriction, including // without limitation the rights to use, copy, modify, merge, publish, // distribute, sublicense, and/or sell copies of the Software, and to permit // persons to whom the Software is furnished to do so, subject to the // following conditions: // // The above copyright notice and this permission notice shall be included // in all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS // OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF // MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN // NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, // DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR // OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE // USE OR OTHER DEALINGS IN THE SOFTWARE. /* * Tests to verify we're writing signed integers correctly */ var SlowBuffer = process.binding('buffer').SlowBuffer; var common = require('../common'); var ASSERT = require('assert'); function test8(clazz) { var buffer = new clazz(2); buffer.writeInt8(0x23, 0); buffer.writeInt8(-5, 1); ASSERT.equal(0x23, buffer[0]); ASSERT.equal(0xfb, buffer[1]); /* Make sure we handle truncation correctly */ ASSERT.throws(function() { buffer.writeInt8(0xabc, 0); }); ASSERT.throws(function() { buffer.writeInt8(0xabc, 0); }); /* Make sure we handle min/max correctly */ buffer.writeInt8(0x7f, 0); buffer.writeInt8(-0x80, 1); ASSERT.equal(0x7f, buffer[0]); ASSERT.equal(0x80, buffer[1]); ASSERT.throws(function() { buffer.writeInt8(0x7f + 1, 0); }); ASSERT.throws(function() { buffer.writeInt8(-0x80 - 1, 0); }); } function test16(clazz) { var buffer = new clazz(6); buffer.writeInt16BE(0x0023, 0); buffer.writeInt16LE(0x0023, 2); ASSERT.equal(0x00, buffer[0]); ASSERT.equal(0x23, buffer[1]); ASSERT.equal(0x23, buffer[2]); ASSERT.equal(0x00, buffer[3]); buffer.writeInt16BE(-5, 0); buffer.writeInt16LE(-5, 2); ASSERT.equal(0xff, buffer[0]); ASSERT.equal(0xfb, buffer[1]); ASSERT.equal(0xfb, buffer[2]); ASSERT.equal(0xff, buffer[3]); buffer.writeInt16BE(-1679, 1); buffer.writeInt16LE(-1679, 3); ASSERT.equal(0xf9, buffer[1]); ASSERT.equal(0x71, buffer[2]); ASSERT.equal(0x71, buffer[3]); ASSERT.equal(0xf9, buffer[4]); /* Make sure we handle min/max correctly */ buffer.writeInt16BE(0x7fff, 0); buffer.writeInt16BE(-0x8000, 2); ASSERT.equal(0x7f, buffer[0]); ASSERT.equal(0xff, buffer[1]); ASSERT.equal(0x80, buffer[2]); ASSERT.equal(0x00, buffer[3]); ASSERT.throws(function() { buffer.writeInt16BE(0x7fff + 1, 0); }); ASSERT.throws(function() { buffer.writeInt16BE(-0x8000 - 1, 0); }); buffer.writeInt16LE(0x7fff, 0); buffer.writeInt16LE(-0x8000, 2); ASSERT.equal(0xff, buffer[0]); ASSERT.equal(0x7f, buffer[1]); ASSERT.equal(0x00, buffer[2]); ASSERT.equal(0x80, buffer[3]); ASSERT.throws(function() { buffer.writeInt16LE(0x7fff + 1, 0); }); ASSERT.throws(function() { buffer.writeInt16LE(-0x8000 - 1, 0); }); } function test32(clazz) { var buffer = new clazz(8); buffer.writeInt32BE(0x23, 0); buffer.writeInt32LE(0x23, 4); ASSERT.equal(0x00, buffer[0]); ASSERT.equal(0x00, buffer[1]); ASSERT.equal(0x00, buffer[2]); ASSERT.equal(0x23, buffer[3]); ASSERT.equal(0x23, buffer[4]); ASSERT.equal(0x00, buffer[5]); ASSERT.equal(0x00, buffer[6]); ASSERT.equal(0x00, buffer[7]); buffer.writeInt32BE(-5, 0); buffer.writeInt32LE(-5, 4); ASSERT.equal(0xff, buffer[0]); ASSERT.equal(0xff, buffer[1]); ASSERT.equal(0xff, buffer[2]); ASSERT.equal(0xfb, buffer[3]); ASSERT.equal(0xfb, buffer[4]); ASSERT.equal(0xff, buffer[5]); ASSERT.equal(0xff, buffer[6]); ASSERT.equal(0xff, buffer[7]); buffer.writeInt32BE(-805306713, 0); buffer.writeInt32LE(-805306713, 4); ASSERT.equal(0xcf, buffer[0]); ASSERT.equal(0xff, buffer[1]); ASSERT.equal(0xfe, buffer[2]); ASSERT.equal(0xa7, buffer[3]); ASSERT.equal(0xa7, buffer[4]); ASSERT.equal(0xfe, buffer[5]); ASSERT.equal(0xff, buffer[6]); ASSERT.equal(0xcf, buffer[7]); /* Make sure we handle min/max correctly */ buffer.writeInt32BE(0x7fffffff, 0); buffer.writeInt32BE(-0x80000000, 4); ASSERT.equal(0x7f, buffer[0]); ASSERT.equal(0xff, buffer[1]); ASSERT.equal(0xff, buffer[2]); ASSERT.equal(0xff, buffer[3]); ASSERT.equal(0x80, buffer[4]); ASSERT.equal(0x00, buffer[5]); ASSERT.equal(0x00, buffer[6]); ASSERT.equal(0x00, buffer[7]); ASSERT.throws(function() { buffer.writeInt32BE(0x7fffffff + 1, 0); }); ASSERT.throws(function() { buffer.writeInt32BE(-0x80000000 - 1, 0); }); buffer.writeInt32LE(0x7fffffff, 0); buffer.writeInt32LE(-0x80000000, 4); ASSERT.equal(0xff, buffer[0]); ASSERT.equal(0xff, buffer[1]); ASSERT.equal(0xff, buffer[2]); ASSERT.equal(0x7f, buffer[3]); ASSERT.equal(0x00, buffer[4]); ASSERT.equal(0x00, buffer[5]); ASSERT.equal(0x00, buffer[6]); ASSERT.equal(0x80, buffer[7]); ASSERT.throws(function() { buffer.writeInt32LE(0x7fffffff + 1, 0); }); ASSERT.throws(function() { buffer.writeInt32LE(-0x80000000 - 1, 0); }); } test8(Buffer); test8(SlowBuffer); test16(Buffer); test16(SlowBuffer); test32(Buffer); test32(SlowBuffer); node-v0.10.25~dfsg2/test/simple/test-cluster-setup-master.js0000644000000000000000000000516012270121457022512 0ustar rootroot// Copyright Joyent, Inc. and other Node contributors. // // Permission is hereby granted, free of charge, to any person obtaining a // copy of this software and associated documentation files (the // "Software"), to deal in the Software without restriction, including // without limitation the rights to use, copy, modify, merge, publish, // distribute, sublicense, and/or sell copies of the Software, and to permit // persons to whom the Software is furnished to do so, subject to the // following conditions: // // The above copyright notice and this permission notice shall be included // in all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS // OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF // MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN // NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, // DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR // OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE // USE OR OTHER DEALINGS IN THE SOFTWARE. var common = require('../common'); var assert = require('assert'); var cluster = require('cluster'); if (cluster.isWorker) { // Just keep the worker alive process.send(process.argv[2]); } else if (cluster.isMaster) { var checks = { args: false, setupEvent: false, settingsObject: false }; var totalWorkers = 2; cluster.once('setup', function() { checks.setupEvent = true; var settings = cluster.settings; if (settings && settings.args && settings.args[0] === 'custom argument' && settings.silent === true && settings.exec === process.argv[1]) { checks.settingsObject = true; } }); // Setup master cluster.setupMaster({ args: ['custom argument'], silent: true }); var correctIn = 0; cluster.on('online', function lisenter(worker) { worker.once('message', function(data) { correctIn += (data === 'custom argument' ? 1 : 0); if (correctIn === totalWorkers) { checks.args = true; } worker.kill(); }); // All workers are online if (cluster.onlineWorkers === totalWorkers) { checks.workers = true; } }); // Start all workers cluster.fork(); cluster.fork(); // Check all values process.once('exit', function() { assert.ok(checks.args, 'The arguments was noy send to the worker'); assert.ok(checks.setupEvent, 'The setup event was never emitted'); var m = 'The settingsObject do not have correct properties'; assert.ok(checks.settingsObject, m); }); } node-v0.10.25~dfsg2/test/simple/test-http-parser.js0000644000000000000000000003345312270121457020661 0ustar rootroot// Copyright Joyent, Inc. and other Node contributors. // // Permission is hereby granted, free of charge, to any person obtaining a // copy of this software and associated documentation files (the // "Software"), to deal in the Software without restriction, including // without limitation the rights to use, copy, modify, merge, publish, // distribute, sublicense, and/or sell copies of the Software, and to permit // persons to whom the Software is furnished to do so, subject to the // following conditions: // // The above copyright notice and this permission notice shall be included // in all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS // OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF // MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN // NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, // DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR // OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE // USE OR OTHER DEALINGS IN THE SOFTWARE. var common = require('../common'); var assert = require('assert'); var HTTPParser = process.binding('http_parser').HTTPParser; var CRLF = '\r\n'; var REQUEST = HTTPParser.REQUEST; var RESPONSE = HTTPParser.RESPONSE; // The purpose of this test is not to check HTTP compliance but to test the // binding. Tests for pathological http messages should be submitted // upstream to https://github.com/joyent/http-parser for inclusion into // deps/http-parser/test.c function newParser(type) { var parser = new HTTPParser(type); parser.headers = []; parser.url = ''; parser.onHeaders = function(headers, url) { parser.headers = parser.headers.concat(headers); parser.url += url; }; parser.onHeadersComplete = function(info) { }; parser.onBody = function(b, start, len) { assert.ok(false, 'Function should not be called.'); }; parser.onMessageComplete = function() { }; return parser; } function mustCall(f, times) { var actual = 0; process.setMaxListeners(256); process.on('exit', function() { assert.equal(actual, times || 1); }); return function() { actual++; return f.apply(this, Array.prototype.slice.call(arguments)); }; } function expectBody(expected) { return mustCall(function(buf, start, len) { var body = '' + buf.slice(start, start + len); assert.equal(body, expected); }); } // // Simple request test. // (function() { var request = Buffer( 'GET /hello HTTP/1.1' + CRLF + CRLF); var parser = newParser(REQUEST); parser.onHeadersComplete = mustCall(function(info) { assert.equal(info.method, 'GET'); assert.equal(info.url || parser.url, '/hello'); assert.equal(info.versionMajor, 1); assert.equal(info.versionMinor, 1); }); parser.execute(request, 0, request.length); // // Check that if we throw an error in the callbacks that error will be // thrown from parser.execute() // parser.onHeadersComplete = function(info) { throw new Error('hello world'); }; parser.reinitialize(HTTPParser.REQUEST); assert.throws(function() { parser.execute(request, 0, request.length); }, Error, 'hello world'); })(); // // Simple response test. // (function() { var request = Buffer( 'HTTP/1.1 200 OK' + CRLF + 'Content-Type: text/plain' + CRLF + 'Content-Length: 4' + CRLF + CRLF + 'pong'); var parser = newParser(RESPONSE); parser.onHeadersComplete = mustCall(function(info) { assert.equal(info.method, undefined); assert.equal(info.versionMajor, 1); assert.equal(info.versionMinor, 1); assert.equal(info.statusCode, 200); }); parser.onBody = mustCall(function(buf, start, len) { var body = '' + buf.slice(start, start + len); assert.equal(body, 'pong'); }); parser.execute(request, 0, request.length); })(); // // Response with no headers. // (function() { var request = Buffer( 'HTTP/1.0 200 Connection established' + CRLF + CRLF); var parser = newParser(RESPONSE); parser.onHeadersComplete = mustCall(function(info) { assert.equal(info.method, undefined); assert.equal(info.versionMajor, 1); assert.equal(info.versionMinor, 0); assert.equal(info.statusCode, 200); assert.deepEqual(info.headers || parser.headers, []); }); parser.execute(request, 0, request.length); })(); // // Trailing headers. // (function() { var request = Buffer( 'POST /it HTTP/1.1' + CRLF + 'Transfer-Encoding: chunked' + CRLF + CRLF + '4' + CRLF + 'ping' + CRLF + '0' + CRLF + 'Vary: *' + CRLF + 'Content-Type: text/plain' + CRLF + CRLF); var seen_body = false; function onHeaders(headers, url) { assert.ok(seen_body); // trailers should come after the body assert.deepEqual(headers, ['Vary', '*', 'Content-Type', 'text/plain']); } var parser = newParser(REQUEST); parser.onHeadersComplete = mustCall(function(info) { assert.equal(info.method, 'POST'); assert.equal(info.url || parser.url, '/it'); assert.equal(info.versionMajor, 1); assert.equal(info.versionMinor, 1); // expect to see trailing headers now parser.onHeaders = mustCall(onHeaders); }); parser.onBody = mustCall(function(buf, start, len) { var body = '' + buf.slice(start, start + len); assert.equal(body, 'ping'); seen_body = true; }); parser.execute(request, 0, request.length); })(); // // Test header ordering. // (function() { var request = Buffer( 'GET / HTTP/1.0' + CRLF + 'X-Filler: 1337' + CRLF + 'X-Filler: 42' + CRLF + 'X-Filler2: 42' + CRLF + CRLF); var parser = newParser(REQUEST); parser.onHeadersComplete = mustCall(function(info) { assert.equal(info.method, 'GET'); assert.equal(info.versionMajor, 1); assert.equal(info.versionMinor, 0); assert.deepEqual(info.headers || parser.headers, ['X-Filler', '1337', 'X-Filler', '42', 'X-Filler2', '42']); }); parser.execute(request, 0, request.length); })(); // // Test large number of headers // (function() { // 256 X-Filler headers var lots_of_headers = 'X-Filler: 42' + CRLF; for (var i = 0; i < 8; ++i) lots_of_headers += lots_of_headers; var request = Buffer( 'GET /foo/bar/baz?quux=42#1337 HTTP/1.0' + CRLF + lots_of_headers + CRLF); var parser = newParser(REQUEST); parser.onHeadersComplete = mustCall(function(info) { assert.equal(info.method, 'GET'); assert.equal(info.url || parser.url, '/foo/bar/baz?quux=42#1337'); assert.equal(info.versionMajor, 1); assert.equal(info.versionMinor, 0); var headers = info.headers || parser.headers; assert.equal(headers.length, 2 * 256); // 256 key/value pairs for (var i = 0; i < headers.length; i += 2) { assert.equal(headers[i], 'X-Filler'); assert.equal(headers[i + 1], '42'); } }); parser.execute(request, 0, request.length); })(); // // Test request body // (function() { var request = Buffer( 'POST /it HTTP/1.1' + CRLF + 'Content-Type: application/x-www-form-urlencoded' + CRLF + 'Content-Length: 15' + CRLF + CRLF + 'foo=42&bar=1337'); var parser = newParser(REQUEST); parser.onHeadersComplete = mustCall(function(info) { assert.equal(info.method, 'POST'); assert.equal(info.url || parser.url, '/it'); assert.equal(info.versionMajor, 1); assert.equal(info.versionMinor, 1); }); parser.onBody = mustCall(function(buf, start, len) { var body = '' + buf.slice(start, start + len); assert.equal(body, 'foo=42&bar=1337'); }); parser.execute(request, 0, request.length); })(); // // Test chunked request body // (function() { var request = Buffer( 'POST /it HTTP/1.1' + CRLF + 'Content-Type: text/plain' + CRLF + 'Transfer-Encoding: chunked' + CRLF + CRLF + '3' + CRLF + '123' + CRLF + '6' + CRLF + '123456' + CRLF + 'A' + CRLF + '1234567890' + CRLF + '0' + CRLF); var parser = newParser(REQUEST); parser.onHeadersComplete = mustCall(function(info) { assert.equal(info.method, 'POST'); assert.equal(info.url || parser.url, '/it'); assert.equal(info.versionMajor, 1); assert.equal(info.versionMinor, 1); }); var body_part = 0, body_parts = ['123', '123456', '1234567890']; function onBody(buf, start, len) { var body = '' + buf.slice(start, start + len); assert.equal(body, body_parts[body_part++]); } parser.onBody = mustCall(onBody, body_parts.length); parser.execute(request, 0, request.length); })(); // // Test chunked request body spread over multiple buffers (packets) // (function() { var request = Buffer( 'POST /it HTTP/1.1' + CRLF + 'Content-Type: text/plain' + CRLF + 'Transfer-Encoding: chunked' + CRLF + CRLF + '3' + CRLF + '123' + CRLF + '6' + CRLF + '123456' + CRLF); var parser = newParser(REQUEST); parser.onHeadersComplete = mustCall(function(info) { assert.equal(info.method, 'POST'); assert.equal(info.url || parser.url, '/it'); assert.equal(info.versionMajor, 1); assert.equal(info.versionMinor, 1); }); var body_part = 0, body_parts = [ '123', '123456', '123456789', '123456789ABC', '123456789ABCDEF']; function onBody(buf, start, len) { var body = '' + buf.slice(start, start + len); assert.equal(body, body_parts[body_part++]); } parser.onBody = mustCall(onBody, body_parts.length); parser.execute(request, 0, request.length); request = Buffer( '9' + CRLF + '123456789' + CRLF + 'C' + CRLF + '123456789ABC' + CRLF + 'F' + CRLF + '123456789ABCDEF' + CRLF + '0' + CRLF); parser.execute(request, 0, request.length); })(); // // Stress test. // (function() { var request = Buffer( 'POST /helpme HTTP/1.1' + CRLF + 'Content-Type: text/plain' + CRLF + 'Transfer-Encoding: chunked' + CRLF + CRLF + '3' + CRLF + '123' + CRLF + '6' + CRLF + '123456' + CRLF + '9' + CRLF + '123456789' + CRLF + 'C' + CRLF + '123456789ABC' + CRLF + 'F' + CRLF + '123456789ABCDEF' + CRLF + '0' + CRLF); function test(a, b) { var parser = newParser(REQUEST); parser.onHeadersComplete = mustCall(function(info) { assert.equal(info.method, 'POST'); assert.equal(info.url || parser.url, '/helpme'); assert.equal(info.versionMajor, 1); assert.equal(info.versionMinor, 1); }); var expected_body = '123123456123456789123456789ABC123456789ABCDEF'; parser.onBody = function(buf, start, len) { var chunk = '' + buf.slice(start, start + len); assert.equal(expected_body.indexOf(chunk), 0); expected_body = expected_body.slice(chunk.length); }; parser.execute(a, 0, a.length); parser.execute(b, 0, b.length); assert.equal(expected_body, ''); } for (var i = 1; i < request.length - 1; ++i) { var a = request.slice(0, i); console.error('request.slice(0, ' + i + ') = ', JSON.stringify(a.toString())); var b = request.slice(i); console.error('request.slice(' + i + ') = ', JSON.stringify(b.toString())); test(a, b); } })(); // // Byte by byte test. // (function() { var request = Buffer( 'POST /it HTTP/1.1' + CRLF + 'Content-Type: text/plain' + CRLF + 'Transfer-Encoding: chunked' + CRLF + CRLF + '3' + CRLF + '123' + CRLF + '6' + CRLF + '123456' + CRLF + '9' + CRLF + '123456789' + CRLF + 'C' + CRLF + '123456789ABC' + CRLF + 'F' + CRLF + '123456789ABCDEF' + CRLF + '0' + CRLF); var parser = newParser(REQUEST); parser.onHeadersComplete = mustCall(function(info) { assert.equal(info.method, 'POST'); assert.equal(info.url || parser.url, '/it'); assert.equal(info.versionMajor, 1); assert.equal(info.versionMinor, 1); assert.deepEqual(info.headers || parser.headers, ['Content-Type', 'text/plain', 'Transfer-Encoding', 'chunked']); }); var expected_body = '123123456123456789123456789ABC123456789ABCDEF'; parser.onBody = function(buf, start, len) { var chunk = '' + buf.slice(start, start + len); assert.equal(expected_body.indexOf(chunk), 0); expected_body = expected_body.slice(chunk.length); }; for (var i = 0; i < request.length; ++i) { parser.execute(request, i, 1); } assert.equal(expected_body, ''); })(); // // Test parser reinit sequence. // (function() { var req1 = Buffer( 'PUT /this HTTP/1.1' + CRLF + 'Content-Type: text/plain' + CRLF + 'Transfer-Encoding: chunked' + CRLF + CRLF + '4' + CRLF + 'ping' + CRLF + '0' + CRLF); var req2 = Buffer( 'POST /that HTTP/1.0' + CRLF + 'Content-Type: text/plain' + CRLF + 'Content-Length: 4' + CRLF + CRLF + 'pong'); function onHeadersComplete1(info) { assert.equal(info.method, 'PUT'); assert.equal(info.url, '/this'); assert.equal(info.versionMajor, 1); assert.equal(info.versionMinor, 1); assert.deepEqual(info.headers, ['Content-Type', 'text/plain', 'Transfer-Encoding', 'chunked']); }; function onHeadersComplete2(info) { assert.equal(info.method, 'POST'); assert.equal(info.url, '/that'); assert.equal(info.versionMajor, 1); assert.equal(info.versionMinor, 0); assert.deepEqual(info.headers, ['Content-Type', 'text/plain', 'Content-Length', '4']); }; var parser = newParser(REQUEST); parser.onHeadersComplete = onHeadersComplete1; parser.onBody = expectBody('ping'); parser.execute(req1, 0, req1.length); parser.reinitialize(REQUEST); parser.onBody = expectBody('pong'); parser.onHeadersComplete = onHeadersComplete2; parser.execute(req2, 0, req2.length); })(); node-v0.10.25~dfsg2/test/simple/test-fs-read-file-sync.js0000644000000000000000000000265112270121457021614 0ustar rootroot// Copyright Joyent, Inc. and other Node contributors. // // Permission is hereby granted, free of charge, to any person obtaining a // copy of this software and associated documentation files (the // "Software"), to deal in the Software without restriction, including // without limitation the rights to use, copy, modify, merge, publish, // distribute, sublicense, and/or sell copies of the Software, and to permit // persons to whom the Software is furnished to do so, subject to the // following conditions: // // The above copyright notice and this permission notice shall be included // in all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS // OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF // MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN // NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, // DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR // OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE // USE OR OTHER DEALINGS IN THE SOFTWARE. var common = require('../common'); var assert = require('assert'); var path = require('path'); var fs = require('fs'); var fn = path.join(common.fixturesDir, 'elipses.txt'); var s = fs.readFileSync(fn, 'utf8'); for (var i = 0; i < s.length; i++) { assert.equal('\u2026', s[i]); } assert.equal(10000, s.length); node-v0.10.25~dfsg2/test/simple/test-stream2-large-read-stall.js0000644000000000000000000000461712270121457023103 0ustar rootroot// Copyright Joyent, Inc. and other Node contributors. // // Permission is hereby granted, free of charge, to any person obtaining a // copy of this software and associated documentation files (the // "Software"), to deal in the Software without restriction, including // without limitation the rights to use, copy, modify, merge, publish, // distribute, sublicense, and/or sell copies of the Software, and to permit // persons to whom the Software is furnished to do so, subject to the // following conditions: // // The above copyright notice and this permission notice shall be included // in all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS // OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF // MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN // NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, // DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR // OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE // USE OR OTHER DEALINGS IN THE SOFTWARE. var common = require('../common.js'); var assert = require('assert'); // If everything aligns so that you do a read(n) of exactly the // remaining buffer, then make sure that 'end' still emits. var READSIZE = 100; var PUSHSIZE = 20; var PUSHCOUNT = 1000; var HWM = 50; var Readable = require('stream').Readable; var r = new Readable({ highWaterMark: HWM }); var rs = r._readableState; r._read = push; r.on('readable', function() { console.error('>> readable'); do { console.error(' > read(%d)', READSIZE); var ret = r.read(READSIZE); console.error(' < %j (%d remain)', ret && ret.length, rs.length); } while (ret && ret.length === READSIZE); console.error('<< after read()', ret && ret.length, rs.needReadable, rs.length); }); var endEmitted = false; r.on('end', function() { endEmitted = true; console.error('end'); }); var pushes = 0; function push() { if (pushes > PUSHCOUNT) return; if (pushes++ === PUSHCOUNT) { console.error(' push(EOF)'); return r.push(null); } console.error(' push #%d', pushes); if (r.push(new Buffer(PUSHSIZE))) setTimeout(push); } // start the flow var ret = r.read(0); process.on('exit', function() { assert.equal(pushes, PUSHCOUNT + 1); assert(endEmitted); }); node-v0.10.25~dfsg2/test/simple/test-zlib-random-byte-pipes.js0000644000000000000000000001110712270121457022675 0ustar rootroot// Copyright Joyent, Inc. and other Node contributors. // // Permission is hereby granted, free of charge, to any person obtaining a // copy of this software and associated documentation files (the // "Software"), to deal in the Software without restriction, including // without limitation the rights to use, copy, modify, merge, publish, // distribute, sublicense, and/or sell copies of the Software, and to permit // persons to whom the Software is furnished to do so, subject to the // following conditions: // // The above copyright notice and this permission notice shall be included // in all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS // OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF // MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN // NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, // DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR // OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE // USE OR OTHER DEALINGS IN THE SOFTWARE. var common = require('../common'); var crypto = require('crypto'); var stream = require('stream'); var Stream = stream.Stream; var util = require('util'); var assert = require('assert'); var zlib = require('zlib'); // emit random bytes, and keep a shasum function RandomReadStream(opt) { Stream.call(this); this.readable = true; this._paused = false; this._processing = false; this._hasher = crypto.createHash('sha1'); opt = opt || {}; // base block size. opt.block = opt.block || 256 * 1024; // total number of bytes to emit opt.total = opt.total || 256 * 1024 * 1024; this._remaining = opt.total; // how variable to make the block sizes opt.jitter = opt.jitter || 1024; this._opt = opt; this._process = this._process.bind(this); process.nextTick(this._process); } util.inherits(RandomReadStream, Stream); RandomReadStream.prototype.pause = function() { this._paused = true; this.emit('pause'); }; RandomReadStream.prototype.resume = function() { // console.error("rrs resume"); this._paused = false; this.emit('resume'); this._process(); }; RandomReadStream.prototype._process = function() { if (this._processing) return; if (this._paused) return; this._processing = true; if (!this._remaining) { this._hash = this._hasher.digest('hex').toLowerCase().trim(); this._processing = false; this.emit('end'); return; } // figure out how many bytes to output // if finished, then just emit end. var block = this._opt.block; var jitter = this._opt.jitter; if (jitter) { block += Math.ceil(Math.random() * jitter - (jitter / 2)); } block = Math.min(block, this._remaining); var buf = new Buffer(block); for (var i = 0; i < block; i++) { buf[i] = Math.random() * 256; } this._hasher.update(buf); this._remaining -= block; console.error('block=%d\nremain=%d\n', block, this._remaining); this._processing = false; this.emit('data', buf); process.nextTick(this._process); }; // a filter that just verifies a shasum function HashStream() { Stream.call(this); this.readable = this.writable = true; this._hasher = crypto.createHash('sha1'); } util.inherits(HashStream, Stream); HashStream.prototype.write = function(c) { // Simulate the way that an fs.ReadStream returns false // on *every* write like a jerk, only to resume a // moment later. this._hasher.update(c); process.nextTick(this.resume.bind(this)); return false; }; HashStream.prototype.resume = function() { this.emit('resume'); process.nextTick(this.emit.bind(this, 'drain')); }; HashStream.prototype.end = function(c) { if (c) { this.write(c); } this._hash = this._hasher.digest('hex').toLowerCase().trim(); this.emit('data', this._hash); this.emit('end'); }; var inp = new RandomReadStream({ total: 1024, block: 256, jitter: 16 }); var out = new HashStream(); var gzip = zlib.createGzip(); var gunz = zlib.createGunzip(); inp.pipe(gzip).pipe(gunz).pipe(out); inp.on('data', function(c) { console.error('inp data', c.length); }); gzip.on('data', function(c) { console.error('gzip data', c.length); }); gunz.on('data', function(c) { console.error('gunz data', c.length); }); out.on('data', function(c) { console.error('out data', c.length); }); var didSomething = false; out.on('data', function(c) { didSomething = true; console.error('hash=%s', c); assert.equal(c, inp._hash, 'hashes should match'); }); process.on('exit', function() { assert(didSomething, 'should have done something'); }); node-v0.10.25~dfsg2/test/simple/test-http-max-headers-count.js0000644000000000000000000000531012270121457022700 0ustar rootroot// Copyright Joyent, Inc. and other Node contributors. // // Permission is hereby granted, free of charge, to any person obtaining a // copy of this software and associated documentation files (the // "Software"), to deal in the Software without restriction, including // without limitation the rights to use, copy, modify, merge, publish, // distribute, sublicense, and/or sell copies of the Software, and to permit // persons to whom the Software is furnished to do so, subject to the // following conditions: // // The above copyright notice and this permission notice shall be included // in all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS // OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF // MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN // NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, // DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR // OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE // USE OR OTHER DEALINGS IN THE SOFTWARE. var common = require('../common'); var assert = require('assert'); var http = require('http'); var requests = 0; var responses = 0; var headers = {}; var N = 2000; for (var i = 0; i < N; ++i) { headers['key' + i] = i; } var maxAndExpected = [ // for server [50, 50], [1500, 1500], [0, N + 2] // Host and Connection ]; var max = maxAndExpected[requests][0]; var expected = maxAndExpected[requests][1]; var server = http.createServer(function(req, res) { assert.equal(Object.keys(req.headers).length, expected); if (++requests < maxAndExpected.length) { max = maxAndExpected[requests][0]; expected = maxAndExpected[requests][1]; server.maxHeadersCount = max; } res.writeHead(200, headers); res.end(); }); server.maxHeadersCount = max; server.listen(common.PORT, function() { var maxAndExpected = [ // for client [20, 20], [1200, 1200], [0, N + 3] // Connection, Date and Transfer-Encoding ]; doRequest(); function doRequest() { var max = maxAndExpected[responses][0]; var expected = maxAndExpected[responses][1]; var req = http.request({ port: common.PORT, headers: headers }, function(res) { assert.equal(Object.keys(res.headers).length, expected); res.on('end', function() { if (++responses < maxAndExpected.length) { doRequest(); } else { server.close(); } }); res.resume(); }); req.maxHeadersCount = max; req.end(); } }); process.on('exit', function() { assert.equal(requests, maxAndExpected.length); assert.equal(responses, maxAndExpected.length); }); node-v0.10.25~dfsg2/test/simple/test-fs-exists.js0000644000000000000000000000302712270121457020327 0ustar rootroot// Copyright Joyent, Inc. and other Node contributors. // // Permission is hereby granted, free of charge, to any person obtaining a // copy of this software and associated documentation files (the // "Software"), to deal in the Software without restriction, including // without limitation the rights to use, copy, modify, merge, publish, // distribute, sublicense, and/or sell copies of the Software, and to permit // persons to whom the Software is furnished to do so, subject to the // following conditions: // // The above copyright notice and this permission notice shall be included // in all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS // OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF // MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN // NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, // DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR // OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE // USE OR OTHER DEALINGS IN THE SOFTWARE. var common = require('../common'); var assert = require('assert'); var fs = require('fs'); var f = __filename; var exists; var doesNotExist; fs.exists(f, function(y) { exists = y; }); fs.exists(f + '-NO', function(y) { doesNotExist = y; }); assert(fs.existsSync(f)); assert(!fs.existsSync(f + '-NO')); process.on('exit', function() { assert.strictEqual(exists, true); assert.strictEqual(doesNotExist, false); }); node-v0.10.25~dfsg2/test/simple/test-bad-unicode.js0000644000000000000000000000241412270121457020553 0ustar rootroot// Copyright Joyent, Inc. and other Node contributors. // // Permission is hereby granted, free of charge, to any person obtaining a // copy of this software and associated documentation files (the // "Software"), to deal in the Software without restriction, including // without limitation the rights to use, copy, modify, merge, publish, // distribute, sublicense, and/or sell copies of the Software, and to permit // persons to whom the Software is furnished to do so, subject to the // following conditions: // // The above copyright notice and this permission notice shall be included // in all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS // OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF // MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN // NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, // DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR // OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE // USE OR OTHER DEALINGS IN THE SOFTWARE. var assert = require('assert'), exception = null; try { eval('"\\uc/ef"'); } catch (e) { exception = e; } assert(exception instanceof SyntaxError); node-v0.10.25~dfsg2/test/simple/test-fs-sync-fd-leak.js0000644000000000000000000000400512270121457021262 0ustar rootroot// Copyright Joyent, Inc. and other Node contributors. // // Permission is hereby granted, free of charge, to any person obtaining a // copy of this software and associated documentation files (the // "Software"), to deal in the Software without restriction, including // without limitation the rights to use, copy, modify, merge, publish, // distribute, sublicense, and/or sell copies of the Software, and to permit // persons to whom the Software is furnished to do so, subject to the // following conditions: // // The above copyright notice and this permission notice shall be included // in all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS // OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF // MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN // NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, // DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR // OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE // USE OR OTHER DEALINGS IN THE SOFTWARE. var common = require('../common'); var assert = require('assert'); var fs = require('fs'); // ensure that (read|write|append)FileSync() closes the file descriptor fs.openSync = function() { return 42; }; fs.closeSync = function(fd) { assert.equal(fd, 42); close_called++; }; fs.readSync = function() { throw new Error('BAM'); }; fs.writeSync = function() { throw new Error('BAM'); }; fs.fstatSync = function() { throw new Error('BAM'); }; ensureThrows(function() { fs.readFileSync('dummy'); }); ensureThrows(function() { fs.writeFileSync('dummy', 'xxx'); }); ensureThrows(function() { fs.appendFileSync('dummy', 'xxx'); }); var close_called = 0; function ensureThrows(cb) { var got_exception = false; close_called = 0; try { cb(); } catch (e) { assert.equal(e.message, 'BAM'); got_exception = true; } assert.equal(close_called, 1); assert.equal(got_exception, true); } node-v0.10.25~dfsg2/test/simple/test-typed-arrays.js0000644000000000000000000001546712270121457021041 0ustar rootroot// Copyright Joyent, Inc. and other Node contributors. // Permission is hereby granted, free of charge, to any person obtaining a // copy of this software and associated documentation files (the // "Software"), to deal in the Software without restriction, including // without limitation the rights to use, copy, modify, merge, publish, // distribute, sublicense, and/or sell copies of the Software, and to permit // persons to whom the Software is furnished to do so, subject to the // following conditions: // The above copyright notice and this permission notice shall be included // in all copies or substantial portions of the Software. // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS // OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF // MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN // NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, // DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR // OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE // USE OR OTHER DEALINGS IN THE SOFTWARE. /* * Test to verify we are using Typed Arrays * (http://www.khronos.org/registry/typedarray/specs/latest/) correctly Test to * verify Buffer can used in Typed Arrays */ var common = require('../common'); var assert = require('assert'); [ 'ArrayBuffer', 'Int8Array', 'Uint8Array', 'Int16Array', 'Uint16Array', 'Int32Array', 'Uint32Array', 'Float32Array', 'Float64Array', 'Uint8ClampedArray' ].forEach(function(name) { var expected = '[object ' + name + ']'; var clazz = global[name]; var obj = new clazz(1); assert.equal(obj.toString(), expected); assert.equal(Object.prototype.toString.call(obj), expected); obj = new DataView(obj.buffer || obj); assert.equal(obj.toString(), '[object DataView]'); assert.equal(Object.prototype.toString.call(obj), '[object DataView]'); // Calling constructor as function should work. clazz(32); }); // Calling constructor as function should work. DataView(ArrayBuffer(32)); var buffer = new ArrayBuffer(16); var uint8 = new Uint8Array(buffer); var uint16 = new Uint16Array(buffer); var uint16slice = new Uint16Array(buffer, 2, 2); var uint32 = new Uint32Array(buffer); assert.equal(uint8.BYTES_PER_ELEMENT, 1); assert.equal(uint16.BYTES_PER_ELEMENT, 2); assert.equal(uint16slice.BYTES_PER_ELEMENT, 2); assert.equal(uint32.BYTES_PER_ELEMENT, 4); // now change the underlying buffer buffer[0] = 0x08; buffer[1] = 0x09; buffer[2] = 0x0a; buffer[3] = 0x0b; buffer[4] = 0x0c; buffer[5] = 0x0d; buffer[6] = 0x0e; buffer[7] = 0x0f; /* This is what we expect the variables to look like at this point (on little-endian machines): uint8 | 0x08 | 0x09 | 0x0a | 0x0b | 0x0c | 0x0d | 0x0e | 0x0f | uint16 | 0x0908 | 0x0b0a | 0x0d0c | 0x0f0e | uint16slice --------------| 0x0b0a | 0x0d0c |-------------- uint32 | 0x0b0a0908 | 0x0f0e0d0c | */ assert.equal(uint8[0], 0x08); assert.equal(uint8[1], 0x09); assert.equal(uint8[2], 0x0a); assert.equal(uint8[3], 0x0b); assert.equal(uint8[4], 0x0c); assert.equal(uint8[5], 0x0d); assert.equal(uint8[6], 0x0e); assert.equal(uint8[7], 0x0f); // determine whether or not typed array values are stored little-endian first // internally var IS_LITTLE_ENDIAN = (new Uint16Array([0x1234])).buffer[0] === 0x34; if (IS_LITTLE_ENDIAN) { assert.equal(uint16[0], 0x0908); assert.equal(uint16[1], 0x0b0a); assert.equal(uint16[2], 0x0d0c); assert.equal(uint16[3], 0x0f0e); assert.equal(uint16slice[0], 0x0b0a); assert.equal(uint16slice[1], 0x0d0c); assert.equal(uint32[0], 0x0b0a0908); assert.equal(uint32[1], 0x0f0e0d0c); } else { assert.equal(uint16[0], 0x0809); assert.equal(uint16[1], 0x0a0b); assert.equal(uint16[2], 0x0c0d); assert.equal(uint16[3], 0x0e0f); assert.equal(uint16slice[0], 0x0a0b); assert.equal(uint16slice[1], 0x0c0d); assert.equal(uint32[0], 0x08090a0b); assert.equal(uint32[1], 0x0c0d0e0f); } // test .subarray(begin, end) var sub = uint8.subarray(2, 4); assert.ok(sub instanceof Uint8Array); assert.equal(sub[0], 0x0a); assert.equal(sub[1], 0x0b); // modifications of a value in the subarray of `uint8` should propagate to // the other views sub[0] = 0x12; sub[1] = 0x34; assert.equal(uint8[2], 0x12); assert.equal(uint8[3], 0x34); // test .set(index, value), .set(arr, offset) and .get(index) uint8.set(1, 0x09); uint8.set([0x0a, 0x0b], 2); assert.equal(uint8.get(1), 0x09); assert.equal(uint8.get(2), 0x0a); assert.equal(uint8.get(3), 0x0b); // test clamped array var uint8c = new Uint8ClampedArray(buffer); uint8c[0] = -1; uint8c[1] = 257; assert.equal(uint8c[0], 0); assert.equal(uint8c[1], 255); uint8c.set(0, -10); uint8c.set(1, 260); assert.equal(uint8c[0], 0); assert.equal(uint8c[1], 255); (function() { var numbers = []; for (var i = 128; i <= 255; ++i) numbers.push(i); var array = new Uint8Array(numbers); var view = new DataView(array.buffer); for (var i = 128; i <= 255; ++i) assert.equal(view.getInt8(i - 128), i - 256); })(); assert.throws(function() { var buf = new DataView(new ArrayBuffer(8)); buf.getFloat64(0xffffffff, true); }, /Index out of range/); assert.throws(function() { var buf = new DataView(new ArrayBuffer(8)); buf.setFloat64(0xffffffff, 0.0, true); }, /Index out of range/); // DataView::setGeneric() default endianness regression test, // see https://github.com/joyent/node/issues/4626 (function() { var buf = new Uint8Array(2); var view = new DataView(buf.buffer); view.setUint16(0, 1); assert.equal(view.getUint16(0), 1); })(); (function() { // Typed array should make a copy of the buffer object, i.e. it's not shared. var b = new Buffer([0]); var a = new Uint8Array(b); assert.notEqual(a.buffer, b); assert.equal(a[0], 0); assert.equal(b[0], 0); a[0] = 1; assert.equal(a[0], 1); assert.equal(b[0], 0); a[0] = 0; b[0] = 1; assert.equal(a[0], 0); assert.equal(b[0], 1); })(); (function() { // Backing store should not be shared. var a = new Uint8Array(1); var b = new Uint8Array(a); a[0] = 0; b[0] = 1; assert.equal(a[0], 0); assert.equal(b[0], 1); assert.notEqual(a, b.buffer); assert.notEqual(a.buffer, b.buffer); })(); (function() { // Backing store should not be shared. var a = new Uint8Array(2); var b = new Uint16Array(a); a[0] = 0; a[1] = 0; b[0] = 257; assert.equal(a[0], 0); assert.equal(a[1], 0); assert.equal(b[0], 257); assert.notEqual(a, b.buffer); assert.notEqual(a.buffer, b.buffer); })(); (function() { // Backing store should be shared. var abuf = new ArrayBuffer(32); var a = new Uint8Array(abuf); var b = new Uint8Array(abuf); a[0] = 0; b[0] = 1; assert.equal(a[0], 1); assert.equal(b[0], 1); assert.equal(a.buffer, b.buffer); })(); assert.throws(function() { new DataView(new Int8Array(1)); }); node-v0.10.25~dfsg2/test/simple/test-net-binary.js0000644000000000000000000000640712270121457020457 0ustar rootroot// Copyright Joyent, Inc. and other Node contributors. // // Permission is hereby granted, free of charge, to any person obtaining a // copy of this software and associated documentation files (the // "Software"), to deal in the Software without restriction, including // without limitation the rights to use, copy, modify, merge, publish, // distribute, sublicense, and/or sell copies of the Software, and to permit // persons to whom the Software is furnished to do so, subject to the // following conditions: // // The above copyright notice and this permission notice shall be included // in all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS // OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF // MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN // NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, // DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR // OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE // USE OR OTHER DEALINGS IN THE SOFTWARE. var common = require('../common'); var assert = require('assert'); var net = require('net'); var binaryString = ''; for (var i = 255; i >= 0; i--) { var s = '\'\\' + i.toString(8) + '\''; var S = eval(s); common.error(s + ' ' + JSON.stringify(S) + ' ' + JSON.stringify(String.fromCharCode(i)) + ' ' + S.charCodeAt(0)); assert.ok(S.charCodeAt(0) == i); assert.ok(S == String.fromCharCode(i)); binaryString += S; } // safe constructor var echoServer = net.Server(function(connection) { console.error('SERVER got connection'); connection.setEncoding('binary'); connection.on('data', function(chunk) { common.error('SERVER recved: ' + JSON.stringify(chunk)); connection.write(chunk, 'binary'); }); connection.on('end', function() { console.error('SERVER ending'); connection.end(); }); }); echoServer.listen(common.PORT); var recv = ''; echoServer.on('listening', function() { console.error('SERVER listening'); var j = 0; var c = net.createConnection({ port: common.PORT }); c.setEncoding('binary'); c.on('data', function(chunk) { console.error('CLIENT data %j', chunk); var n = j + chunk.length; while (j < n && j < 256) { common.error('CLIENT write ' + j); c.write(String.fromCharCode(j), 'binary'); j++; } if (j === 256) { console.error('CLIENT ending'); c.end(); } recv += chunk; }); c.on('connect', function() { console.error('CLIENT connected, writing'); c.write(binaryString, 'binary'); }); c.on('close', function() { console.error('CLIENT closed'); console.dir(recv); echoServer.close(); }); c.on('finish', function() { console.error('CLIENT finished'); }); }); process.on('exit', function() { console.log('recv: ' + JSON.stringify(recv)); assert.equal(2 * 256, recv.length); var a = recv.split(''); var first = a.slice(0, 256).reverse().join(''); console.log('first: ' + JSON.stringify(first)); var second = a.slice(256, 2 * 256).join(''); console.log('second: ' + JSON.stringify(second)); assert.equal(first, second); }); node-v0.10.25~dfsg2/test/simple/test-exception-handler2.js0000644000000000000000000000307412270121457022077 0ustar rootroot// Copyright Joyent, Inc. and other Node contributors. // // Permission is hereby granted, free of charge, to any person obtaining a // copy of this software and associated documentation files (the // "Software"), to deal in the Software without restriction, including // without limitation the rights to use, copy, modify, merge, publish, // distribute, sublicense, and/or sell copies of the Software, and to permit // persons to whom the Software is furnished to do so, subject to the // following conditions: // // The above copyright notice and this permission notice shall be included // in all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS // OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF // MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN // NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, // DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR // OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE // USE OR OTHER DEALINGS IN THE SOFTWARE. var common = require('../common'); var assert = require('assert'); process.on('uncaughtException', function(err) { console.log('Caught exception: ' + err); }); var timeoutFired = false; setTimeout(function() { console.log('This will still run.'); timeoutFired = true; }, 500); process.on('exit', function() { assert.ok(timeoutFired); }); // Intentionally cause an exception, but don't catch it. nonexistentFunc(); console.log('This will not run.'); node-v0.10.25~dfsg2/test/simple/test-http-client-get-url.js0000644000000000000000000000320712270121457022212 0ustar rootroot// Copyright Joyent, Inc. and other Node contributors. // // Permission is hereby granted, free of charge, to any person obtaining a // copy of this software and associated documentation files (the // "Software"), to deal in the Software without restriction, including // without limitation the rights to use, copy, modify, merge, publish, // distribute, sublicense, and/or sell copies of the Software, and to permit // persons to whom the Software is furnished to do so, subject to the // following conditions: // // The above copyright notice and this permission notice shall be included // in all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS // OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF // MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN // NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, // DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR // OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE // USE OR OTHER DEALINGS IN THE SOFTWARE. var common = require('../common'); var assert = require('assert'); var http = require('http'); var seen_req = false; var server = http.createServer(function(req, res) { assert.equal('GET', req.method); assert.equal('/foo?bar', req.url); res.writeHead(200, {'Content-Type': 'text/plain'}); res.write('hello\n'); res.end(); server.close(); seen_req = true; }); server.listen(common.PORT, function() { http.get('http://127.0.0.1:' + common.PORT + '/foo?bar'); }); process.on('exit', function() { assert(seen_req); }); node-v0.10.25~dfsg2/test/simple/test-stream-readable-flow-recursion.js0000644000000000000000000000470412270121457024411 0ustar rootroot// Copyright Joyent, Inc. and other Node contributors. // // Permission is hereby granted, free of charge, to any person obtaining a // copy of this software and associated documentation files (the // "Software"), to deal in the Software without restriction, including // without limitation the rights to use, copy, modify, merge, publish, // distribute, sublicense, and/or sell copies of the Software, and to permit // persons to whom the Software is furnished to do so, subject to the // following conditions: // // The above copyright notice and this permission notice shall be included // in all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS // OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF // MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN // NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, // DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR // OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE // USE OR OTHER DEALINGS IN THE SOFTWARE. var common = require('../common'); var assert = require('assert'); // this test verifies that passing a huge number to read(size) // will push up the highWaterMark, and cause the stream to read // more data continuously, but without triggering a nextTick // warning or RangeError. var Readable = require('stream').Readable; // throw an error if we trigger a nextTick warning. process.throwDeprecation = true; var stream = new Readable({ highWaterMark: 2 }); var reads = 0; var total = 5000; stream._read = function(size) { reads++; size = Math.min(size, total); total -= size; if (size === 0) stream.push(null); else stream.push(new Buffer(size)); }; var depth = 0; function flow(stream, size, callback) { depth += 1; var chunk = stream.read(size); if (!chunk) stream.once('readable', flow.bind(null, stream, size, callback)); else callback(chunk); depth -= 1; console.log('flow(' + depth + '): exit'); } flow(stream, 5000, function() { console.log('complete (' + depth + ')'); }); process.on('exit', function(code) { assert.equal(reads, 2); // we pushed up the high water mark assert.equal(stream._readableState.highWaterMark, 8192); // length is 0 right now, because we pulled it all out. assert.equal(stream._readableState.length, 0); assert(!code); assert.equal(depth, 0); console.log('ok'); }); node-v0.10.25~dfsg2/test/simple/test-regress-GH-784.js0000644000000000000000000000744412270121457020677 0ustar rootroot// Copyright Joyent, Inc. and other Node contributors. // // Permission is hereby granted, free of charge, to any person obtaining a // copy of this software and associated documentation files (the // "Software"), to deal in the Software without restriction, including // without limitation the rights to use, copy, modify, merge, publish, // distribute, sublicense, and/or sell copies of the Software, and to permit // persons to whom the Software is furnished to do so, subject to the // following conditions: // // The above copyright notice and this permission notice shall be included // in all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS // OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF // MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN // NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, // DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR // OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE // USE OR OTHER DEALINGS IN THE SOFTWARE. // Regression test for GH-784 // https://github.com/joyent/node/issues/784 // // The test works by making a total of 8 requests to the server. The first // two are made with the server off - they should come back as ECONNREFUSED. // The next two are made with server on - they should come back successful. // The next two are made with the server off - and so on. Without the fix // we were experiencing parse errors and instead of ECONNREFUSED. var common = require('../common'); var http = require('http'); var assert = require('assert'); var server = http.createServer(function(req, res) { var body = ''; req.setEncoding('utf8'); req.on('data', function(chunk) { body += chunk; }); req.on('end', function() { assert.equal('PING', body); res.writeHead(200); res.end('PONG'); }); }); server.on('listening', pingping); function serverOn() { console.error('Server ON'); server.listen(common.PORT); } function serverOff() { console.error('Server OFF'); server.close(); pingping(); } var responses = []; function afterPing(result) { responses.push(result); console.error('afterPing. responses.length = ' + responses.length); switch (responses.length) { case 2: assert.ok(/ECONNREFUSED/.test(responses[0])); assert.ok(/ECONNREFUSED/.test(responses[1])); serverOn(); break; case 4: assert.ok(/success/.test(responses[2])); assert.ok(/success/.test(responses[3])); serverOff(); break; case 6: assert.ok(/ECONNREFUSED/.test(responses[4])); assert.ok(/ECONNREFUSED/.test(responses[5])); serverOn(); break; case 8: assert.ok(/success/.test(responses[6])); assert.ok(/success/.test(responses[7])); server.close(); // we should go to process.on('exit') from here. break; } } function ping() { console.error('making req'); var opt = { port: common.PORT, path: '/ping', method: 'POST' }; var req = http.request(opt, function(res) { var body = ''; res.setEncoding('utf8'); res.on('data', function(chunk) { body += chunk; }); res.on('end', function() { assert.equal('PONG', body); assert.ok(!hadError); gotEnd = true; afterPing('success'); }); }); req.end('PING'); var gotEnd = false; var hadError = false; req.on('error', function(error) { console.log('Error making ping req: ' + error); hadError = true; assert.ok(!gotEnd); afterPing(error.message); }); } function pingping() { ping(); ping(); } pingping(); process.on('exit', function() { console.error("process.on('exit')"); console.error(responses); assert.equal(8, responses.length); }); node-v0.10.25~dfsg2/test/simple/test-domain-nested-throw.js0000644000000000000000000000545612270121457022302 0ustar rootroot// Copyright Joyent, Inc. and other Node contributors. // // Permission is hereby granted, free of charge, to any person obtaining a // copy of this software and associated documentation files (the // "Software"), to deal in the Software without restriction, including // without limitation the rights to use, copy, modify, merge, publish, // distribute, sublicense, and/or sell copies of the Software, and to permit // persons to whom the Software is furnished to do so, subject to the // following conditions: // // The above copyright notice and this permission notice shall be included // in all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS // OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF // MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN // NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, // DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR // OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE // USE OR OTHER DEALINGS IN THE SOFTWARE. var common = require('../common'); var assert = require('assert'); var domain = require('domain'); var dispose; switch (process.argv[2]) { case 'true': dispose = true; break; case 'false': dispose = false; break; default: parent(); return; } function parent() { var node = process.execPath; var spawn = require('child_process').spawn; var opt = { stdio: 'inherit' }; var child = spawn(node, [__filename, 'true'], opt); child.on('exit', function(c) { assert(!c); child = spawn(node, [__filename, 'false'], opt); child.on('exit', function(c) { assert(!c); console.log('ok'); }); }); } var gotDomain1Error = false; var gotDomain2Error = false; var threw1 = false; var threw2 = false; function throw1() { threw1 = true; throw new Error('handled by domain1'); } function throw2() { threw2 = true; throw new Error('handled by domain2'); } function inner(throw1, throw2) { var domain1 = domain.createDomain(); domain1.on('error', function (err) { if (gotDomain1Error) { console.error('got domain 1 twice'); process.exit(1); } if (dispose) domain1.dispose(); gotDomain1Error = true; throw2(); }); domain1.run(function () { throw1(); }); } function outer() { var domain2 = domain.createDomain(); domain2.on('error', function (err) { if (gotDomain2Error) { console.error('got domain 2 twice'); process.exit(1); } gotDomain2Error = true; }); domain2.run(function () { inner(throw1, throw2); }); } process.on('exit', function() { assert(gotDomain1Error); assert(gotDomain2Error); assert(threw1); assert(threw2); console.log('ok', dispose); }); outer(); node-v0.10.25~dfsg2/test/simple/test-stream2-stderr-sync.js0000644000000000000000000000715112270121457022234 0ustar rootroot// Copyright Joyent, Inc. and other Node contributors. // // Permission is hereby granted, free of charge, to any person obtaining a // copy of this software and associated documentation files (the // "Software"), to deal in the Software without restriction, including // without limitation the rights to use, copy, modify, merge, publish, // distribute, sublicense, and/or sell copies of the Software, and to permit // persons to whom the Software is furnished to do so, subject to the // following conditions: // // The above copyright notice and this permission notice shall be included // in all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS // OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF // MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN // NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, // DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR // OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE // USE OR OTHER DEALINGS IN THE SOFTWARE. // Make sure that sync writes to stderr get processed before exiting. var common = require('../common.js'); var assert = require('assert'); function parent() { var spawn = require('child_process').spawn; var assert = require('assert'); var i = 0; children.forEach(function(_, c) { var child = spawn(process.execPath, [__filename, '' + c]); var err = ''; child.stderr.on('data', function(c) { err += c; }); child.on('close', function() { assert.equal(err, 'child ' + c + '\nfoo\nbar\nbaz\n'); console.log('ok %d child #%d', ++i, c); if (i === children.length) console.log('1..' + i); }); }); } function child0() { // Just a very simple wrapper around TTY(2) // Essentially the same as stderr, but without all the net stuff. var Writable = require('stream').Writable; var util = require('util'); // a lowlevel stderr writer var TTY = process.binding('tty_wrap').TTY; var handle = new TTY(2, false); util.inherits(W, Writable); function W(opts) { Writable.call(this, opts); } W.prototype._write = function(chunk, encoding, cb) { var req = handle.writeUtf8String(chunk.toString() + '\n'); // here's the problem. // it needs to tell the Writable machinery that it's ok to write // more, but that the current buffer length is handle.writeQueueSize req.oncomplete = afterWrite if (req.writeQueueSize === 0) req.cb = cb; else cb(); } function afterWrite(status, handle, req) { if (req.cb) req.cb(); } var w = new W w.write('child 0'); w.write('foo'); w.write('bar'); w.write('baz'); } // using console.error function child1() { console.error('child 1'); console.error('foo'); console.error('bar'); console.error('baz'); } // using process.stderr function child2() { process.stderr.write('child 2\n'); process.stderr.write('foo\n'); process.stderr.write('bar\n'); process.stderr.write('baz\n'); } // using a net socket function child3() { var net = require('net'); var socket = new net.Socket({ fd: 2 }); socket.write('child 3\n'); socket.write('foo\n'); socket.write('bar\n'); socket.write('baz\n'); } function child4() { console.error('child 4\nfoo\nbar\nbaz'); } function child5() { process.stderr.write('child 5\nfoo\nbar\nbaz\n'); } var children = [ child0, child1, child2, child3, child4, child5 ]; if (!process.argv[2]) { parent(); } else { children[process.argv[2]](); // immediate process.exit to kill any waiting stuff. process.exit(); } node-v0.10.25~dfsg2/test/simple/test-repl-require-cache.js0000644000000000000000000000263612270121457022064 0ustar rootroot// Copyright Joyent, Inc. and other Node contributors. // // Permission is hereby granted, free of charge, to any person obtaining a // copy of this software and associated documentation files (the // "Software"), to deal in the Software without restriction, including // without limitation the rights to use, copy, modify, merge, publish, // distribute, sublicense, and/or sell copies of the Software, and to permit // persons to whom the Software is furnished to do so, subject to the // following conditions: // // The above copyright notice and this permission notice shall be included // in all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS // OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF // MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN // NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, // DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR // OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE // USE OR OTHER DEALINGS IN THE SOFTWARE. var common = require('../common'), assert = require('assert'), repl = require('repl'); // https://github.com/joyent/node/issues/3226 require.cache.something = 1; assert.equal(require.cache.something, 1); repl.start({ useGlobal: false }).rli.close(); assert.equal(require.cache.something, 1); node-v0.10.25~dfsg2/test/simple/test-stdin-hang.js0000644000000000000000000000260012270121457020432 0ustar rootroot// Copyright Joyent, Inc. and other Node contributors. // // Permission is hereby granted, free of charge, to any person obtaining a // copy of this software and associated documentation files (the // "Software"), to deal in the Software without restriction, including // without limitation the rights to use, copy, modify, merge, publish, // distribute, sublicense, and/or sell copies of the Software, and to permit // persons to whom the Software is furnished to do so, subject to the // following conditions: // // The above copyright notice and this permission notice shall be included // in all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS // OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF // MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN // NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, // DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR // OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE // USE OR OTHER DEALINGS IN THE SOFTWARE. var common = require('../common'); // This test *only* verifies that invoking the stdin getter does not // cause node to hang indefinitely. // If it does, then the test-runner will nuke it. // invoke the getter. process.stdin; console.error('Should exit normally now.'); node-v0.10.25~dfsg2/test/simple/test-fs-read-file-sync-hostname.js0000644000000000000000000000256012270121457023427 0ustar rootroot// Copyright Joyent, Inc. and other Node contributors. // // Permission is hereby granted, free of charge, to any person obtaining a // copy of this software and associated documentation files (the // "Software"), to deal in the Software without restriction, including // without limitation the rights to use, copy, modify, merge, publish, // distribute, sublicense, and/or sell copies of the Software, and to permit // persons to whom the Software is furnished to do so, subject to the // following conditions: // // The above copyright notice and this permission notice shall be included // in all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS // OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF // MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN // NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, // DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR // OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE // USE OR OTHER DEALINGS IN THE SOFTWARE. var common = require('../common'); var assert = require('assert'); var fs = require('fs'); // test reading from hostname if (process.platform === 'linux2') { var hostname = fs.readFileSync('/proc/sys/kernel/hostname'); assert.ok(hostname.length > 0); } node-v0.10.25~dfsg2/test/simple/test-cluster-net-listen.js0000644000000000000000000000317512270121457022147 0ustar rootroot// Copyright Joyent, Inc. and other Node contributors. // // Permission is hereby granted, free of charge, to any person obtaining a // copy of this software and associated documentation files (the // "Software"), to deal in the Software without restriction, including // without limitation the rights to use, copy, modify, merge, publish, // distribute, sublicense, and/or sell copies of the Software, and to permit // persons to whom the Software is furnished to do so, subject to the // following conditions: // // The above copyright notice and this permission notice shall be included // in all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS // OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF // MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN // NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, // DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR // OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE // USE OR OTHER DEALINGS IN THE SOFTWARE. var common = require('../common'); var assert = require('assert'); var cluster = require('cluster'); var net = require('net'); if (cluster.isMaster) { // ensure that the worker exits peacefully var worker = cluster.fork(); worker.on('exit', function(statusCode) { assert.equal(statusCode, 0); worker = null; }); process.on('exit', function() { assert.equal(worker, null); }); } else { // listen() without port should not trigger a libuv assert net.createServer(assert.fail).listen(process.exit); } node-v0.10.25~dfsg2/test/simple/test-cluster-master-error.js0000644000000000000000000000731712270121457022511 0ustar rootroot// Copyright Joyent, Inc. and other Node contributors. // // Permission is hereby granted, free of charge, to any person obtaining a // copy of this software and associated documentation files (the // "Software"), to deal in the Software without restriction, including // without limitation the rights to use, copy, modify, merge, publish, // distribute, sublicense, and/or sell copies of the Software, and to permit // persons to whom the Software is furnished to do so, subject to the // following conditions: // // The above copyright notice and this permission notice shall be included // in all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS // OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF // MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN // NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, // DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR // OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE // USE OR OTHER DEALINGS IN THE SOFTWARE. var common = require('../common'); var assert = require('assert'); var cluster = require('cluster'); // Cluster setup if (cluster.isWorker) { var http = require('http'); http.Server(function() { }).listen(common.PORT, '127.0.0.1'); } else if (process.argv[2] === 'cluster') { var totalWorkers = 2; // Send PID to testcase process var forkNum = 0; cluster.on('fork', function forkEvent(worker) { // Send PID process.send({ cmd: 'worker', workerPID: worker.process.pid }); // Stop listening when done if (++forkNum === totalWorkers) { cluster.removeListener('fork', forkEvent); } }); // Throw accidently error when all workers are listening var listeningNum = 0; cluster.on('listening', function listeningEvent() { // When all workers are listening if (++listeningNum === totalWorkers) { // Stop listening cluster.removeListener('listening', listeningEvent); // throw accidently error process.nextTick(function() { console.error('about to throw'); throw new Error('accidently error'); }); } }); // Startup a basic cluster cluster.fork(); cluster.fork(); } else { // This is the testcase var fork = require('child_process').fork; var isAlive = function(pid) { try { //this will throw an error if the process is dead process.kill(pid, 0); return true; } catch (e) { return false; } }; var existMaster = false; var existWorker = false; // List all workers var workers = []; // Spawn a cluster process var master = fork(process.argv[1], ['cluster'], {silent: true}); // Handle messages from the cluster master.on('message', function(data) { // Add worker pid to list and progress tracker if (data.cmd === 'worker') { workers.push(data.workerPID); } }); // When cluster is dead master.on('exit', function(code) { // Check that the cluster died accidently existMaster = !!code; // Give the workers time to shut down setTimeout(checkWorkers, 200); function checkWorkers() { // When master is dead all workers should be dead to var alive = false; workers.forEach(function(pid) { if (isAlive(pid)) { alive = true; } }); // If a worker was alive this did not act as expected existWorker = !alive; } }); process.once('exit', function() { var m = 'The master did not die after an error was throwed'; assert.ok(existMaster, m); m = 'The workers did not die after an error in the master'; assert.ok(existWorker, m); }); } node-v0.10.25~dfsg2/test/simple/test-stream2-unpipe-drain.js0000644000000000000000000000426312270121457022353 0ustar rootroot// Copyright Joyent, Inc. and other Node contributors. // // Permission is hereby granted, free of charge, to any person obtaining a // copy of this software and associated documentation files (the // "Software"), to deal in the Software without restriction, including // without limitation the rights to use, copy, modify, merge, publish, // distribute, sublicense, and/or sell copies of the Software, and to permit // persons to whom the Software is furnished to do so, subject to the // following conditions: // // The above copyright notice and this permission notice shall be included // in all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS // OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF // MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN // NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, // DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR // OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE // USE OR OTHER DEALINGS IN THE SOFTWARE. var common = require('../common.js'); var assert = require('assert'); var stream = require('stream'); var crypto = require('crypto'); var util = require('util'); function TestWriter() { stream.Writable.call(this); } util.inherits(TestWriter, stream.Writable); TestWriter.prototype._write = function (buffer, encoding, callback) { console.log('write called'); // super slow write stream (callback never called) }; var dest = new TestWriter(); function TestReader(id) { stream.Readable.call(this); this.reads = 0; } util.inherits(TestReader, stream.Readable); TestReader.prototype._read = function (size) { this.reads += 1; this.push(crypto.randomBytes(size)); }; var src1 = new TestReader(); var src2 = new TestReader(); src1.pipe(dest); src1.once('readable', function () { process.nextTick(function () { src2.pipe(dest); src2.once('readable', function () { process.nextTick(function () { src1.unpipe(dest); }); }); }); }); process.on('exit', function () { assert.equal(src1.reads, 2); assert.equal(src2.reads, 2); }); node-v0.10.25~dfsg2/test/simple/test-tls-server-slab.js0000644000000000000000000000415512270121457021432 0ustar rootroot// Copyright Joyent, Inc. and other Node contributors. // // Permission is hereby granted, free of charge, to any person obtaining a // copy of this software and associated documentation files (the // "Software"), to deal in the Software without restriction, including // without limitation the rights to use, copy, modify, merge, publish, // distribute, sublicense, and/or sell copies of the Software, and to permit // persons to whom the Software is furnished to do so, subject to the // following conditions: // // The above copyright notice and this permission notice shall be included // in all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS // OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF // MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN // NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, // DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR // OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE // USE OR OTHER DEALINGS IN THE SOFTWARE. var common = require('../common'); var assert = require('assert'); var tls = require('tls'); var fs = require('fs'); var clientConnected = 0; var serverConnected = 0; var options = { key: fs.readFileSync(common.fixturesDir + '/keys/agent1-key.pem'), cert: fs.readFileSync(common.fixturesDir + '/keys/agent1-cert.pem') }; tls.SLAB_BUFFER_SIZE = 100 * 1024; var server = tls.Server(options, function(socket) { assert(socket._buffer.pool.length == tls.SLAB_BUFFER_SIZE); if (++serverConnected === 2) { server.close(); } }); server.listen(common.PORT, function() { var client1 = tls.connect({ port: common.PORT, rejectUnauthorized: false }, function() { ++clientConnected; client1.end(); }); var client2 = tls.connect({ port: common.PORT, rejectUnauthorized: false }); client2.on('secureConnect', function() { ++clientConnected; client2.end(); }); }); process.on('exit', function() { assert.equal(clientConnected, 2); assert.equal(serverConnected, 2); }); node-v0.10.25~dfsg2/test/simple/test-fs-read-stream-fd.js0000644000000000000000000000317012270121457021602 0ustar rootroot// Copyright Joyent, Inc. and other Node contributors. // // Permission is hereby granted, free of charge, to any person obtaining a // copy of this software and associated documentation files (the // "Software"), to deal in the Software without restriction, including // without limitation the rights to use, copy, modify, merge, publish, // distribute, sublicense, and/or sell copies of the Software, and to permit // persons to whom the Software is furnished to do so, subject to the // following conditions: // // The above copyright notice and this permission notice shall be included // in all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS // OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF // MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN // NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, // DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR // OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE // USE OR OTHER DEALINGS IN THE SOFTWARE. var fs = require('fs'); var assert = require('assert'); var path = require('path'); var common = require('../common'); var file = path.join(common.tmpDir, '/read_stream_fd_test.txt'); var input = 'hello world'; var output = ''; var fd, stream; fs.writeFileSync(file, input); fd = fs.openSync(file, 'r'); stream = fs.createReadStream(null, { fd: fd, encoding: 'utf8' }); stream.on('data', function(data) { output += data; }); process.on('exit', function() { fs.unlinkSync(file); assert.equal(output, input); }); node-v0.10.25~dfsg2/test/simple/test-fs-null-bytes.js0000644000000000000000000000665412270121457021117 0ustar rootroot// Copyright Joyent, Inc. and other Node contributors. // // Permission is hereby granted, free of charge, to any person obtaining a // copy of this software and associated documentation files (the // "Software"), to deal in the Software without restriction, including // without limitation the rights to use, copy, modify, merge, publish, // distribute, sublicense, and/or sell copies of the Software, and to permit // persons to whom the Software is furnished to do so, subject to the // following conditions: // // The above copyright notice and this permission notice shall be included // in all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS // OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF // MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN // NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, // DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR // OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE // USE OR OTHER DEALINGS IN THE SOFTWARE. var common = require('../common'); var assert = require('assert'); var fs = require('fs'); function check(async, sync) { var expected = /Path must be a string without null bytes./; var argsSync = Array.prototype.slice.call(arguments, 2); var argsAsync = argsSync.concat(function(er) { assert(er && er.message.match(expected)); }); if (sync) assert.throws(function() { console.error(sync.name, argsSync); sync.apply(null, argsSync); }, expected); if (async) async.apply(null, argsAsync); } check(fs.appendFile, fs.appendFileSync, 'foo\u0000bar'); check(fs.chmod, fs.chmodSync, 'foo\u0000bar', '0644'); check(fs.chown, fs.chownSync, 'foo\u0000bar', 12, 34); check(fs.link, fs.linkSync, 'foo\u0000bar', 'foobar'); check(fs.link, fs.linkSync, 'foobar', 'foo\u0000bar'); check(fs.lstat, fs.lstatSync, 'foo\u0000bar'); check(fs.mkdir, fs.mkdirSync, 'foo\u0000bar', '0755'); check(fs.open, fs.openSync, 'foo\u0000bar', 'r'); check(fs.readFile, fs.readFileSync, 'foo\u0000bar'); check(fs.readdir, fs.readdirSync, 'foo\u0000bar'); check(fs.readlink, fs.readlinkSync, 'foo\u0000bar'); check(fs.realpath, fs.realpathSync, 'foo\u0000bar'); check(fs.rename, fs.renameSync, 'foo\u0000bar', 'foobar'); check(fs.rename, fs.renameSync, 'foobar', 'foo\u0000bar'); check(fs.rmdir, fs.rmdirSync, 'foo\u0000bar'); check(fs.stat, fs.statSync, 'foo\u0000bar'); check(fs.symlink, fs.symlinkSync, 'foo\u0000bar', 'foobar'); check(fs.symlink, fs.symlinkSync, 'foobar', 'foo\u0000bar'); check(fs.truncate, fs.truncateSync, 'foo\u0000bar'); check(fs.unlink, fs.unlinkSync, 'foo\u0000bar'); check(null, fs.unwatchFile, 'foo\u0000bar', assert.fail); check(fs.utimes, fs.utimesSync, 'foo\u0000bar', 0, 0); check(null, fs.watch, 'foo\u0000bar', assert.fail); check(null, fs.watchFile, 'foo\u0000bar', assert.fail); check(fs.writeFile, fs.writeFileSync, 'foo\u0000bar'); // an 'error' for exists means that it doesn't exist. // one of many reasons why this file is the absolute worst. fs.exists('foo\u0000bar', function(exists) { assert(!exists); }); assert(!fs.existsSync('foo\u0000bar')); node-v0.10.25~dfsg2/test/simple/test-tls-session-cache.js0000644000000000000000000000723512270121457021733 0ustar rootroot// Copyright Joyent, Inc. and other Node contributors. // // Permission is hereby granted, free of charge, to any person obtaining a // copy of this software and associated documentation files (the // "Software"), to deal in the Software without restriction, including // without limitation the rights to use, copy, modify, merge, publish, // distribute, sublicense, and/or sell copies of the Software, and to permit // persons to whom the Software is furnished to do so, subject to the // following conditions: // // The above copyright notice and this permission notice shall be included // in all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS // OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF // MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN // NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, // DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR // OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE // USE OR OTHER DEALINGS IN THE SOFTWARE. if (!process.versions.openssl) { console.error('Skipping because node compiled without OpenSSL.'); process.exit(0); } require('child_process').exec('openssl version', function(err) { if (err !== null) { console.error('Skipping because openssl command is not available.'); process.exit(0); } doTest(); }); function doTest() { var common = require('../common'); var assert = require('assert'); var tls = require('tls'); var fs = require('fs'); var join = require('path').join; var spawn = require('child_process').spawn; var keyFile = join(common.fixturesDir, 'agent.key'); var certFile = join(common.fixturesDir, 'agent.crt'); var key = fs.readFileSync(keyFile); var cert = fs.readFileSync(certFile); var options = { key: key, cert: cert, ca: [cert], requestCert: true }; var requestCount = 0; var session; var badOpenSSL = false; var server = tls.createServer(options, function(cleartext) { cleartext.on('error', function(er) { // We're ok with getting ECONNRESET in this test, but it's // timing-dependent, and thus unreliable. Any other errors // are just failures, though. if (er.code !== 'ECONNRESET') throw er; }); ++requestCount; cleartext.end(); }); server.on('newSession', function(id, data) { assert.ok(!session); session = { id: id, data: data }; }); server.on('resumeSession', function(id, callback) { assert.ok(session); assert.equal(session.id.toString('hex'), id.toString('hex')); // Just to check that async really works there setTimeout(function() { callback(null, session.data); }, 100); }); server.listen(common.PORT, function() { var client = spawn('openssl', [ 's_client', '-connect', 'localhost:' + common.PORT, '-key', join(common.fixturesDir, 'agent.key'), '-cert', join(common.fixturesDir, 'agent.crt'), '-reconnect', '-no_ticket' ], { stdio: [ 0, 1, 'pipe' ] }); var err = ''; client.stderr.setEncoding('utf8'); client.stderr.on('data', function(chunk) { err += chunk; }); client.on('exit', function(code) { if (/^unknown option/.test(err)) { // using an incompatible version of openssl assert(code); badOpenSSL = true; } else assert.equal(code, 0); server.close(); }); }); process.on('exit', function() { if (!badOpenSSL) { assert.ok(session); // initial request + reconnect requests (5 times) assert.equal(requestCount, 6); } }); } node-v0.10.25~dfsg2/test/simple/test-https-timeout-server-2.js0000644000000000000000000000350512270121457022674 0ustar rootroot// Copyright Joyent, Inc. and other Node contributors. // // Permission is hereby granted, free of charge, to any person obtaining a // copy of this software and associated documentation files (the // "Software"), to deal in the Software without restriction, including // without limitation the rights to use, copy, modify, merge, publish, // distribute, sublicense, and/or sell copies of the Software, and to permit // persons to whom the Software is furnished to do so, subject to the // following conditions: // // The above copyright notice and this permission notice shall be included // in all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS // OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF // MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN // NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, // DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR // OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE // USE OR OTHER DEALINGS IN THE SOFTWARE. if (!process.versions.openssl) process.exit(); var common = require('../common'); var assert = require('assert'); var https = require('https'); var net = require('net'); var tls = require('tls'); var fs = require('fs'); var options = { key: fs.readFileSync(common.fixturesDir + '/keys/agent1-key.pem'), cert: fs.readFileSync(common.fixturesDir + '/keys/agent1-cert.pem') }; var server = https.createServer(options, assert.fail); server.on('secureConnection', function(cleartext) { cleartext.setTimeout(50, function() { cleartext.destroy(); server.close(); }); }); server.listen(common.PORT, function() { tls.connect({ host: '127.0.0.1', port: common.PORT, rejectUnauthorized: false }); }); node-v0.10.25~dfsg2/test/simple/test-http-client-timeout.js0000644000000000000000000000332712270121457022324 0ustar rootroot// Copyright Joyent, Inc. and other Node contributors. // // Permission is hereby granted, free of charge, to any person obtaining a // copy of this software and associated documentation files (the // "Software"), to deal in the Software without restriction, including // without limitation the rights to use, copy, modify, merge, publish, // distribute, sublicense, and/or sell copies of the Software, and to permit // persons to whom the Software is furnished to do so, subject to the // following conditions: // // The above copyright notice and this permission notice shall be included // in all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS // OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF // MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN // NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, // DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR // OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE // USE OR OTHER DEALINGS IN THE SOFTWARE. var common = require('../common'); var assert = require('assert'); var http = require('http'); var options = { method: 'GET', port: common.PORT, host: '127.0.0.1', path: '/' }; var server = http.createServer(function(req, res) { // this space intentionally left blank }); server.listen(options.port, options.host, function() { var req = http.request(options, function(res) { // this space intentionally left blank }); req.on('close', function() { server.close(); }); function destroy() { req.destroy(); } req.setTimeout(1, destroy); req.on('error', destroy); req.end(); }); node-v0.10.25~dfsg2/test/simple/test-crypto-hash-stream-pipe.js0000644000000000000000000000311112270121457023061 0ustar rootroot// Copyright Joyent, Inc. and other Node contributors. // // Permission is hereby granted, free of charge, to any person obtaining a // copy of this software and associated documentation files (the // "Software"), to deal in the Software without restriction, including // without limitation the rights to use, copy, modify, merge, publish, // distribute, sublicense, and/or sell copies of the Software, and to permit // persons to whom the Software is furnished to do so, subject to the // following conditions: // // The above copyright notice and this permission notice shall be included // in all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS // OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF // MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN // NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, // DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR // OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE // USE OR OTHER DEALINGS IN THE SOFTWARE. var common = require('../common'); var assert = require('assert'); var crypto = require('crypto'); var stream = require('stream') var s = new stream.PassThrough(); var h = crypto.createHash('sha1'); var expect = '15987e60950cf22655b9323bc1e281f9c4aff47e'; var gotData = false; process.on('exit', function() { assert(gotData); console.log('ok'); }); s.pipe(h).on('data', function(c) { assert.equal(c, expect); gotData = true; }).setEncoding('hex'); s.end('aoeu'); node-v0.10.25~dfsg2/test/simple/test-require-json.js0000644000000000000000000000256712270121457021035 0ustar rootroot// Copyright Joyent, Inc. and other Node contributors. // // Permission is hereby granted, free of charge, to any person obtaining a // copy of this software and associated documentation files (the // "Software"), to deal in the Software without restriction, including // without limitation the rights to use, copy, modify, merge, publish, // distribute, sublicense, and/or sell copies of the Software, and to permit // persons to whom the Software is furnished to do so, subject to the // following conditions: // // The above copyright notice and this permission notice shall be included // in all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS // OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF // MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN // NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, // DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR // OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE // USE OR OTHER DEALINGS IN THE SOFTWARE. var assert = require('assert'); try { require('../fixtures/invalid.json'); } catch (err) { var re = /test[\/\\]fixtures[\/\\]invalid.json: Unexpected string/; var i = err.message.match(re); assert(null !== i, 'require() json error should include path'); } node-v0.10.25~dfsg2/test/simple/test-child-process-ipc.js0000644000000000000000000000415612270121457021716 0ustar rootroot// Copyright Joyent, Inc. and other Node contributors. // // Permission is hereby granted, free of charge, to any person obtaining a // copy of this software and associated documentation files (the // "Software"), to deal in the Software without restriction, including // without limitation the rights to use, copy, modify, merge, publish, // distribute, sublicense, and/or sell copies of the Software, and to permit // persons to whom the Software is furnished to do so, subject to the // following conditions: // // The above copyright notice and this permission notice shall be included // in all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS // OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF // MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN // NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, // DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR // OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE // USE OR OTHER DEALINGS IN THE SOFTWARE. var common = require('../common'); var assert = require('assert'); var spawn = require('child_process').spawn; var path = require('path'); var sub = path.join(common.fixturesDir, 'echo.js'); var gotHelloWorld = false; var gotEcho = false; var child = spawn(process.argv[0], [sub]); child.stderr.on('data', function(data) { console.log('parent stderr: ' + data); }); child.stdout.setEncoding('utf8'); child.stdout.on('data', function(data) { console.log('child said: ' + JSON.stringify(data)); if (!gotHelloWorld) { console.error('testing for hello world'); assert.equal('hello world\r\n', data); gotHelloWorld = true; console.error('writing echo me'); child.stdin.write('echo me\r\n'); } else { console.error('testing for echo me'); assert.equal('echo me\r\n', data); gotEcho = true; child.stdin.end(); } }); child.stdout.on('end', function(data) { console.log('child end'); }); process.on('exit', function() { assert.ok(gotHelloWorld); assert.ok(gotEcho); }); node-v0.10.25~dfsg2/test/simple/test-pipe-stream.js0000644000000000000000000000446312270121457020635 0ustar rootroot// Copyright Joyent, Inc. and other Node contributors. // // Permission is hereby granted, free of charge, to any person obtaining a // copy of this software and associated documentation files (the // "Software"), to deal in the Software without restriction, including // without limitation the rights to use, copy, modify, merge, publish, // distribute, sublicense, and/or sell copies of the Software, and to permit // persons to whom the Software is furnished to do so, subject to the // following conditions: // // The above copyright notice and this permission notice shall be included // in all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS // OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF // MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN // NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, // DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR // OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE // USE OR OTHER DEALINGS IN THE SOFTWARE. var common = require('../common'); var assert = require('assert'); var net = require('net'); function test(clazz, cb) { var have_ping = false; var have_pong = false; function check() { assert.ok(have_ping); assert.ok(have_pong); } function ping() { var conn = new clazz(); conn.on('error', function(err) { throw err; }); conn.connect(common.PIPE, function() { conn.write('PING', 'utf-8'); }); conn.on('data', function(data) { assert.equal(data.toString(), 'PONG'); have_pong = true; conn.destroy(); }); } function pong(conn) { conn.on('error', function(err) { throw err; }); conn.on('data', function(data) { assert.equal(data.toString(), 'PING'); have_ping = true; conn.write('PONG', 'utf-8'); }); conn.on('close', function() { server.close(); }); } var timeout = setTimeout(function() { server.close(); }, 2000); var server = net.Server(); server.listen(common.PIPE, ping); server.on('connection', pong); server.on('close', function() { clearTimeout(timeout); check(); cb && cb(); }); } test(net.Stream, function() { test(net.Socket); }); node-v0.10.25~dfsg2/test/simple/test-net-local-address-port.js0000644000000000000000000000332012270121457022661 0ustar rootroot// Copyright Joyent, Inc. and other Node contributors. // // Permission is hereby granted, free of charge, to any person obtaining a // copy of this software and associated documentation files (the // "Software"), to deal in the Software without restriction, including // without limitation the rights to use, copy, modify, merge, publish, // distribute, sublicense, and/or sell copies of the Software, and to permit // persons to whom the Software is furnished to do so, subject to the // following conditions: // // The above copyright notice and this permission notice shall be included // in all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS // OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF // MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN // NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, // DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR // OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE // USE OR OTHER DEALINGS IN THE SOFTWARE. var common = require('../common'); var assert = require('assert'); var net = require('net'); var conns = 0, conns_closed = 0; var server = net.createServer(function(socket) { conns++; assert.equal('127.0.0.1', socket.localAddress); assert.equal(socket.localPort, common.PORT); socket.on('end', function() { server.close(); }); socket.resume(); }); server.listen(common.PORT, '127.0.0.1', function() { var client = net.createConnection(common.PORT, '127.0.0.1'); client.on('connect', function() { client.end(); }); }); process.on('exit', function() { assert.equal(1, conns); }); node-v0.10.25~dfsg2/test/simple/helper-debugger-repl.js0000644000000000000000000001024412270121457021425 0ustar rootroot// Copyright Joyent, Inc. and other Node contributors. // // Permission is hereby granted, free of charge, to any person obtaining a // copy of this software and associated documentation files (the // "Software"), to deal in the Software without restriction, including // without limitation the rights to use, copy, modify, merge, publish, // distribute, sublicense, and/or sell copies of the Software, and to permit // persons to whom the Software is furnished to do so, subject to the // following conditions: // // The above copyright notice and this permission notice shall be included // in all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS // OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF // MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN // NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, // DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR // OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE // USE OR OTHER DEALINGS IN THE SOFTWARE. process.env.NODE_DEBUGGER_TIMEOUT = 2000; var common = require('../common'); var assert = require('assert'); var spawn = require('child_process').spawn; var port = common.PORT + 1337; var child; var buffer = ''; var expected = []; function startDebugger(scriptToDebug) { scriptToDebug = process.env.NODE_DEBUGGER_TEST_SCRIPT || common.fixturesDir + '/' + scriptToDebug; child = spawn(process.execPath, ['debug', '--port=' + port, scriptToDebug]); console.error('./node', 'debug', '--port=' + port, scriptToDebug); child.stdout.setEncoding('utf-8'); child.stdout.on('data', function(data) { data = (buffer + data).split('\n'); buffer = data.pop(); data.forEach(function(line) { child.emit('line', line); }); }); child.stderr.pipe(process.stderr); child.on('line', function(line) { line = line.replace(/^(debug> *)+/, ''); console.log(line); assert.ok(expected.length > 0, 'Got unexpected line: ' + line); var expectedLine = expected[0].lines.shift(); assert.ok(line.match(expectedLine) !== null, line + ' != ' + expectedLine); if (expected[0].lines.length === 0) { var callback = expected[0].callback; expected.shift(); callback && callback(); } }); var childClosed = false; child.on('close', function(code) { assert(!code); childClosed = true; }); var quitCalled = false; function quit() { if (quitCalled || childClosed) return; quitCalled = true; child.stdin.write('quit'); child.kill('SIGTERM'); } setTimeout(function() { console.error('dying badly buffer=%j', buffer); var err = 'Timeout'; if (expected.length > 0 && expected[0].lines) { err = err + '. Expected: ' + expected[0].lines.shift(); } child.on('close', function() { console.error('child is closed'); throw new Error(err); }); quit(); }, 5000).unref(); process.once('uncaughtException', function(e) { console.error('UncaughtException', e, e.stack); quit(); console.error(e.toString()); process.exit(1); }); process.on('exit', function(code) { console.error('process exit', code); quit(); if (code === 0) assert(childClosed); }); } function addTest(input, output) { function next() { if (expected.length > 0) { console.log('debug> ' + expected[0].input); child.stdin.write(expected[0].input + '\n'); if (!expected[0].lines) { var callback = expected[0].callback; expected.shift(); callback && callback(); } } else { quit(); } }; expected.push({input: input, lines: output, callback: next}); } var handshakeLines = [ /listening on port \d+/, /connecting.* ok/ ]; var initialBreakLines = [ /break in .*:1/, /1/, /2/, /3/ ]; var initialLines = handshakeLines.concat(initialBreakLines); // Process initial lines addTest(null, initialLines); exports.startDebugger = startDebugger; exports.addTest = addTest; exports.initialLines = initialLines; exports.handshakeLines = handshakeLines; exports.initialBreakLines = initialBreakLines; node-v0.10.25~dfsg2/test/simple/test-stream-readable-event.js0000644000000000000000000000664412270121457022561 0ustar rootroot// Copyright Joyent, Inc. and other Node contributors. // // Permission is hereby granted, free of charge, to any person obtaining a // copy of this software and associated documentation files (the // "Software"), to deal in the Software without restriction, including // without limitation the rights to use, copy, modify, merge, publish, // distribute, sublicense, and/or sell copies of the Software, and to permit // persons to whom the Software is furnished to do so, subject to the // following conditions: // // The above copyright notice and this permission notice shall be included // in all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS // OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF // MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN // NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, // DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR // OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE // USE OR OTHER DEALINGS IN THE SOFTWARE. var common = require('../common'); var assert = require('assert'); var Readable = require('stream').Readable; (function first() { // First test, not reading when the readable is added. // make sure that on('readable', ...) triggers a readable event. var r = new Readable({ highWaterMark: 3 }); var _readCalled = false; r._read = function(n) { _readCalled = true; }; // This triggers a 'readable' event, which is lost. r.push(new Buffer('blerg')); var caughtReadable = false; setTimeout(function() { // we're testing what we think we are assert(!r._readableState.reading); r.on('readable', function() { caughtReadable = true; }); }); process.on('exit', function() { // we're testing what we think we are assert(!_readCalled); assert(caughtReadable); console.log('ok 1'); }); })(); (function second() { // second test, make sure that readable is re-emitted if there's // already a length, while it IS reading. var r = new Readable({ highWaterMark: 3 }); var _readCalled = false; r._read = function(n) { _readCalled = true; }; // This triggers a 'readable' event, which is lost. r.push(new Buffer('bl')); var caughtReadable = false; setTimeout(function() { // assert we're testing what we think we are assert(r._readableState.reading); r.on('readable', function() { caughtReadable = true; }); }); process.on('exit', function() { // we're testing what we think we are assert(_readCalled); assert(caughtReadable); console.log('ok 2'); }); })(); (function third() { // Third test, not reading when the stream has not passed // the highWaterMark but *has* reached EOF. var r = new Readable({ highWaterMark: 30 }); var _readCalled = false; r._read = function(n) { _readCalled = true; }; // This triggers a 'readable' event, which is lost. r.push(new Buffer('blerg')); r.push(null); var caughtReadable = false; setTimeout(function() { // assert we're testing what we think we are assert(!r._readableState.reading); r.on('readable', function() { caughtReadable = true; }); }); process.on('exit', function() { // we're testing what we think we are assert(!_readCalled); assert(caughtReadable); console.log('ok 3'); }); })(); node-v0.10.25~dfsg2/test/simple/test-string-decoder-end.js0000644000000000000000000000473512270121457022066 0ustar rootroot// Copyright Joyent, Inc. and other Node contributors. // // Permission is hereby granted, free of charge, to any person obtaining a // copy of this software and associated documentation files (the // "Software"), to deal in the Software without restriction, including // without limitation the rights to use, copy, modify, merge, publish, // distribute, sublicense, and/or sell copies of the Software, and to permit // persons to whom the Software is furnished to do so, subject to the // following conditions: // // The above copyright notice and this permission notice shall be included // in all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS // OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF // MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN // NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, // DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR // OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE // USE OR OTHER DEALINGS IN THE SOFTWARE. // verify that the string decoder works getting 1 byte at a time, // the whole buffer at once, and that both match the .toString(enc) // result of the entire buffer. var assert = require('assert'); var SD = require('string_decoder').StringDecoder; var encodings = ['base64', 'hex', 'utf8', 'utf16le', 'ucs2']; var bufs = [ '☃💩', 'asdf' ].map(function(b) { return new Buffer(b); }); // also test just arbitrary bytes from 0-15. for (var i = 1; i <= 16; i++) { var bytes = new Array(i).join('.').split('.').map(function(_, j) { return j + 0x78; }); bufs.push(new Buffer(bytes)); } encodings.forEach(testEncoding); console.log('ok'); function testEncoding(encoding) { bufs.forEach(function(buf) { testBuf(encoding, buf); }); } function testBuf(encoding, buf) { console.error('# %s', encoding, buf); // write one byte at a time. var s = new SD(encoding); var res1 = ''; for (var i = 0; i < buf.length; i++) { res1 += s.write(buf.slice(i, i + 1)); } res1 += s.end(); // write the whole buffer at once. var res2 = ''; var s = new SD(encoding); res2 += s.write(buf); res2 += s.end(); // .toString() on the buffer var res3 = buf.toString(encoding); console.log('expect=%j', res3); assert.equal(res1, res3, 'one byte at a time should match toString'); assert.equal(res2, res3, 'all bytes at once should match toString'); } node-v0.10.25~dfsg2/test/simple/test-stream-big-push.js0000644000000000000000000000464112270121457021414 0ustar rootroot// Copyright Joyent, Inc. and other Node contributors. // // Permission is hereby granted, free of charge, to any person obtaining a // copy of this software and associated documentation files (the // "Software"), to deal in the Software without restriction, including // without limitation the rights to use, copy, modify, merge, publish, // distribute, sublicense, and/or sell copies of the Software, and to permit // persons to whom the Software is furnished to do so, subject to the // following conditions: // // The above copyright notice and this permission notice shall be included // in all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS // OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF // MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN // NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, // DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR // OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE // USE OR OTHER DEALINGS IN THE SOFTWARE. var common = require('../common'); var assert = require('assert'); var stream = require('stream'); var str = 'asdfasdfasdfasdfasdf'; var r = new stream.Readable({ highWaterMark: 5, encoding: 'utf8' }); var reads = 0; var eofed = false; var ended = false; r._read = function(n) { if (reads === 0) { setTimeout(function() { r.push(str); }); reads++; } else if (reads === 1) { var ret = r.push(str); assert.equal(ret, false); reads++; } else { assert(!eofed); eofed = true; r.push(null); } }; r.on('end', function() { ended = true; }); // push some data in to start. // we've never gotten any read event at this point. var ret = r.push(str); // should be false. > hwm assert(!ret); var chunk = r.read(); assert.equal(chunk, str); chunk = r.read(); assert.equal(chunk, null); r.once('readable', function() { // this time, we'll get *all* the remaining data, because // it's been added synchronously, as the read WOULD take // us below the hwm, and so it triggered a _read() again, // which synchronously added more, which we then return. chunk = r.read(); assert.equal(chunk, str + str); chunk = r.read(); assert.equal(chunk, null); }); process.on('exit', function() { assert(eofed); assert(ended); assert.equal(reads, 2); console.log('ok'); }); node-v0.10.25~dfsg2/test/simple/test-https-localaddress.js0000644000000000000000000000441312270121457022202 0ustar rootroot// Copyright Joyent, Inc. and other Node contributors. // // Permission is hereby granted, free of charge, to any person obtaining a // copy of this software and associated documentation files (the // "Software"), to deal in the Software without restriction, including // without limitation the rights to use, copy, modify, merge, publish, // distribute, sublicense, and/or sell copies of the Software, and to permit // persons to whom the Software is furnished to do so, subject to the // following conditions: // // The above copyright notice and this permission notice shall be included // in all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS // OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF // MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN // NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, // DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR // OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE // USE OR OTHER DEALINGS IN THE SOFTWARE. var common = require('../common'); var https = require('https'), fs = require('fs'), assert = require('assert'); if (['linux', 'win32'].indexOf(process.platform) == -1) { console.log('Skipping platform-specific test.'); process.exit(); } var options = { key: fs.readFileSync(common.fixturesDir + '/keys/agent1-key.pem'), cert: fs.readFileSync(common.fixturesDir + '/keys/agent1-cert.pem') }; var server = https.createServer(options, function (req, res) { console.log("Connect from: " + req.connection.socket.remoteAddress); assert.equal('127.0.0.2', req.connection.socket.remoteAddress); req.on('end', function() { res.writeHead(200, { 'Content-Type': 'text/plain' }); res.end('You are from: ' + req.connection.remoteAddress); }); req.resume(); }); server.listen(common.PORT, "127.0.0.1", function() { var options = { host: 'localhost', port: common.PORT, path: '/', method: 'GET', localAddress: '127.0.0.2', rejectUnauthorized: false }; var req = https.request(options, function(res) { res.on('end', function() { server.close(); process.exit(); }); res.resume(); }); req.end(); }); node-v0.10.25~dfsg2/test/simple/test-cluster-uncaught-exception.js0000644000000000000000000000373112270121457023675 0ustar rootroot// Copyright Joyent, Inc. and other Node contributors. // // Permission is hereby granted, free of charge, to any person obtaining a // copy of this software and associated documentation files (the // "Software"), to deal in the Software without restriction, including // without limitation the rights to use, copy, modify, merge, publish, // distribute, sublicense, and/or sell copies of the Software, and to permit // persons to whom the Software is furnished to do so, subject to the // following conditions: // // The above copyright notice and this permission notice shall be included // in all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS // OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF // MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN // NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, // DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR // OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE // USE OR OTHER DEALINGS IN THE SOFTWARE. // Installing a custom uncaughtException handler should override the default // one that the cluster module installs. // https://github.com/joyent/node/issues/2556 var common = require('../common'); var assert = require('assert'); var cluster = require('cluster'); var fork = require('child_process').fork; var MAGIC_EXIT_CODE = 42; var isTestRunner = process.argv[2] != 'child'; if (isTestRunner) { var exitCode = -1; process.on('exit', function() { assert.equal(exitCode, MAGIC_EXIT_CODE); }); var master = fork(__filename, ['child']); master.on('exit', function(code) { exitCode = code; }); } else if (cluster.isMaster) { process.on('uncaughtException', function() { process.nextTick(function() { process.exit(MAGIC_EXIT_CODE); }); }); cluster.fork(); throw new Error('kill master'); } else { // worker process.exit(); } node-v0.10.25~dfsg2/test/simple/test-child-process-stdio.js0000644000000000000000000000276512270121457022271 0ustar rootroot// Copyright Joyent, Inc. and other Node contributors. // // Permission is hereby granted, free of charge, to any person obtaining a // copy of this software and associated documentation files (the // "Software"), to deal in the Software without restriction, including // without limitation the rights to use, copy, modify, merge, publish, // distribute, sublicense, and/or sell copies of the Software, and to permit // persons to whom the Software is furnished to do so, subject to the // following conditions: // // The above copyright notice and this permission notice shall be included // in all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS // OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF // MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN // NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, // DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR // OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE // USE OR OTHER DEALINGS IN THE SOFTWARE. var common = require('../common'); var assert = require('assert'); var spawn = require('child_process').spawn; var options = {stdio: ['pipe']}; var child = common.spawnPwd(options); assert.notEqual(child.stdout, null); assert.notEqual(child.stderr, null); options = {stdio: 'ignore'}; child = common.spawnPwd(options); assert.equal(child.stdout, null); assert.equal(child.stderr, null); node-v0.10.25~dfsg2/test/simple/test-net-server-address.js0000644000000000000000000000433512270121457022122 0ustar rootroot// Copyright Joyent, Inc. and other Node contributors. // // Permission is hereby granted, free of charge, to any person obtaining a // copy of this software and associated documentation files (the // "Software"), to deal in the Software without restriction, including // without limitation the rights to use, copy, modify, merge, publish, // distribute, sublicense, and/or sell copies of the Software, and to permit // persons to whom the Software is furnished to do so, subject to the // following conditions: // // The above copyright notice and this permission notice shall be included // in all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS // OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF // MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN // NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, // DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR // OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE // USE OR OTHER DEALINGS IN THE SOFTWARE. var common = require('../common'); var assert = require('assert'); var net = require('net'); // Test on IPv4 Server var localhost_ipv4 = '127.0.0.1'; var family_ipv4 = 'IPv4'; var server_ipv4 = net.createServer(); server_ipv4.on('error', function(e) { console.log('Error on ipv4 socket: ' + e.toString()); }); server_ipv4.listen(common.PORT, localhost_ipv4, function() { var address_ipv4 = server_ipv4.address(); assert.strictEqual(address_ipv4.address, localhost_ipv4); assert.strictEqual(address_ipv4.port, common.PORT); assert.strictEqual(address_ipv4.family, family_ipv4); server_ipv4.close(); }); // Test on IPv6 Server var localhost_ipv6 = '::1'; var family_ipv6 = 'IPv6'; var server_ipv6 = net.createServer(); server_ipv6.on('error', function(e) { console.log('Error on ipv6 socket: ' + e.toString()); }); server_ipv6.listen(common.PORT, localhost_ipv6, function() { var address_ipv6 = server_ipv6.address(); assert.strictEqual(address_ipv6.address, localhost_ipv6); assert.strictEqual(address_ipv6.port, common.PORT); assert.strictEqual(address_ipv6.family, family_ipv6); server_ipv6.close(); }); node-v0.10.25~dfsg2/test/simple/test-tls-peer-certificate.js0000644000000000000000000000426312270121457022420 0ustar rootroot// Copyright Joyent, Inc. and other Node contributors. // // Permission is hereby granted, free of charge, to any person obtaining a // copy of this software and associated documentation files (the // "Software"), to deal in the Software without restriction, including // without limitation the rights to use, copy, modify, merge, publish, // distribute, sublicense, and/or sell copies of the Software, and to permit // persons to whom the Software is furnished to do so, subject to the // following conditions: // // The above copyright notice and this permission notice shall be included // in all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS // OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF // MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN // NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, // DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR // OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE // USE OR OTHER DEALINGS IN THE SOFTWARE. if (!process.versions.openssl) { console.error('Skipping because node compiled without OpenSSL.'); process.exit(0); } var common = require('../common'); var assert = require('assert'); var tls = require('tls'); var fs = require('fs'); var util = require('util'); var join = require('path').join; var spawn = require('child_process').spawn; var options = { key: fs.readFileSync(join(common.fixturesDir, 'agent.key')), cert: fs.readFileSync(join(common.fixturesDir, 'alice.crt')) }; var verified = false; var server = tls.createServer(options, function(cleartext) { cleartext.end('World'); }); server.listen(common.PORT, function() { var socket = tls.connect({ port: common.PORT, rejectUnauthorized: false }, function() { var peerCert = socket.getPeerCertificate(); common.debug(util.inspect(peerCert)); assert.equal(peerCert.subject.subjectAltName, 'uniformResourceIdentifier:http://localhost:8000/alice.foaf#me'); verified = true; server.close(); }); socket.end('Hello'); }); process.on('exit', function() { assert.ok(verified); }); node-v0.10.25~dfsg2/test/simple/test-http-client-abort2.js0000644000000000000000000000274012270121457022025 0ustar rootroot// Copyright Joyent, Inc. and other Node contributors. // // Permission is hereby granted, free of charge, to any person obtaining a // copy of this software and associated documentation files (the // "Software"), to deal in the Software without restriction, including // without limitation the rights to use, copy, modify, merge, publish, // distribute, sublicense, and/or sell copies of the Software, and to permit // persons to whom the Software is furnished to do so, subject to the // following conditions: // // The above copyright notice and this permission notice shall be included // in all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS // OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF // MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN // NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, // DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR // OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE // USE OR OTHER DEALINGS IN THE SOFTWARE. var common = require('../common'); var assert = require('assert'); var http = require('http'); var server = http.createServer(function(req, res) { res.end('Hello'); }); server.listen(common.PORT, function() { var req = http.get({port: common.PORT}, function(res) { res.on('data', function(data) { req.abort(); server.close(); }); }); }); node-v0.10.25~dfsg2/test/simple/test-http-eof-on-connect.js0000644000000000000000000000331512270121457022171 0ustar rootroot// Copyright Joyent, Inc. and other Node contributors. // // Permission is hereby granted, free of charge, to any person obtaining a // copy of this software and associated documentation files (the // "Software"), to deal in the Software without restriction, including // without limitation the rights to use, copy, modify, merge, publish, // distribute, sublicense, and/or sell copies of the Software, and to permit // persons to whom the Software is furnished to do so, subject to the // following conditions: // // The above copyright notice and this permission notice shall be included // in all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS // OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF // MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN // NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, // DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR // OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE // USE OR OTHER DEALINGS IN THE SOFTWARE. var common = require('../common'); var assert = require('assert'); var net = require('net'); var http = require('http'); // This is a regression test for https://github.com/joyent/node/issues/44 // It is separate from test-http-malformed-request.js because it is only // reproduceable on the first packet on the first connection to a server. var server = http.createServer(function(req, res) {}); server.listen(common.PORT); server.on('listening', function() { net.createConnection(common.PORT).on('connect', function() { this.destroy(); }).on('close', function() { server.close(); }); }); node-v0.10.25~dfsg2/test/simple/test-http-keep-alive-close-on-header.js0000644000000000000000000000544612270121457024353 0ustar rootroot// Copyright Joyent, Inc. and other Node contributors. // // Permission is hereby granted, free of charge, to any person obtaining a // copy of this software and associated documentation files (the // "Software"), to deal in the Software without restriction, including // without limitation the rights to use, copy, modify, merge, publish, // distribute, sublicense, and/or sell copies of the Software, and to permit // persons to whom the Software is furnished to do so, subject to the // following conditions: // // The above copyright notice and this permission notice shall be included // in all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS // OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF // MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN // NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, // DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR // OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE // USE OR OTHER DEALINGS IN THE SOFTWARE. var common = require('../common'); var assert = require('assert'); var http = require('http'); var util = require('util'); var body = 'hello world\n'; var headers = {'connection': 'keep-alive'}; var server = http.createServer(function(req, res) { res.writeHead(200, {'Content-Length': body.length, 'Connection': 'close'}); res.write(body); res.end(); }); var connectCount = 0; server.listen(common.PORT, function() { var agent = new http.Agent({ maxSockets: 1 }); var request = http.request({ method: 'GET', path: '/', headers: headers, port: common.PORT, agent: agent }, function(res) { assert.equal(1, agent.sockets['localhost:' + common.PORT].length); res.resume(); }); request.on('socket', function(s) { s.on('connect', function() { connectCount++; }); }); request.end(); request = http.request({ method: 'GET', path: '/', headers: headers, port: common.PORT, agent: agent }, function(res) { assert.equal(1, agent.sockets['localhost:' + common.PORT].length); res.resume(); }); request.on('socket', function(s) { s.on('connect', function() { connectCount++; }); }); request.end(); request = http.request({ method: 'GET', path: '/', headers: headers, port: common.PORT, agent: agent }, function(response) { response.on('end', function() { assert.equal(1, agent.sockets['localhost:' + common.PORT].length); server.close(); }); response.resume(); }); request.on('socket', function(s) { s.on('connect', function() { connectCount++; }); }); request.end(); }); process.on('exit', function() { assert.equal(3, connectCount); }); node-v0.10.25~dfsg2/test/simple/test-readdouble.js0000644000000000000000000000760712270121457020520 0ustar rootroot// Copyright Joyent, Inc. and other Node contributors. // // Permission is hereby granted, free of charge, to any person obtaining a // copy of this software and associated documentation files (the // "Software"), to deal in the Software without restriction, including // without limitation the rights to use, copy, modify, merge, publish, // distribute, sublicense, and/or sell copies of the Software, and to permit // persons to whom the Software is furnished to do so, subject to the // following conditions: // // The above copyright notice and this permission notice shall be included // in all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS // OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF // MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN // NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, // DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR // OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE // USE OR OTHER DEALINGS IN THE SOFTWARE. /* * Tests to verify we're reading in doubles correctly */ var SlowBuffer = process.binding('buffer').SlowBuffer; var common = require('../common'); var ASSERT = require('assert'); /* * Test (64 bit) double */ function test(clazz) { var buffer = new clazz(8); buffer[0] = 0x55; buffer[1] = 0x55; buffer[2] = 0x55; buffer[3] = 0x55; buffer[4] = 0x55; buffer[5] = 0x55; buffer[6] = 0xd5; buffer[7] = 0x3f; ASSERT.equal(1.1945305291680097e+103, buffer.readDoubleBE(0)); ASSERT.equal(0.3333333333333333, buffer.readDoubleLE(0)); buffer[0] = 1; buffer[1] = 0; buffer[2] = 0; buffer[3] = 0; buffer[4] = 0; buffer[5] = 0; buffer[6] = 0xf0; buffer[7] = 0x3f; ASSERT.equal(7.291122019655968e-304, buffer.readDoubleBE(0)); ASSERT.equal(1.0000000000000002, buffer.readDoubleLE(0)); buffer[0] = 2; ASSERT.equal(4.778309726801735e-299, buffer.readDoubleBE(0)); ASSERT.equal(1.0000000000000004, buffer.readDoubleLE(0)); buffer[0] = 1; buffer[6] = 0; buffer[7] = 0; ASSERT.equal(7.291122019556398e-304, buffer.readDoubleBE(0)); ASSERT.equal(5e-324, buffer.readDoubleLE(0)); buffer[0] = 0xff; buffer[1] = 0xff; buffer[2] = 0xff; buffer[3] = 0xff; buffer[4] = 0xff; buffer[5] = 0xff; buffer[6] = 0x0f; buffer[7] = 0x00; ASSERT.ok(isNaN(buffer.readDoubleBE(0))); ASSERT.equal(2.225073858507201e-308, buffer.readDoubleLE(0)); buffer[6] = 0xef; buffer[7] = 0x7f; ASSERT.ok(isNaN(buffer.readDoubleBE(0))); ASSERT.equal(1.7976931348623157e+308, buffer.readDoubleLE(0)); buffer[0] = 0; buffer[1] = 0; buffer[2] = 0; buffer[3] = 0; buffer[4] = 0; buffer[5] = 0; buffer[6] = 0xf0; buffer[7] = 0x3f; ASSERT.equal(3.03865e-319, buffer.readDoubleBE(0)); ASSERT.equal(1, buffer.readDoubleLE(0)); buffer[6] = 0; buffer[7] = 0x40; ASSERT.equal(3.16e-322, buffer.readDoubleBE(0)); ASSERT.equal(2, buffer.readDoubleLE(0)); buffer[7] = 0xc0; ASSERT.equal(9.5e-322, buffer.readDoubleBE(0)); ASSERT.equal(-2, buffer.readDoubleLE(0)); buffer[6] = 0x10; buffer[7] = 0; ASSERT.equal(2.0237e-320, buffer.readDoubleBE(0)); ASSERT.equal(2.2250738585072014e-308, buffer.readDoubleLE(0)); buffer[6] = 0; ASSERT.equal(0, buffer.readDoubleBE(0)); ASSERT.equal(0, buffer.readDoubleLE(0)); ASSERT.equal(false, 1 / buffer.readDoubleLE(0) < 0); buffer[7] = 0x80; ASSERT.equal(6.3e-322, buffer.readDoubleBE(0)); ASSERT.equal(0, buffer.readDoubleLE(0)); ASSERT.equal(true, 1 / buffer.readDoubleLE(0) < 0); buffer[6] = 0xf0; buffer[7] = 0x7f; ASSERT.equal(3.0418e-319, buffer.readDoubleBE(0)); ASSERT.equal(Infinity, buffer.readDoubleLE(0)); buffer[6] = 0xf0; buffer[7] = 0xff; ASSERT.equal(3.04814e-319, buffer.readDoubleBE(0)); ASSERT.equal(-Infinity, buffer.readDoubleLE(0)); } test(Buffer); test(SlowBuffer); node-v0.10.25~dfsg2/test/simple/test-http-url.parse-post.js0000644000000000000000000000377712270121457022271 0ustar rootroot// Copyright Joyent, Inc. and other Node contributors. // // Permission is hereby granted, free of charge, to any person obtaining a // copy of this software and associated documentation files (the // "Software"), to deal in the Software without restriction, including // without limitation the rights to use, copy, modify, merge, publish, // distribute, sublicense, and/or sell copies of the Software, and to permit // persons to whom the Software is furnished to do so, subject to the // following conditions: // // The above copyright notice and this permission notice shall be included // in all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS // OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF // MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN // NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, // DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR // OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE // USE OR OTHER DEALINGS IN THE SOFTWARE. var common = require('../common'); var assert = require('assert'); var http = require('http'); var https = require('https'); var url = require('url'); var testURL = url.parse('http://localhost:' + common.PORT + '/asdf?qwer=zxcv'); testURL.method = 'POST'; function check(request) { //url.parse should not mess with the method assert.strictEqual(request.method, 'POST'); //everything else should be right assert.strictEqual(request.url, '/asdf?qwer=zxcv'); //the host header should use the url.parse.hostname assert.strictEqual(request.headers.host, testURL.hostname + ':' + testURL.port); } var server = http.createServer(function(request, response) { // run the check function check.call(this, request, response); response.writeHead(200, {}); response.end('ok'); server.close(); }); server.listen(common.PORT, function() { // make the request http.request(testURL).end(); }); node-v0.10.25~dfsg2/test/simple/test-file-read-noexist.js0000644000000000000000000000325612270121457021725 0ustar rootroot// Copyright Joyent, Inc. and other Node contributors. // // Permission is hereby granted, free of charge, to any person obtaining a // copy of this software and associated documentation files (the // "Software"), to deal in the Software without restriction, including // without limitation the rights to use, copy, modify, merge, publish, // distribute, sublicense, and/or sell copies of the Software, and to permit // persons to whom the Software is furnished to do so, subject to the // following conditions: // // The above copyright notice and this permission notice shall be included // in all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS // OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF // MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN // NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, // DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR // OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE // USE OR OTHER DEALINGS IN THE SOFTWARE. var common = require('../common'); var assert = require('assert'); var path = require('path'); var fs = require('fs'); var got_error = false; var filename = path.join(common.fixturesDir, 'does_not_exist.txt'); fs.readFile(filename, 'raw', function(err, content) { if (err) { got_error = true; } else { common.debug('cat returned some content: ' + content); common.debug('this shouldn\'t happen as the file doesn\'t exist...'); assert.equal(true, false); } }); process.on('exit', function() { console.log('done'); assert.equal(true, got_error); }); node-v0.10.25~dfsg2/test/simple/test-force-repl.js0000644000000000000000000000326712270121457020446 0ustar rootroot// Copyright Joyent, Inc. and other Node contributors. // // Permission is hereby granted, free of charge, to any person obtaining a // copy of this software and associated documentation files (the // "Software"), to deal in the Software without restriction, including // without limitation the rights to use, copy, modify, merge, publish, // distribute, sublicense, and/or sell copies of the Software, and to permit // persons to whom the Software is furnished to do so, subject to the // following conditions: // // The above copyright notice and this permission notice shall be included // in all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS // OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF // MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN // NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, // DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR // OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE // USE OR OTHER DEALINGS IN THE SOFTWARE. var common = require('../common'); var assert = require('assert'); var spawn = require('child_process').spawn; // spawn a node child process in "interactive" mode (force the repl) var cp = spawn(process.execPath, ['-i']); var gotToEnd = false; var timeoutId = setTimeout(function() { throw new Error('timeout!'); }, 1000); // give node + the repl 1 second to boot up cp.stdout.setEncoding('utf8'); cp.stdout.once('data', function(b) { clearTimeout(timeoutId); assert.equal(b, '> '); gotToEnd = true; cp.kill(); }); process.on('exit', function() { assert(gotToEnd); }); node-v0.10.25~dfsg2/test/simple/test-domain-from-timer.js0000644000000000000000000000312112270121457021723 0ustar rootroot// Copyright Joyent, Inc. and other Node contributors. // // Permission is hereby granted, free of charge, to any person obtaining a // copy of this software and associated documentation files (the // "Software"), to deal in the Software without restriction, including // without limitation the rights to use, copy, modify, merge, publish, // distribute, sublicense, and/or sell copies of the Software, and to permit // persons to whom the Software is furnished to do so, subject to the // following conditions: // // The above copyright notice and this permission notice shall be included // in all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS // OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF // MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN // NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, // DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR // OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE // USE OR OTHER DEALINGS IN THE SOFTWARE. // Simple tests of most basic domain functionality. var common = require('../common'); var assert = require('assert'); // timeouts call the callback directly from cc, so need to make sure the // domain will be used regardless setTimeout(function() { var domain = require('domain'); var d = domain.create(); d.run(function() { process.nextTick(function() { console.trace('in nexttick', process.domain === d) assert.equal(process.domain, d); }); }); }); node-v0.10.25~dfsg2/test/simple/test-tls-pause-close.js0000644000000000000000000000610012270121457021415 0ustar rootroot// Copyright Joyent, Inc. and other Node contributors. // // Permission is hereby granted, free of charge, to any person obtaining a // copy of this software and associated documentation files (the // "Software"), to deal in the Software without restriction, including // without limitation the rights to use, copy, modify, merge, publish, // distribute, sublicense, and/or sell copies of the Software, and to permit // persons to whom the Software is furnished to do so, subject to the // following conditions: // // The above copyright notice and this permission notice shall be included // in all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS // OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF // MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN // NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, // DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR // OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE // USE OR OTHER DEALINGS IN THE SOFTWARE. if (!process.versions.openssl) { console.error('Skipping because node compiled without OpenSSL.'); process.exit(0); } var common = require('../common'); var assert = require('assert'); var tls = require('tls'); var fs = require('fs'); var path = require('path'); var serverClosed = false; var serverSocketClosed = false; var clientClosed = false; var clientSocketClosed = false; var options = { key: fs.readFileSync(path.join(common.fixturesDir, 'test_key.pem')), cert: fs.readFileSync(path.join(common.fixturesDir, 'test_cert.pem')) }; var server = tls.createServer(options, function(s) { console.log('server connected'); s.socket.on('end', function() { console.log('server socket ended'); }); s.socket.on('close', function() { console.log('server socket closed'); serverSocketClosed = true; }); s.on('end', function() { console.log('server ended'); }); s.on('close', function() { console.log('server closed'); serverClosed = true; }); s.pause(); console.log('server paused'); process.nextTick(function() { s.resume(); console.log('server resumed'); }); s.end(); }); server.listen(common.PORT, function() { var c = tls.connect({ port: common.PORT, rejectUnauthorized: false }, function() { console.log('client connected'); c.socket.on('end', function() { console.log('client socket ended'); }); c.socket.on('close', function() { console.log('client socket closed'); clientSocketClosed = true; }); c.pause(); console.log('client paused'); process.nextTick(function() { c.resume(); console.log('client resumed'); }); }); c.on('end', function() { console.log('client ended'); }); c.on('close', function() { console.log('client closed'); clientClosed = true; server.close(); }); }); process.on('exit', function() { assert(serverClosed); assert(serverSocketClosed); assert(clientClosed); assert(clientSocketClosed); }); node-v0.10.25~dfsg2/test/simple/test-tls-client-resume.js0000644000000000000000000000517312270121457021762 0ustar rootroot// Copyright Joyent, Inc. and other Node contributors. // // Permission is hereby granted, free of charge, to any person obtaining a // copy of this software and associated documentation files (the // "Software"), to deal in the Software without restriction, including // without limitation the rights to use, copy, modify, merge, publish, // distribute, sublicense, and/or sell copies of the Software, and to permit // persons to whom the Software is furnished to do so, subject to the // following conditions: // // The above copyright notice and this permission notice shall be included // in all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS // OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF // MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN // NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, // DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR // OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE // USE OR OTHER DEALINGS IN THE SOFTWARE. // Create an ssl server. First connection, validate that not resume. // Cache session and close connection. Use session on second connection. // ASSERT resumption. if (!process.versions.openssl) { console.error('Skipping because node compiled without OpenSSL.'); process.exit(0); } var common = require('../common'); var assert = require('assert'); var tls = require('tls'); var fs = require('fs'); var options = { key: fs.readFileSync(common.fixturesDir + '/keys/agent2-key.pem'), cert: fs.readFileSync(common.fixturesDir + '/keys/agent2-cert.pem') }; var connections = 0; // create server var server = tls.Server(options, function(socket) { socket.end('Goodbye'); connections++; }); // start listening server.listen(common.PORT, function() { var session1 = null; var client1 = tls.connect({ port: common.PORT, rejectUnauthorized: false }, function() { console.log('connect1'); assert.ok(!client1.isSessionReused(), 'Session *should not* be reused.'); session1 = client1.getSession(); }); client1.on('close', function() { console.log('close1'); var opts = { port: common.PORT, rejectUnauthorized: false, session: session1 }; var client2 = tls.connect(opts, function() { console.log('connect2'); assert.ok(client2.isSessionReused(), 'Session *should* be reused.'); }); client2.on('close', function() { console.log('close2'); server.close(); }); }); }); process.on('exit', function() { assert.equal(2, connections); }); node-v0.10.25~dfsg2/test/simple/test-readfloat.js0000644000000000000000000000557512270121457020355 0ustar rootroot// Copyright Joyent, Inc. and other Node contributors. // // Permission is hereby granted, free of charge, to any person obtaining a // copy of this software and associated documentation files (the // "Software"), to deal in the Software without restriction, including // without limitation the rights to use, copy, modify, merge, publish, // distribute, sublicense, and/or sell copies of the Software, and to permit // persons to whom the Software is furnished to do so, subject to the // following conditions: // // The above copyright notice and this permission notice shall be included // in all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS // OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF // MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN // NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, // DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR // OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE // USE OR OTHER DEALINGS IN THE SOFTWARE. /* * Tests to verify we're reading in floats correctly */ var SlowBuffer = process.binding('buffer').SlowBuffer; var common = require('../common'); var ASSERT = require('assert'); /* * Test (32 bit) float */ function test(clazz) { var buffer = new clazz(4); buffer[0] = 0; buffer[1] = 0; buffer[2] = 0x80; buffer[3] = 0x3f; ASSERT.equal(4.600602988224807e-41, buffer.readFloatBE(0)); ASSERT.equal(1, buffer.readFloatLE(0)); buffer[0] = 0; buffer[1] = 0; buffer[2] = 0; buffer[3] = 0xc0; ASSERT.equal(2.6904930515036488e-43, buffer.readFloatBE(0)); ASSERT.equal(-2, buffer.readFloatLE(0)); buffer[0] = 0xff; buffer[1] = 0xff; buffer[2] = 0x7f; buffer[3] = 0x7f; ASSERT.ok(isNaN(buffer.readFloatBE(0))); ASSERT.equal(3.4028234663852886e+38, buffer.readFloatLE(0)); buffer[0] = 0xab; buffer[1] = 0xaa; buffer[2] = 0xaa; buffer[3] = 0x3e; ASSERT.equal(-1.2126478207002966e-12, buffer.readFloatBE(0)); ASSERT.equal(0.3333333432674408, buffer.readFloatLE(0)); buffer[0] = 0; buffer[1] = 0; buffer[2] = 0; buffer[3] = 0; ASSERT.equal(0, buffer.readFloatBE(0)); ASSERT.equal(0, buffer.readFloatLE(0)); ASSERT.equal(false, 1 / buffer.readFloatLE(0) < 0); buffer[3] = 0x80; ASSERT.equal(1.793662034335766e-43, buffer.readFloatBE(0)); ASSERT.equal(0, buffer.readFloatLE(0)); ASSERT.equal(true, 1 / buffer.readFloatLE(0) < 0); buffer[0] = 0; buffer[1] = 0; buffer[2] = 0x80; buffer[3] = 0x7f; ASSERT.equal(4.609571298396486e-41, buffer.readFloatBE(0)); ASSERT.equal(Infinity, buffer.readFloatLE(0)); buffer[0] = 0; buffer[1] = 0; buffer[2] = 0x80; buffer[3] = 0xff; ASSERT.equal(4.627507918739843e-41, buffer.readFloatBE(0)); ASSERT.equal(-Infinity, buffer.readFloatLE(0)); } test(Buffer); test(SlowBuffer); node-v0.10.25~dfsg2/test/simple/test-http-mutable-headers.js0000644000000000000000000001136712270121457022427 0ustar rootroot// Copyright Joyent, Inc. and other Node contributors. // // Permission is hereby granted, free of charge, to any person obtaining a // copy of this software and associated documentation files (the // "Software"), to deal in the Software without restriction, including // without limitation the rights to use, copy, modify, merge, publish, // distribute, sublicense, and/or sell copies of the Software, and to permit // persons to whom the Software is furnished to do so, subject to the // following conditions: // // The above copyright notice and this permission notice shall be included // in all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS // OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF // MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN // NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, // DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR // OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE // USE OR OTHER DEALINGS IN THE SOFTWARE. var common = require('../common'); var assert = require('assert'); var http = require('http'); // Simple test of Node's HTTP Client mutable headers // OutgoingMessage.prototype.setHeader(name, value) // OutgoingMessage.prototype.getHeader(name) // OutgoingMessage.prototype.removeHeader(name, value) // ServerResponse.prototype.statusCode // .method // .path var testsComplete = 0; var test = 'headers'; var content = 'hello world\n'; var cookies = [ 'session_token=; path=/; expires=Sun, 15-Sep-2030 13:48:52 GMT', 'prefers_open_id=; path=/; expires=Thu, 01-Jan-1970 00:00:00 GMT' ]; var s = http.createServer(function(req, res) { switch (test) { case 'headers': assert.throws(function() { res.setHeader() }); assert.throws(function() { res.setHeader('someHeader') }); assert.throws(function() { res.getHeader() }); assert.throws(function() { res.removeHeader() }); res.setHeader('x-test-header', 'testing'); res.setHeader('X-TEST-HEADER2', 'testing'); res.setHeader('set-cookie', cookies); res.setHeader('x-test-array-header', [1, 2, 3]); var val1 = res.getHeader('x-test-header'); var val2 = res.getHeader('x-test-header2'); assert.equal(val1, 'testing'); assert.equal(val2, 'testing'); res.removeHeader('x-test-header2'); break; case 'contentLength': res.setHeader('content-length', content.length); assert.equal(content.length, res.getHeader('Content-Length')); break; case 'transferEncoding': res.setHeader('transfer-encoding', 'chunked'); assert.equal(res.getHeader('Transfer-Encoding'), 'chunked'); break; case 'writeHead': res.statusCode = 404; res.setHeader('x-foo', 'keyboard cat'); res.writeHead(200, { 'x-foo': 'bar', 'x-bar': 'baz' }); break; } res.statusCode = 201; res.end(content); }); s.listen(common.PORT, nextTest); function nextTest() { if (test === 'end') { return s.close(); } var bufferedResponse = ''; http.get({ port: common.PORT }, function(response) { console.log('TEST: ' + test); console.log('STATUS: ' + response.statusCode); console.log('HEADERS: '); console.dir(response.headers); switch (test) { case 'headers': assert.equal(response.statusCode, 201); assert.equal(response.headers['x-test-header'], 'testing'); assert.equal(response.headers['x-test-array-header'], [1, 2, 3].join(', ')); assert.deepEqual(cookies, response.headers['set-cookie']); assert.equal(response.headers['x-test-header2'] !== undefined, false); // Make the next request test = 'contentLength'; console.log('foobar'); break; case 'contentLength': assert.equal(response.headers['content-length'], content.length); test = 'transferEncoding'; break; case 'transferEncoding': assert.equal(response.headers['transfer-encoding'], 'chunked'); test = 'writeHead'; break; case 'writeHead': assert.equal(response.headers['x-foo'], 'bar'); assert.equal(response.headers['x-bar'], 'baz'); assert.equal(200, response.statusCode); test = 'end'; break; default: throw Error('?'); } response.setEncoding('utf8'); response.on('data', function(s) { bufferedResponse += s; }); response.on('end', function() { assert.equal(content, bufferedResponse); testsComplete++; nextTest(); }); }); } process.on('exit', function() { assert.equal(4, testsComplete); }); node-v0.10.25~dfsg2/test/simple/test-cluster-disconnect.js0000644000000000000000000000633412270121457022216 0ustar rootroot// Copyright Joyent, Inc. and other Node contributors. // // Permission is hereby granted, free of charge, to any person obtaining a // copy of this software and associated documentation files (the // "Software"), to deal in the Software without restriction, including // without limitation the rights to use, copy, modify, merge, publish, // distribute, sublicense, and/or sell copies of the Software, and to permit // persons to whom the Software is furnished to do so, subject to the // following conditions: // // The above copyright notice and this permission notice shall be included // in all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS // OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF // MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN // NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, // DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR // OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE // USE OR OTHER DEALINGS IN THE SOFTWARE. var common = require('../common'); var assert = require('assert'); var cluster = require('cluster'); var net = require('net'); if (cluster.isWorker) { net.createServer(function(socket) { socket.end('echo'); }).listen(common.PORT, '127.0.0.1'); net.createServer(function(socket) { socket.end('echo'); }).listen(common.PORT + 1, '127.0.0.1'); } else if (cluster.isMaster) { // test a single TCP server var testConnection = function(port, cb) { var socket = net.connect(port, '127.0.0.1', function() { // buffer result var result = ''; socket.on('data', function(chunk) { result += chunk; }); // check result socket.on('end', function() { cb(result === 'echo'); }); }); }; // test both servers created in the cluster var testCluster = function(cb) { var servers = 2; var done = 0; for (var i = 0, l = servers; i < l; i++) { testConnection(common.PORT + i, function(success) { assert.ok(success); done += 1; if (done === servers) { cb(); } }); } }; // start two workers and execute callback when both is listening var startCluster = function(cb) { var workers = 8; var online = 0; for (var i = 0, l = workers; i < l; i++) { var worker = cluster.fork(); worker.on('listening', function() { online += 1; if (online === workers) { cb(); } }); } }; var results = { start: 0, test: 0, disconnect: 0 }; var test = function(again) { //1. start cluster startCluster(function() { results.start += 1; //2. test cluster testCluster(function() { results.test += 1; //3. disconnect cluster cluster.disconnect(function() { results.disconnect += 1; // run test again to confirm cleanup if (again) { test(); } }); }); }); }; test(true); process.once('exit', function() { assert.equal(results.start, 2); assert.equal(results.test, 2); assert.equal(results.disconnect, 2); }); } node-v0.10.25~dfsg2/test/simple/test-net-listen-fd0.js0000644000000000000000000000275712270121457021144 0ustar rootroot// Copyright Joyent, Inc. and other Node contributors. // // Permission is hereby granted, free of charge, to any person obtaining a // copy of this software and associated documentation files (the // "Software"), to deal in the Software without restriction, including // without limitation the rights to use, copy, modify, merge, publish, // distribute, sublicense, and/or sell copies of the Software, and to permit // persons to whom the Software is furnished to do so, subject to the // following conditions: // // The above copyright notice and this permission notice shall be included // in all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS // OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF // MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN // NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, // DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR // OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE // USE OR OTHER DEALINGS IN THE SOFTWARE. var common = require('../common'); var assert = require('assert'); var net = require('net'); var gotError = false; process.on('exit', function() { assert.equal(gotError, true); }); // this should fail with an async EINVAL error, not throw an exception net.createServer(assert.fail).listen({fd:0}).on('error', function(e) { assert.equal(e.code, 'EINVAL'); gotError = true; }); node-v0.10.25~dfsg2/test/simple/test-util-format.js0000644000000000000000000000511312270121457020643 0ustar rootroot// Copyright Joyent, Inc. and other Node contributors. // // Permission is hereby granted, free of charge, to any person obtaining a // copy of this software and associated documentation files (the // "Software"), to deal in the Software without restriction, including // without limitation the rights to use, copy, modify, merge, publish, // distribute, sublicense, and/or sell copies of the Software, and to permit // persons to whom the Software is furnished to do so, subject to the // following conditions: // // The above copyright notice and this permission notice shall be included // in all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS // OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF // MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN // NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, // DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR // OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE // USE OR OTHER DEALINGS IN THE SOFTWARE. var common = require('../common'); var assert = require('assert'); var util = require('util'); assert.equal(util.format(), ''); assert.equal(util.format(''), ''); assert.equal(util.format([]), '[]'); assert.equal(util.format({}), '{}'); assert.equal(util.format(null), 'null'); assert.equal(util.format(true), 'true'); assert.equal(util.format(false), 'false'); assert.equal(util.format('test'), 'test'); // CHECKME this is for console.log() compatibility - but is it *right*? assert.equal(util.format('foo', 'bar', 'baz'), 'foo bar baz'); assert.equal(util.format('%d', 42.0), '42'); assert.equal(util.format('%d', 42), '42'); assert.equal(util.format('%s', 42), '42'); assert.equal(util.format('%j', 42), '42'); assert.equal(util.format('%d', '42.0'), '42'); assert.equal(util.format('%d', '42'), '42'); assert.equal(util.format('%s', '42'), '42'); assert.equal(util.format('%j', '42'), '"42"'); assert.equal(util.format('%%s%s', 'foo'), '%sfoo'); assert.equal(util.format('%s'), '%s'); assert.equal(util.format('%s', undefined), 'undefined'); assert.equal(util.format('%s', 'foo'), 'foo'); assert.equal(util.format('%s:%s'), '%s:%s'); assert.equal(util.format('%s:%s', undefined), 'undefined:%s'); assert.equal(util.format('%s:%s', 'foo'), 'foo:%s'); assert.equal(util.format('%s:%s', 'foo', 'bar'), 'foo:bar'); assert.equal(util.format('%s:%s', 'foo', 'bar', 'baz'), 'foo:bar baz'); assert.equal(util.format('%%%s%%', 'hi'), '%hi%'); assert.equal(util.format('%%%s%%%%', 'hi'), '%hi%%'); node-v0.10.25~dfsg2/test/simple/test-http-server.js0000644000000000000000000000741012270121457020665 0ustar rootroot// Copyright Joyent, Inc. and other Node contributors. // // Permission is hereby granted, free of charge, to any person obtaining a // copy of this software and associated documentation files (the // "Software"), to deal in the Software without restriction, including // without limitation the rights to use, copy, modify, merge, publish, // distribute, sublicense, and/or sell copies of the Software, and to permit // persons to whom the Software is furnished to do so, subject to the // following conditions: // // The above copyright notice and this permission notice shall be included // in all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS // OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF // MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN // NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, // DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR // OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE // USE OR OTHER DEALINGS IN THE SOFTWARE. var common = require('../common'); var assert = require('assert'); var net = require('net'); var http = require('http'); var url = require('url'); var qs = require('querystring'); var request_number = 0; var requests_sent = 0; var server_response = ''; var client_got_eof = false; var server = http.createServer(function(req, res) { res.id = request_number; req.id = request_number++; if (req.id == 0) { assert.equal('GET', req.method); assert.equal('/hello', url.parse(req.url).pathname); assert.equal('world', qs.parse(url.parse(req.url).query).hello); assert.equal('b==ar', qs.parse(url.parse(req.url).query).foo); } if (req.id == 1) { common.error('req 1'); assert.equal('POST', req.method); assert.equal('/quit', url.parse(req.url).pathname); } if (req.id == 2) { common.error('req 2'); assert.equal('foo', req.headers['x-x']); } if (req.id == 3) { common.error('req 3'); assert.equal('bar', req.headers['x-x']); this.close(); common.error('server closed'); } setTimeout(function() { res.writeHead(200, {'Content-Type': 'text/plain'}); res.write(url.parse(req.url).pathname); res.end(); }, 1); }); server.listen(common.PORT); server.httpAllowHalfOpen = true; server.on('listening', function() { var c = net.createConnection(common.PORT); c.setEncoding('utf8'); c.on('connect', function() { c.write('GET /hello?hello=world&foo=b==ar HTTP/1.1\r\n\r\n'); requests_sent += 1; }); c.on('data', function(chunk) { server_response += chunk; if (requests_sent == 1) { c.write('POST /quit HTTP/1.1\r\n\r\n'); requests_sent += 1; } if (requests_sent == 2) { c.write('GET / HTTP/1.1\r\nX-X: foo\r\n\r\n' + 'GET / HTTP/1.1\r\nX-X: bar\r\n\r\n'); // Note: we are making the connection half-closed here // before we've gotten the response from the server. This // is a pretty bad thing to do and not really supported // by many http servers. Node supports it optionally if // you set server.httpAllowHalfOpen=true, which we've done // above. c.end(); assert.equal(c.readyState, 'readOnly'); requests_sent += 2; } }); c.on('end', function() { client_got_eof = true; }); c.on('close', function() { assert.equal(c.readyState, 'closed'); }); }); process.on('exit', function() { assert.equal(4, request_number); assert.equal(4, requests_sent); var hello = new RegExp('/hello'); assert.equal(true, hello.exec(server_response) != null); var quit = new RegExp('/quit'); assert.equal(true, quit.exec(server_response) != null); assert.equal(true, client_got_eof); }); node-v0.10.25~dfsg2/test/simple/test-fs-append-file-sync.js0000644000000000000000000000777012270121457022157 0ustar rootroot// Copyright Joyent, Inc. and other Node contributors. // // Permission is hereby granted, free of charge, to any person obtaining a // copy of this software and associated documentation files (the // "Software"), to deal in the Software without restriction, including // without limitation the rights to use, copy, modify, merge, publish, // distribute, sublicense, and/or sell copies of the Software, and to permit // persons to whom the Software is furnished to do so, subject to the // following conditions: // // The above copyright notice and this permission notice shall be included // in all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS // OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF // MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN // NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, // DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR // OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE // USE OR OTHER DEALINGS IN THE SOFTWARE. var common = require('../common'); var assert = require('assert'); var join = require('path').join; var fs = require('fs'); var currentFileData = 'ABCD'; var num = 220; var data = '南越国是前203年至前111年存在于岭南地区的一个国家,国都位于番禺,疆域包括今天中国的广东、' + '广西两省区的大部份地区,福建省、湖南、贵州、云南的一小部份地区和越南的北部。' + '南越国是秦朝灭亡后,由南海郡尉赵佗于前203年起兵兼并桂林郡和象郡后建立。' + '前196年和前179年,南越国曾先后两次名义上臣属于西汉,成为西汉的“外臣”。前112年,' + '南越国末代君主赵建德与西汉发生战争,被汉武帝于前111年所灭。南越国共存在93年,' + '历经五代君主。南越国是岭南地区的第一个有记载的政权国家,采用封建制和郡县制并存的制度,' + '它的建立保证了秦末乱世岭南地区社会秩序的稳定,有效的改善了岭南地区落后的政治、##济现状。\n'; // test that empty file will be created and have content added var filename = join(common.tmpDir, 'append-sync.txt'); common.error('appending to ' + filename); fs.appendFileSync(filename, data); var fileData = fs.readFileSync(filename); console.error('filedata is a ' + typeof fileData); assert.equal(Buffer.byteLength(data), fileData.length); // test that appends data to a non empty file var filename2 = join(common.tmpDir, 'append-sync2.txt'); fs.writeFileSync(filename2, currentFileData); common.error('appending to ' + filename2); fs.appendFileSync(filename2, data); var fileData2 = fs.readFileSync(filename2); assert.equal(Buffer.byteLength(data) + currentFileData.length, fileData2.length); // test that appendFileSync accepts buffers var filename3 = join(common.tmpDir, 'append-sync3.txt'); fs.writeFileSync(filename3, currentFileData); common.error('appending to ' + filename3); var buf = new Buffer(data, 'utf8'); fs.appendFileSync(filename3, buf); var fileData3 = fs.readFileSync(filename3); assert.equal(buf.length + currentFileData.length, fileData3.length); // test that appendFile accepts numbers. var filename4 = join(common.tmpDir, 'append-sync4.txt'); fs.writeFileSync(filename4, currentFileData, { mode: m }); common.error('appending to ' + filename4); var m = 0600; fs.appendFileSync(filename4, num, { mode: m }); // windows permissions aren't unix if (process.platform !== 'win32') { var st = fs.statSync(filename4); assert.equal(st.mode & 0700, m); } var fileData4 = fs.readFileSync(filename4); assert.equal(Buffer.byteLength('' + num) + currentFileData.length, fileData4.length); //exit logic for cleanup process.on('exit', function() { common.error('done'); fs.unlinkSync(filename); fs.unlinkSync(filename2); fs.unlinkSync(filename3); fs.unlinkSync(filename4); }); node-v0.10.25~dfsg2/test/simple/test-process-exec-argv.js0000644000000000000000000000317212270121457021740 0ustar rootroot// Copyright Joyent, Inc. and other Node contributors. // // Permission is hereby granted, free of charge, to any person obtaining a // copy of this software and associated documentation files (the // "Software"), to deal in the Software without restriction, including // without limitation the rights to use, copy, modify, merge, publish, // distribute, sublicense, and/or sell copies of the Software, and to permit // persons to whom the Software is furnished to do so, subject to the // following conditions: // // The above copyright notice and this permission notice shall be included // in all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS // OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF // MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN // NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, // DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR // OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE // USE OR OTHER DEALINGS IN THE SOFTWARE. var assert = require('assert'); var spawn = require('child_process').spawn; if (process.argv[2] === 'child') { process.stdout.write(JSON.stringify(process.execArgv)); } else { var execArgv = ['--harmony_proxies', '--max-stack-size=0']; var args = [__filename, 'child', 'arg0']; var child = spawn(process.execPath, execArgv.concat(args)); var out = ''; child.stdout.on('data', function (chunk) { out += chunk; }); child.on('exit', function () { assert.deepEqual(JSON.parse(out), execArgv); }); } node-v0.10.25~dfsg2/test/simple/test-http-date-header.js0000644000000000000000000000361312270121457021523 0ustar rootroot// Copyright Joyent, Inc. and other Node contributors. // // Permission is hereby granted, free of charge, to any person obtaining a // copy of this software and associated documentation files (the // "Software"), to deal in the Software without restriction, including // without limitation the rights to use, copy, modify, merge, publish, // distribute, sublicense, and/or sell copies of the Software, and to permit // persons to whom the Software is furnished to do so, subject to the // following conditions: // // The above copyright notice and this permission notice shall be included // in all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS // OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF // MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN // NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, // DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR // OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE // USE OR OTHER DEALINGS IN THE SOFTWARE. var common = require('../common'); var assert = require('assert'); var http = require('http'); var testResBody = 'other stuff!\n'; var server = http.createServer(function(req, res) { assert.ok(! ('date' in req.headers), 'Request headers contained a Date.'); res.writeHead(200, { 'Content-Type': 'text/plain' }); res.end(testResBody); }); server.listen(common.PORT); server.addListener('listening', function() { var options = { port: common.PORT, path: '/', method: 'GET' }; var req = http.request(options, function(res) { assert.ok('date' in res.headers, 'Response headers didn\'t contain a Date.'); res.addListener('end', function() { server.close(); process.exit(); }); res.resume(); }); req.end(); }); node-v0.10.25~dfsg2/test/simple/test-https-no-reader.js0000644000000000000000000000434212270121457021417 0ustar rootroot// Copyright Joyent, Inc. and other Node contributors. // // Permission is hereby granted, free of charge, to any person obtaining a // copy of this software and associated documentation files (the // "Software"), to deal in the Software without restriction, including // without limitation the rights to use, copy, modify, merge, publish, // distribute, sublicense, and/or sell copies of the Software, and to permit // persons to whom the Software is furnished to do so, subject to the // following conditions: // // The above copyright notice and this permission notice shall be included // in all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS // OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF // MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN // NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, // DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR // OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE // USE OR OTHER DEALINGS IN THE SOFTWARE. if (!process.versions.openssl) { console.error('Skipping because node compiled without OpenSSL.'); process.exit(0); } var common = require('../common'); var assert = require('assert'); var https = require('https'); var Buffer = require('buffer').Buffer; var fs = require('fs'); var path = require('path'); var options = { key: fs.readFileSync(path.join(common.fixturesDir, 'test_key.pem')), cert: fs.readFileSync(path.join(common.fixturesDir, 'test_cert.pem')) }; var buf = new Buffer(1024 * 1024); var sent = 0; var received = 0; var server = https.createServer(options, function(req, res) { res.writeHead(200); for (var i = 0; i < 50; i++) { res.write(buf); } res.end(); }); server.listen(common.PORT, function() { var resumed = false; var req = https.request({ method: 'POST', port: common.PORT, rejectUnauthorized: false }, function(res) { res.read(0); setTimeout(function() { // Read buffer should be somewhere near high watermark // (i.e. should not leak) assert(res._readableState.length < 100 * 1024); process.exit(0); }, 5000); }); req.end(); }); node-v0.10.25~dfsg2/test/simple/test-child-process-internal.js0000644000000000000000000000361412270121457022755 0ustar rootroot// Copyright Joyent, Inc. and other Node contributors. // // Permission is hereby granted, free of charge, to any person obtaining a // copy of this software and associated documentation files (the // "Software"), to deal in the Software without restriction, including // without limitation the rights to use, copy, modify, merge, publish, // distribute, sublicense, and/or sell copies of the Software, and to permit // persons to whom the Software is furnished to do so, subject to the // following conditions: // // The above copyright notice and this permission notice shall be included // in all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS // OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF // MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN // NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, // DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR // OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE // USE OR OTHER DEALINGS IN THE SOFTWARE. var common = require('../common'); var assert = require('assert'); //messages var PREFIX = 'NODE_'; var normal = {cmd: 'foo' + PREFIX}; var internal = {cmd: PREFIX + 'bar'}; if (process.argv[2] === 'child') { //send non-internal message containing PREFIX at a non prefix position process.send(normal); //send inernal message process.send(internal); process.exit(0); } else { var fork = require('child_process').fork; var child = fork(process.argv[1], ['child']); var gotNormal; child.once('message', function(data) { gotNormal = data; }); var gotInternal; child.once('internalMessage', function(data) { gotInternal = data; }); process.on('exit', function() { assert.deepEqual(gotNormal, normal); assert.deepEqual(gotInternal, internal); }); } node-v0.10.25~dfsg2/test/simple/test-fs-readfile-empty.js0000644000000000000000000000300212270121457021710 0ustar rootroot// Copyright Joyent, Inc. and other Node contributors. // // Permission is hereby granted, free of charge, to any person obtaining a // copy of this software and associated documentation files (the // "Software"), to deal in the Software without restriction, including // without limitation the rights to use, copy, modify, merge, publish, // distribute, sublicense, and/or sell copies of the Software, and to permit // persons to whom the Software is furnished to do so, subject to the // following conditions: // // The above copyright notice and this permission notice shall be included // in all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS // OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF // MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN // NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, // DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR // OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE // USE OR OTHER DEALINGS IN THE SOFTWARE. var common = require('../common'); var assert = require('assert'); var path = require('path'), fs = require('fs'), fn = path.join(common.fixturesDir, 'empty.txt'); fs.readFile(fn, function(err, data) { assert.ok(data); }); fs.readFile(fn, 'utf8', function(err, data) { assert.strictEqual('', data); }); assert.ok(fs.readFileSync(fn)); assert.strictEqual('', fs.readFileSync(fn, 'utf8')); node-v0.10.25~dfsg2/test/simple/test-http-status-code.js0000644000000000000000000000431612270121457021614 0ustar rootroot// Copyright Joyent, Inc. and other Node contributors. // // Permission is hereby granted, free of charge, to any person obtaining a // copy of this software and associated documentation files (the // "Software"), to deal in the Software without restriction, including // without limitation the rights to use, copy, modify, merge, publish, // distribute, sublicense, and/or sell copies of the Software, and to permit // persons to whom the Software is furnished to do so, subject to the // following conditions: // // The above copyright notice and this permission notice shall be included // in all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS // OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF // MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN // NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, // DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR // OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE // USE OR OTHER DEALINGS IN THE SOFTWARE. var common = require('../common'); var assert = require('assert'); var http = require('http'); // Simple test of Node's HTTP ServerResponse.statusCode // ServerResponse.prototype.statusCode var testsComplete = 0; var tests = [200, 202, 300, 404, 500]; var testIdx = 0; var s = http.createServer(function(req, res) { var t = tests[testIdx]; res.writeHead(t, {'Content-Type': 'text/plain'}); console.log('--\nserver: statusCode after writeHead: ' + res.statusCode); assert.equal(res.statusCode, t); res.end('hello world\n'); }); s.listen(common.PORT, nextTest); function nextTest() { if (testIdx + 1 === tests.length) { return s.close(); } var test = tests[testIdx]; http.get({ port: common.PORT }, function(response) { console.log('client: expected status: ' + test); console.log('client: statusCode: ' + response.statusCode); assert.equal(response.statusCode, test); response.on('end', function() { testsComplete++; testIdx += 1; nextTest(); }); response.resume(); }); } process.on('exit', function() { assert.equal(4, testsComplete); }); node-v0.10.25~dfsg2/test/simple/test-net-write-slow.js0000644000000000000000000000410712270121457021302 0ustar rootroot// Copyright Joyent, Inc. and other Node contributors. // // Permission is hereby granted, free of charge, to any person obtaining a // copy of this software and associated documentation files (the // "Software"), to deal in the Software without restriction, including // without limitation the rights to use, copy, modify, merge, publish, // distribute, sublicense, and/or sell copies of the Software, and to permit // persons to whom the Software is furnished to do so, subject to the // following conditions: // // The above copyright notice and this permission notice shall be included // in all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS // OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF // MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN // NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, // DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR // OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE // USE OR OTHER DEALINGS IN THE SOFTWARE. var common = require('../common'); var assert = require('assert'); var net = require('net'); var SIZE = 2E5; var N = 10; var flushed = 0; var received = 0; var buf = new Buffer(SIZE); buf.fill(0x61); // 'a' var server = net.createServer(function(socket) { socket.setNoDelay(); socket.setTimeout(1000); socket.on('timeout', function() { assert.fail('flushed: ' + flushed + ', received: ' + received + '/' + SIZE * N); }); for (var i = 0; i < N; ++i) { socket.write(buf, function() { ++flushed; if (flushed === N) { socket.setTimeout(0); } }); } socket.end(); }).listen(common.PORT, function() { var conn = net.connect(common.PORT); conn.on('data', function(buf) { received += buf.length; conn.pause(); setTimeout(function() { conn.resume(); }, 20); }); conn.on('end', function() { server.close(); }); }); process.on('exit', function() { assert.equal(received, SIZE * N); }); node-v0.10.25~dfsg2/test/simple/test-fs-realpath.js0000644000000000000000000004463212270121457020617 0ustar rootroot// Copyright Joyent, Inc. and other Node contributors. // // Permission is hereby granted, free of charge, to any person obtaining a // copy of this software and associated documentation files (the // "Software"), to deal in the Software without restriction, including // without limitation the rights to use, copy, modify, merge, publish, // distribute, sublicense, and/or sell copies of the Software, and to permit // persons to whom the Software is furnished to do so, subject to the // following conditions: // // The above copyright notice and this permission notice shall be included // in all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS // OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF // MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN // NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, // DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR // OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE // USE OR OTHER DEALINGS IN THE SOFTWARE. var common = require('../common'); var assert = require('assert'); var fs = require('fs'); var path = require('path'); var exec = require('child_process').exec; var async_completed = 0, async_expected = 0, unlink = []; var isWindows = process.platform === 'win32'; var skipSymlinks = false; var root = '/'; if (isWindows) { // something like "C:\\" root = process.cwd().substr(0, 3); // On Windows, creating symlinks requires admin privileges. // We'll only try to run symlink test if we have enough privileges. try { exec('whoami /priv', function(err, o) { if (err || o.indexOf('SeCreateSymbolicLinkPrivilege') == -1) { skipSymlinks = true; } runTest(); }); } catch (er) { // better safe than sorry skipSymlinks = true; process.nextTick(runTest); } } else { process.nextTick(runTest); } function tmp(p) { return path.join(common.tmpDir, p); } var fixturesAbsDir = common.fixturesDir; var tmpAbsDir = common.tmpDir; console.error("absolutes\n%s\n%s", fixturesAbsDir, tmpAbsDir); function asynctest(testBlock, args, callback, assertBlock) { async_expected++; testBlock.apply(testBlock, args.concat(function(err) { var ignoreError = false; if (assertBlock) { try { ignoreError = assertBlock.apply(assertBlock, arguments); } catch (e) { err = e; } } async_completed++; callback(ignoreError ? null : err); })); } // sub-tests: function test_simple_error_callback(cb) { var ncalls = 0; fs.realpath('/this/path/does/not/exist', function(err, s) { assert(err); assert(!s); ncalls++; cb(); }); process.on('exit', function() { assert.equal(ncalls, 1); }); } function test_simple_relative_symlink(callback) { console.log('test_simple_relative_symlink'); if (skipSymlinks) { console.log('skipping symlink test (no privs)'); return runNextTest(); } var entry = common.tmpDir + '/symlink', expected = common.tmpDir + '/cycles/root.js'; [ [entry, '../tmp/cycles/root.js'] ].forEach(function(t) { try {fs.unlinkSync(t[0]);}catch (e) {} console.log('fs.symlinkSync(%j, %j, %j)', t[1], t[0], 'file'); fs.symlinkSync(t[1], t[0], 'file'); unlink.push(t[0]); }); var result = fs.realpathSync(entry); assert.equal(result, path.resolve(expected), 'got ' + common.inspect(result) + ' expected ' + common.inspect(expected)); asynctest(fs.realpath, [entry], callback, function(err, result) { assert.equal(result, path.resolve(expected), 'got ' + common.inspect(result) + ' expected ' + common.inspect(expected)); }); } function test_simple_absolute_symlink(callback) { console.log('test_simple_absolute_symlink'); // this one should still run, even if skipSymlinks is set, // because it uses a junction. var type = skipSymlinks ? 'junction' : 'dir'; console.log('using type=%s', type); var entry = tmpAbsDir + '/symlink', expected = fixturesAbsDir + '/nested-index/one'; [ [entry, expected] ].forEach(function(t) { try {fs.unlinkSync(t[0]);} catch (e) {} console.error('fs.symlinkSync(%j, %j, %j)', t[1], t[0], type); fs.symlinkSync(t[1], t[0], type); unlink.push(t[0]); }); var result = fs.realpathSync(entry); assert.equal(result, path.resolve(expected), 'got ' + common.inspect(result) + ' expected ' + common.inspect(expected)); asynctest(fs.realpath, [entry], callback, function(err, result) { assert.equal(result, path.resolve(expected), 'got ' + common.inspect(result) + ' expected ' + common.inspect(expected)); }); } function test_deep_relative_file_symlink(callback) { console.log('test_deep_relative_file_symlink'); if (skipSymlinks) { console.log('skipping symlink test (no privs)'); return runNextTest(); } var expected = path.join(common.fixturesDir, 'cycles', 'root.js'); var linkData1 = '../../cycles/root.js'; var linkPath1 = path.join(common.fixturesDir, 'nested-index', 'one', 'symlink1.js'); try {fs.unlinkSync(linkPath1);} catch (e) {} fs.symlinkSync(linkData1, linkPath1, 'file'); var linkData2 = '../one/symlink1.js'; var entry = path.join(common.fixturesDir, 'nested-index', 'two', 'symlink1-b.js'); try {fs.unlinkSync(entry);} catch (e) {} fs.symlinkSync(linkData2, entry, 'file'); unlink.push(linkPath1); unlink.push(entry); assert.equal(fs.realpathSync(entry), path.resolve(expected)); asynctest(fs.realpath, [entry], callback, function(err, result) { assert.equal(result, path.resolve(expected), 'got ' + common.inspect(result) + ' expected ' + common.inspect(path.resolve(expected))); }); } function test_deep_relative_dir_symlink(callback) { console.log('test_deep_relative_dir_symlink'); if (skipSymlinks) { console.log('skipping symlink test (no privs)'); return runNextTest(); } var expected = path.join(common.fixturesDir, 'cycles', 'folder'); var linkData1b = '../../cycles/folder'; var linkPath1b = path.join(common.fixturesDir, 'nested-index', 'one', 'symlink1-dir'); try {fs.unlinkSync(linkPath1b);} catch (e) {} fs.symlinkSync(linkData1b, linkPath1b, 'dir'); var linkData2b = '../one/symlink1-dir'; var entry = path.join(common.fixturesDir, 'nested-index', 'two', 'symlink12-dir'); try {fs.unlinkSync(entry);} catch (e) {} fs.symlinkSync(linkData2b, entry, 'dir'); unlink.push(linkPath1b); unlink.push(entry); assert.equal(fs.realpathSync(entry), path.resolve(expected)); asynctest(fs.realpath, [entry], callback, function(err, result) { assert.equal(result, path.resolve(expected), 'got ' + common.inspect(result) + ' expected ' + common.inspect(path.resolve(expected))); }); } function test_cyclic_link_protection(callback) { console.log('test_cyclic_link_protection'); if (skipSymlinks) { console.log('skipping symlink test (no privs)'); return runNextTest(); } var entry = common.tmpDir + '/cycles/realpath-3a'; [ [entry, '../cycles/realpath-3b'], [common.tmpDir + '/cycles/realpath-3b', '../cycles/realpath-3c'], [common.tmpDir + '/cycles/realpath-3c', '../cycles/realpath-3a'] ].forEach(function(t) { try {fs.unlinkSync(t[0]);} catch (e) {} fs.symlinkSync(t[1], t[0], 'dir'); unlink.push(t[0]); }); assert.throws(function() { fs.realpathSync(entry); }); asynctest(fs.realpath, [entry], callback, function(err, result) { assert.ok(err && true); return true; }); } function test_cyclic_link_overprotection(callback) { console.log('test_cyclic_link_overprotection'); if (skipSymlinks) { console.log('skipping symlink test (no privs)'); return runNextTest(); } var cycles = common.tmpDir + '/cycles'; var expected = fs.realpathSync(cycles); var folder = cycles + '/folder'; var link = folder + '/cycles'; var testPath = cycles; for (var i = 0; i < 10; i++) testPath += '/folder/cycles'; try {fs.unlinkSync(link)} catch (ex) {} fs.symlinkSync(cycles, link, 'dir'); unlink.push(link); assert.equal(fs.realpathSync(testPath), path.resolve(expected)); asynctest(fs.realpath, [testPath], callback, function(er, res) { assert.equal(res, path.resolve(expected)); }); } function test_relative_input_cwd(callback) { console.log('test_relative_input_cwd'); // we need to get the relative path to the tmp dir from cwd. // When the test runner is running it, that will be .../node/test // but it's more common to run `./node test/.../`, so detect it here. var entrydir = process.cwd(); var entry = common.tmpDir.substr(entrydir.length + 1) + '/cycles/realpath-3a'; var expected = common.tmpDir + '/cycles/root.js'; [ [entry, '../cycles/realpath-3b'], [common.tmpDir + '/cycles/realpath-3b', '../cycles/realpath-3c'], [common.tmpDir + '/cycles/realpath-3c', 'root.js'] ].forEach(function(t) { var fn = t[0]; console.error('fn=%j', fn); try {fs.unlinkSync(fn);} catch (e) {} var b = path.basename(t[1]); var type = (b === 'root.js' ? 'file' : 'dir'); console.log('fs.symlinkSync(%j, %j, %j)', t[1], fn, type); fs.symlinkSync(t[1], fn, 'file'); unlink.push(fn); }); var origcwd = process.cwd(); process.chdir(entrydir); assert.equal(fs.realpathSync(entry), path.resolve(expected)); asynctest(fs.realpath, [entry], callback, function(err, result) { process.chdir(origcwd); assert.equal(result, path.resolve(expected), 'got ' + common.inspect(result) + ' expected ' + common.inspect(path.resolve(expected))); return true; }); } function test_deep_symlink_mix(callback) { console.log('test_deep_symlink_mix'); if (isWindows) { // This one is a mix of files and directories, and it's quite tricky // to get the file/dir links sorted out correctly. console.log('skipping symlink test (no way to work on windows)'); return runNextTest(); } // todo: check to see that common.fixturesDir is not rooted in the // same directory as our test symlink. /* /tmp/node-test-realpath-f1 -> ../tmp/node-test-realpath-d1/foo /tmp/node-test-realpath-d1 -> ../node-test-realpath-d2 /tmp/node-test-realpath-d2/foo -> ../node-test-realpath-f2 /tmp/node-test-realpath-f2 -> /node/test/fixtures/nested-index/one/realpath-c /node/test/fixtures/nested-index/one/realpath-c -> /node/test/fixtures/nested-index/two/realpath-c /node/test/fixtures/nested-index/two/realpath-c -> ../../cycles/root.js /node/test/fixtures/cycles/root.js (hard) */ var entry = tmp('node-test-realpath-f1'); try { fs.unlinkSync(tmp('node-test-realpath-d2/foo')); } catch (e) {} try { fs.rmdirSync(tmp('node-test-realpath-d2')); } catch (e) {} fs.mkdirSync(tmp('node-test-realpath-d2'), 0700); try { [ [entry, '../tmp/node-test-realpath-d1/foo'], [tmp('node-test-realpath-d1'), '../tmp/node-test-realpath-d2'], [tmp('node-test-realpath-d2/foo'), '../node-test-realpath-f2'], [tmp('node-test-realpath-f2'), fixturesAbsDir + '/nested-index/one/realpath-c'], [fixturesAbsDir + '/nested-index/one/realpath-c', fixturesAbsDir + '/nested-index/two/realpath-c'], [fixturesAbsDir + '/nested-index/two/realpath-c', '../../../tmp/cycles/root.js'] ].forEach(function(t) { //common.debug('setting up '+t[0]+' -> '+t[1]); try { fs.unlinkSync(t[0]); } catch (e) {} fs.symlinkSync(t[1], t[0]); unlink.push(t[0]); }); } finally { unlink.push(tmp('node-test-realpath-d2')); } var expected = tmpAbsDir + '/cycles/root.js'; assert.equal(fs.realpathSync(entry), path.resolve(expected)); asynctest(fs.realpath, [entry], callback, function(err, result) { assert.equal(result, path.resolve(expected), 'got ' + common.inspect(result) + ' expected ' + common.inspect(path.resolve(expected))); return true; }); } function test_non_symlinks(callback) { console.log('test_non_symlinks'); var entrydir = path.dirname(tmpAbsDir); var entry = tmpAbsDir.substr(entrydir.length + 1) + '/cycles/root.js'; var expected = tmpAbsDir + '/cycles/root.js'; var origcwd = process.cwd(); process.chdir(entrydir); assert.equal(fs.realpathSync(entry), path.resolve(expected)); asynctest(fs.realpath, [entry], callback, function(err, result) { process.chdir(origcwd); assert.equal(result, path.resolve(expected), 'got ' + common.inspect(result) + ' expected ' + common.inspect(path.resolve(expected))); return true; }); } var upone = path.join(process.cwd(), '..'); function test_escape_cwd(cb) { console.log('test_escape_cwd'); asynctest(fs.realpath, ['..'], cb, function(er, uponeActual) { assert.equal(upone, uponeActual, 'realpath("..") expected: ' + path.resolve(upone) + ' actual:' + uponeActual); }); } var uponeActual = fs.realpathSync('..'); assert.equal(upone, uponeActual, 'realpathSync("..") expected: ' + path.resolve(upone) + ' actual:' + uponeActual); // going up with .. multiple times // . // `-- a/ // |-- b/ // | `-- e -> .. // `-- d -> .. // realpath(a/b/e/d/a/b/e/d/a) ==> a function test_up_multiple(cb) { console.error('test_up_multiple'); if (skipSymlinks) { console.log('skipping symlink test (no privs)'); return runNextTest(); } fs.mkdirSync(tmp('a'), 0755); fs.mkdirSync(tmp('a/b'), 0755); fs.symlinkSync('..', tmp('a/d'), 'dir'); unlink.push(tmp('a/d')); fs.symlinkSync('..', tmp('a/b/e'), 'dir'); unlink.push(tmp('a/b/e')); var abedabed = tmp('abedabed'.split('').join('/')); var abedabed_real = tmp(''); var abedabeda = tmp('abedabeda'.split('').join('/')); var abedabeda_real = tmp('a'); assert.equal(fs.realpathSync(abedabeda), abedabeda_real); assert.equal(fs.realpathSync(abedabed), abedabed_real); fs.realpath(abedabeda, function (er, real) { if (er) throw er; assert.equal(abedabeda_real, real); fs.realpath(abedabed, function (er, real) { if (er) throw er; assert.equal(abedabed_real, real); cb(); }); }); } // absolute symlinks with children. // . // `-- a/ // |-- b/ // | `-- c/ // | `-- x.txt // `-- link -> /tmp/node-test-realpath-abs-kids/a/b/ // realpath(root+'/a/link/c/x.txt') ==> root+'/a/b/c/x.txt' function test_abs_with_kids(cb) { console.log('test_abs_with_kids'); // this one should still run, even if skipSymlinks is set, // because it uses a junction. var type = skipSymlinks ? 'junction' : 'dir'; console.log('using type=%s', type); var root = tmpAbsDir + '/node-test-realpath-abs-kids'; function cleanup() { ['/a/b/c/x.txt', '/a/link' ].forEach(function(file) { try {fs.unlinkSync(root + file)} catch (ex) {} }); ['/a/b/c', '/a/b', '/a', '' ].forEach(function(folder) { try {fs.rmdirSync(root + folder)} catch (ex) {} }); } function setup() { cleanup(); ['', '/a', '/a/b', '/a/b/c' ].forEach(function(folder) { console.log('mkdir ' + root + folder); fs.mkdirSync(root + folder, 0700); }); fs.writeFileSync(root + '/a/b/c/x.txt', 'foo'); fs.symlinkSync(root + '/a/b', root + '/a/link', type); } setup(); var linkPath = root + '/a/link/c/x.txt'; var expectPath = root + '/a/b/c/x.txt'; var actual = fs.realpathSync(linkPath); // console.log({link:linkPath,expect:expectPath,actual:actual},'sync'); assert.equal(actual, path.resolve(expectPath)); asynctest(fs.realpath, [linkPath], cb, function(er, actual) { // console.log({link:linkPath,expect:expectPath,actual:actual},'async'); assert.equal(actual, path.resolve(expectPath)); cleanup(); }); } function test_lying_cache_liar(cb) { var n = 2; // this should not require *any* stat calls, since everything // checked by realpath will be found in the cache. console.log('test_lying_cache_liar'); var cache = { '/foo/bar/baz/bluff' : '/foo/bar/bluff', '/1/2/3/4/5/6/7' : '/1', '/a' : '/a', '/a/b' : '/a/b', '/a/b/c' : '/a/b', '/a/b/d' : '/a/b/d' }; if (isWindows) { var wc = {}; Object.keys(cache).forEach(function(k) { wc[ path.resolve(k) ] = path.resolve(cache[k]); }); cache = wc; } var bluff = path.resolve('/foo/bar/baz/bluff'); var rps = fs.realpathSync(bluff, cache); assert.equal(cache[bluff], rps); var nums = path.resolve('/1/2/3/4/5/6/7'); var called = false; // no sync cb calling! fs.realpath(nums, cache, function(er, rp) { called = true; assert.equal(cache[nums], rp); if (--n === 0) cb(); }); assert(called === false); var test = path.resolve('/a/b/c/d'), expect = path.resolve('/a/b/d'); var actual = fs.realpathSync(test, cache); assert.equal(expect, actual); fs.realpath(test, cache, function(er, actual) { assert.equal(expect, actual); if (--n === 0) cb(); }); } // ---------------------------------------------------------------------------- var tests = [ test_simple_error_callback, test_simple_relative_symlink, test_simple_absolute_symlink, test_deep_relative_file_symlink, test_deep_relative_dir_symlink, test_cyclic_link_protection, test_cyclic_link_overprotection, test_relative_input_cwd, test_deep_symlink_mix, test_non_symlinks, test_escape_cwd, test_abs_with_kids, test_lying_cache_liar, test_up_multiple ]; var numtests = tests.length; var testsRun = 0; function runNextTest(err) { if (err) throw err; var test = tests.shift(); if (!test) { return console.log(numtests + ' subtests completed OK for fs.realpath'); } testsRun++; test(runNextTest); } assert.equal(root, fs.realpathSync('/')); fs.realpath('/', function(err, result) { assert.equal(null, err); assert.equal(root, result); }); function runTest() { var tmpDirs = ['cycles', 'cycles/folder']; tmpDirs.forEach(function(t) { t = tmp(t); var s; try { s = fs.statSync(t); } catch (ex) {} if (s) return; fs.mkdirSync(t, 0700); }); fs.writeFileSync(tmp('cycles/root.js'), "console.error('roooot!');"); console.error('start tests'); runNextTest(); } process.on('exit', function() { assert.equal(numtests, testsRun); unlink.forEach(function(path) { try {fs.unlinkSync(path);} catch (e) {} }); assert.equal(async_completed, async_expected); }); node-v0.10.25~dfsg2/test/simple/test-http-url.parse-https.request.js0000644000000000000000000000421512270121457024121 0ustar rootroot// Copyright Joyent, Inc. and other Node contributors. // // Permission is hereby granted, free of charge, to any person obtaining a // copy of this software and associated documentation files (the // "Software"), to deal in the Software without restriction, including // without limitation the rights to use, copy, modify, merge, publish, // distribute, sublicense, and/or sell copies of the Software, and to permit // persons to whom the Software is furnished to do so, subject to the // following conditions: // // The above copyright notice and this permission notice shall be included // in all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS // OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF // MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN // NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, // DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR // OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE // USE OR OTHER DEALINGS IN THE SOFTWARE. var common = require('../common'); var assert = require('assert'); var https = require('https'); var url = require('url'); var fs = require('fs'); var clientRequest; // https options var httpsOptions = { key: fs.readFileSync(common.fixturesDir + '/keys/agent1-key.pem'), cert: fs.readFileSync(common.fixturesDir + '/keys/agent1-cert.pem') }; var testURL = url.parse('https://localhost:' + common.PORT); testURL.rejectUnauthorized = false; function check(request) { // assert that I'm https assert.ok(request.socket.encrypted); } var server = https.createServer(httpsOptions, function(request, response) { // run the check function check.call(this, request, response); response.writeHead(200, {}); response.end('ok'); server.close(); }); server.listen(common.PORT, function() { // make the request var clientRequest = https.request(testURL); // since there is a little magic with the agent // make sure that the request uses the https.Agent assert.ok(clientRequest.agent instanceof https.Agent); clientRequest.end(); }); node-v0.10.25~dfsg2/test/simple/test-eval-require.js0000644000000000000000000000271212270121457021003 0ustar rootroot// Copyright Joyent, Inc. and other Node contributors. // // Permission is hereby granted, free of charge, to any person obtaining a // copy of this software and associated documentation files (the // "Software"), to deal in the Software without restriction, including // without limitation the rights to use, copy, modify, merge, publish, // distribute, sublicense, and/or sell copies of the Software, and to permit // persons to whom the Software is furnished to do so, subject to the // following conditions: // // The above copyright notice and this permission notice shall be included // in all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS // OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF // MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN // NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, // DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR // OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE // USE OR OTHER DEALINGS IN THE SOFTWARE. var common = require('../common'); var assert = require('assert'); var spawn = require('child_process').spawn; var path = require('path'); var fs = require('fs'); var options = { cwd: common.fixturesDir }; var child = spawn(process.execPath, ['-e', 'require("foo")'], options); child.on('exit', function(code) { assert.equal(code, 0); }); node-v0.10.25~dfsg2/test/simple/test-dgram-bind.js0000644000000000000000000000253112270121457020405 0ustar rootroot// Copyright Joyent, Inc. and other Node contributors. // // Permission is hereby granted, free of charge, to any person obtaining a // copy of this software and associated documentation files (the // "Software"), to deal in the Software without restriction, including // without limitation the rights to use, copy, modify, merge, publish, // distribute, sublicense, and/or sell copies of the Software, and to permit // persons to whom the Software is furnished to do so, subject to the // following conditions: // // The above copyright notice and this permission notice shall be included // in all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS // OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF // MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN // NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, // DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR // OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE // USE OR OTHER DEALINGS IN THE SOFTWARE. var common = require('../common'); var assert = require('assert'); var dgram = require('dgram'); var socket = dgram.createSocket('udp4'); socket.on('listening', function () { socket.close(); }); socket.bind(); // should not throw node-v0.10.25~dfsg2/test/simple/test-dgram-implicit-bind.js0000644000000000000000000000346412270121457022223 0ustar rootroot// Copyright Joyent, Inc. and other Node contributors. // // Permission is hereby granted, free of charge, to any person obtaining a // copy of this software and associated documentation files (the // "Software"), to deal in the Software without restriction, including // without limitation the rights to use, copy, modify, merge, publish, // distribute, sublicense, and/or sell copies of the Software, and to permit // persons to whom the Software is furnished to do so, subject to the // following conditions: // // The above copyright notice and this permission notice shall be included // in all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS // OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF // MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN // NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, // DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR // OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE // USE OR OTHER DEALINGS IN THE SOFTWARE. var common = require('../common'); var assert = require('assert'); var dgram = require('dgram'); var source = dgram.createSocket('udp4'); var target = dgram.createSocket('udp4'); var messages = 0; process.on('exit', function() { assert.equal(messages, 2); }); target.on('message', function(buf) { if (buf.toString() === 'abc') ++messages; if (buf.toString() === 'def') ++messages; if (messages === 2) { source.close(); target.close(); } }); target.on('listening', function() { // Second .send() call should not throw a bind error. source.send(Buffer('abc'), 0, 3, common.PORT, '127.0.0.1'); source.send(Buffer('def'), 0, 3, common.PORT, '127.0.0.1'); }); target.bind(common.PORT); node-v0.10.25~dfsg2/test/simple/test-http-request-end-twice.js0000644000000000000000000000305612270121457022726 0ustar rootroot// Copyright Joyent, Inc. and other Node contributors. // // Permission is hereby granted, free of charge, to any person obtaining a // copy of this software and associated documentation files (the // "Software"), to deal in the Software without restriction, including // without limitation the rights to use, copy, modify, merge, publish, // distribute, sublicense, and/or sell copies of the Software, and to permit // persons to whom the Software is furnished to do so, subject to the // following conditions: // // The above copyright notice and this permission notice shall be included // in all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS // OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF // MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN // NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, // DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR // OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE // USE OR OTHER DEALINGS IN THE SOFTWARE. var common = require('../common'); var assert = require('assert'); var http = require('http'); var server = http.Server(function(req, res) { res.writeHead(200, {'Content-Type': 'text/plain'}); res.end('hello world\n'); }); server.listen(common.PORT, function() { var req = http.get({port: common.PORT}, function(res) { res.on('end', function() { assert.ok(!req.end()); server.close(); }); res.resume(); }); }); node-v0.10.25~dfsg2/test/simple/test-deprecation-flags.js0000644000000000000000000000452312270121457021773 0ustar rootroot// Copyright Joyent, Inc. and other Node contributors. // // Permission is hereby granted, free of charge, to any person obtaining a // copy of this software and associated documentation files (the // "Software"), to deal in the Software without restriction, including // without limitation the rights to use, copy, modify, merge, publish, // distribute, sublicense, and/or sell copies of the Software, and to permit // persons to whom the Software is furnished to do so, subject to the // following conditions: // // The above copyright notice and this permission notice shall be included // in all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS // OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF // MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN // NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, // DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR // OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE // USE OR OTHER DEALINGS IN THE SOFTWARE. var common = require('../common'); var assert = require('assert'); var execFile = require('child_process').execFile; var depmod = require.resolve('../fixtures/deprecated.js'); var node = process.execPath; var normal = [depmod]; var noDep = ['--no-deprecation', depmod]; var traceDep = ['--trace-deprecation', depmod]; execFile(node, normal, function(er, stdout, stderr) { console.error('normal: show deprecation warning'); assert.equal(er, null); assert.equal(stdout, ''); assert.equal(stderr, 'util.p: Use console.error() instead.\n\'This is deprecated\'\n'); console.log('normal ok'); }); execFile(node, noDep, function(er, stdout, stderr) { console.error('--no-deprecation: silence deprecations'); assert.equal(er, null); assert.equal(stdout, ''); assert.equal(stderr, '\'This is deprecated\'\n'); console.log('silent ok'); }); execFile(node, traceDep, function(er, stdout, stderr) { console.error('--trace-deprecation: show stack'); assert.equal(er, null); assert.equal(stdout, ''); var stack = stderr.trim().split('\n'); // just check the top and bottom. assert.equal(stack[0], 'Trace: util.p: Use console.error() instead.'); assert.equal(stack.pop(), '\'This is deprecated\''); console.log('trace ok'); }); node-v0.10.25~dfsg2/test/simple/test-http-set-trailers.js0000644000000000000000000000640512270121457022000 0ustar rootroot// Copyright Joyent, Inc. and other Node contributors. // // Permission is hereby granted, free of charge, to any person obtaining a // copy of this software and associated documentation files (the // "Software"), to deal in the Software without restriction, including // without limitation the rights to use, copy, modify, merge, publish, // distribute, sublicense, and/or sell copies of the Software, and to permit // persons to whom the Software is furnished to do so, subject to the // following conditions: // // The above copyright notice and this permission notice shall be included // in all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS // OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF // MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN // NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, // DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR // OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE // USE OR OTHER DEALINGS IN THE SOFTWARE. var common = require('../common'); var assert = require('assert'); var http = require('http'); var net = require('net'); var outstanding_reqs = 0; var server = http.createServer(function(req, res) { res.writeHead(200, [['content-type', 'text/plain']]); res.addTrailers({'x-foo': 'bar'}); res.end('stuff' + '\n'); }); server.listen(common.PORT); // first, we test an HTTP/1.0 request. server.on('listening', function() { var c = net.createConnection(common.PORT); var res_buffer = ''; c.setEncoding('utf8'); c.on('connect', function() { outstanding_reqs++; c.write('GET / HTTP/1.0\r\n\r\n'); }); c.on('data', function(chunk) { //console.log(chunk); res_buffer += chunk; }); c.on('end', function() { c.end(); assert.ok(! /x-foo/.test(res_buffer), 'Trailer in HTTP/1.0 response.'); outstanding_reqs--; if (outstanding_reqs == 0) { server.close(); process.exit(); } }); }); // now, we test an HTTP/1.1 request. server.on('listening', function() { var c = net.createConnection(common.PORT); var res_buffer = ''; var tid; c.setEncoding('utf8'); c.on('connect', function() { outstanding_reqs++; c.write('GET / HTTP/1.1\r\n\r\n'); tid = setTimeout(assert.fail, 2000, 'Couldn\'t find last chunk.'); }); c.on('data', function(chunk) { //console.log(chunk); res_buffer += chunk; if (/0\r\n/.test(res_buffer)) { // got the end. outstanding_reqs--; clearTimeout(tid); assert.ok( /0\r\nx-foo: bar\r\n\r\n$/.test(res_buffer), 'No trailer in HTTP/1.1 response.' ); if (outstanding_reqs == 0) { server.close(); process.exit(); } } }); }); // now, see if the client sees the trailers. server.on('listening', function() { http.get({ port: common.PORT, path: '/hello', headers: {} }, function(res) { res.on('end', function() { //console.log(res.trailers); assert.ok('x-foo' in res.trailers, 'Client doesn\'t see trailers.'); outstanding_reqs--; if (outstanding_reqs == 0) { server.close(); process.exit(); } }); res.resume(); }); outstanding_reqs++; }); node-v0.10.25~dfsg2/test/simple/test-tls-client-reject.js0000644000000000000000000000525712270121457021741 0ustar rootroot// Copyright Joyent, Inc. and other Node contributors. // // Permission is hereby granted, free of charge, to any person obtaining a // copy of this software and associated documentation files (the // "Software"), to deal in the Software without restriction, including // without limitation the rights to use, copy, modify, merge, publish, // distribute, sublicense, and/or sell copies of the Software, and to permit // persons to whom the Software is furnished to do so, subject to the // following conditions: // // The above copyright notice and this permission notice shall be included // in all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS // OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF // MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN // NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, // DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR // OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE // USE OR OTHER DEALINGS IN THE SOFTWARE. if (!process.versions.openssl) { console.error('Skipping because node compiled without OpenSSL.'); process.exit(0); } var common = require('../common'); var assert = require('assert'); var tls = require('tls'); var fs = require('fs'); var path = require('path'); var options = { key: fs.readFileSync(path.join(common.fixturesDir, 'test_key.pem')), cert: fs.readFileSync(path.join(common.fixturesDir, 'test_cert.pem')) }; var connectCount = 0; var server = tls.createServer(options, function(socket) { ++connectCount; socket.on('data', function(data) { common.debug(data.toString()); assert.equal(data, 'ok'); }); }).listen(common.PORT, function() { unauthorized(); }); function unauthorized() { var socket = tls.connect({ port: common.PORT, rejectUnauthorized: false }, function() { assert(!socket.authorized); socket.end(); rejectUnauthorized(); }); socket.on('error', function(err) { assert(false); }); socket.write('ok'); } function rejectUnauthorized() { var socket = tls.connect(common.PORT, function() { assert(false); }); socket.on('error', function(err) { common.debug(err); authorized(); }); socket.write('ng'); } function authorized() { var socket = tls.connect(common.PORT, { ca: [fs.readFileSync(path.join(common.fixturesDir, 'test_cert.pem'))] }, function() { assert(socket.authorized); socket.end(); server.close(); }); socket.on('error', function(err) { assert(false); }); socket.write('ok'); } process.on('exit', function() { assert.equal(connectCount, 3); }); node-v0.10.25~dfsg2/test/simple/test-regression-object-prototype.js0000644000000000000000000000233412270121457024071 0ustar rootroot// Copyright Joyent, Inc. and other Node contributors. // // Permission is hereby granted, free of charge, to any person obtaining a // copy of this software and associated documentation files (the // "Software"), to deal in the Software without restriction, including // without limitation the rights to use, copy, modify, merge, publish, // distribute, sublicense, and/or sell copies of the Software, and to permit // persons to whom the Software is furnished to do so, subject to the // following conditions: // // The above copyright notice and this permission notice shall be included // in all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS // OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF // MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN // NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, // DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR // OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE // USE OR OTHER DEALINGS IN THE SOFTWARE. //console.log('puts before'); Object.prototype.xadsadsdasasdxx = function() { }; console.log('puts after'); node-v0.10.25~dfsg2/test/simple/test-timers.js0000644000000000000000000000377512270121457017717 0ustar rootroot// Copyright Joyent, Inc. and other Node contributors. // // Permission is hereby granted, free of charge, to any person obtaining a // copy of this software and associated documentation files (the // "Software"), to deal in the Software without restriction, including // without limitation the rights to use, copy, modify, merge, publish, // distribute, sublicense, and/or sell copies of the Software, and to permit // persons to whom the Software is furnished to do so, subject to the // following conditions: // // The above copyright notice and this permission notice shall be included // in all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS // OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF // MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN // NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, // DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR // OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE // USE OR OTHER DEALINGS IN THE SOFTWARE. var common = require('../common'); var assert = require('assert'); var inputs = [ undefined, null, true, false, '', [], {}, NaN, +Infinity, -Infinity, (1.0 / 0.0), // sanity check parseFloat('x'), // NaN -10, -1, -0.5, -0.0, 0, 0.0, 0.5, 1, 1.0, 10, 2147483648, // browser behaviour: timeouts > 2^31-1 run on next tick 12345678901234 // ditto ]; var timeouts = []; var intervals = []; inputs.forEach(function(value, index) { setTimeout(function() { timeouts[index] = true; }, value); var handle = setInterval(function() { clearInterval(handle); // disarm timer or we'll never finish intervals[index] = true; }, value); }); process.on('exit', function() { // assert that all timers have run inputs.forEach(function(value, index) { assert.equal(true, timeouts[index]); assert.equal(true, intervals[index]); }); }); node-v0.10.25~dfsg2/test/simple/test-zlib-from-string.js0000644000000000000000000000766012270121457021616 0ustar rootroot// Copyright Joyent, Inc. and other Node contributors. // // Permission is hereby granted, free of charge, to any person obtaining a // copy of this software and associated documentation files (the // "Software"), to deal in the Software without restriction, including // without limitation the rights to use, copy, modify, merge, publish, // distribute, sublicense, and/or sell copies of the Software, and to permit // persons to whom the Software is furnished to do so, subject to the // following conditions: // // The above copyright notice and this permission notice shall be included // in all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS // OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF // MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN // NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, // DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR // OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE // USE OR OTHER DEALINGS IN THE SOFTWARE. // test compressing and uncompressing a string with zlib var common = require('../common.js'); var assert = require('assert'); var zlib = require('zlib'); var inputString = 'ΩΩLorem ipsum dolor sit amet, consectetur adipiscing el' + 'it. Morbi faucibus, purus at gravida dictum, libero arcu convallis la' + 'cus, in commodo libero metus eu nisi. Nullam commodo, neque nec porta' + ' placerat, nisi est fermentum augue, vitae gravida tellus sapien sit ' + 'amet tellus. Aenean non diam orci. Proin quis elit turpis. Suspendiss' + 'e non diam ipsum. Suspendisse nec ullamcorper odio. Vestibulum arcu m' + 'i, sodales non suscipit id, ultrices ut massa. Sed ac sem sit amet ar' + 'cu malesuada fermentum. Nunc sed. '; var expectedBase64Deflate = 'eJxdUUtOQzEMvMoc4OndgT0gJCT2buJWlpI4jePeqZfpm' + 'XAKLRKbLOzx/HK73q6vOrhCunlF1qIDJhNUeW5I2ozT5OkDlKWLJWkncJG5403HQXAkT3' + 'Jw29B9uIEmToMukglZ0vS6ociBh4JG8sV4oVLEUCitK2kxq1WzPnChHDzsaGKy491Lofo' + 'AbWh8do43oeuYhB5EPCjcLjzYJo48KrfQBvnJecNFJvHT1+RSQsGoC7dn2t/xjhduTA1N' + 'WyQIZR0pbHwMDatnD+crPqKSqGPHp1vnlsWM/07ubf7bheF7kqSj84Bm0R1fYTfaK8vqq' + 'qfKBtNMhe3OZh6N95CTvMX5HJJi4xOVzCgUOIMSLH7wmeOHaFE4RdpnGavKtrB5xzfO/Ll9'; var expectedBase64Gzip = 'H4sIAAAAAAAAA11RS05DMQy8yhzg6d2BPSAkJPZu4laWkjiN' + '496pl+mZcAotEpss7PH8crverq86uEK6eUXWogMmE1R5bkjajNPk6QOUpYslaSdwkbnjT' + 'cdBcCRPcnDb0H24gSZOgy6SCVnS9LqhyIGHgkbyxXihUsRQKK0raTGrVbM+cKEcPOxoYr' + 'Lj3Uuh+gBtaHx2jjeh65iEHkQ8KNwuPNgmjjwqt9AG+cl5w0Um8dPX5FJCwagLt2fa3/G' + 'OF25MDU1bJAhlHSlsfAwNq2cP5ys+opKoY8enW+eWxYz/Tu5t/tuF4XuSpKPzgGbRHV9h' + 'N9ory+qqp8oG00yF7c5mHo33kJO8xfkckmLjE5XMKBQ4gxIsfvCZ44doUThF2mcZq8q2s' + 'HnHNzRtagj5AQAA'; zlib.deflate(inputString, function(err, buffer) { assert.equal(buffer.toString('base64'), expectedBase64Deflate, 'deflate encoded string should match'); }); zlib.gzip(inputString, function(err, buffer) { // Can't actually guarantee that we'll get exactly the same // deflated bytes when we compress a string, since the header // depends on stuff other than the input string itself. // However, decrypting it should definitely yield the same // result that we're expecting, and this should match what we get // from inflating the known valid deflate data. zlib.gunzip(buffer, function(err, gunzipped) { assert.equal(gunzipped.toString(), inputString, 'Should get original string after gzip/gunzip'); }); }); var buffer = new Buffer(expectedBase64Deflate, 'base64'); zlib.unzip(buffer, function(err, buffer) { assert.equal(buffer.toString(), inputString, 'decoded inflated string should match'); }); buffer = new Buffer(expectedBase64Gzip, 'base64'); zlib.unzip(buffer, function(err, buffer) { assert.equal(buffer.toString(), inputString, 'decoded gunzipped string should match'); }); node-v0.10.25~dfsg2/test/simple/test-stdout-close-unref.js0000644000000000000000000000233512270121457022145 0ustar rootroot// Copyright Joyent, Inc. and other Node contributors. // // Permission is hereby granted, free of charge, to any person obtaining a // copy of this software and associated documentation files (the // "Software"), to deal in the Software without restriction, including // without limitation the rights to use, copy, modify, merge, publish, // distribute, sublicense, and/or sell copies of the Software, and to permit // persons to whom the Software is furnished to do so, subject to the // following conditions: // // The above copyright notice and this permission notice shall be included // in all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS // OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF // MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN // NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, // DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR // OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE // USE OR OTHER DEALINGS IN THE SOFTWARE. process.stdin.resume(); process.stdin._handle.close(); process.stdin._handle.unref(); // Should not segfault. node-v0.10.25~dfsg2/test/simple/test-pipe-file-to-http.js0000644000000000000000000000624312270121457021654 0ustar rootroot// Copyright Joyent, Inc. and other Node contributors. // // Permission is hereby granted, free of charge, to any person obtaining a // copy of this software and associated documentation files (the // "Software"), to deal in the Software without restriction, including // without limitation the rights to use, copy, modify, merge, publish, // distribute, sublicense, and/or sell copies of the Software, and to permit // persons to whom the Software is furnished to do so, subject to the // following conditions: // // The above copyright notice and this permission notice shall be included // in all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS // OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF // MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN // NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, // DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR // OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE // USE OR OTHER DEALINGS IN THE SOFTWARE. var common = require('../common'); var assert = require('assert'); var fs = require('fs'); var http = require('http'); var path = require('path'); var cp = require('child_process'); var filename = path.join(common.tmpDir || '/tmp', 'big'); var clientReqComplete = false; var count = 0; var server = http.createServer(function(req, res) { console.error('SERVER request'); var timeoutId; assert.equal('POST', req.method); req.pause(); common.error('request paused'); setTimeout(function() { req.resume(); common.error('request resumed'); }, 1000); req.on('data', function(chunk) { common.error('recv data! nchars = ' + chunk.length); count += chunk.length; }); req.on('end', function() { if (timeoutId) { clearTimeout(timeoutId); } console.log('request complete from server'); res.writeHead(200, {'Content-Type': 'text/plain'}); res.end(); }); }); server.listen(common.PORT); server.on('listening', function() { var cmd = common.ddCommand(filename, 10240); console.log('dd command: ', cmd); cp.exec(cmd, function(err, stdout, stderr) { if (err) throw err; console.error('EXEC returned successfully stdout=%d stderr=%d', stdout.length, stderr.length); makeRequest(); }); }); function makeRequest() { var req = http.request({ port: common.PORT, path: '/', method: 'POST' }); common.error('pipe!'); var s = fs.ReadStream(filename); s.pipe(req); s.on('data', function(chunk) { console.error('FS data chunk=%d', chunk.length); }); s.on('end', function() { console.error('FS end'); }); s.on('close', function(err) { if (err) throw err; clientReqComplete = true; common.error('client finished sending request'); }); req.on('response', function(res) { console.error('RESPONSE', res.statusCode, res.headers); res.resume(); res.on('end', function() { console.error('RESPONSE end'); server.close(); }); }); } process.on('exit', function() { assert.equal(1024 * 10240, count); assert.ok(clientReqComplete); }); node-v0.10.25~dfsg2/test/simple/test-vm-create-context-arg.js0000644000000000000000000000263012270121457022515 0ustar rootroot// Copyright Joyent, Inc. and other Node contributors. // // Permission is hereby granted, free of charge, to any person obtaining a // copy of this software and associated documentation files (the // "Software"), to deal in the Software without restriction, including // without limitation the rights to use, copy, modify, merge, publish, // distribute, sublicense, and/or sell copies of the Software, and to permit // persons to whom the Software is furnished to do so, subject to the // following conditions: // // The above copyright notice and this permission notice shall be included // in all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS // OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF // MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN // NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, // DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR // OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE // USE OR OTHER DEALINGS IN THE SOFTWARE. var common = require('../common'); var assert = require('assert'); var vm = require('vm'); assert.throws(function() { var ctx = vm.createContext('string is not supported'); }); assert.doesNotThrow(function() { var ctx = vm.createContext({ a: 1 }); ctx = vm.createContext([0, 1, 2, 3]); }); node-v0.10.25~dfsg2/test/simple/test-cluster-listening-port.js0000644000000000000000000000326312270121457023041 0ustar rootroot// Copyright Joyent, Inc. and other Node contributors. // // Permission is hereby granted, free of charge, to any person obtaining a // copy of this software and associated documentation files (the // "Software"), to deal in the Software without restriction, including // without limitation the rights to use, copy, modify, merge, publish, // distribute, sublicense, and/or sell copies of the Software, and to permit // persons to whom the Software is furnished to do so, subject to the // following conditions: // // The above copyright notice and this permission notice shall be included // in all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS // OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF // MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN // NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, // DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR // OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE // USE OR OTHER DEALINGS IN THE SOFTWARE. var assert = require('assert'); var cluster = require('cluster'); var net = require('net'); if (cluster.isMaster) { var port = null; cluster.fork(); cluster.on('listening', function(worker, address) { port = address.port; // ensure that the port is not 0 or null assert(port); // ensure that the port is numerical assert.strictEqual(typeof(port), 'number'); worker.kill(); }); process.on('exit', function() { // ensure that the 'listening' handler has been called assert(port); }); } else { net.createServer(assert.fail).listen(0); } node-v0.10.25~dfsg2/test/simple/test-http-many-ended-pipelines.js0000644000000000000000000000356312270121457023373 0ustar rootroot// Copyright Joyent, Inc. and other Node contributors. // // Permission is hereby granted, free of charge, to any person obtaining a // copy of this software and associated documentation files (the // "Software"), to deal in the Software without restriction, including // without limitation the rights to use, copy, modify, merge, publish, // distribute, sublicense, and/or sell copies of the Software, and to permit // persons to whom the Software is furnished to do so, subject to the // following conditions: // // The above copyright notice and this permission notice shall be included // in all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS // OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF // MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN // NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, // DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR // OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE // USE OR OTHER DEALINGS IN THE SOFTWARE. var common = require('../common'); var assert = require('assert'); // no warnings should happen! var trace = console.trace; console.trace = function() { trace.apply(console, arguments); throw new Error('no tracing should happen here'); }; var http = require('http'); var net = require('net'); var server = http.createServer(function(req, res) { res.end('ok'); // Oh no! The connection died! req.socket.destroy(); }); server.listen(common.PORT); var client = net.connect({ port: common.PORT, allowHalfOpen: true }); for (var i = 0; i < 20; i++) { client.write('GET / HTTP/1.1\r\n' + 'Host: some.host.name\r\n'+ '\r\n\r\n'); } client.end(); client.on('connect', function() { server.close(); }); client.pipe(process.stdout); node-v0.10.25~dfsg2/test/simple/test-http-res-write-end-dont-take-array.js0000644000000000000000000000451012270121457025042 0ustar rootroot// Copyright Joyent, Inc. and other Node contributors. // // Permission is hereby granted, free of charge, to any person obtaining a // copy of this software and associated documentation files (the // "Software"), to deal in the Software without restriction, including // without limitation the rights to use, copy, modify, merge, publish, // distribute, sublicense, and/or sell copies of the Software, and to permit // persons to whom the Software is furnished to do so, subject to the // following conditions: // // The above copyright notice and this permission notice shall be included // in all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS // OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF // MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN // NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, // DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR // OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE // USE OR OTHER DEALINGS IN THE SOFTWARE. var common = require('../common'); var assert = require('assert'); var http = require('http'); var test = 1; var server = http.createServer(function(req, res) { res.writeHead(200, {'Content-Type': 'text/plain'}); if (test === 1) { // write should accept string res.write('string'); // write should accept buffer res.write(new Buffer('asdf')); // write should not accept an Array assert.throws(function() { res.write(['array']); }, TypeError, 'first argument must be a string or Buffer'); // end should not accept an Array assert.throws(function() { res.end(['moo']); }, TypeError, 'first argument must be a string or Buffer'); // end should accept string res.end('string'); } else if (test === 2) { // end should accept Buffer res.end(new Buffer('asdf')); } }); server.listen(common.PORT, function() { // just make a request, other tests handle responses http.get({port: common.PORT}, function(res) { res.resume(); // lazy serial test, becuase we can only call end once per request test += 1; // do it again to test .end(Buffer); http.get({port: common.PORT}, function(res) { res.resume(); server.close(); }); }); }); node-v0.10.25~dfsg2/test/simple/test-https-drain.js0000644000000000000000000000540612270121457020642 0ustar rootroot// Copyright Joyent, Inc. and other Node contributors. // // Permission is hereby granted, free of charge, to any person obtaining a // copy of this software and associated documentation files (the // "Software"), to deal in the Software without restriction, including // without limitation the rights to use, copy, modify, merge, publish, // distribute, sublicense, and/or sell copies of the Software, and to permit // persons to whom the Software is furnished to do so, subject to the // following conditions: // // The above copyright notice and this permission notice shall be included // in all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS // OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF // MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN // NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, // DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR // OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE // USE OR OTHER DEALINGS IN THE SOFTWARE. if (!process.versions.openssl) { console.error('Skipping because node compiled without OpenSSL.'); process.exit(0); } var common = require('../common'); var assert = require('assert'); var https = require('https'); var fs = require('fs'); var path = require('path'); var options = { key: fs.readFileSync(path.join(common.fixturesDir, 'test_key.pem')), cert: fs.readFileSync(path.join(common.fixturesDir, 'test_cert.pem')) }; var bufSize = 1024 * 1024; var sent = 0; var received = 0; var server = https.createServer(options, function(req, res) { res.writeHead(200); req.pipe(res); }); server.listen(common.PORT, function() { var resumed = false; var req = https.request({ method: 'POST', port: common.PORT, rejectUnauthorized: false }, function(res) { var timer; res.pause(); common.debug('paused'); send(); function send() { if (req.write(new Buffer(bufSize))) { sent += bufSize; assert.ok(sent < 100 * 1024 * 1024); // max 100MB return process.nextTick(send); } sent += bufSize; common.debug('sent: ' + sent); resumed = true; res.resume(); common.debug('resumed'); timer = setTimeout(function() { process.exit(1); }, 1000); } res.on('data', function(data) { assert.ok(resumed); if (timer) { clearTimeout(timer); timer = null; } received += data.length; if (received >= sent) { common.debug('received: ' + received); req.end(); server.close(); } }); }); req.write('a'); ++sent; }); process.on('exit', function() { assert.equal(sent, received); }); node-v0.10.25~dfsg2/test/simple/test-http-exit-delay.js0000644000000000000000000000363212270121457021426 0ustar rootroot// Copyright Joyent, Inc. and other Node contributors. // // Permission is hereby granted, free of charge, to any person obtaining a // copy of this software and associated documentation files (the // "Software"), to deal in the Software without restriction, including // without limitation the rights to use, copy, modify, merge, publish, // distribute, sublicense, and/or sell copies of the Software, and to permit // persons to whom the Software is furnished to do so, subject to the // following conditions: // // The above copyright notice and this permission notice shall be included // in all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS // OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF // MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN // NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, // DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR // OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE // USE OR OTHER DEALINGS IN THE SOFTWARE. var assert = require('assert'); var common = require('../common.js'); var http = require('http'); var start; var server = http.createServer(function(req, res) { req.resume(); req.on('end', function() { res.end('Success'); }); server.close(function() { start = process.hrtime(); }); }); server.listen(common.PORT, 'localhost', function() { var interval_id = setInterval(function() { if (new Date().getMilliseconds() > 100) return; var req = http.request({ 'host': 'localhost', 'port': common.PORT, 'agent': false, 'method': 'PUT' }); req.end('Test'); clearInterval(interval_id); }, 10); }); process.on('exit', function() { var d = process.hrtime(start); assert.equal(d[0], 0); assert(d[1] / 1e9 < 0.03); console.log('ok'); }); node-v0.10.25~dfsg2/test/simple/test-zerolengthbufferbug.js0000644000000000000000000000360612270121457022456 0ustar rootroot// Copyright Joyent, Inc. and other Node contributors. // // Permission is hereby granted, free of charge, to any person obtaining a // copy of this software and associated documentation files (the // "Software"), to deal in the Software without restriction, including // without limitation the rights to use, copy, modify, merge, publish, // distribute, sublicense, and/or sell copies of the Software, and to permit // persons to whom the Software is furnished to do so, subject to the // following conditions: // // The above copyright notice and this permission notice shall be included // in all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS // OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF // MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN // NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, // DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR // OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE // USE OR OTHER DEALINGS IN THE SOFTWARE. // Serving up a zero-length buffer should work. var common = require('../common'); var assert = require('assert'); var http = require('http'); var server = http.createServer(function(req, res) { var buffer = new Buffer(0); // FIXME: WTF gjslint want this? res.writeHead(200, {'Content-Type': 'text/html', 'Content-Length': buffer.length}); res.end(buffer); }); var gotResponse = false; var resBodySize = 0; server.listen(common.PORT, function() { http.get({ port: common.PORT }, function(res) { gotResponse = true; res.on('data', function(d) { resBodySize += d.length; }); res.on('end', function(d) { server.close(); }); }); }); process.on('exit', function() { assert.ok(gotResponse); assert.equal(0, resBodySize); }); node-v0.10.25~dfsg2/test/simple/test-sys.js0000644000000000000000000001167512270121457017230 0ustar rootroot// Copyright Joyent, Inc. and other Node contributors. // // Permission is hereby granted, free of charge, to any person obtaining a // copy of this software and associated documentation files (the // "Software"), to deal in the Software without restriction, including // without limitation the rights to use, copy, modify, merge, publish, // distribute, sublicense, and/or sell copies of the Software, and to permit // persons to whom the Software is furnished to do so, subject to the // following conditions: // // The above copyright notice and this permission notice shall be included // in all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS // OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF // MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN // NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, // DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR // OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE // USE OR OTHER DEALINGS IN THE SOFTWARE. var common = require('../common'); var assert = require('assert'); assert.equal('0', common.inspect(0)); assert.equal('1', common.inspect(1)); assert.equal('false', common.inspect(false)); assert.equal("''", common.inspect('')); assert.equal("'hello'", common.inspect('hello')); assert.equal('[Function]', common.inspect(function() {})); assert.equal('undefined', common.inspect(undefined)); assert.equal('null', common.inspect(null)); assert.equal('/foo(bar\\n)?/gi', common.inspect(/foo(bar\n)?/gi)); assert.equal(new Date('2010-02-14T12:48:40+01:00').toString(), common.inspect(new Date('Sun, 14 Feb 2010 11:48:40 GMT'))); assert.equal("'\\n\\u0001'", common.inspect('\n\u0001')); assert.equal('[]', common.inspect([])); assert.equal('{}', common.inspect(Object.create([]))); assert.equal('[ 1, 2 ]', common.inspect([1, 2])); assert.equal('[ 1, [ 2, 3 ] ]', common.inspect([1, [2, 3]])); assert.equal('{}', common.inspect({})); assert.equal('{ a: 1 }', common.inspect({a: 1})); assert.equal('{ a: [Function] }', common.inspect({a: function() {}})); assert.equal('{ a: 1, b: 2 }', common.inspect({a: 1, b: 2})); assert.equal('{ a: {} }', common.inspect({'a': {}})); assert.equal('{ a: { b: 2 } }', common.inspect({'a': {'b': 2}})); assert.equal('{ a: { b: { c: [Object] } } }', common.inspect({'a': {'b': { 'c': { 'd': 2 }}}})); assert.equal('{ a: { b: { c: { d: 2 } } } }', common.inspect({'a': {'b': { 'c': { 'd': 2 }}}}, false, null)); assert.equal('[ 1, 2, 3, [length]: 3 ]', common.inspect([1, 2, 3], true)); assert.equal('{ a: [Object] }', common.inspect({'a': {'b': { 'c': 2}}}, false, 0)); assert.equal('{ a: { b: [Object] } }', common.inspect({'a': {'b': { 'c': 2}}}, false, 1)); assert.equal('{ visible: 1 }', common.inspect(Object.create({}, {visible: {value: 1, enumerable: true}, hidden: {value: 2}})) ); // Due to the hash seed randomization it's not deterministic the order that // the following ways this hash is displayed. // See http://codereview.chromium.org/9124004/ var out = common.inspect(Object.create({}, {visible: {value: 1, enumerable: true}, hidden: {value: 2}}), true); if (out !== '{ [hidden]: 2, visible: 1 }' && out !== '{ visible: 1, [hidden]: 2 }') { assert.ok(false); } // Objects without prototype var out = common.inspect(Object.create(null, { name: {value: 'Tim', enumerable: true}, hidden: {value: 'secret'}}), true); if (out !== "{ [hidden]: 'secret', name: 'Tim' }" && out !== "{ name: 'Tim', [hidden]: 'secret' }") { assert(false); } assert.equal('{ name: \'Tim\' }', common.inspect(Object.create(null, {name: {value: 'Tim', enumerable: true}, hidden: {value: 'secret'}})) ); // Dynamic properties assert.equal('{ readonly: [Getter] }', common.inspect({get readonly() {}})); assert.equal('{ readwrite: [Getter/Setter] }', common.inspect({get readwrite() {},set readwrite(val) {}})); assert.equal('{ writeonly: [Setter] }', common.inspect({set writeonly(val) {}})); var value = {}; value['a'] = value; assert.equal('{ a: [Circular] }', common.inspect(value)); // Array with dynamic properties value = [1, 2, 3]; value.__defineGetter__('growingLength', function() { this.push(true); return this.length; }); assert.equal('[ 1, 2, 3, growingLength: [Getter] ]', common.inspect(value)); // Function with properties value = function() {}; value.aprop = 42; assert.equal('{ [Function] aprop: 42 }', common.inspect(value)); // Regular expressions with properties value = /123/ig; value.aprop = 42; assert.equal('{ /123/gi aprop: 42 }', common.inspect(value)); // Dates with properties value = new Date('Sun, 14 Feb 2010 11:48:40 GMT'); value.aprop = 42; assert.equal('{ Sun, 14 Feb 2010 11:48:40 GMT aprop: 42 }', common.inspect(value) ); node-v0.10.25~dfsg2/test/simple/test-require-cache-without-stat.js0000644000000000000000000000460612270121457023575 0ustar rootroot// Copyright Joyent, Inc. and other Node contributors. // // Permission is hereby granted, free of charge, to any person obtaining a // copy of this software and associated documentation files (the // "Software"), to deal in the Software without restriction, including // without limitation the rights to use, copy, modify, merge, publish, // distribute, sublicense, and/or sell copies of the Software, and to permit // persons to whom the Software is furnished to do so, subject to the // following conditions: // // The above copyright notice and this permission notice shall be included // in all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS // OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF // MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN // NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, // DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR // OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE // USE OR OTHER DEALINGS IN THE SOFTWARE. // We've experienced a regression where the module loader stats a bunch of // directories on require() even if it's been called before. The require() // should caching the request. var common = require('../common'); var fs = require('fs'); var assert = require('assert'); var counter = 0; // Switch out the two stat implementations so that they increase a counter // each time they are called. var _statSync = fs.statSync; var _stat = fs.stat; fs.statSync = function() { counter++; return _statSync.apply(this, arguments); }; fs.stat = function() { counter++; return _stat.apply(this, arguments); }; // Load the module 'a' and 'http' once. It should become cached. require(common.fixturesDir + '/a'); require('../fixtures/a.js'); require('./../fixtures/a.js'); require('http'); console.log('counterBefore = %d', counter); var counterBefore = counter; // Now load the module a bunch of times with equivalent paths. // stat should not be called. for (var i = 0; i < 100; i++) { require(common.fixturesDir + '/a'); require('../fixtures/a.js'); require('./../fixtures/a.js'); } // Do the same with a built-in module for (var i = 0; i < 100; i++) { require('http'); } console.log('counterAfter = %d', counter); var counterAfter = counter; assert.equal(counterBefore, counterAfter); node-v0.10.25~dfsg2/test/simple/test-stream-big-packet.js0000644000000000000000000000512712270121457021704 0ustar rootroot// Copyright Joyent, Inc. and other Node contributors. // // Permission is hereby granted, free of charge, to any person obtaining a // copy of this software and associated documentation files (the // "Software"), to deal in the Software without restriction, including // without limitation the rights to use, copy, modify, merge, publish, // distribute, sublicense, and/or sell copies of the Software, and to permit // persons to whom the Software is furnished to do so, subject to the // following conditions: // // The above copyright notice and this permission notice shall be included // in all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS // OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF // MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN // NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, // DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR // OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE // USE OR OTHER DEALINGS IN THE SOFTWARE. var common = require('../common'); var assert = require('assert'); var util = require('util'); var stream = require('stream'); var passed = false; function PassThrough () { stream.Transform.call(this); }; util.inherits(PassThrough, stream.Transform); PassThrough.prototype._transform = function (chunk, encoding, done) { this.push(chunk); done(); }; function TestStream () { stream.Transform.call(this); }; util.inherits(TestStream, stream.Transform); TestStream.prototype._transform = function (chunk, encoding, done) { if (!passed) { // Char 'a' only exists in the last write passed = chunk.toString().indexOf('a') >= 0; } done(); }; var s1 = new PassThrough(); var s2 = new PassThrough(); var s3 = new TestStream(); s1.pipe(s3); // Don't let s2 auto close which may close s3 s2.pipe(s3, {end: false}); // We must write a buffer larger than highWaterMark var big = new Buffer(s1._writableState.highWaterMark + 1); big.fill('x'); // Since big is larger than highWaterMark, it will be buffered internally. assert(!s1.write(big)); // 'tiny' is small enough to pass through internal buffer. assert(s2.write('tiny')); // Write some small data in next IO loop, which will never be written to s3 // Because 'drain' event is not emitted from s1 and s1 is still paused setImmediate(s1.write.bind(s1), 'later'); // Assert after two IO loops when all operations have been done. process.on('exit', function () { assert(passed, 'Large buffer is not handled properly by Writable Stream'); }); node-v0.10.25~dfsg2/test/simple/test-domain-http-server.js0000644000000000000000000000664412270121457022142 0ustar rootroot// Copyright Joyent, Inc. and other Node contributors. // // Permission is hereby granted, free of charge, to any person obtaining a // copy of this software and associated documentation files (the // "Software"), to deal in the Software without restriction, including // without limitation the rights to use, copy, modify, merge, publish, // distribute, sublicense, and/or sell copies of the Software, and to permit // persons to whom the Software is furnished to do so, subject to the // following conditions: // // The above copyright notice and this permission notice shall be included // in all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS // OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF // MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN // NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, // DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR // OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE // USE OR OTHER DEALINGS IN THE SOFTWARE. var domain = require('domain'); var http = require('http'); var assert = require('assert'); var common = require('../common.js'); var objects = { foo: 'bar', baz: {}, num: 42, arr: [1,2,3] }; objects.baz.asdf = objects; var serverCaught = 0; var clientCaught = 0; var disposeEmit = 0; var server = http.createServer(function(req, res) { var dom = domain.create(); req.resume(); dom.add(req); dom.add(res); dom.on('error', function(er) { serverCaught++; console.log('horray! got a server error', er); // try to send a 500. If that fails, oh well. res.writeHead(500, {'content-type':'text/plain'}); res.end(er.stack || er.message || 'Unknown error'); }); var data; dom.run(function() { // Now, an action that has the potential to fail! // if you request 'baz', then it'll throw a JSON circular ref error. data = JSON.stringify(objects[req.url.replace(/[^a-z]/g, '')]); // this line will throw if you pick an unknown key assert(data !== undefined, 'Data should not be undefined'); res.writeHead(200); res.end(data); }); }); server.listen(common.PORT, next); function next() { console.log('listening on localhost:%d', common.PORT); // now hit it a few times var dom = domain.create(); var requests = 0; var responses = 0; makeReq('/'); makeReq('/foo'); makeReq('/arr'); makeReq('/baz'); makeReq('/num'); function makeReq(p) { requests++; var dom = domain.create(); dom.on('error', function(er) { clientCaught++; console.log('client error', er); req.socket.destroy(); }); var req = http.get({ host: 'localhost', port: common.PORT, path: p }); dom.add(req); req.on('response', function(res) { responses++; console.error('requests=%d responses=%d', requests, responses); if (responses === requests) { console.error('done, closing server'); // no more coming. server.close(); } dom.add(res); var d = ''; res.on('data', function(c) { d += c; }); res.on('end', function() { console.error('trying to parse json', d); d = JSON.parse(d); console.log('json!', d); }); }); } } process.on('exit', function() { assert.equal(serverCaught, 2); assert.equal(clientCaught, 2); console.log('ok'); }); node-v0.10.25~dfsg2/test/simple/test-script-static-context.js0000644000000000000000000000333712270121457022661 0ustar rootroot// Copyright Joyent, Inc. and other Node contributors. // // Permission is hereby granted, free of charge, to any person obtaining a // copy of this software and associated documentation files (the // "Software"), to deal in the Software without restriction, including // without limitation the rights to use, copy, modify, merge, publish, // distribute, sublicense, and/or sell copies of the Software, and to permit // persons to whom the Software is furnished to do so, subject to the // following conditions: // // The above copyright notice and this permission notice shall be included // in all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS // OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF // MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN // NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, // DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR // OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE // USE OR OTHER DEALINGS IN THE SOFTWARE. var common = require('../common'); var assert = require('assert'); var Script = require('vm').Script; common.debug('run in a new empty context'); var context = Script.createContext(); var result = Script.runInContext('"passed";', context); assert.equal('passed', result); common.debug('create a new pre-populated context'); context = Script.createContext({'foo': 'bar', 'thing': 'lala'}); assert.equal('bar', context.foo); assert.equal('lala', context.thing); common.debug('test updating context'); result = Script.runInContext('var foo = 3;', context); assert.equal(3, context.foo); assert.equal('lala', context.thing); node-v0.10.25~dfsg2/test/simple/test-child-process-stdio-inherit.js0000644000000000000000000000362012270121457023720 0ustar rootroot// Copyright Joyent, Inc. and other Node contributors. // // Permission is hereby granted, free of charge, to any person obtaining a // copy of this software and associated documentation files (the // "Software"), to deal in the Software without restriction, including // without limitation the rights to use, copy, modify, merge, publish, // distribute, sublicense, and/or sell copies of the Software, and to permit // persons to whom the Software is furnished to do so, subject to the // following conditions: // // The above copyright notice and this permission notice shall be included // in all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS // OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF // MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN // NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, // DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR // OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE // USE OR OTHER DEALINGS IN THE SOFTWARE. var common = require('../common'); var assert = require('assert'); var spawn = require('child_process').spawn; if (process.argv[2] === 'parent') parent(); else grandparent(); function grandparent() { var child = spawn(process.execPath, [__filename, 'parent']); child.stderr.pipe(process.stderr); var output = ''; var input = 'asdfasdf'; child.stdout.on('data', function(chunk) { output += chunk; }); child.stdout.setEncoding('utf8'); child.stdin.end(input); child.on('close', function(code, signal) { assert.equal(code, 0); assert.equal(signal, null); // cat on windows adds a \r\n at the end. assert.equal(output.trim(), input.trim()); }); } function parent() { // should not immediately exit. var child = common.spawnCat({ stdio: 'inherit' }); } node-v0.10.25~dfsg2/test/simple/test-http-header-response-splitting.js0000644000000000000000000000432612270121457024461 0ustar rootroot// Copyright Joyent, Inc. and other Node contributors. // // Permission is hereby granted, free of charge, to any person obtaining a // copy of this software and associated documentation files (the // "Software"), to deal in the Software without restriction, including // without limitation the rights to use, copy, modify, merge, publish, // distribute, sublicense, and/or sell copies of the Software, and to permit // persons to whom the Software is furnished to do so, subject to the // following conditions: // // The above copyright notice and this permission notice shall be included // in all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS // OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF // MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN // NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, // DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR // OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE // USE OR OTHER DEALINGS IN THE SOFTWARE. var common = require('../common'), assert = require('assert'), http = require('http'); var testIndex = 0, responses = 0; var server = http.createServer(function(req, res) { switch (testIndex++) { case 0: res.writeHead(200, { test: 'foo \r\ninvalid: bar' }); break; case 1: res.writeHead(200, { test: 'foo \ninvalid: bar' }); break; case 2: res.writeHead(200, { test: 'foo \rinvalid: bar' }); break; case 3: res.writeHead(200, { test: 'foo \n\n\ninvalid: bar' }); break; case 4: res.writeHead(200, { test: 'foo \r\n \r\n \r\ninvalid: bar' }); server.close(); break; default: assert(false); } res.end('Hi mars!'); }); server.listen(common.PORT, function() { for (var i = 0; i < 5; i++) { var req = http.get({ port: common.PORT, path: '/' }, function(res) { assert.strictEqual(res.headers.test, 'foo invalid: bar'); assert.strictEqual(res.headers.invalid, undefined); responses++; res.resume(); }); } }); process.on('exit', function() { assert.strictEqual(responses, 5); }); node-v0.10.25~dfsg2/test/simple/test-stream-pipe-multi.js0000644000000000000000000000611612270121457021762 0ustar rootroot// Copyright Joyent, Inc. and other Node contributors. // // Permission is hereby granted, free of charge, to any person obtaining a // copy of this software and associated documentation files (the // "Software"), to deal in the Software without restriction, including // without limitation the rights to use, copy, modify, merge, publish, // distribute, sublicense, and/or sell copies of the Software, and to permit // persons to whom the Software is furnished to do so, subject to the // following conditions: // // The above copyright notice and this permission notice shall be included // in all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS // OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF // MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN // NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, // DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR // OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE // USE OR OTHER DEALINGS IN THE SOFTWARE. // Test that having a bunch of streams piping in parallel // doesn't break anything. var common = require('../common'); var assert = require('assert'); var Stream = require('stream').Stream; var rr = []; var ww = []; var cnt = 100; var chunks = 1000; var chunkSize = 250; var data = new Buffer(chunkSize); var wclosed = 0; var rclosed = 0; function FakeStream() { Stream.apply(this); this.wait = false; this.writable = true; this.readable = true; } FakeStream.prototype = Object.create(Stream.prototype); FakeStream.prototype.write = function(chunk) { console.error(this.ID, 'write', this.wait); if (this.wait) { process.nextTick(this.emit.bind(this, 'drain')); } this.wait = !this.wait; return this.wait; }; FakeStream.prototype.end = function() { this.emit('end'); process.nextTick(this.close.bind(this)); }; // noop - closes happen automatically on end. FakeStream.prototype.close = function() { this.emit('close'); }; // expect all streams to close properly. process.on('exit', function() { assert.equal(cnt, wclosed, 'writable streams closed'); assert.equal(cnt, rclosed, 'readable streams closed'); }); for (var i = 0; i < chunkSize; i++) { chunkSize[i] = i % 256; } for (var i = 0; i < cnt; i++) { var r = new FakeStream(); r.on('close', function() { console.error(this.ID, 'read close'); rclosed++; }); rr.push(r); var w = new FakeStream(); w.on('close', function() { console.error(this.ID, 'write close'); wclosed++; }); ww.push(w); r.ID = w.ID = i; r.pipe(w); } // now start passing through data // simulate a relatively fast async stream. rr.forEach(function(r) { var cnt = chunks; var paused = false; r.on('pause', function() { paused = true; }); r.on('resume', function() { paused = false; step(); }); function step() { r.emit('data', data); if (--cnt === 0) { r.end(); return; } if (paused) return; process.nextTick(step); } process.nextTick(step); }); node-v0.10.25~dfsg2/test/simple/test-stream2-objects.js0000644000000000000000000001530512270121457021410 0ustar rootroot// Copyright Joyent, Inc. and other Node contributors. // // Permission is hereby granted, free of charge, to any person obtaining a // copy of this software and associated documentation files (the // "Software"), to deal in the Software without restriction, including // without limitation the rights to use, copy, modify, merge, publish, // distribute, sublicense, and/or sell copies of the Software, and to permit // persons to whom the Software is furnished to do so, subject to the // following conditions: // // The above copyright notice and this permission notice shall be included // in all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS // OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF // MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN // NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, // DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR // OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE // USE OR OTHER DEALINGS IN THE SOFTWARE. var common = require('../common.js'); var Readable = require('_stream_readable'); var Writable = require('_stream_writable'); var assert = require('assert'); // tiny node-tap lookalike. var tests = []; var count = 0; function test(name, fn) { count++; tests.push([name, fn]); } function run() { var next = tests.shift(); if (!next) return console.error('ok'); var name = next[0]; var fn = next[1]; console.log('# %s', name); fn({ same: assert.deepEqual, equal: assert.equal, end: function() { count--; run(); } }); } // ensure all tests have run process.on('exit', function() { assert.equal(count, 0); }); process.nextTick(run); function toArray(callback) { var stream = new Writable({ objectMode: true }); var list = []; stream.write = function(chunk) { list.push(chunk); }; stream.end = function() { callback(list); }; return stream; } function fromArray(list) { var r = new Readable({ objectMode: true }); r._read = noop; list.forEach(function(chunk) { r.push(chunk); }); r.push(null); return r; } function noop() {} test('can read objects from stream', function(t) { var r = fromArray([{ one: '1'}, { two: '2' }]); var v1 = r.read(); var v2 = r.read(); var v3 = r.read(); assert.deepEqual(v1, { one: '1' }); assert.deepEqual(v2, { two: '2' }); assert.deepEqual(v3, null); t.end(); }); test('can pipe objects into stream', function(t) { var r = fromArray([{ one: '1'}, { two: '2' }]); r.pipe(toArray(function(list) { assert.deepEqual(list, [ { one: '1' }, { two: '2' } ]); t.end(); })); }); test('read(n) is ignored', function(t) { var r = fromArray([{ one: '1'}, { two: '2' }]); var value = r.read(2); assert.deepEqual(value, { one: '1' }); t.end(); }); test('can read objects from _read (sync)', function(t) { var r = new Readable({ objectMode: true }); var list = [{ one: '1'}, { two: '2' }]; r._read = function(n) { var item = list.shift(); r.push(item || null); }; r.pipe(toArray(function(list) { assert.deepEqual(list, [ { one: '1' }, { two: '2' } ]); t.end(); })); }); test('can read objects from _read (async)', function(t) { var r = new Readable({ objectMode: true }); var list = [{ one: '1'}, { two: '2' }]; r._read = function(n) { var item = list.shift(); process.nextTick(function() { r.push(item || null); }); }; r.pipe(toArray(function(list) { assert.deepEqual(list, [ { one: '1' }, { two: '2' } ]); t.end(); })); }); test('can read strings as objects', function(t) { var r = new Readable({ objectMode: true }); r._read = noop; var list = ['one', 'two', 'three']; list.forEach(function(str) { r.push(str); }); r.push(null); r.pipe(toArray(function(array) { assert.deepEqual(array, list); t.end(); })); }); test('read(0) for object streams', function(t) { var r = new Readable({ objectMode: true }); r._read = noop; r.push('foobar'); r.push(null); var v = r.read(0); r.pipe(toArray(function(array) { assert.deepEqual(array, ['foobar']); t.end(); })); }); test('falsey values', function(t) { var r = new Readable({ objectMode: true }); r._read = noop; r.push(false); r.push(0); r.push(''); r.push(null); r.pipe(toArray(function(array) { assert.deepEqual(array, [false, 0, '']); t.end(); })); }); test('high watermark _read', function(t) { var r = new Readable({ highWaterMark: 6, objectMode: true }); var calls = 0; var list = ['1', '2', '3', '4', '5', '6', '7', '8']; r._read = function(n) { calls++; }; list.forEach(function(c) { r.push(c); }); var v = r.read(); assert.equal(calls, 0); assert.equal(v, '1'); var v2 = r.read(); assert.equal(calls, 1); assert.equal(v2, '2'); t.end(); }); test('high watermark push', function(t) { var r = new Readable({ highWaterMark: 6, objectMode: true }); r._read = function(n) {}; for (var i = 0; i < 6; i++) { var bool = r.push(i); assert.equal(bool, i === 5 ? false : true); } t.end(); }); test('can write objects to stream', function(t) { var w = new Writable({ objectMode: true }); w._write = function(chunk, encoding, cb) { assert.deepEqual(chunk, { foo: 'bar' }); cb(); }; w.on('finish', function() { t.end(); }); w.write({ foo: 'bar' }); w.end(); }); test('can write multiple objects to stream', function(t) { var w = new Writable({ objectMode: true }); var list = []; w._write = function(chunk, encoding, cb) { list.push(chunk); cb(); }; w.on('finish', function() { assert.deepEqual(list, [0, 1, 2, 3, 4]); t.end(); }); w.write(0); w.write(1); w.write(2); w.write(3); w.write(4); w.end(); }); test('can write strings as objects', function(t) { var w = new Writable({ objectMode: true }); var list = []; w._write = function(chunk, encoding, cb) { list.push(chunk); process.nextTick(cb); }; w.on('finish', function() { assert.deepEqual(list, ['0', '1', '2', '3', '4']); t.end(); }); w.write('0'); w.write('1'); w.write('2'); w.write('3'); w.write('4'); w.end(); }); test('buffers finish until cb is called', function(t) { var w = new Writable({ objectMode: true }); var called = false; w._write = function(chunk, encoding, cb) { assert.equal(chunk, 'foo'); process.nextTick(function() { called = true; cb(); }); }; w.on('finish', function() { assert.equal(called, true); t.end(); }); w.write('foo'); w.end(); }); node-v0.10.25~dfsg2/test/simple/test-stream2-finish-pipe.js0000644000000000000000000000313512270121457022170 0ustar rootroot// Copyright Joyent, Inc. and other Node contributors. // // Permission is hereby granted, free of charge, to any person obtaining a // copy of this software and associated documentation files (the // "Software"), to deal in the Software without restriction, including // without limitation the rights to use, copy, modify, merge, publish, // distribute, sublicense, and/or sell copies of the Software, and to permit // persons to whom the Software is furnished to do so, subject to the // following conditions: // // The above copyright notice and this permission notice shall be included // in all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS // OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF // MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN // NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, // DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR // OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE // USE OR OTHER DEALINGS IN THE SOFTWARE. var common = require('../common.js'); var stream = require('stream'); var Buffer = require('buffer').Buffer; var r = new stream.Readable(); r._read = function(size) { r.push(new Buffer(size)); }; var w = new stream.Writable(); w._write = function(data, encoding, cb) { cb(null); }; r.pipe(w); // This might sound unrealistic, but it happens in net.js. When // `socket.allowHalfOpen === false`, EOF will cause `.destroySoon()` call which // ends the writable side of net.Socket. w.end(); node-v0.10.25~dfsg2/test/simple/test-http-bind-twice.js0000644000000000000000000000320012270121457021375 0ustar rootroot// Copyright Joyent, Inc. and other Node contributors. // // Permission is hereby granted, free of charge, to any person obtaining a // copy of this software and associated documentation files (the // "Software"), to deal in the Software without restriction, including // without limitation the rights to use, copy, modify, merge, publish, // distribute, sublicense, and/or sell copies of the Software, and to permit // persons to whom the Software is furnished to do so, subject to the // following conditions: // // The above copyright notice and this permission notice shall be included // in all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS // OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF // MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN // NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, // DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR // OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE // USE OR OTHER DEALINGS IN THE SOFTWARE. var common = require('../common'); var assert = require('assert'); var http = require('http'); var gotError = false; process.on('exit', function() { assert(gotError); }); function dontCall() { assert(false); } var server1 = http.createServer(dontCall); server1.listen(common.PORT, '127.0.0.1', function() {}); var server2 = http.createServer(dontCall); server2.listen(common.PORT, '127.0.0.1', dontCall); server2.on('error', function(e) { assert.equal(e.code, 'EADDRINUSE'); server1.close(); gotError = true; }); node-v0.10.25~dfsg2/test/simple/test-fs-symlink-dir-junction.js0000644000000000000000000000432712270121457023105 0ustar rootroot// Copyright Joyent, Inc. and other Node contributors. // // Permission is hereby granted, free of charge, to any person obtaining a // copy of this software and associated documentation files (the // "Software"), to deal in the Software without restriction, including // without limitation the rights to use, copy, modify, merge, publish, // distribute, sublicense, and/or sell copies of the Software, and to permit // persons to whom the Software is furnished to do so, subject to the // following conditions: // // The above copyright notice and this permission notice shall be included // in all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS // OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF // MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN // NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, // DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR // OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE // USE OR OTHER DEALINGS IN THE SOFTWARE. var common = require('../common'); var assert = require('assert'); var path = require('path'); var fs = require('fs'); var completed = 0; var expected_tests = 4; // test creating and reading symbolic link var linkData = path.join(common.fixturesDir, 'cycles/'); var linkPath = path.join(common.tmpDir, 'cycles_link'); // Delete previously created link try { fs.unlinkSync(linkPath); } catch (e) {} console.log('linkData: ' + linkData); console.log('linkPath: ' + linkPath); fs.symlink(linkData, linkPath, 'junction', function(err) { if (err) throw err; completed++; fs.lstat(linkPath, function(err, stats) { if (err) throw err; assert.ok(stats.isSymbolicLink()); completed++; fs.readlink(linkPath, function(err, destination) { if (err) throw err; assert.equal(destination, linkData); completed++; fs.unlink(linkPath, function(err) { if (err) throw err; assert(!fs.existsSync(linkPath)); assert(fs.existsSync(linkData)); completed++; }); }); }); }); process.on('exit', function() { assert.equal(completed, expected_tests); }); node-v0.10.25~dfsg2/test/simple/test-readline-interface.js0000644000000000000000000001376312270121457022133 0ustar rootroot// Copyright Joyent, Inc. and other Node contributors. // // Permission is hereby granted, free of charge, to any person obtaining a // copy of this software and associated documentation files (the // "Software"), to deal in the Software without restriction, including // without limitation the rights to use, copy, modify, merge, publish, // distribute, sublicense, and/or sell copies of the Software, and to permit // persons to whom the Software is furnished to do so, subject to the // following conditions: // // The above copyright notice and this permission notice shall be included // in all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS // OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF // MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN // NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, // DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR // OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE // USE OR OTHER DEALINGS IN THE SOFTWARE. var assert = require('assert'); var readline = require('readline'); var EventEmitter = require('events').EventEmitter; var inherits = require('util').inherits; function FakeInput() { EventEmitter.call(this); } inherits(FakeInput, EventEmitter); FakeInput.prototype.resume = function() {}; FakeInput.prototype.pause = function() {}; FakeInput.prototype.write = function() {}; FakeInput.prototype.end = function() {}; [ true, false ].forEach(function(terminal) { var fi; var rli; var called; // sending a full line fi = new FakeInput(); rli = new readline.Interface({ input: fi, output: fi, terminal: terminal }); called = false; rli.on('line', function(line) { called = true; assert.equal(line, 'asdf'); }); fi.emit('data', 'asdf\n'); assert.ok(called); // sending a blank line fi = new FakeInput(); rli = new readline.Interface({ input: fi, output: fi, terminal: terminal }); called = false; rli.on('line', function(line) { called = true; assert.equal(line, ''); }); fi.emit('data', '\n'); assert.ok(called); // sending a single character with no newline fi = new FakeInput(); rli = new readline.Interface(fi, {}); called = false; rli.on('line', function(line) { called = true; }); fi.emit('data', 'a'); assert.ok(!called); rli.close(); // sending a single character with no newline and then a newline fi = new FakeInput(); rli = new readline.Interface({ input: fi, output: fi, terminal: terminal }); called = false; rli.on('line', function(line) { called = true; assert.equal(line, 'a'); }); fi.emit('data', 'a'); assert.ok(!called); fi.emit('data', '\n'); assert.ok(called); rli.close(); // sending multiple newlines at once fi = new FakeInput(); rli = new readline.Interface({ input: fi, output: fi, terminal: terminal }); var expectedLines = ['foo', 'bar', 'baz']; var callCount = 0; rli.on('line', function(line) { assert.equal(line, expectedLines[callCount]); callCount++; }); fi.emit('data', expectedLines.join('\n') + '\n'); assert.equal(callCount, expectedLines.length); rli.close(); // sending multiple newlines at once that does not end with a new line fi = new FakeInput(); rli = new readline.Interface({ input: fi, output: fi, terminal: terminal }); expectedLines = ['foo', 'bar', 'baz', 'bat']; callCount = 0; rli.on('line', function(line) { assert.equal(line, expectedLines[callCount]); callCount++; }); fi.emit('data', expectedLines.join('\n')); assert.equal(callCount, expectedLines.length - 1); rli.close(); // \r\n should emit one line event, not two fi = new FakeInput(); rli = new readline.Interface({ input: fi, output: fi, terminal: terminal }); expectedLines = ['foo', 'bar', 'baz', 'bat']; callCount = 0; rli.on('line', function(line) { assert.equal(line, expectedLines[callCount]); callCount++; }); fi.emit('data', expectedLines.join('\r\n')); assert.equal(callCount, expectedLines.length - 1); rli.close(); // \r\n should emit one line event when split across multiple writes. fi = new FakeInput(); rli = new readline.Interface({ input: fi, output: fi, terminal: terminal }); expectedLines = ['foo', 'bar', 'baz', 'bat']; callCount = 0; rli.on('line', function(line) { assert.equal(line, expectedLines[callCount]); callCount++; }); expectedLines.forEach(function(line) { fi.emit('data', line + '\r'); fi.emit('data', '\n'); }); assert.equal(callCount, expectedLines.length); rli.close(); // \r should behave like \n when alone fi = new FakeInput(); rli = new readline.Interface({ input: fi, output: fi, terminal: true }); expectedLines = ['foo', 'bar', 'baz', 'bat']; callCount = 0; rli.on('line', function(line) { assert.equal(line, expectedLines[callCount]); callCount++; }); fi.emit('data', expectedLines.join('\r')); assert.equal(callCount, expectedLines.length - 1); rli.close(); // \r at start of input should output blank line fi = new FakeInput(); rli = new readline.Interface({ input: fi, output: fi, terminal: true }); expectedLines = ['', 'foo' ]; callCount = 0; rli.on('line', function(line) { assert.equal(line, expectedLines[callCount]); callCount++; }); fi.emit('data', '\rfoo\r'); assert.equal(callCount, expectedLines.length); rli.close(); // sending a multi-byte utf8 char over multiple writes var buf = Buffer('☮', 'utf8'); fi = new FakeInput(); rli = new readline.Interface({ input: fi, output: fi, terminal: terminal }); callCount = 0; rli.on('line', function(line) { callCount++; assert.equal(line, buf.toString('utf8')); }); [].forEach.call(buf, function(i) { fi.emit('data', Buffer([i])); }); assert.equal(callCount, 0); fi.emit('data', '\n'); assert.equal(callCount, 1); rli.close(); assert.deepEqual(fi.listeners('end'), []); assert.deepEqual(fi.listeners(terminal ? 'keypress' : 'data'), []); }); node-v0.10.25~dfsg2/test/simple/test-http-localaddress.js0000644000000000000000000000402412270121457022015 0ustar rootroot// Copyright Joyent, Inc. and other Node contributors. // // Permission is hereby granted, free of charge, to any person obtaining a // copy of this software and associated documentation files (the // "Software"), to deal in the Software without restriction, including // without limitation the rights to use, copy, modify, merge, publish, // distribute, sublicense, and/or sell copies of the Software, and to permit // persons to whom the Software is furnished to do so, subject to the // following conditions: // // The above copyright notice and this permission notice shall be included // in all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS // OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF // MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN // NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, // DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR // OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE // USE OR OTHER DEALINGS IN THE SOFTWARE. var common = require('../common'); var http = require('http'), assert = require('assert'); if (['linux', 'win32'].indexOf(process.platform) == -1) { console.log('Skipping platform-specific test.'); process.exit(); } var server = http.createServer(function (req, res) { console.log("Connect from: " + req.connection.remoteAddress); assert.equal('127.0.0.2', req.connection.remoteAddress); req.on('end', function() { res.writeHead(200, { 'Content-Type': 'text/plain' }); res.end('You are from: ' + req.connection.remoteAddress); }); req.resume(); }); server.listen(common.PORT, "127.0.0.1", function() { var options = { host: 'localhost', port: common.PORT, path: '/', method: 'GET', localAddress: '127.0.0.2' }; var req = http.request(options, function(res) { res.on('end', function() { server.close(); process.exit(); }); res.resume(); }); req.end(); }); node-v0.10.25~dfsg2/test/simple/test-timers-uncaught-exception.js0000644000000000000000000000375412270121457023524 0ustar rootroot// Copyright Joyent, Inc. and other Node contributors. // // Permission is hereby granted, free of charge, to any person obtaining a // copy of this software and associated documentation files (the // "Software"), to deal in the Software without restriction, including // without limitation the rights to use, copy, modify, merge, publish, // distribute, sublicense, and/or sell copies of the Software, and to permit // persons to whom the Software is furnished to do so, subject to the // following conditions: // // The above copyright notice and this permission notice shall be included // in all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS // OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF // MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN // NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, // DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR // OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE // USE OR OTHER DEALINGS IN THE SOFTWARE. var common = require('../common'); var assert = require('assert'); var exceptions = 0; var timer1 = 0; var timer2 = 0; // the first timer throws... console.error('set first timer'); setTimeout(function() { console.error('first timer'); timer1++; throw new Error('BAM!'); }, 100); // ...but the second one should still run console.error('set second timer'); setTimeout(function() { console.error('second timer'); assert.equal(timer1, 1); timer2++; }, 100); function uncaughtException(err) { console.error('uncaught handler'); assert.equal(err.message, 'BAM!'); exceptions++; } process.on('uncaughtException', uncaughtException); var exited = false; process.on('exit', function() { assert(!exited); exited = true; process.removeListener('uncaughtException', uncaughtException); assert.equal(exceptions, 1); assert.equal(timer1, 1); assert.equal(timer2, 1); }); node-v0.10.25~dfsg2/test/simple/test-https-timeout-server.js0000644000000000000000000000420612270121457022534 0ustar rootroot// Copyright Joyent, Inc. and other Node contributors. // // Permission is hereby granted, free of charge, to any person obtaining a // copy of this software and associated documentation files (the // "Software"), to deal in the Software without restriction, including // without limitation the rights to use, copy, modify, merge, publish, // distribute, sublicense, and/or sell copies of the Software, and to permit // persons to whom the Software is furnished to do so, subject to the // following conditions: // // The above copyright notice and this permission notice shall be included // in all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS // OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF // MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN // NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, // DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR // OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE // USE OR OTHER DEALINGS IN THE SOFTWARE. if (!process.versions.openssl) process.exit(); var common = require('../common'); var assert = require('assert'); var https = require('https'); var net = require('net'); var tls = require('tls'); var fs = require('fs'); var clientErrors = 0; process.on('exit', function() { assert.equal(clientErrors, 1); }); var options = { key: fs.readFileSync(common.fixturesDir + '/keys/agent1-key.pem'), cert: fs.readFileSync(common.fixturesDir + '/keys/agent1-cert.pem'), handshakeTimeout: 50 }; var server = https.createServer(options, assert.fail); server.on('clientError', function(err, conn) { // Don't hesitate to update the asserts if the internal structure of // the cleartext object ever changes. We're checking that the https.Server // has closed the client connection. assert.equal(conn._secureEstablished, false); assert.equal(conn._doneFlag, true); assert.equal(conn.ssl, null); server.close(); clientErrors++; }); server.listen(common.PORT, function() { net.connect({ host: '127.0.0.1', port: common.PORT }); }); node-v0.10.25~dfsg2/test/simple/test-net-settimeout.js0000644000000000000000000000365012270121457021372 0ustar rootroot// Copyright Joyent, Inc. and other Node contributors. // // Permission is hereby granted, free of charge, to any person obtaining a // copy of this software and associated documentation files (the // "Software"), to deal in the Software without restriction, including // without limitation the rights to use, copy, modify, merge, publish, // distribute, sublicense, and/or sell copies of the Software, and to permit // persons to whom the Software is furnished to do so, subject to the // following conditions: // // The above copyright notice and this permission notice shall be included // in all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS // OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF // MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN // NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, // DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR // OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE // USE OR OTHER DEALINGS IN THE SOFTWARE. // This example sets a timeout then immediately attempts to disable the timeout // https://github.com/joyent/node/pull/2245 var common = require('../common'); var net = require('net'); var assert = require('assert'); var T = 100; var server = net.createServer(function(c) { c.write('hello'); }); server.listen(common.PORT); var killers = [0, Infinity, NaN]; var left = killers.length; killers.forEach(function(killer) { var socket = net.createConnection(common.PORT, 'localhost'); socket.setTimeout(T, function() { socket.destroy(); if (--left === 0) server.close(); assert.ok(killer !== 0); clearTimeout(timeout); }); socket.setTimeout(killer); var timeout = setTimeout(function() { socket.destroy(); if (--left === 0) server.close(); assert.ok(killer === 0); }, T * 2); }); node-v0.10.25~dfsg2/test/simple/test-dgram-pingpong.js0000644000000000000000000000667012270121457021322 0ustar rootroot// Copyright Joyent, Inc. and other Node contributors. // // Permission is hereby granted, free of charge, to any person obtaining a // copy of this software and associated documentation files (the // "Software"), to deal in the Software without restriction, including // without limitation the rights to use, copy, modify, merge, publish, // distribute, sublicense, and/or sell copies of the Software, and to permit // persons to whom the Software is furnished to do so, subject to the // following conditions: // // The above copyright notice and this permission notice shall be included // in all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS // OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF // MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN // NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, // DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR // OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE // USE OR OTHER DEALINGS IN THE SOFTWARE. var common = require('../common'); var assert = require('assert'); var Buffer = require('buffer').Buffer; var dgram = require('dgram'); var debug = false; var tests_run = 0; function pingPongTest(port, host) { var callbacks = 0; var N = 500; var count = 0; var sent_final_ping = false; var server = dgram.createSocket('udp4', function(msg, rinfo) { if (debug) console.log('server got: ' + msg + ' from ' + rinfo.address + ':' + rinfo.port); if (/PING/.exec(msg)) { var buf = new Buffer(4); buf.write('PONG'); server.send(buf, 0, buf.length, rinfo.port, rinfo.address, function(err, sent) { callbacks++; }); } }); server.on('error', function(e) { throw e; }); server.on('listening', function() { console.log('server listening on ' + port + ' ' + host); var buf = new Buffer('PING'), client = dgram.createSocket('udp4'); client.on('message', function(msg, rinfo) { if (debug) console.log('client got: ' + msg + ' from ' + rinfo.address + ':' + rinfo.port); assert.equal('PONG', msg.toString('ascii')); count += 1; if (count < N) { client.send(buf, 0, buf.length, port, 'localhost'); } else { sent_final_ping = true; client.send(buf, 0, buf.length, port, 'localhost', function() { client.close(); }); } }); client.on('close', function() { console.log('client has closed, closing server'); assert.equal(N, count); tests_run += 1; server.close(); assert.equal(N - 1, callbacks); }); client.on('error', function(e) { throw e; }); console.log('Client sending to ' + port + ', localhost ' + buf); client.send(buf, 0, buf.length, port, 'localhost', function(err, bytes) { if (err) { throw err; } console.log('Client sent ' + bytes + ' bytes'); }); count += 1; }); server.bind(port, host); } // All are run at once, so run on different ports pingPongTest(common.PORT + 0, 'localhost'); pingPongTest(common.PORT + 1, 'localhost'); pingPongTest(common.PORT + 2); //pingPongTest('/tmp/pingpong.sock'); process.on('exit', function() { assert.equal(3, tests_run); console.log('done'); }); node-v0.10.25~dfsg2/test/simple/test-stream-pipe-error-handling.js0000644000000000000000000000642712270121457023550 0ustar rootroot// Copyright Joyent, Inc. and other Node contributors. // // Permission is hereby granted, free of charge, to any person obtaining a // copy of this software and associated documentation files (the // "Software"), to deal in the Software without restriction, including // without limitation the rights to use, copy, modify, merge, publish, // distribute, sublicense, and/or sell copies of the Software, and to permit // persons to whom the Software is furnished to do so, subject to the // following conditions: // // The above copyright notice and this permission notice shall be included // in all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS // OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF // MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN // NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, // DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR // OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE // USE OR OTHER DEALINGS IN THE SOFTWARE. var common = require('../common'); var assert = require('assert'); var Stream = require('stream').Stream; (function testErrorListenerCatches() { var source = new Stream(); var dest = new Stream(); source.pipe(dest); var gotErr = null; source.on('error', function(err) { gotErr = err; }); var err = new Error('This stream turned into bacon.'); source.emit('error', err); assert.strictEqual(gotErr, err); })(); (function testErrorWithoutListenerThrows() { var source = new Stream(); var dest = new Stream(); source.pipe(dest); var err = new Error('This stream turned into bacon.'); var gotErr = null; try { source.emit('error', err); } catch (e) { gotErr = e; } assert.strictEqual(gotErr, err); })(); (function testErrorWithRemovedListenerThrows() { var EE = require('events').EventEmitter; var R = Stream.Readable; var W = Stream.Writable; var r = new R; var w = new W; var removed = false; var didTest = false; process.on('exit', function() { assert(didTest); console.log('ok'); }); r._read = function() { setTimeout(function() { assert(removed); assert.throws(function() { w.emit('error', new Error('fail')); }); didTest = true; }); }; w.on('error', myOnError); r.pipe(w); w.removeListener('error', myOnError); removed = true; function myOnError(er) { throw new Error('this should not happen'); } })(); (function testErrorWithRemovedListenerThrows() { var EE = require('events').EventEmitter; var R = Stream.Readable; var W = Stream.Writable; var r = new R; var w = new W; var removed = false; var didTest = false; var caught = false; process.on('exit', function() { assert(didTest); console.log('ok'); }); r._read = function() { setTimeout(function() { assert(removed); w.emit('error', new Error('fail')); didTest = true; }); }; w.on('error', myOnError); w._write = function() {}; r.pipe(w); // Removing some OTHER random listener should not do anything w.removeListener('error', function() {}); removed = true; function myOnError(er) { assert(!caught); caught = true; } })(); node-v0.10.25~dfsg2/test/simple/test-process-active-wraps.js0000644000000000000000000000414712270121457022467 0ustar rootroot// Copyright Joyent, Inc. and other Node contributors. // // Permission is hereby granted, free of charge, to any person obtaining a // copy of this software and associated documentation files (the // "Software"), to deal in the Software without restriction, including // without limitation the rights to use, copy, modify, merge, publish, // distribute, sublicense, and/or sell copies of the Software, and to permit // persons to whom the Software is furnished to do so, subject to the // following conditions: // // The above copyright notice and this permission notice shall be included // in all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS // OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF // MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN // NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, // DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR // OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE // USE OR OTHER DEALINGS IN THE SOFTWARE. var common = require('../common'); var assert = require('assert'); var spawn = require('child_process').spawn; var net = require('net'); function expect(activeHandles, activeRequests) { assert.equal(process._getActiveHandles().length, activeHandles); assert.equal(process._getActiveRequests().length, activeRequests); } var handles = []; (function() { expect(0, 0); var server = net.createServer().listen(common.PORT); expect(1, 0); server.close(); expect(1, 0); // server handle doesn't shut down until next tick handles.push(server); })(); (function() { expect(1, 0); var conn = net.createConnection(common.PORT); conn.on('error', function() { /* ignore */ }); expect(2, 1); conn.destroy(); expect(2, 1); // client handle doesn't shut down until next tick handles.push(conn); })(); (function() { var n = 0; handles.forEach(function(handle) { handle.once('close', onclose); }); function onclose() { if (++n === handles.length) setImmediate(expect, 0, 0); } })(); node-v0.10.25~dfsg2/test/simple/test-fs-read.js0000644000000000000000000000335312270121457017725 0ustar rootroot// Copyright Joyent, Inc. and other Node contributors. // // Permission is hereby granted, free of charge, to any person obtaining a // copy of this software and associated documentation files (the // "Software"), to deal in the Software without restriction, including // without limitation the rights to use, copy, modify, merge, publish, // distribute, sublicense, and/or sell copies of the Software, and to permit // persons to whom the Software is furnished to do so, subject to the // following conditions: // // The above copyright notice and this permission notice shall be included // in all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS // OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF // MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN // NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, // DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR // OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE // USE OR OTHER DEALINGS IN THE SOFTWARE. var common = require('../common'); var assert = require('assert'); var path = require('path'), fs = require('fs'), filepath = path.join(common.fixturesDir, 'x.txt'), fd = fs.openSync(filepath, 'r'), expected = 'xyz\n', readCalled = 0; fs.read(fd, expected.length, 0, 'utf-8', function(err, str, bytesRead) { readCalled++; assert.ok(!err); assert.equal(str, expected); assert.equal(bytesRead, expected.length); }); var r = fs.readSync(fd, expected.length, 0, 'utf-8'); assert.equal(r[0], expected); assert.equal(r[1], expected.length); process.on('exit', function() { assert.equal(readCalled, 1); }); node-v0.10.25~dfsg2/test/simple/test-dgram-address.js0000644000000000000000000000450312270121457021117 0ustar rootroot// Copyright Joyent, Inc. and other Node contributors. // // Permission is hereby granted, free of charge, to any person obtaining a // copy of this software and associated documentation files (the // "Software"), to deal in the Software without restriction, including // without limitation the rights to use, copy, modify, merge, publish, // distribute, sublicense, and/or sell copies of the Software, and to permit // persons to whom the Software is furnished to do so, subject to the // following conditions: // // The above copyright notice and this permission notice shall be included // in all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS // OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF // MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN // NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, // DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR // OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE // USE OR OTHER DEALINGS IN THE SOFTWARE. var common = require('../common'); var assert = require('assert'); var dgram = require('dgram'); // IPv4 Test var localhost_ipv4 = '127.0.0.1'; var socket_ipv4 = dgram.createSocket('udp4'); var family_ipv4 = 'IPv4'; socket_ipv4.on('listening', function() { var address_ipv4 = socket_ipv4.address(); assert.strictEqual(address_ipv4.address, localhost_ipv4); assert.strictEqual(address_ipv4.port, common.PORT); assert.strictEqual(address_ipv4.family, family_ipv4); socket_ipv4.close(); }); socket_ipv4.on('error', function(e) { console.log('Error on udp4 socket. ' + e.toString()); socket_ipv4.close(); }); socket_ipv4.bind(common.PORT, localhost_ipv4); // IPv6 Test var localhost_ipv6 = '::1'; var socket_ipv6 = dgram.createSocket('udp6'); var family_ipv6 = 'IPv6'; socket_ipv6.on('listening', function() { var address_ipv6 = socket_ipv6.address(); assert.strictEqual(address_ipv6.address, localhost_ipv6); assert.strictEqual(address_ipv6.port, common.PORT); assert.strictEqual(address_ipv6.family, family_ipv6); socket_ipv6.close(); }); socket_ipv6.on('error', function(e) { console.log('Error on udp6 socket. ' + e.toString()); socket_ipv6.close(); }); socket_ipv6.bind(common.PORT, localhost_ipv6); node-v0.10.25~dfsg2/test/simple/test-stream2-unpipe-leak.js0000644000000000000000000000470212270121457022170 0ustar rootroot// Copyright Joyent, Inc. and other Node contributors. // // Permission is hereby granted, free of charge, to any person obtaining a // copy of this software and associated documentation files (the // "Software"), to deal in the Software without restriction, including // without limitation the rights to use, copy, modify, merge, publish, // distribute, sublicense, and/or sell copies of the Software, and to permit // persons to whom the Software is furnished to do so, subject to the // following conditions: // // The above copyright notice and this permission notice shall be included // in all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS // OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF // MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN // NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, // DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR // OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE // USE OR OTHER DEALINGS IN THE SOFTWARE. var common = require('../common.js'); var assert = require('assert'); var stream = require('stream'); var chunk = new Buffer('hallo'); var util = require('util'); function TestWriter() { stream.Writable.call(this); } util.inherits(TestWriter, stream.Writable); TestWriter.prototype._write = function(buffer, encoding, callback) { callback(null); }; var dest = new TestWriter(); // Set this high so that we'd trigger a nextTick warning // and/or RangeError if we do maybeReadMore wrong. function TestReader() { stream.Readable.call(this, { highWaterMark: 0x10000 }); } util.inherits(TestReader, stream.Readable); TestReader.prototype._read = function(size) { this.push(chunk); }; var src = new TestReader(); for (var i = 0; i < 10; i++) { src.pipe(dest); src.unpipe(dest); } assert.equal(src.listeners('end').length, 0); assert.equal(src.listeners('readable').length, 0); assert.equal(dest.listeners('unpipe').length, 0); assert.equal(dest.listeners('drain').length, 0); assert.equal(dest.listeners('error').length, 0); assert.equal(dest.listeners('close').length, 0); assert.equal(dest.listeners('finish').length, 0); console.error(src._readableState); process.on('exit', function() { assert(src._readableState.length >= src._readableState.highWaterMark); src._readableState.buffer.length = 0; console.error(src._readableState); }); node-v0.10.25~dfsg2/test/simple/test-fs-sir-writes-alot.js0000644000000000000000000000454712270121457022065 0ustar rootroot// Copyright Joyent, Inc. and other Node contributors. // // Permission is hereby granted, free of charge, to any person obtaining a // copy of this software and associated documentation files (the // "Software"), to deal in the Software without restriction, including // without limitation the rights to use, copy, modify, merge, publish, // distribute, sublicense, and/or sell copies of the Software, and to permit // persons to whom the Software is furnished to do so, subject to the // following conditions: // // The above copyright notice and this permission notice shall be included // in all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS // OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF // MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN // NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, // DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR // OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE // USE OR OTHER DEALINGS IN THE SOFTWARE. var common = require('../common'); var fs = require('fs'); var assert = require('assert'); var join = require('path').join; var filename = join(common.tmpDir, 'out.txt'); try { fs.unlinkSync(filename); } catch (e) { // might not exist, that's okay. } var fd = fs.openSync(filename, 'w'); var line = 'aaaaaaaaaaaaaaaaaaaaaaaaaaaa\n'; var N = 10240, complete = 0; for (var i = 0; i < N; i++) { // Create a new buffer for each write. Before the write is actually // executed by the thread pool, the buffer will be collected. var buffer = new Buffer(line); fs.write(fd, buffer, 0, buffer.length, null, function(er, written) { complete++; if (complete === N) { fs.closeSync(fd); var s = fs.createReadStream(filename); s.on('data', testBuffer); } }); } var bytesChecked = 0; function testBuffer(b) { for (var i = 0; i < b.length; i++) { bytesChecked++; if (b[i] !== 'a'.charCodeAt(0) && b[i] !== '\n'.charCodeAt(0)) { throw new Error('invalid char ' + i + ',' + b[i]); } } } process.on('exit', function() { // Probably some of the writes are going to overlap, so we can't assume // that we get (N * line.length). Let's just make sure we've checked a // few... assert.ok(bytesChecked > 1000); }); node-v0.10.25~dfsg2/test/simple/test-tls-set-ciphers.js0000644000000000000000000000421612270121457021431 0ustar rootroot// Copyright Joyent, Inc. and other Node contributors. // // Permission is hereby granted, free of charge, to any person obtaining a // copy of this software and associated documentation files (the // "Software"), to deal in the Software without restriction, including // without limitation the rights to use, copy, modify, merge, publish, // distribute, sublicense, and/or sell copies of the Software, and to permit // persons to whom the Software is furnished to do so, subject to the // following conditions: // // The above copyright notice and this permission notice shall be included // in all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS // OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF // MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN // NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, // DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR // OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE // USE OR OTHER DEALINGS IN THE SOFTWARE. var common = require('../common'); var assert = require('assert'); var exec = require('child_process').exec; var tls = require('tls'); var fs = require('fs'); if (process.platform === 'win32') { console.log("Skipping test, you probably don't have openssl installed."); process.exit(); } var options = { key: fs.readFileSync(common.fixturesDir + '/keys/agent2-key.pem'), cert: fs.readFileSync(common.fixturesDir + '/keys/agent2-cert.pem'), ciphers: 'RC4-MD5' }; var reply = 'I AM THE WALRUS'; // something recognizable var nconns = 0; var response = ''; process.on('exit', function() { assert.equal(nconns, 1); assert.notEqual(response.indexOf(reply), -1); }); var server = tls.createServer(options, function(conn) { conn.end(reply); nconns++; }); server.listen(common.PORT, '127.0.0.1', function() { var cmd = 'openssl s_client -cipher ' + options.ciphers + ' -connect 127.0.0.1:' + common.PORT; exec(cmd, function(err, stdout, stderr) { if (err) throw err; response = stdout; server.close(); }); }); node-v0.10.25~dfsg2/test/simple/test-process-kill-null.js0000644000000000000000000000314012270121457021755 0ustar rootroot// Copyright Joyent, Inc. and other Node contributors. // // Permission is hereby granted, free of charge, to any person obtaining a // copy of this software and associated documentation files (the // "Software"), to deal in the Software without restriction, including // without limitation the rights to use, copy, modify, merge, publish, // distribute, sublicense, and/or sell copies of the Software, and to permit // persons to whom the Software is furnished to do so, subject to the // following conditions: // // The above copyright notice and this permission notice shall be included // in all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS // OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF // MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN // NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, // DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR // OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE // USE OR OTHER DEALINGS IN THE SOFTWARE. var common = require('../common'); var assert = require('assert'); var spawn = require('child_process').spawn; var cat = spawn('cat'); var called; assert.ok(process.kill(cat.pid, 0)); cat.on('exit', function() { assert.throws(function() { process.kill(cat.pid, 0); }, Error); }); cat.stdout.on('data', function() { called = true; process.kill(cat.pid, 'SIGKILL'); }); // EPIPE when null sig fails cat.stdin.write('test'); process.on('exit', function() { assert.ok(called); }); node-v0.10.25~dfsg2/test/simple/test-http-get-pipeline-problem.js0000644000000000000000000000647612270121457023412 0ustar rootroot// Copyright Joyent, Inc. and other Node contributors. // // Permission is hereby granted, free of charge, to any person obtaining a // copy of this software and associated documentation files (the // "Software"), to deal in the Software without restriction, including // without limitation the rights to use, copy, modify, merge, publish, // distribute, sublicense, and/or sell copies of the Software, and to permit // persons to whom the Software is furnished to do so, subject to the // following conditions: // // The above copyright notice and this permission notice shall be included // in all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS // OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF // MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN // NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, // DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR // OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE // USE OR OTHER DEALINGS IN THE SOFTWARE. // We are demonstrating a problem with http.get when queueing up many // transfers. The server simply introduces some delay and sends a file. // Note this is demonstrated with connection: close. var common = require('../common'); var assert = require('assert'); var http = require('http'); var fs = require('fs'); var image = fs.readFileSync(common.fixturesDir + '/person.jpg'); console.log('image.length = ' + image.length); var total = 100; var requests = 0, responses = 0; var server = http.Server(function(req, res) { if (++requests == total) { server.close(); } setTimeout(function() { res.writeHead(200, { 'content-type': 'image/jpeg', 'connection': 'close', 'content-length': image.length }); res.end(image); }, 1); }); server.listen(common.PORT, function() { for (var i = 0; i < total; i++) { (function() { var x = i; var opts = { port: common.PORT, headers: { connection: 'close' } }; http.get(opts, function(res) { console.error('recv ' + x); var s = fs.createWriteStream(common.tmpDir + '/' + x + '.jpg'); res.pipe(s); // TODO there should be a callback to pipe() that will allow // us to get a callback when the pipe is finished. res.on('end', function() { console.error('done ' + x); if (++responses == total) { s.on('close', checkFiles); } }); }).on('error', function(e) { console.error('error! ', e.message); throw e; }); })(); } }); var checkedFiles = false; function checkFiles() { // Should see 1.jpg, 2.jpg, ..., 100.jpg in tmpDir var files = fs.readdirSync(common.tmpDir); assert(total <= files.length); for (var i = 0; i < total; i++) { var fn = i + '.jpg'; assert.ok(files.indexOf(fn) >= 0, "couldn't find '" + fn + "'"); var stat = fs.statSync(common.tmpDir + '/' + fn); assert.equal(image.length, stat.size, "size doesn't match on '" + fn + "'. Got " + stat.size + ' bytes'); } checkedFiles = true; } process.on('exit', function() { assert.equal(total, requests); assert.equal(total, responses); assert.ok(checkedFiles); }); node-v0.10.25~dfsg2/test/simple/test-tls-set-encoding.js0000644000000000000000000000425212270121457021562 0ustar rootroot// Copyright Joyent, Inc. and other Node contributors. // // Permission is hereby granted, free of charge, to any person obtaining a // copy of this software and associated documentation files (the // "Software"), to deal in the Software without restriction, including // without limitation the rights to use, copy, modify, merge, publish, // distribute, sublicense, and/or sell copies of the Software, and to permit // persons to whom the Software is furnished to do so, subject to the // following conditions: // // The above copyright notice and this permission notice shall be included // in all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS // OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF // MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN // NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, // DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR // OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE // USE OR OTHER DEALINGS IN THE SOFTWARE. var common = require('../common'); var assert = require('assert'); var tls = require('tls'); var fs = require('fs'); var options = { key: fs.readFileSync(common.fixturesDir + '/keys/agent2-key.pem'), cert: fs.readFileSync(common.fixturesDir + '/keys/agent2-cert.pem') }; var connections = 0; var message = 'hello world\n'; var server = tls.Server(options, function(socket) { socket.end(message); connections++; }); server.listen(common.PORT, function() { var client = tls.connect({ port: common.PORT, rejectUnauthorized: false }); var buffer = ''; client.setEncoding('utf8'); client.on('data', function(d) { assert.ok(typeof d === 'string'); buffer += d; }); client.on('close', function() { // readyState is deprecated but we want to make // sure this isn't triggering an assert in lib/net.js // See issue #1069. assert.equal('closed', client.readyState); assert.equal(buffer, message); console.log(message); server.close(); }); }); process.on('exit', function() { assert.equal(1, connections); }); node-v0.10.25~dfsg2/test/simple/test-tls-close-notify.js0000644000000000000000000000401412270121457021612 0ustar rootroot// Copyright Joyent, Inc. and other Node contributors. // // Permission is hereby granted, free of charge, to any person obtaining a // copy of this software and associated documentation files (the // "Software"), to deal in the Software without restriction, including // without limitation the rights to use, copy, modify, merge, publish, // distribute, sublicense, and/or sell copies of the Software, and to permit // persons to whom the Software is furnished to do so, subject to the // following conditions: // // The above copyright notice and this permission notice shall be included // in all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS // OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF // MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN // NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, // DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR // OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE // USE OR OTHER DEALINGS IN THE SOFTWARE. if (!process.versions.openssl) { console.error('Skipping because node compiled without OpenSSL.'); process.exit(0); } var assert = require('assert'); var fs = require('fs'); var net = require('net'); var tls = require('tls'); var common = require('../common'); var ended = 0; var server = tls.createServer({ key: fs.readFileSync(common.fixturesDir + '/keys/agent1-key.pem'), cert: fs.readFileSync(common.fixturesDir + '/keys/agent1-cert.pem') }, function(c) { // Send close-notify without shutting down TCP socket if (c.pair.ssl.shutdown() !== 1) c.pair.ssl.shutdown(); }).listen(common.PORT, function() { var c = tls.connect(common.PORT, { rejectUnauthorized: false }, function() { // Ensure that we receive 'end' event anyway c.on('end', function() { ended++; c.destroy(); server.close(); }); }); }); process.on('exit', function() { assert.equal(ended, 1); }); node-v0.10.25~dfsg2/test/simple/test-regress-GH-819.js0000644000000000000000000000247512270121457020675 0ustar rootroot// Copyright Joyent, Inc. and other Node contributors. // // Permission is hereby granted, free of charge, to any person obtaining a // copy of this software and associated documentation files (the // "Software"), to deal in the Software without restriction, including // without limitation the rights to use, copy, modify, merge, publish, // distribute, sublicense, and/or sell copies of the Software, and to permit // persons to whom the Software is furnished to do so, subject to the // following conditions: // // The above copyright notice and this permission notice shall be included // in all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS // OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF // MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN // NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, // DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR // OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE // USE OR OTHER DEALINGS IN THE SOFTWARE. var common = require('../common'); var net = require('net'); var assert = require('assert'); // Connect to something that we need to DNS resolve var c = net.createConnection(80, 'google.com'); c.destroy(); node-v0.10.25~dfsg2/test/simple/test-net-keepalive.js0000644000000000000000000000374612270121457021143 0ustar rootroot// Copyright Joyent, Inc. and other Node contributors. // // Permission is hereby granted, free of charge, to any person obtaining a // copy of this software and associated documentation files (the // "Software"), to deal in the Software without restriction, including // without limitation the rights to use, copy, modify, merge, publish, // distribute, sublicense, and/or sell copies of the Software, and to permit // persons to whom the Software is furnished to do so, subject to the // following conditions: // // The above copyright notice and this permission notice shall be included // in all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS // OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF // MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN // NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, // DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR // OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE // USE OR OTHER DEALINGS IN THE SOFTWARE. var common = require('../common'); var assert = require('assert'); var net = require('net'); var serverConnection; var echoServer = net.createServer(function(connection) { serverConnection = connection; connection.setTimeout(0); assert.notEqual(connection.setKeepAlive, undefined); // send a keepalive packet after 1000 ms connection.setKeepAlive(true, 1000); connection.on('end', function() { connection.end(); }); }); echoServer.listen(common.PORT); echoServer.on('listening', function() { var clientConnection = net.createConnection(common.PORT); clientConnection.setTimeout(0); setTimeout(function() { // make sure both connections are still open assert.equal(serverConnection.readyState, 'open'); assert.equal(clientConnection.readyState, 'open'); serverConnection.end(); clientConnection.end(); echoServer.close(); }, 1200); }); node-v0.10.25~dfsg2/test/simple/test-tls-handshake-nohang.js0000644000000000000000000000250412270121457022377 0ustar rootroot// Copyright Joyent, Inc. and other Node contributors. // // Permission is hereby granted, free of charge, to any person obtaining a // copy of this software and associated documentation files (the // "Software"), to deal in the Software without restriction, including // without limitation the rights to use, copy, modify, merge, publish, // distribute, sublicense, and/or sell copies of the Software, and to permit // persons to whom the Software is furnished to do so, subject to the // following conditions: // // The above copyright notice and this permission notice shall be included // in all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS // OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF // MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN // NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, // DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR // OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE // USE OR OTHER DEALINGS IN THE SOFTWARE. var common = require('../common'); var assert = require('assert'); var tls = require('tls'); // neither should hang tls.createSecurePair(null, false, false, false); tls.createSecurePair(null, true, false, false); node-v0.10.25~dfsg2/test/simple/test-tls-server-missing-options.js0000644000000000000000000000306412270121457023651 0ustar rootroot// Copyright Joyent, Inc. and other Node contributors. // // Permission is hereby granted, free of charge, to any person obtaining a // copy of this software and associated documentation files (the // "Software"), to deal in the Software without restriction, including // without limitation the rights to use, copy, modify, merge, publish, // distribute, sublicense, and/or sell copies of the Software, and to permit // persons to whom the Software is furnished to do so, subject to the // following conditions: // // The above copyright notice and this permission notice shall be included // in all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS // OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF // MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN // NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, // DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR // OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE // USE OR OTHER DEALINGS IN THE SOFTWARE. if (!process.versions.openssl) { console.error('Skipping because node compiled without OpenSSL.'); process.exit(0); } var common = require('../common'); var assert = require('assert'); var https = require('https'); var tls = require('tls'); assert.throws(function() { tls.createServer({ /* empty */}).listen(0); }, /missing.+certificate/i); assert.throws(function() { https.createServer({ /* empty */}).listen(0); }, /missing.+certificate/i); node-v0.10.25~dfsg2/test/simple/test-error-reporting.js0000644000000000000000000000443712270121457021550 0ustar rootroot// Copyright Joyent, Inc. and other Node contributors. // // Permission is hereby granted, free of charge, to any person obtaining a // copy of this software and associated documentation files (the // "Software"), to deal in the Software without restriction, including // without limitation the rights to use, copy, modify, merge, publish, // distribute, sublicense, and/or sell copies of the Software, and to permit // persons to whom the Software is furnished to do so, subject to the // following conditions: // // The above copyright notice and this permission notice shall be included // in all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS // OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF // MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN // NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, // DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR // OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE // USE OR OTHER DEALINGS IN THE SOFTWARE. var common = require('../common'); var assert = require('assert'); var exec = require('child_process').exec; var path = require('path'); var exits = 0; function errExec(script, callback) { var cmd = '"' + process.argv[0] + '" "' + path.join(common.fixturesDir, script) + '"'; return exec(cmd, function(err, stdout, stderr) { // There was some error assert.ok(err); // More than one line of error output. assert.ok(stderr.split('\n').length > 2); // Assert the script is mentioned in error output. assert.ok(stderr.indexOf(script) >= 0); // Proxy the args for more tests. callback(err, stdout, stderr); // Count the tests exits++; console.log('.'); }); } // Simple throw error errExec('throws_error.js', function(err, stdout, stderr) { assert.ok(/blah/.test(stderr)); }); // Trying to JSON.parse(undefined) errExec('throws_error2.js', function(err, stdout, stderr) { assert.ok(/SyntaxError/.test(stderr)); }); // Trying to JSON.parse(undefined) in nextTick errExec('throws_error3.js', function(err, stdout, stderr) { assert.ok(/SyntaxError/.test(stderr)); }); process.on('exit', function() { assert.equal(3, exits); }); node-v0.10.25~dfsg2/test/simple/test-net-pause-resume-connecting.js0000644000000000000000000000505012270121457023724 0ustar rootroot// Copyright Joyent, Inc. and other Node contributors. // // Permission is hereby granted, free of charge, to any person obtaining a // copy of this software and associated documentation files (the // "Software"), to deal in the Software without restriction, including // without limitation the rights to use, copy, modify, merge, publish, // distribute, sublicense, and/or sell copies of the Software, and to permit // persons to whom the Software is furnished to do so, subject to the // following conditions: // // The above copyright notice and this permission notice shall be included // in all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS // OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF // MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN // NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, // DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR // OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE // USE OR OTHER DEALINGS IN THE SOFTWARE. var common = require('../common'), assert = require('assert'), net = require('net'); var connections = 0, dataEvents = 0, conn; // Server var server = net.createServer(function(conn) { connections++; conn.end('This was the year he fell to pieces.'); if (connections === 5) server.close(); }); server.listen(common.PORT); // Client 1 conn = require('net').createConnection(common.PORT, 'localhost'); conn.resume(); conn.on('data', onDataOk); // Client 2 conn = require('net').createConnection(common.PORT, 'localhost'); conn.pause(); conn.resume(); conn.on('data', onDataOk); // Client 3 conn = require('net').createConnection(common.PORT, 'localhost'); conn.pause(); conn.on('data', onDataError); scheduleTearDown(conn); // Client 4 conn = require('net').createConnection(common.PORT, 'localhost'); conn.resume(); conn.pause(); conn.resume(); conn.on('data', onDataOk); // Client 5 conn = require('net').createConnection(common.PORT, 'localhost'); conn.resume(); conn.resume(); conn.pause(); conn.on('data', onDataError); scheduleTearDown(conn); // Client helper functions function onDataError() { assert(false); } function onDataOk() { dataEvents++; } function scheduleTearDown(conn) { setTimeout(function() { conn.removeAllListeners('data'); conn.resume(); }, 100); } // Exit sanity checks process.on('exit', function() { assert.strictEqual(connections, 5); assert.strictEqual(dataEvents, 3); }); node-v0.10.25~dfsg2/test/simple/test-net-reconnect.js0000644000000000000000000000523212270121457021146 0ustar rootroot// Copyright Joyent, Inc. and other Node contributors. // // Permission is hereby granted, free of charge, to any person obtaining a // copy of this software and associated documentation files (the // "Software"), to deal in the Software without restriction, including // without limitation the rights to use, copy, modify, merge, publish, // distribute, sublicense, and/or sell copies of the Software, and to permit // persons to whom the Software is furnished to do so, subject to the // following conditions: // // The above copyright notice and this permission notice shall be included // in all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS // OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF // MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN // NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, // DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR // OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE // USE OR OTHER DEALINGS IN THE SOFTWARE. var common = require('../common'); var assert = require('assert'); var net = require('net'); var N = 50; var c = 0; var client_recv_count = 0; var disconnect_count = 0; var server = net.createServer(function(socket) { console.error('SERVER: got socket connection'); socket.resume(); console.error('SERVER connect, writing'); socket.write('hello\r\n'); socket.on('end', function() { console.error('SERVER socket end, calling end()'); socket.end(); }); socket.on('close', function(had_error) { console.log('SERVER had_error: ' + JSON.stringify(had_error)); assert.equal(false, had_error); }); }); server.listen(common.PORT, function() { console.log('SERVER listening'); var client = net.createConnection(common.PORT); client.setEncoding('UTF8'); client.on('connect', function() { console.error('CLIENT connected', client._writableState); }); client.on('data', function(chunk) { client_recv_count += 1; console.log('client_recv_count ' + client_recv_count); assert.equal('hello\r\n', chunk); console.error('CLIENT: calling end', client._writableState); client.end(); }); client.on('end', function() { console.error('CLIENT end'); }); client.on('close', function(had_error) { console.log('CLIENT disconnect'); assert.equal(false, had_error); if (disconnect_count++ < N) client.connect(common.PORT); // reconnect else server.close(); }); }); process.on('exit', function() { assert.equal(N + 1, disconnect_count); assert.equal(N + 1, client_recv_count); }); node-v0.10.25~dfsg2/test/simple/test-net-connect-buffer.js0000644000000000000000000000661112270121457022070 0ustar rootroot// Copyright Joyent, Inc. and other Node contributors. // // Permission is hereby granted, free of charge, to any person obtaining a // copy of this software and associated documentation files (the // "Software"), to deal in the Software without restriction, including // without limitation the rights to use, copy, modify, merge, publish, // distribute, sublicense, and/or sell copies of the Software, and to permit // persons to whom the Software is furnished to do so, subject to the // following conditions: // // The above copyright notice and this permission notice shall be included // in all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS // OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF // MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN // NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, // DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR // OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE // USE OR OTHER DEALINGS IN THE SOFTWARE. var common = require('../common'); var assert = require('assert'); var net = require('net'); var tcpPort = common.PORT; var dataWritten = false; var connectHappened = false; var tcp = net.Server(function(s) { tcp.close(); console.log('tcp server connection'); var buf = ''; s.on('data', function(d) { buf += d; }); s.on('end', function() { console.error('SERVER: end', buf.toString()); assert.equal(buf, "L'État, c'est moi"); console.log('tcp socket disconnect'); s.end(); }); s.on('error', function(e) { console.log('tcp server-side error: ' + e.message); process.exit(1); }); }); tcp.listen(common.PORT, function() { var socket = net.Stream({ highWaterMark: 0 }); console.log('Connecting to socket '); socket.connect(tcpPort, function() { console.log('socket connected'); connectHappened = true; }); console.log('_connecting = ' + socket._connecting); assert.equal('opening', socket.readyState); // Make sure that anything besides a buffer or a string throws. [null, true, false, undefined, 1, 1.0, 1 / 0, +Infinity, -Infinity, [], {} ].forEach(function(v) { function f() { console.error('write', v); socket.write(v); } assert.throws(f, TypeError); }); // Write a string that contains a multi-byte character sequence to test that // `bytesWritten` is incremented with the # of bytes, not # of characters. var a = "L'État, c'est "; var b = 'moi'; // We're still connecting at this point so the datagram is first pushed onto // the connect queue. Make sure that it's not added to `bytesWritten` again // when the actual write happens. var r = socket.write(a, function(er) { console.error('write cb'); dataWritten = true; assert.ok(connectHappened); console.error('socket.bytesWritten', socket.bytesWritten); //assert.equal(socket.bytesWritten, Buffer(a + b).length); console.error('data written'); }); console.error('socket.bytesWritten', socket.bytesWritten); console.error('write returned', r); assert.equal(socket.bytesWritten, Buffer(a).length); assert.equal(false, r); socket.end(b); assert.equal('opening', socket.readyState); }); process.on('exit', function() { assert.ok(connectHappened); assert.ok(dataWritten); }); node-v0.10.25~dfsg2/test/simple/test-http-default-encoding.js0000644000000000000000000000371712270121457022575 0ustar rootroot// Copyright Joyent, Inc. and other Node contributors. // // Permission is hereby granted, free of charge, to any person obtaining a // copy of this software and associated documentation files (the // "Software"), to deal in the Software without restriction, including // without limitation the rights to use, copy, modify, merge, publish, // distribute, sublicense, and/or sell copies of the Software, and to permit // persons to whom the Software is furnished to do so, subject to the // following conditions: // // The above copyright notice and this permission notice shall be included // in all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS // OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF // MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN // NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, // DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR // OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE // USE OR OTHER DEALINGS IN THE SOFTWARE. var common = require('../common'); var assert = require('assert'); var http = require('http'); var expected = 'This is a unicode text: سلام'; var result = ''; var server = http.Server(function(req, res) { req.setEncoding('utf8'); req.on('data', function(chunk) { result += chunk; }).on('end', function() { clearTimeout(timeout); server.close(); }); var timeout = setTimeout(function() { process.exit(1); }, 100); res.writeHead(200); res.end('hello world\n'); }); server.listen(common.PORT, function() { http.request({ port: common.PORT, path: '/', method: 'POST' }, function(res) { console.log(res.statusCode); res.resume(); }).on('error', function(e) { console.log(e.message); process.exit(1); }).end(expected); }); process.on('exit', function() { assert.equal(expected, result); }); node-v0.10.25~dfsg2/test/simple/test-signal-unregister.js0000644000000000000000000000356312270121457022051 0ustar rootroot// Copyright Joyent, Inc. and other Node contributors. // // Permission is hereby granted, free of charge, to any person obtaining a // copy of this software and associated documentation files (the // "Software"), to deal in the Software without restriction, including // without limitation the rights to use, copy, modify, merge, publish, // distribute, sublicense, and/or sell copies of the Software, and to permit // persons to whom the Software is furnished to do so, subject to the // following conditions: // // The above copyright notice and this permission notice shall be included // in all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS // OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF // MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN // NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, // DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR // OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE // USE OR OTHER DEALINGS IN THE SOFTWARE. var common = require('../common'); var assert = require('assert'); var childKilled = false, done = false, spawn = require('child_process').spawn, util = require('util'), child; var join = require('path').join; child = spawn(process.argv[0], [join(common.fixturesDir, 'should_exit.js')]); child.on('exit', function() { if (!done) childKilled = true; }); setTimeout(function() { console.log('Sending SIGINT'); child.kill('SIGINT'); setTimeout(function() { console.log('Chance has been given to die'); done = true; if (!childKilled) { // Cleanup console.log('Child did not die on SIGINT, sending SIGTERM'); child.kill('SIGTERM'); } }, 200); }, 200); process.on('exit', function() { assert.ok(childKilled); }); node-v0.10.25~dfsg2/test/simple/test-domain-exit-dispose.js0000644000000000000000000000426312270121457022267 0ustar rootroot// Copyright Joyent, Inc. and other Node contributors. // // Permission is hereby granted, free of charge, to any person obtaining a // copy of this software and associated documentation files (the // "Software"), to deal in the Software without restriction, including // without limitation the rights to use, copy, modify, merge, publish, // distribute, sublicense, and/or sell copies of the Software, and to permit // persons to whom the Software is furnished to do so, subject to the // following conditions: // // The above copyright notice and this permission notice shall be included // in all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS // OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF // MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN // NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, // DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR // OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE // USE OR OTHER DEALINGS IN THE SOFTWARE. var common = require('../common.js'); var assert = require('assert'); var domain = require('domain'); var disposalFailed = false; // no matter what happens, we should increment a 10 times. var a = 0; log(); function log(){ console.log(a++, process.domain); if (a < 10) setTimeout(log, 20); } // in 50ms we'll throw an error. setTimeout(err, 50); function err(){ var d = domain.create(); d.on('error', handle); d.run(err2); function err2() { // this timeout should never be called, since the domain gets // disposed when the error happens. setTimeout(function() { console.error('This should not happen.'); disposalFailed = true; process.exit(1); }); // this function doesn't exist, and throws an error as a result. err3(); } function handle(e) { // this should clean up everything properly. d.dispose(); console.error(e); console.error('in handler', process.domain, process.domain === d); } } process.on('exit', function() { assert.equal(a, 10); assert.equal(disposalFailed, false); console.log('ok'); }); node-v0.10.25~dfsg2/test/simple/test-http-url.parse-only-support-http-https-protocol.js0000644000000000000000000000516112270121457027740 0ustar rootroot// Copyright Joyent, Inc. and other Node contributors. // // Permission is hereby granted, free of charge, to any person obtaining a // copy of this software and associated documentation files (the // "Software"), to deal in the Software without restriction, including // without limitation the rights to use, copy, modify, merge, publish, // distribute, sublicense, and/or sell copies of the Software, and to permit // persons to whom the Software is furnished to do so, subject to the // following conditions: // // The above copyright notice and this permission notice shall be included // in all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS // OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF // MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN // NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, // DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR // OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE // USE OR OTHER DEALINGS IN THE SOFTWARE. var common = require('../common'); var assert = require('assert'); var http = require('http'); var url = require('url'); assert.throws(function() { http.request(url.parse('file:///whatever')); }, function(err) { if (err instanceof Error) { assert.strictEqual(err.message, 'Protocol:file: not supported.'); return true; } }); assert.throws(function() { http.request(url.parse('mailto:asdf@asdf.com')); }, function(err) { if (err instanceof Error) { assert.strictEqual(err.message, 'Protocol:mailto: not supported.'); return true; } }); assert.throws(function() { http.request(url.parse('ftp://www.example.com')); }, function(err) { if (err instanceof Error) { assert.strictEqual(err.message, 'Protocol:ftp: not supported.'); return true; } }); assert.throws(function() { http.request(url.parse('javascript:alert(\'hello\');')); }, function(err) { if (err instanceof Error) { assert.strictEqual(err.message, 'Protocol:javascript: not supported.'); return true; } }); assert.throws(function() { http.request(url.parse('xmpp:isaacschlueter@jabber.org')); }, function(err) { if (err instanceof Error) { assert.strictEqual(err.message, 'Protocol:xmpp: not supported.'); return true; } }); assert.throws(function() { http.request(url.parse('f://some.host/path')); }, function(err) { if (err instanceof Error) { assert.strictEqual(err.message, 'Protocol:f: not supported.'); return true; } }); //TODO do I need to test url.parse(notPrococol.example.com)? node-v0.10.25~dfsg2/test/simple/test-timers-immediate.js0000644000000000000000000000354312270121457021644 0ustar rootroot// Copyright Joyent, Inc. and other Node contributors. // // Permission is hereby granted, free of charge, to any person obtaining a // copy of this software and associated documentation files (the // "Software"), to deal in the Software without restriction, including // without limitation the rights to use, copy, modify, merge, publish, // distribute, sublicense, and/or sell copies of the Software, and to permit // persons to whom the Software is furnished to do so, subject to the // following conditions: // // The above copyright notice and this permission notice shall be included // in all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS // OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF // MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN // NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, // DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR // OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE // USE OR OTHER DEALINGS IN THE SOFTWARE. var common = require('../common'); var assert = require('assert'); var immediateA = false, immediateB = false, immediateC = [], before; setImmediate(function() { try { immediateA = process.hrtime(before); } catch(e) { console.log('failed to get hrtime with offset'); } clearImmediate(immediateB); }); before = process.hrtime(); immediateB = setImmediate(function() { immediateB = true; }); setImmediate(function(x, y, z) { immediateC = [x, y, z]; }, 1, 2, 3); process.on('exit', function() { assert.ok(immediateA, 'Immediate should happen after normal execution'); assert.notStrictEqual(immediateB, true, 'immediateB should not fire'); assert.deepEqual(immediateC, [1, 2, 3], 'immediateC args should match'); }); node-v0.10.25~dfsg2/test/simple/test-abort-fatal-error.js0000644000000000000000000000314012270121457021721 0ustar rootroot// Copyright Joyent, Inc. and other Node contributors. // Permission is hereby granted, free of charge, to any person obtaining a // copy of this software and associated documentation files (the // "Software"), to deal in the Software without restriction, including // without limitation the rights to use, copy, modify, merge, publish, // distribute, sublicense, and/or sell copies of the Software, and to permit // persons to whom the Software is furnished to do so, subject to the // following conditions: // The above copyright notice and this permission notice shall be included // in all copies or substantial portions of the Software. // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS // OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF // MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN // NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, // DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR // OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE // USE OR OTHER DEALINGS IN THE SOFTWARE. var assert = require('assert'); var common = require('../common'); if (process.platform === 'win32') { console.log('skipping test on windows'); process.exit(0); } var exec = require('child_process').exec; var cmdline = 'ulimit -c 0; ' + process.execPath; cmdline += ' --max-old-space-size=1 --max-new-space-size=1'; cmdline += ' -e "setInterval(function() { new Buffer(1024); }, 1);"'; exec(cmdline, function(err, stdout, stderr) { assert(err); assert(stderr.toString().match(/abort/i)); }); node-v0.10.25~dfsg2/test/simple/test-tls-interleave.js0000644000000000000000000000447112270121457021344 0ustar rootroot// Copyright Joyent, Inc. and other Node contributors. // // Permission is hereby granted, free of charge, to any person obtaining a // copy of this software and associated documentation files (the // "Software"), to deal in the Software without restriction, including // without limitation the rights to use, copy, modify, merge, publish, // distribute, sublicense, and/or sell copies of the Software, and to permit // persons to whom the Software is furnished to do so, subject to the // following conditions: // // The above copyright notice and this permission notice shall be included // in all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS // OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF // MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN // NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, // DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR // OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE // USE OR OTHER DEALINGS IN THE SOFTWARE. var common = require('../common'); var assert = require('assert'); var tls = require('tls'); var fs = require('fs'); var PORT = common.PORT; var dir = common.fixturesDir; var options = { key: fs.readFileSync(dir + '/test_key.pem'), cert: fs.readFileSync(dir + '/test_cert.pem'), ca: [ fs.readFileSync(dir + '/test_ca.pem') ] }; var writes = [ 'some server data', 'and a separate packet', 'and one more', ]; var receivedWrites = 0; var server = tls.createServer(options, function(c) { writes.forEach(function(str) { c.write(str); }); }).listen(PORT, function() { var c = tls.connect(PORT, { rejectUnauthorized: false }, function() { c.write('some client data'); c.on('readable', function() { var data = c.read(); if (data === null) return; data = data.toString(); while (data.length !== 0) { assert.strictEqual(data.indexOf(writes[receivedWrites]), 0); data = data.slice(writes[receivedWrites].length); if (++receivedWrites === writes.length) { c.end(); server.close(); } } }); }); }); process.on('exit', function() { assert.equal(receivedWrites, writes.length); }); node-v0.10.25~dfsg2/test/simple/test-buffer-regress-GH-2659.js0000644000000000000000000000263312270121457022224 0ustar rootroot// Copyright Joyent, Inc. and other Node contributors. // // Permission is hereby granted, free of charge, to any person obtaining a // copy of this software and associated documentation files (the // "Software"), to deal in the Software without restriction, including // without limitation the rights to use, copy, modify, merge, publish, // distribute, sublicense, and/or sell copies of the Software, and to permit // persons to whom the Software is furnished to do so, subject to the // following conditions: // // The above copyright notice and this permission notice shall be included // in all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS // OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF // MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN // NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, // DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR // OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE // USE OR OTHER DEALINGS IN THE SOFTWARE. var common = require('../common'); var assert = require('assert'); // This is not a great test. It depends on a Node internal, namely the slab // size. Maybe we should expose that in some way. Then again, maybe not... for (var n = 1; n <= 8192; ++n) { Buffer(n); Buffer(0).write('', 'base64'); } node-v0.10.25~dfsg2/test/simple/test-child-process-env.js0000644000000000000000000000340712270121457021731 0ustar rootroot// Copyright Joyent, Inc. and other Node contributors. // // Permission is hereby granted, free of charge, to any person obtaining a // copy of this software and associated documentation files (the // "Software"), to deal in the Software without restriction, including // without limitation the rights to use, copy, modify, merge, publish, // distribute, sublicense, and/or sell copies of the Software, and to permit // persons to whom the Software is furnished to do so, subject to the // following conditions: // // The above copyright notice and this permission notice shall be included // in all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS // OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF // MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN // NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, // DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR // OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE // USE OR OTHER DEALINGS IN THE SOFTWARE. var common = require('../common'); var assert = require('assert'); var spawn = require('child_process').spawn; var isWindows = process.platform === 'win32'; var env = { 'HELLO': 'WORLD' }; env.__proto__ = { 'FOO': 'BAR' }; if (isWindows) { var child = spawn('cmd.exe', ['/c', 'set'], {env: env}); } else { var child = spawn('/usr/bin/env', [], {env: env}); } var response = ''; child.stdout.setEncoding('utf8'); child.stdout.on('data', function(chunk) { console.log('stdout: ' + chunk); response += chunk; }); process.on('exit', function() { assert.ok(response.indexOf('HELLO=WORLD') >= 0); assert.ok(response.indexOf('FOO=BAR') >= 0); }); node-v0.10.25~dfsg2/test/simple/test-module-loading-error.js0000644000000000000000000000317612270121457022436 0ustar rootroot// Copyright Joyent, Inc. and other Node contributors. // // Permission is hereby granted, free of charge, to any person obtaining a // copy of this software and associated documentation files (the // "Software"), to deal in the Software without restriction, including // without limitation the rights to use, copy, modify, merge, publish, // distribute, sublicense, and/or sell copies of the Software, and to permit // persons to whom the Software is furnished to do so, subject to the // following conditions: // // The above copyright notice and this permission notice shall be included // in all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS // OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF // MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN // NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, // DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR // OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE // USE OR OTHER DEALINGS IN THE SOFTWARE. var common = require('../common'); var assert = require('assert'); common.debug('load test-module-loading-error.js'); var error_desc = { win32: '%1 is not a valid Win32 application', linux: 'file too short', sunos: 'unknown file type' }; var dlerror_msg = error_desc[process.platform]; if (!dlerror_msg) { console.error('Skipping test, platform not supported.'); process.exit(); } try { require('../fixtures/module-loading-error.node'); } catch (e) { assert.notEqual(e.toString().indexOf(dlerror_msg), -1); } node-v0.10.25~dfsg2/test/simple/test-fs-write-stream-end.js0000644000000000000000000000332112270121457022174 0ustar rootroot// Copyright Joyent, Inc. and other Node contributors. // // Permission is hereby granted, free of charge, to any person obtaining a // copy of this software and associated documentation files (the // "Software"), to deal in the Software without restriction, including // without limitation the rights to use, copy, modify, merge, publish, // distribute, sublicense, and/or sell copies of the Software, and to permit // persons to whom the Software is furnished to do so, subject to the // following conditions: // // The above copyright notice and this permission notice shall be included // in all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS // OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF // MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN // NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, // DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR // OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE // USE OR OTHER DEALINGS IN THE SOFTWARE. var common = require('../common'); var assert = require('assert'); var path = require('path'); var fs = require('fs'); (function() { var file = path.join(common.tmpDir, 'write-end-test0.txt'); var stream = fs.createWriteStream(file); stream.end(); stream.on('close', common.mustCall(function() { })); })(); (function() { var file = path.join(common.tmpDir, 'write-end-test1.txt'); var stream = fs.createWriteStream(file); stream.end('a\n', 'utf8'); stream.on('close', common.mustCall(function() { var content = fs.readFileSync(file, 'utf8'); assert.equal(content, 'a\n'); })); })(); node-v0.10.25~dfsg2/test/simple/test-process-config.js0000644000000000000000000000345112270121457021324 0ustar rootroot// Copyright Joyent, Inc. and other Node contributors. // // Permission is hereby granted, free of charge, to any person obtaining a // copy of this software and associated documentation files (the // "Software"), to deal in the Software without restriction, including // without limitation the rights to use, copy, modify, merge, publish, // distribute, sublicense, and/or sell copies of the Software, and to permit // persons to whom the Software is furnished to do so, subject to the // following conditions: // // The above copyright notice and this permission notice shall be included // in all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS // OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF // MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN // NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, // DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR // OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE // USE OR OTHER DEALINGS IN THE SOFTWARE. var common = require('../common'); var assert = require('assert'); var fs = require('fs'); var path = require('path'); // check for existence assert(process.hasOwnProperty('config')); // ensure that `process.config` is an Object assert(Object(process.config) === process.config); var configPath = path.resolve(__dirname, '..', '..', 'config.gypi'); var config = fs.readFileSync(configPath, 'utf8'); // clean up comment at the first line config = config.split('\n').slice(1).join('\n').replace(/'/g, '"'); config = JSON.parse(config, function(key, value) { if (value === 'true') return true; if (value === 'false') return false; return value; }); assert.deepEqual(config, process.config); node-v0.10.25~dfsg2/test/simple/test-http-extra-response.js0000644000000000000000000000527412270121457022344 0ustar rootroot// Copyright Joyent, Inc. and other Node contributors. // // Permission is hereby granted, free of charge, to any person obtaining a // copy of this software and associated documentation files (the // "Software"), to deal in the Software without restriction, including // without limitation the rights to use, copy, modify, merge, publish, // distribute, sublicense, and/or sell copies of the Software, and to permit // persons to whom the Software is furnished to do so, subject to the // following conditions: // // The above copyright notice and this permission notice shall be included // in all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS // OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF // MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN // NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, // DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR // OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE // USE OR OTHER DEALINGS IN THE SOFTWARE. var common = require('../common'); var assert = require('assert'); var http = require('http'); var net = require('net'); // If an HTTP server is broken and sends data after the end of the response, // node should ignore it and drop the connection. // Demos this bug: https://github.com/joyent/node/issues/680 var body = 'hello world\r\n'; var fullResponse = 'HTTP/1.1 500 Internal Server Error\r\n' + 'Content-Length: ' + body.length + '\r\n' + 'Content-Type: text/plain\r\n' + 'Date: Fri + 18 Feb 2011 06:22:45 GMT\r\n' + 'Host: 10.20.149.2\r\n' + 'Access-Control-Allow-Credentials: true\r\n' + 'Server: badly broken/0.1 (OS NAME)\r\n' + '\r\n' + body; var gotResponse = false; var server = net.createServer(function(socket) { var postBody = ''; socket.setEncoding('utf8'); socket.on('data', function(chunk) { postBody += chunk; if (postBody.indexOf('\r\n') > -1) { socket.write(fullResponse); // omg, I wrote the response twice, what a terrible HTTP server I am. socket.end(fullResponse); } }); }); server.listen(common.PORT, function() { http.get({ port: common.PORT }, function(res) { var buffer = ''; console.log('Got res code: ' + res.statusCode); res.setEncoding('utf8'); res.on('data', function(chunk) { buffer += chunk; }); res.on('end', function() { console.log('Response ended, read ' + buffer.length + ' bytes'); assert.equal(body, buffer); server.close(); gotResponse = true; }); }); }); process.on('exit', function() { assert.ok(gotResponse); }); node-v0.10.25~dfsg2/test/simple/test-stream-push-order.js0000644000000000000000000000330312270121457021760 0ustar rootroot// Copyright Joyent, Inc. and other Node contributors. // // Permission is hereby granted, free of charge, to any person obtaining a // copy of this software and associated documentation files (the // "Software"), to deal in the Software without restriction, including // without limitation the rights to use, copy, modify, merge, publish, // distribute, sublicense, and/or sell copies of the Software, and to permit // persons to whom the Software is furnished to do so, subject to the // following conditions: // // The above copyright notice and this permission notice shall be included // in all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS // OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF // MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN // NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, // DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR // OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE // USE OR OTHER DEALINGS IN THE SOFTWARE. var common = require('../common.js'); var Readable = require('stream').Readable; var assert = require('assert'); var s = new Readable({ highWaterMark: 20, encoding: 'ascii' }); var list = ['1', '2', '3', '4', '5', '6']; s._read = function (n) { var one = list.shift(); if (!one) { s.push(null); } else { var two = list.shift(); s.push(one); s.push(two); } }; var v = s.read(0); // ACTUALLY [1, 3, 5, 6, 4, 2] process.on("exit", function () { assert.deepEqual(s._readableState.buffer, ['1', '2', '3', '4', '5', '6']); console.log("ok"); }); node-v0.10.25~dfsg2/test/simple/test-child-process-fork3.js0000644000000000000000000000241112270121457022157 0ustar rootroot// Copyright Joyent, Inc. and other Node contributors. // // Permission is hereby granted, free of charge, to any person obtaining a // copy of this software and associated documentation files (the // "Software"), to deal in the Software without restriction, including // without limitation the rights to use, copy, modify, merge, publish, // distribute, sublicense, and/or sell copies of the Software, and to permit // persons to whom the Software is furnished to do so, subject to the // following conditions: // // The above copyright notice and this permission notice shall be included // in all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS // OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF // MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN // NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, // DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR // OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE // USE OR OTHER DEALINGS IN THE SOFTWARE. var common = require('../common'); var child_process = require('child_process'); child_process.fork(common.fixturesDir + '/empty.js'); // should not hang node-v0.10.25~dfsg2/test/simple/test-writeuint.js0000644000000000000000000001021312270121457020427 0ustar rootroot// Copyright Joyent, Inc. and other Node contributors. // // Permission is hereby granted, free of charge, to any person obtaining a // copy of this software and associated documentation files (the // "Software"), to deal in the Software without restriction, including // without limitation the rights to use, copy, modify, merge, publish, // distribute, sublicense, and/or sell copies of the Software, and to permit // persons to whom the Software is furnished to do so, subject to the // following conditions: // // The above copyright notice and this permission notice shall be included // in all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS // OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF // MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN // NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, // DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR // OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE // USE OR OTHER DEALINGS IN THE SOFTWARE. /* * A battery of tests to help us read a series of uints */ var SlowBuffer = process.binding('buffer').SlowBuffer; var common = require('../common'); var ASSERT = require('assert'); /* * We need to check the following things: * - We are correctly resolving big endian (doesn't mean anything for 8 bit) * - Correctly resolving little endian (doesn't mean anything for 8 bit) * - Correctly using the offsets * - Correctly interpreting values that are beyond the signed range as unsigned */ function test8(clazz) { var data = new clazz(4); data.writeUInt8(23, 0); data.writeUInt8(23, 1); data.writeUInt8(23, 2); data.writeUInt8(23, 3); ASSERT.equal(23, data[0]); ASSERT.equal(23, data[1]); ASSERT.equal(23, data[2]); ASSERT.equal(23, data[3]); data.writeUInt8(23, 0); data.writeUInt8(23, 1); data.writeUInt8(23, 2); data.writeUInt8(23, 3); ASSERT.equal(23, data[0]); ASSERT.equal(23, data[1]); ASSERT.equal(23, data[2]); ASSERT.equal(23, data[3]); data.writeUInt8(255, 0); ASSERT.equal(255, data[0]); data.writeUInt8(255, 0); ASSERT.equal(255, data[0]); } function test16(clazz) { var value = 0x2343; var data = new clazz(4); data.writeUInt16BE(value, 0); ASSERT.equal(0x23, data[0]); ASSERT.equal(0x43, data[1]); data.writeUInt16BE(value, 1); ASSERT.equal(0x23, data[1]); ASSERT.equal(0x43, data[2]); data.writeUInt16BE(value, 2); ASSERT.equal(0x23, data[2]); ASSERT.equal(0x43, data[3]); data.writeUInt16LE(value, 0); ASSERT.equal(0x23, data[1]); ASSERT.equal(0x43, data[0]); data.writeUInt16LE(value, 1); ASSERT.equal(0x23, data[2]); ASSERT.equal(0x43, data[1]); data.writeUInt16LE(value, 2); ASSERT.equal(0x23, data[3]); ASSERT.equal(0x43, data[2]); value = 0xff80; data.writeUInt16LE(value, 0); ASSERT.equal(0xff, data[1]); ASSERT.equal(0x80, data[0]); data.writeUInt16BE(value, 0); ASSERT.equal(0xff, data[0]); ASSERT.equal(0x80, data[1]); } function test32(clazz) { var data = new clazz(6); var value = 0xe7f90a6d; data.writeUInt32BE(value, 0); ASSERT.equal(0xe7, data[0]); ASSERT.equal(0xf9, data[1]); ASSERT.equal(0x0a, data[2]); ASSERT.equal(0x6d, data[3]); data.writeUInt32BE(value, 1); ASSERT.equal(0xe7, data[1]); ASSERT.equal(0xf9, data[2]); ASSERT.equal(0x0a, data[3]); ASSERT.equal(0x6d, data[4]); data.writeUInt32BE(value, 2); ASSERT.equal(0xe7, data[2]); ASSERT.equal(0xf9, data[3]); ASSERT.equal(0x0a, data[4]); ASSERT.equal(0x6d, data[5]); data.writeUInt32LE(value, 0); ASSERT.equal(0xe7, data[3]); ASSERT.equal(0xf9, data[2]); ASSERT.equal(0x0a, data[1]); ASSERT.equal(0x6d, data[0]); data.writeUInt32LE(value, 1); ASSERT.equal(0xe7, data[4]); ASSERT.equal(0xf9, data[3]); ASSERT.equal(0x0a, data[2]); ASSERT.equal(0x6d, data[1]); data.writeUInt32LE(value, 2); ASSERT.equal(0xe7, data[5]); ASSERT.equal(0xf9, data[4]); ASSERT.equal(0x0a, data[3]); ASSERT.equal(0x6d, data[2]); } test8(Buffer); test8(SlowBuffer); test16(Buffer); test16(SlowBuffer); test32(Buffer); test32(SlowBuffer); node-v0.10.25~dfsg2/test/simple/test-event-emitter-once.js0000644000000000000000000000364612270121457022123 0ustar rootroot// Copyright Joyent, Inc. and other Node contributors. // // Permission is hereby granted, free of charge, to any person obtaining a // copy of this software and associated documentation files (the // "Software"), to deal in the Software without restriction, including // without limitation the rights to use, copy, modify, merge, publish, // distribute, sublicense, and/or sell copies of the Software, and to permit // persons to whom the Software is furnished to do so, subject to the // following conditions: // // The above copyright notice and this permission notice shall be included // in all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS // OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF // MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN // NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, // DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR // OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE // USE OR OTHER DEALINGS IN THE SOFTWARE. var common = require('../common'); var assert = require('assert'); var events = require('events'); var e = new events.EventEmitter(); var times_hello_emited = 0; e.once('hello', function(a, b) { times_hello_emited++; }); e.emit('hello', 'a', 'b'); e.emit('hello', 'a', 'b'); e.emit('hello', 'a', 'b'); e.emit('hello', 'a', 'b'); var remove = function() { assert.fail(1, 0, 'once->foo should not be emitted', '!'); }; e.once('foo', remove); e.removeListener('foo', remove); e.emit('foo'); process.on('exit', function() { assert.equal(1, times_hello_emited); }); var times_recurse_emitted = 0; e.once('e', function() { e.emit('e'); times_recurse_emitted++; }); e.once('e', function() { times_recurse_emitted++; }); e.emit('e'); process.on('exit', function() { assert.equal(2, times_recurse_emitted); }); node-v0.10.25~dfsg2/test/simple/test-socket-write-after-fin-error.js0000644000000000000000000000512612270121457024024 0ustar rootroot// Copyright Joyent, Inc. and other Node contributors. // // Permission is hereby granted, free of charge, to any person obtaining a // copy of this software and associated documentation files (the // "Software"), to deal in the Software without restriction, including // without limitation the rights to use, copy, modify, merge, publish, // distribute, sublicense, and/or sell copies of the Software, and to permit // persons to whom the Software is furnished to do so, subject to the // following conditions: // // The above copyright notice and this permission notice shall be included // in all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS // OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF // MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN // NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, // DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR // OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE // USE OR OTHER DEALINGS IN THE SOFTWARE. var common = require('../common'); var assert = require('assert'); // This is similar to simple/test-socket-write-after-fin, except that // we don't set allowHalfOpen. Then we write after the client has sent // a FIN, and this is an error. However, the standard "write after end" // message is too vague, and doesn't actually tell you what happens. var net = require('net'); var serverData = ''; var gotServerEnd = false; var clientData = ''; var gotClientEnd = false; var gotServerError = false; var server = net.createServer(function(sock) { sock.setEncoding('utf8'); sock.on('error', function(er) { console.error(er.code + ': ' + er.message); gotServerError = er; }); sock.on('data', function(c) { serverData += c; }); sock.on('end', function() { gotServerEnd = true sock.write(serverData); sock.end(); }); server.close(); }); server.listen(common.PORT); var sock = net.connect(common.PORT); sock.setEncoding('utf8'); sock.on('data', function(c) { clientData += c; }); sock.on('end', function() { gotClientEnd = true; }); process.on('exit', function() { assert.equal(clientData, ''); assert.equal(serverData, 'hello1hello2hello3\nTHUNDERMUSCLE!'); assert(gotClientEnd); assert(gotServerEnd); assert(gotServerError); assert.equal(gotServerError.code, 'EPIPE'); assert.notEqual(gotServerError.message, 'write after end'); console.log('ok'); }); sock.write('hello1'); sock.write('hello2'); sock.write('hello3\n'); sock.end('THUNDERMUSCLE!'); node-v0.10.25~dfsg2/test/simple/test-stream2-set-encoding.js0000644000000000000000000001677612270121457022353 0ustar rootroot// Copyright Joyent, Inc. and other Node contributors. // // Permission is hereby granted, free of charge, to any person obtaining a // copy of this software and associated documentation files (the // "Software"), to deal in the Software without restriction, including // without limitation the rights to use, copy, modify, merge, publish, // distribute, sublicense, and/or sell copies of the Software, and to permit // persons to whom the Software is furnished to do so, subject to the // following conditions: // // The above copyright notice and this permission notice shall be included // in all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS // OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF // MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN // NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, // DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR // OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE // USE OR OTHER DEALINGS IN THE SOFTWARE. var common = require('../common.js'); var assert = require('assert'); var R = require('_stream_readable'); var util = require('util'); // tiny node-tap lookalike. var tests = []; var count = 0; function test(name, fn) { count++; tests.push([name, fn]); } function run() { var next = tests.shift(); if (!next) return console.error('ok'); var name = next[0]; var fn = next[1]; console.log('# %s', name); fn({ same: assert.deepEqual, equal: assert.equal, end: function () { count--; run(); } }); } // ensure all tests have run process.on("exit", function () { assert.equal(count, 0); }); process.nextTick(run); ///// util.inherits(TestReader, R); function TestReader(n, opts) { R.call(this, opts); this.pos = 0; this.len = n || 100; } TestReader.prototype._read = function(n) { setTimeout(function() { if (this.pos >= this.len) { // double push(null) to test eos handling this.push(null); return this.push(null); } n = Math.min(n, this.len - this.pos); if (n <= 0) { // double push(null) to test eos handling this.push(null); return this.push(null); } this.pos += n; var ret = new Buffer(n); ret.fill('a'); console.log("this.push(ret)", ret) return this.push(ret); }.bind(this), 1); }; test('setEncoding utf8', function(t) { var tr = new TestReader(100); tr.setEncoding('utf8'); var out = []; var expect = [ 'aaaaaaaaaa', 'aaaaaaaaaa', 'aaaaaaaaaa', 'aaaaaaaaaa', 'aaaaaaaaaa', 'aaaaaaaaaa', 'aaaaaaaaaa', 'aaaaaaaaaa', 'aaaaaaaaaa', 'aaaaaaaaaa' ]; tr.on('readable', function flow() { var chunk; while (null !== (chunk = tr.read(10))) out.push(chunk); }); tr.on('end', function() { t.same(out, expect); t.end(); }); }); test('setEncoding hex', function(t) { var tr = new TestReader(100); tr.setEncoding('hex'); var out = []; var expect = [ '6161616161', '6161616161', '6161616161', '6161616161', '6161616161', '6161616161', '6161616161', '6161616161', '6161616161', '6161616161', '6161616161', '6161616161', '6161616161', '6161616161', '6161616161', '6161616161', '6161616161', '6161616161', '6161616161', '6161616161' ]; tr.on('readable', function flow() { var chunk; while (null !== (chunk = tr.read(10))) out.push(chunk); }); tr.on('end', function() { t.same(out, expect); t.end(); }); }); test('setEncoding hex with read(13)', function(t) { var tr = new TestReader(100); tr.setEncoding('hex'); var out = []; var expect = [ "6161616161616", "1616161616161", "6161616161616", "1616161616161", "6161616161616", "1616161616161", "6161616161616", "1616161616161", "6161616161616", "1616161616161", "6161616161616", "1616161616161", "6161616161616", "1616161616161", "6161616161616", "16161" ]; tr.on('readable', function flow() { console.log("readable once") var chunk; while (null !== (chunk = tr.read(13))) out.push(chunk); }); tr.on('end', function() { console.log("END") t.same(out, expect); t.end(); }); }); test('setEncoding base64', function(t) { var tr = new TestReader(100); tr.setEncoding('base64'); var out = []; var expect = [ 'YWFhYWFhYW', 'FhYWFhYWFh', 'YWFhYWFhYW', 'FhYWFhYWFh', 'YWFhYWFhYW', 'FhYWFhYWFh', 'YWFhYWFhYW', 'FhYWFhYWFh', 'YWFhYWFhYW', 'FhYWFhYWFh', 'YWFhYWFhYW', 'FhYWFhYWFh', 'YWFhYWFhYW', 'FhYQ==' ]; tr.on('readable', function flow() { var chunk; while (null !== (chunk = tr.read(10))) out.push(chunk); }); tr.on('end', function() { t.same(out, expect); t.end(); }); }); test('encoding: utf8', function(t) { var tr = new TestReader(100, { encoding: 'utf8' }); var out = []; var expect = [ 'aaaaaaaaaa', 'aaaaaaaaaa', 'aaaaaaaaaa', 'aaaaaaaaaa', 'aaaaaaaaaa', 'aaaaaaaaaa', 'aaaaaaaaaa', 'aaaaaaaaaa', 'aaaaaaaaaa', 'aaaaaaaaaa' ]; tr.on('readable', function flow() { var chunk; while (null !== (chunk = tr.read(10))) out.push(chunk); }); tr.on('end', function() { t.same(out, expect); t.end(); }); }); test('encoding: hex', function(t) { var tr = new TestReader(100, { encoding: 'hex' }); var out = []; var expect = [ '6161616161', '6161616161', '6161616161', '6161616161', '6161616161', '6161616161', '6161616161', '6161616161', '6161616161', '6161616161', '6161616161', '6161616161', '6161616161', '6161616161', '6161616161', '6161616161', '6161616161', '6161616161', '6161616161', '6161616161' ]; tr.on('readable', function flow() { var chunk; while (null !== (chunk = tr.read(10))) out.push(chunk); }); tr.on('end', function() { t.same(out, expect); t.end(); }); }); test('encoding: hex with read(13)', function(t) { var tr = new TestReader(100, { encoding: 'hex' }); var out = []; var expect = [ "6161616161616", "1616161616161", "6161616161616", "1616161616161", "6161616161616", "1616161616161", "6161616161616", "1616161616161", "6161616161616", "1616161616161", "6161616161616", "1616161616161", "6161616161616", "1616161616161", "6161616161616", "16161" ]; tr.on('readable', function flow() { var chunk; while (null !== (chunk = tr.read(13))) out.push(chunk); }); tr.on('end', function() { t.same(out, expect); t.end(); }); }); test('encoding: base64', function(t) { var tr = new TestReader(100, { encoding: 'base64' }); var out = []; var expect = [ 'YWFhYWFhYW', 'FhYWFhYWFh', 'YWFhYWFhYW', 'FhYWFhYWFh', 'YWFhYWFhYW', 'FhYWFhYWFh', 'YWFhYWFhYW', 'FhYWFhYWFh', 'YWFhYWFhYW', 'FhYWFhYWFh', 'YWFhYWFhYW', 'FhYWFhYWFh', 'YWFhYWFhYW', 'FhYQ==' ]; tr.on('readable', function flow() { var chunk; while (null !== (chunk = tr.read(10))) out.push(chunk); }); tr.on('end', function() { t.same(out, expect); t.end(); }); }); node-v0.10.25~dfsg2/test/simple/test-buffer-concat.js0000644000000000000000000000327712270121457021127 0ustar rootroot// Copyright Joyent, Inc. and other Node contributors. // // Permission is hereby granted, free of charge, to any person obtaining a // copy of this software and associated documentation files (the // "Software"), to deal in the Software without restriction, including // without limitation the rights to use, copy, modify, merge, publish, // distribute, sublicense, and/or sell copies of the Software, and to permit // persons to whom the Software is furnished to do so, subject to the // following conditions: // // The above copyright notice and this permission notice shall be included // in all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS // OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF // MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN // NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, // DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR // OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE // USE OR OTHER DEALINGS IN THE SOFTWARE. var common = require('../common'); var assert = require('assert'); var zero = []; var one = [ new Buffer('asdf') ]; var long = []; for (var i = 0; i < 10; i++) long.push(new Buffer('asdf')); var flatZero = Buffer.concat(zero); var flatOne = Buffer.concat(one); var flatLong = Buffer.concat(long); var flatLongLen = Buffer.concat(long, 40); assert(flatZero.length === 0); assert(flatOne.toString() === 'asdf'); assert(flatOne === one[0]); assert(flatLong.toString() === (new Array(10+1).join('asdf'))); assert(flatLongLen.toString() === (new Array(10+1).join('asdf'))); console.log("ok"); node-v0.10.25~dfsg2/test/simple/test-https-strict.js0000644000000000000000000001414712270121457021057 0ustar rootroot// Copyright Joyent, Inc. and other Node contributors. // // Permission is hereby granted, free of charge, to any person obtaining a // copy of this software and associated documentation files (the // "Software"), to deal in the Software without restriction, including // without limitation the rights to use, copy, modify, merge, publish, // distribute, sublicense, and/or sell copies of the Software, and to permit // persons to whom the Software is furnished to do so, subject to the // following conditions: // // The above copyright notice and this permission notice shall be included // in all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS // OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF // MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN // NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, // DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR // OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE // USE OR OTHER DEALINGS IN THE SOFTWARE. if (!process.versions.openssl) { console.error('Skipping because node compiled without OpenSSL.'); process.exit(0); } // disable strict server certificate validation by the client process.env.NODE_TLS_REJECT_UNAUTHORIZED = '0'; var common = require('../common'); var assert = require('assert'); var fs = require('fs'); var path = require('path'); var https = require('https'); function file(fname) { return path.resolve(common.fixturesDir, 'keys', fname); } function read(fname) { return fs.readFileSync(file(fname)); } // key1 is signed by ca1. var key1 = read('agent1-key.pem'); var cert1 = read('agent1-cert.pem'); // key2 has a self signed cert var key2 = read('agent2-key.pem'); var cert2 = read('agent2-cert.pem'); // key3 is signed by ca2. var key3 = read('agent3-key.pem'); var cert3 = read('agent3-cert.pem'); var ca1 = read('ca1-cert.pem'); var ca2 = read('ca2-cert.pem'); // different agents to use different CA lists. // this api is beyond bad. var agent0 = new https.Agent(); var agent1 = new https.Agent({ ca: [ca1] }); var agent2 = new https.Agent({ ca: [ca2] }); var agent3 = new https.Agent({ ca: [ca1, ca2] }); var options1 = { key: key1, cert: cert1 }; var options2 = { key: key2, cert: cert2 }; var options3 = { key: key3, cert: cert3 }; var server1 = server(options1); var server2 = server(options2); var server3 = server(options3); var listenWait = 0; var port = common.PORT; var port1 = port++; var port2 = port++; var port3 = port++; server1.listen(port1, listening()); server2.listen(port2, listening()); server3.listen(port3, listening()); var responseErrors = {}; var expectResponseCount = 0; var responseCount = 0; var pending = 0; function server(options, port) { var s = https.createServer(options, handler); s.requests = []; s.expectCount = 0; return s; } function handler(req, res) { this.requests.push(req.url); res.statusCode = 200; res.setHeader('foo', 'bar'); res.end('hello, world\n'); } function listening() { listenWait++; return function() { listenWait--; if (listenWait === 0) { allListening(); } } } function makeReq(path, port, error, host, ca) { pending++; var options = { port: port, path: path, ca: ca }; var whichCa = 0; if (!ca) { options.agent = agent0; } else { if (!Array.isArray(ca)) ca = [ca]; if (-1 !== ca.indexOf(ca1) && -1 !== ca.indexOf(ca2)) { options.agent = agent3; } else if (-1 !== ca.indexOf(ca1)) { options.agent = agent1; } else if (-1 !== ca.indexOf(ca2)) { options.agent = agent2; } else { options.agent = agent0; } } if (host) { options.headers = { host: host } } var req = https.get(options); expectResponseCount++; var server = port === port1 ? server1 : port === port2 ? server2 : port === port3 ? server3 : null; if (!server) throw new Error('invalid port: '+port); server.expectCount++; req.on('response', function(res) { responseCount++; assert.equal(res.connection.authorizationError, error); responseErrors[path] = res.connection.authorizationError; pending--; if (pending === 0) { server1.close(); server2.close(); server3.close(); } res.resume(); }) } function allListening() { // ok, ready to start the tests! // server1: host 'agent1', signed by ca1 makeReq('/inv1', port1, 'UNABLE_TO_VERIFY_LEAF_SIGNATURE'); makeReq('/inv1-ca1', port1, 'Hostname/IP doesn\'t match certificate\'s altnames', null, ca1); makeReq('/inv1-ca1ca2', port1, 'Hostname/IP doesn\'t match certificate\'s altnames', null, [ca1, ca2]); makeReq('/val1-ca1', port1, null, 'agent1', ca1); makeReq('/val1-ca1ca2', port1, null, 'agent1', [ca1, ca2]); makeReq('/inv1-ca2', port1, 'UNABLE_TO_VERIFY_LEAF_SIGNATURE', 'agent1', ca2); // server2: self-signed, host = 'agent2' // doesn't matter that thename matches, all of these will error. makeReq('/inv2', port2, 'DEPTH_ZERO_SELF_SIGNED_CERT'); makeReq('/inv2-ca1', port2, 'DEPTH_ZERO_SELF_SIGNED_CERT', 'agent2', ca1); makeReq('/inv2-ca1ca2', port2, 'DEPTH_ZERO_SELF_SIGNED_CERT', 'agent2', [ca1, ca2]); // server3: host 'agent3', signed by ca2 makeReq('/inv3', port3, 'UNABLE_TO_VERIFY_LEAF_SIGNATURE'); makeReq('/inv3-ca2', port3, 'Hostname/IP doesn\'t match certificate\'s altnames', null, ca2); makeReq('/inv3-ca1ca2', port3, 'Hostname/IP doesn\'t match certificate\'s altnames', null, [ca1, ca2]); makeReq('/val3-ca2', port3, null, 'agent3', ca2); makeReq('/val3-ca1ca2', port3, null, 'agent3', [ca1, ca2]); makeReq('/inv3-ca1', port3, 'UNABLE_TO_VERIFY_LEAF_SIGNATURE', 'agent1', ca1); } process.on('exit', function() { console.error(responseErrors); assert.equal(server1.requests.length, server1.expectCount); assert.equal(server2.requests.length, server2.expectCount); assert.equal(server3.requests.length, server3.expectCount); assert.equal(responseCount, expectResponseCount); }); node-v0.10.25~dfsg2/test/simple/test-dgram-unref.js0000644000000000000000000000273412270121457020615 0ustar rootroot// Copyright Joyent, Inc. and other Node contributors. // // Permission is hereby granted, free of charge, to any person obtaining a // copy of this software and associated documentation files (the // "Software"), to deal in the Software without restriction, including // without limitation the rights to use, copy, modify, merge, publish, // distribute, sublicense, and/or sell copies of the Software, and to permit // persons to whom the Software is furnished to do so, subject to the // following conditions: // // The above copyright notice and this permission notice shall be included // in all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS // OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF // MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN // NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, // DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR // OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE // USE OR OTHER DEALINGS IN THE SOFTWARE. var common = require('../common'); var assert = require('assert'); var dgram = require('dgram'); var closed = false; var s = dgram.createSocket('udp4'); s.bind(); s.unref(); setTimeout(function() { closed = true; s.close(); }, 1000).unref(); process.on('exit', function() { assert.strictEqual(closed, false, 'Unrefd socket should not hold loop open'); }); node-v0.10.25~dfsg2/test/simple/test-crypto-binary-default.js0000644000000000000000000006241112270121457022630 0ustar rootroot// Copyright Joyent, Inc. and other Node contributors. // // Permission is hereby granted, free of charge, to any person obtaining a // copy of this software and associated documentation files (the // "Software"), to deal in the Software without restriction, including // without limitation the rights to use, copy, modify, merge, publish, // distribute, sublicense, and/or sell copies of the Software, and to permit // persons to whom the Software is furnished to do so, subject to the // following conditions: // // The above copyright notice and this permission notice shall be included // in all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS // OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF // MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN // NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, // DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR // OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE // USE OR OTHER DEALINGS IN THE SOFTWARE. // This is the same as test/simple/test-crypto, but from before the shift // to use buffers by default. var common = require('../common'); var assert = require('assert'); try { var crypto = require('crypto'); } catch (e) { console.log('Not compiled with OPENSSL support.'); process.exit(); } crypto.DEFAULT_ENCODING = 'binary'; var fs = require('fs'); var path = require('path'); // Test Certificates var caPem = fs.readFileSync(common.fixturesDir + '/test_ca.pem', 'ascii'); var certPem = fs.readFileSync(common.fixturesDir + '/test_cert.pem', 'ascii'); var certPfx = fs.readFileSync(common.fixturesDir + '/test_cert.pfx'); var keyPem = fs.readFileSync(common.fixturesDir + '/test_key.pem', 'ascii'); var rsaPubPem = fs.readFileSync(common.fixturesDir + '/test_rsa_pubkey.pem', 'ascii'); var rsaKeyPem = fs.readFileSync(common.fixturesDir + '/test_rsa_privkey.pem', 'ascii'); try { var credentials = crypto.createCredentials( {key: keyPem, cert: certPem, ca: caPem}); } catch (e) { console.log('Not compiled with OPENSSL support.'); process.exit(); } // PFX tests assert.doesNotThrow(function() { crypto.createCredentials({pfx:certPfx, passphrase:'sample'}); }); assert.throws(function() { crypto.createCredentials({pfx:certPfx}); }, 'mac verify failure'); assert.throws(function() { crypto.createCredentials({pfx:certPfx, passphrase:'test'}); }, 'mac verify failure'); assert.throws(function() { crypto.createCredentials({pfx:'sample', passphrase:'test'}); }, 'not enough data'); // Test HMAC var h1 = crypto.createHmac('sha1', 'Node') .update('some data') .update('to hmac') .digest('hex'); assert.equal(h1, '19fd6e1ba73d9ed2224dd5094a71babe85d9a892', 'test HMAC'); // Test HMAC-SHA-* (rfc 4231 Test Cases) var rfc4231 = [ { key: new Buffer('0b0b0b0b0b0b0b0b0b0b0b0b0b0b0b0b0b0b0b0b', 'hex'), data: new Buffer('4869205468657265', 'hex'), // 'Hi There' hmac: { sha224: '896fb1128abbdf196832107cd49df33f47b4b1169912ba4f53684b22', sha256: 'b0344c61d8db38535ca8afceaf0bf12b881dc200c9833da726e9376c' + '2e32cff7', sha384: 'afd03944d84895626b0825f4ab46907f15f9dadbe4101ec682aa034c' + '7cebc59cfaea9ea9076ede7f4af152e8b2fa9cb6', sha512: '87aa7cdea5ef619d4ff0b4241a1d6cb02379f4e2ce4ec2787ad0b305' + '45e17cdedaa833b7d6b8a702038b274eaea3f4e4be9d914eeb61f170' + '2e696c203a126854' } }, { key: new Buffer('4a656665', 'hex'), // 'Jefe' data: new Buffer('7768617420646f2079612077616e7420666f72206e6f74686' + '96e673f', 'hex'), // 'what do ya want for nothing?' hmac: { sha224: 'a30e01098bc6dbbf45690f3a7e9e6d0f8bbea2a39e6148008fd05e44', sha256: '5bdcc146bf60754e6a042426089575c75a003f089d2739839dec58b9' + '64ec3843', sha384: 'af45d2e376484031617f78d2b58a6b1b9c7ef464f5a01b47e42ec373' + '6322445e8e2240ca5e69e2c78b3239ecfab21649', sha512: '164b7a7bfcf819e2e395fbe73b56e0a387bd64222e831fd610270cd7' + 'ea2505549758bf75c05a994a6d034f65f8f0e6fdcaeab1a34d4a6b4b' + '636e070a38bce737' } }, { key: new Buffer('aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa', 'hex'), data: new Buffer('ddddddddddddddddddddddddddddddddddddddddddddddddd' + 'ddddddddddddddddddddddddddddddddddddddddddddddddddd', 'hex'), hmac: { sha224: '7fb3cb3588c6c1f6ffa9694d7d6ad2649365b0c1f65d69d1ec8333ea', sha256: '773ea91e36800e46854db8ebd09181a72959098b3ef8c122d9635514' + 'ced565fe', sha384: '88062608d3e6ad8a0aa2ace014c8a86f0aa635d947ac9febe83ef4e5' + '5966144b2a5ab39dc13814b94e3ab6e101a34f27', sha512: 'fa73b0089d56a284efb0f0756c890be9b1b5dbdd8ee81a3655f83e33' + 'b2279d39bf3e848279a722c806b485a47e67c807b946a337bee89426' + '74278859e13292fb' } }, { key: new Buffer('0102030405060708090a0b0c0d0e0f10111213141516171819', 'hex'), data: new Buffer('cdcdcdcdcdcdcdcdcdcdcdcdcdcdcdcdcdcdcdcdcdcdcdcdc' + 'dcdcdcdcdcdcdcdcdcdcdcdcdcdcdcdcdcdcdcdcdcdcdcdcdcd', 'hex'), hmac: { sha224: '6c11506874013cac6a2abc1bb382627cec6a90d86efc012de7afec5a', sha256: '82558a389a443c0ea4cc819899f2083a85f0faa3e578f8077a2e3ff4' + '6729665b', sha384: '3e8a69b7783c25851933ab6290af6ca77a9981480850009cc5577c6e' + '1f573b4e6801dd23c4a7d679ccf8a386c674cffb', sha512: 'b0ba465637458c6990e5a8c5f61d4af7e576d97ff94b872de76f8050' + '361ee3dba91ca5c11aa25eb4d679275cc5788063a5f19741120c4f2d' + 'e2adebeb10a298dd' } }, { key: new Buffer('0c0c0c0c0c0c0c0c0c0c0c0c0c0c0c0c0c0c0c0c', 'hex'), // 'Test With Truncation' data: new Buffer('546573742057697468205472756e636174696f6e', 'hex'), hmac: { sha224: '0e2aea68a90c8d37c988bcdb9fca6fa8', sha256: 'a3b6167473100ee06e0c796c2955552b', sha384: '3abf34c3503b2a23a46efc619baef897', sha512: '415fad6271580a531d4179bc891d87a6' }, truncate: true }, { key: new Buffer('aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa' + 'aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa' + 'aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa' + 'aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa' + 'aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa' + 'aaaaaaaaaaaa', 'hex'), // 'Test Using Larger Than Block-Size Key - Hash Key First' data: new Buffer('54657374205573696e67204c6172676572205468616e20426' + 'c6f636b2d53697a65204b6579202d2048617368204b657920' + '4669727374', 'hex'), hmac: { sha224: '95e9a0db962095adaebe9b2d6f0dbce2d499f112f2d2b7273fa6870e', sha256: '60e431591ee0b67f0d8a26aacbf5b77f8e0bc6213728c5140546040f' + '0ee37f54', sha384: '4ece084485813e9088d2c63a041bc5b44f9ef1012a2b588f3cd11f05' + '033ac4c60c2ef6ab4030fe8296248df163f44952', sha512: '80b24263c7c1a3ebb71493c1dd7be8b49b46d1f41b4aeec1121b0137' + '83f8f3526b56d037e05f2598bd0fd2215d6a1e5295e64f73f63f0aec' + '8b915a985d786598' } }, { key: new Buffer('aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa' + 'aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa' + 'aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa' + 'aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa' + 'aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa' + 'aaaaaaaaaaaa', 'hex'), // 'This is a test using a larger than block-size key and a larger ' + // 'than block-size data. The key needs to be hashed before being ' + // 'used by the HMAC algorithm.' data: new Buffer('5468697320697320612074657374207573696e672061206c6' + '172676572207468616e20626c6f636b2d73697a65206b6579' + '20616e642061206c6172676572207468616e20626c6f636b2' + 'd73697a6520646174612e20546865206b6579206e65656473' + '20746f20626520686173686564206265666f7265206265696' + 'e6720757365642062792074686520484d414320616c676f72' + '6974686d2e', 'hex'), hmac: { sha224: '3a854166ac5d9f023f54d517d0b39dbd946770db9c2b95c9f6f565d1', sha256: '9b09ffa71b942fcb27635fbcd5b0e944bfdc63644f0713938a7f5153' + '5c3a35e2', sha384: '6617178e941f020d351e2f254e8fd32c602420feb0b8fb9adccebb82' + '461e99c5a678cc31e799176d3860e6110c46523e', sha512: 'e37b6a775dc87dbaa4dfa9f96e5e3ffddebd71f8867289865df5a32d' + '20cdc944b6022cac3c4982b10d5eeb55c3e4de15134676fb6de04460' + '65c97440fa8c6a58' } } ]; for (var i = 0, l = rfc4231.length; i < l; i++) { for (var hash in rfc4231[i]['hmac']) { var result = crypto.createHmac(hash, rfc4231[i]['key']) .update(rfc4231[i]['data']) .digest('hex'); if (rfc4231[i]['truncate']) { result = result.substr(0, 32); // first 128 bits == 32 hex chars } assert.equal(rfc4231[i]['hmac'][hash], result, 'Test HMAC-' + hash + ': Test case ' + (i + 1) + ' rfc 4231'); } } // Test HMAC-MD5/SHA1 (rfc 2202 Test Cases) var rfc2202_md5 = [ { key: new Buffer('0b0b0b0b0b0b0b0b0b0b0b0b0b0b0b0b', 'hex'), data: 'Hi There', hmac: '9294727a3638bb1c13f48ef8158bfc9d' }, { key: 'Jefe', data: 'what do ya want for nothing?', hmac: '750c783e6ab0b503eaa86e310a5db738' }, { key: new Buffer('aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa', 'hex'), data: new Buffer('ddddddddddddddddddddddddddddddddddddddddddddddddd' + 'ddddddddddddddddddddddddddddddddddddddddddddddddddd', 'hex'), hmac: '56be34521d144c88dbb8c733f0e8b3f6' }, { key: new Buffer('0102030405060708090a0b0c0d0e0f10111213141516171819', 'hex'), data: new Buffer('cdcdcdcdcdcdcdcdcdcdcdcdcdcdcdcdcdcdcdcdcdcdc' + 'dcdcdcdcdcdcdcdcdcdcdcdcdcdcdcdcdcdcdcdcdcdcd' + 'cdcdcdcdcd', 'hex'), hmac: '697eaf0aca3a3aea3a75164746ffaa79' }, { key: new Buffer('0c0c0c0c0c0c0c0c0c0c0c0c0c0c0c0c', 'hex'), data: 'Test With Truncation', hmac: '56461ef2342edc00f9bab995690efd4c' }, { key: new Buffer('aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa' + 'aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa' + 'aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa' + 'aaaaaaaaaaaaaaaaaaaaaa', 'hex'), data: 'Test Using Larger Than Block-Size Key - Hash Key First', hmac: '6b1ab7fe4bd7bf8f0b62e6ce61b9d0cd' }, { key: new Buffer('aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa' + 'aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa' + 'aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa' + 'aaaaaaaaaaaaaaaaaaaaaa', 'hex'), data: 'Test Using Larger Than Block-Size Key and Larger Than One ' + 'Block-Size Data', hmac: '6f630fad67cda0ee1fb1f562db3aa53e' } ]; var rfc2202_sha1 = [ { key: new Buffer('0b0b0b0b0b0b0b0b0b0b0b0b0b0b0b0b0b0b0b0b', 'hex'), data: 'Hi There', hmac: 'b617318655057264e28bc0b6fb378c8ef146be00' }, { key: 'Jefe', data: 'what do ya want for nothing?', hmac: 'effcdf6ae5eb2fa2d27416d5f184df9c259a7c79' }, { key: new Buffer('aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa', 'hex'), data: new Buffer('ddddddddddddddddddddddddddddddddddddddddddddd' + 'ddddddddddddddddddddddddddddddddddddddddddddd' + 'dddddddddd', 'hex'), hmac: '125d7342b9ac11cd91a39af48aa17b4f63f175d3' }, { key: new Buffer('0102030405060708090a0b0c0d0e0f10111213141516171819', 'hex'), data: new Buffer('cdcdcdcdcdcdcdcdcdcdcdcdcdcdcdcdcdcdcdcdcdcdc' + 'dcdcdcdcdcdcdcdcdcdcdcdcdcdcdcdcdcdcdcdcdcdcd' + 'cdcdcdcdcd', 'hex'), hmac: '4c9007f4026250c6bc8414f9bf50c86c2d7235da' }, { key: new Buffer('0c0c0c0c0c0c0c0c0c0c0c0c0c0c0c0c0c0c0c0c', 'hex'), data: 'Test With Truncation', hmac: '4c1a03424b55e07fe7f27be1d58bb9324a9a5a04' }, { key: new Buffer('aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa' + 'aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa' + 'aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa' + 'aaaaaaaaaaaaaaaaaaaaaa', 'hex'), data: 'Test Using Larger Than Block-Size Key - Hash Key First', hmac: 'aa4ae5e15272d00e95705637ce8a3b55ed402112' }, { key: new Buffer('aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa' + 'aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa' + 'aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa' + 'aaaaaaaaaaaaaaaaaaaaaa', 'hex'), data: 'Test Using Larger Than Block-Size Key and Larger Than One ' + 'Block-Size Data', hmac: 'e8e99d0f45237d786d6bbaa7965c7808bbff1a91' } ]; for (var i = 0, l = rfc2202_md5.length; i < l; i++) { assert.equal(rfc2202_md5[i]['hmac'], crypto.createHmac('md5', rfc2202_md5[i]['key']) .update(rfc2202_md5[i]['data']) .digest('hex'), 'Test HMAC-MD5 : Test case ' + (i + 1) + ' rfc 2202'); } for (var i = 0, l = rfc2202_sha1.length; i < l; i++) { assert.equal(rfc2202_sha1[i]['hmac'], crypto.createHmac('sha1', rfc2202_sha1[i]['key']) .update(rfc2202_sha1[i]['data']) .digest('hex'), 'Test HMAC-SHA1 : Test case ' + (i + 1) + ' rfc 2202'); } // Test hashing var a0 = crypto.createHash('sha1').update('Test123').digest('hex'); var a1 = crypto.createHash('md5').update('Test123').digest('binary'); var a2 = crypto.createHash('sha256').update('Test123').digest('base64'); var a3 = crypto.createHash('sha512').update('Test123').digest(); // binary var a4 = crypto.createHash('sha1').update('Test123').digest('buffer'); assert.equal(a0, '8308651804facb7b9af8ffc53a33a22d6a1c8ac2', 'Test SHA1'); assert.equal(a1, 'h\u00ea\u00cb\u0097\u00d8o\fF!\u00fa+\u000e\u0017\u00ca' + '\u00bd\u008c', 'Test MD5 as binary'); assert.equal(a2, '2bX1jws4GYKTlxhloUB09Z66PoJZW+y+hq5R8dnx9l4=', 'Test SHA256 as base64'); assert.equal(a3, '\u00c1(4\u00f1\u0003\u001fd\u0097!O\'\u00d4C/&Qz\u00d4' + '\u0094\u0015l\u00b8\u008dQ+\u00db\u001d\u00c4\u00b5}\u00b2' + '\u00d6\u0092\u00a3\u00df\u00a2i\u00a1\u009b\n\n*\u000f' + '\u00d7\u00d6\u00a2\u00a8\u0085\u00e3<\u0083\u009c\u0093' + '\u00c2\u0006\u00da0\u00a1\u00879(G\u00ed\'', 'Test SHA512 as assumed binary'); assert.deepEqual(a4, new Buffer('8308651804facb7b9af8ffc53a33a22d6a1c8ac2', 'hex'), 'Test SHA1'); // Test multiple updates to same hash var h1 = crypto.createHash('sha1').update('Test123').digest('hex'); var h2 = crypto.createHash('sha1').update('Test').update('123').digest('hex'); assert.equal(h1, h2, 'multipled updates'); // Test hashing for binary files var fn = path.join(common.fixturesDir, 'sample.png'); var sha1Hash = crypto.createHash('sha1'); var fileStream = fs.createReadStream(fn); fileStream.on('data', function(data) { sha1Hash.update(data); }); fileStream.on('close', function() { assert.equal(sha1Hash.digest('hex'), '22723e553129a336ad96e10f6aecdf0f45e4149e', 'Test SHA1 of sample.png'); }); // Issue #2227: unknown digest method should throw an error. assert.throws(function() { crypto.createHash('xyzzy'); }); // Test signing and verifying var s1 = crypto.createSign('RSA-SHA1') .update('Test123') .sign(keyPem, 'base64'); var verified = crypto.createVerify('RSA-SHA1') .update('Test') .update('123') .verify(certPem, s1, 'base64'); assert.strictEqual(verified, true, 'sign and verify (base 64)'); var s2 = crypto.createSign('RSA-SHA256') .update('Test123') .sign(keyPem); // binary var verified = crypto.createVerify('RSA-SHA256') .update('Test') .update('123') .verify(certPem, s2); // binary assert.strictEqual(verified, true, 'sign and verify (binary)'); var s3 = crypto.createSign('RSA-SHA1') .update('Test123') .sign(keyPem, 'buffer'); var verified = crypto.createVerify('RSA-SHA1') .update('Test') .update('123') .verify(certPem, s3); assert.strictEqual(verified, true, 'sign and verify (buffer)'); function testCipher1(key) { // Test encryption and decryption var plaintext = 'Keep this a secret? No! Tell everyone about node.js!'; var cipher = crypto.createCipher('aes192', key); // encrypt plaintext which is in utf8 format // to a ciphertext which will be in hex var ciph = cipher.update(plaintext, 'utf8', 'hex'); // Only use binary or hex, not base64. ciph += cipher.final('hex'); var decipher = crypto.createDecipher('aes192', key); var txt = decipher.update(ciph, 'hex', 'utf8'); txt += decipher.final('utf8'); assert.equal(txt, plaintext, 'encryption and decryption'); } function testCipher2(key) { // encryption and decryption with Base64 // reported in https://github.com/joyent/node/issues/738 var plaintext = '32|RmVZZkFUVmpRRkp0TmJaUm56ZU9qcnJkaXNNWVNpTTU*|iXmckfRWZBGWWELw' + 'eCBsThSsfUHLeRe0KCsK8ooHgxie0zOINpXxfZi/oNG7uq9JWFVCk70gfzQH8ZUJ' + 'jAfaFg**'; var cipher = crypto.createCipher('aes256', key); // encrypt plaintext which is in utf8 format // to a ciphertext which will be in Base64 var ciph = cipher.update(plaintext, 'utf8', 'base64'); ciph += cipher.final('base64'); var decipher = crypto.createDecipher('aes256', key); var txt = decipher.update(ciph, 'base64', 'utf8'); txt += decipher.final('utf8'); assert.equal(txt, plaintext, 'encryption and decryption with Base64'); } function testCipher3(key, iv) { // Test encyrption and decryption with explicit key and iv var plaintext = '32|RmVZZkFUVmpRRkp0TmJaUm56ZU9qcnJkaXNNWVNpTTU*|iXmckfRWZBGWWELw' + 'eCBsThSsfUHLeRe0KCsK8ooHgxie0zOINpXxfZi/oNG7uq9JWFVCk70gfzQH8ZUJ' + 'jAfaFg**'; var cipher = crypto.createCipheriv('des-ede3-cbc', key, iv); var ciph = cipher.update(plaintext, 'utf8', 'hex'); ciph += cipher.final('hex'); var decipher = crypto.createDecipheriv('des-ede3-cbc', key, iv); var txt = decipher.update(ciph, 'hex', 'utf8'); txt += decipher.final('utf8'); assert.equal(txt, plaintext, 'encryption and decryption with key and iv'); } function testCipher4(key, iv) { // Test encyrption and decryption with explicit key and iv var plaintext = '32|RmVZZkFUVmpRRkp0TmJaUm56ZU9qcnJkaXNNWVNpTTU*|iXmckfRWZBGWWELw' + 'eCBsThSsfUHLeRe0KCsK8ooHgxie0zOINpXxfZi/oNG7uq9JWFVCk70gfzQH8ZUJ' + 'jAfaFg**'; var cipher = crypto.createCipheriv('des-ede3-cbc', key, iv); var ciph = cipher.update(plaintext, 'utf8', 'buffer'); ciph = Buffer.concat([ciph, cipher.final('buffer')]); var decipher = crypto.createDecipheriv('des-ede3-cbc', key, iv); var txt = decipher.update(ciph, 'buffer', 'utf8'); txt += decipher.final('utf8'); assert.equal(txt, plaintext, 'encryption and decryption with key and iv'); } testCipher1('MySecretKey123'); testCipher1(new Buffer('MySecretKey123')); testCipher2('0123456789abcdef'); testCipher2(new Buffer('0123456789abcdef')); testCipher3('0123456789abcd0123456789', '12345678'); testCipher3('0123456789abcd0123456789', new Buffer('12345678')); testCipher3(new Buffer('0123456789abcd0123456789'), '12345678'); testCipher3(new Buffer('0123456789abcd0123456789'), new Buffer('12345678')); testCipher4(new Buffer('0123456789abcd0123456789'), new Buffer('12345678')); // update() should only take buffers / strings assert.throws(function() { crypto.createHash('sha1').update({foo: 'bar'}); }, /buffer/); // Test Diffie-Hellman with two parties sharing a secret, // using various encodings as we go along var dh1 = crypto.createDiffieHellman(256); var p1 = dh1.getPrime('buffer'); var dh2 = crypto.createDiffieHellman(p1, 'base64'); var key1 = dh1.generateKeys(); var key2 = dh2.generateKeys('hex'); var secret1 = dh1.computeSecret(key2, 'hex', 'base64'); var secret2 = dh2.computeSecret(key1, 'binary', 'buffer'); assert.equal(secret1, secret2.toString('base64')); // Create "another dh1" using generated keys from dh1, // and compute secret again var dh3 = crypto.createDiffieHellman(p1, 'buffer'); var privkey1 = dh1.getPrivateKey(); dh3.setPublicKey(key1); dh3.setPrivateKey(privkey1); assert.equal(dh1.getPrime(), dh3.getPrime()); assert.equal(dh1.getGenerator(), dh3.getGenerator()); assert.equal(dh1.getPublicKey(), dh3.getPublicKey()); assert.equal(dh1.getPrivateKey(), dh3.getPrivateKey()); var secret3 = dh3.computeSecret(key2, 'hex', 'base64'); assert.equal(secret1, secret3); // https://github.com/joyent/node/issues/2338 assert.throws(function() { var p = 'FFFFFFFFFFFFFFFFC90FDAA22168C234C4C6628B80DC1CD129024E088A67CC74' + '020BBEA63B139B22514A08798E3404DDEF9519B3CD3A431B302B0A6DF25F1437' + '4FE1356D6D51C245E485B576625E7EC6F44C42E9A637ED6B0BFF5CB6F406B7ED' + 'EE386BFB5A899FA5AE9F24117C4B1FE649286651ECE65381FFFFFFFFFFFFFFFF'; crypto.createDiffieHellman(p, 'hex'); }); // Test RSA key signing/verification var rsaSign = crypto.createSign('RSA-SHA1'); var rsaVerify = crypto.createVerify('RSA-SHA1'); assert.ok(rsaSign); assert.ok(rsaVerify); rsaSign.update(rsaPubPem); var rsaSignature = rsaSign.sign(rsaKeyPem, 'hex'); assert.equal(rsaSignature, '5c50e3145c4e2497aadb0eabc83b342d0b0021ece0d4c4a064b7c' + '8f020d7e2688b122bfb54c724ac9ee169f83f66d2fe90abeb95e8' + 'e1290e7e177152a4de3d944cf7d4883114a20ed0f78e70e25ef0f' + '60f06b858e6af42a2f276ede95bbc6bc9a9bbdda15bd663186a6f' + '40819a7af19e577bb2efa5e579a1f5ce8a0d4ca8b8f6'); rsaVerify.update(rsaPubPem); assert.strictEqual(rsaVerify.verify(rsaPubPem, rsaSignature, 'hex'), true); // // Test RSA signing and verification // (function() { var privateKey = fs.readFileSync( common.fixturesDir + '/test_rsa_privkey_2.pem'); var publicKey = fs.readFileSync( common.fixturesDir + '/test_rsa_pubkey_2.pem'); var input = 'I AM THE WALRUS'; var signature = '79d59d34f56d0e94aa6a3e306882b52ed4191f07521f25f505a078dc2f89' + '396e0c8ac89e996fde5717f4cb89199d8fec249961fcb07b74cd3d2a4ffa' + '235417b69618e4bcd76b97e29975b7ce862299410e1b522a328e44ac9bb2' + '8195e0268da7eda23d9825ac43c724e86ceeee0d0d4465678652ccaf6501' + '0ddfb299bedeb1ad'; var sign = crypto.createSign('RSA-SHA256'); sign.update(input); var output = sign.sign(privateKey, 'hex'); assert.equal(output, signature); var verify = crypto.createVerify('RSA-SHA256'); verify.update(input); assert.strictEqual(verify.verify(publicKey, signature, 'hex'), true); })(); // // Test DSA signing and verification // (function() { var privateKey = fs.readFileSync( common.fixturesDir + '/test_dsa_privkey.pem'); var publicKey = fs.readFileSync( common.fixturesDir + '/test_dsa_pubkey.pem'); var input = 'I AM THE WALRUS'; // DSA signatures vary across runs so there is no static string to verify // against var sign = crypto.createSign('DSS1'); sign.update(input); var signature = sign.sign(privateKey, 'hex'); var verify = crypto.createVerify('DSS1'); verify.update(input); assert.strictEqual(verify.verify(publicKey, signature, 'hex'), true); })(); // // Test PBKDF2 with RFC 6070 test vectors (except #4) // function testPBKDF2(password, salt, iterations, keylen, expected) { var actual = crypto.pbkdf2Sync(password, salt, iterations, keylen); assert.equal(actual, expected); crypto.pbkdf2(password, salt, iterations, keylen, function(err, actual) { assert.equal(actual, expected); }); } testPBKDF2('password', 'salt', 1, 20, '\x0c\x60\xc8\x0f\x96\x1f\x0e\x71\xf3\xa9\xb5\x24' + '\xaf\x60\x12\x06\x2f\xe0\x37\xa6'); testPBKDF2('password', 'salt', 2, 20, '\xea\x6c\x01\x4d\xc7\x2d\x6f\x8c\xcd\x1e\xd9\x2a' + '\xce\x1d\x41\xf0\xd8\xde\x89\x57'); testPBKDF2('password', 'salt', 4096, 20, '\x4b\x00\x79\x01\xb7\x65\x48\x9a\xbe\xad\x49\xd9\x26' + '\xf7\x21\xd0\x65\xa4\x29\xc1'); testPBKDF2('passwordPASSWORDpassword', 'saltSALTsaltSALTsaltSALTsaltSALTsalt', 4096, 25, '\x3d\x2e\xec\x4f\xe4\x1c\x84\x9b\x80\xc8\xd8\x36\x62' + '\xc0\xe4\x4a\x8b\x29\x1a\x96\x4c\xf2\xf0\x70\x38'); testPBKDF2('pass\0word', 'sa\0lt', 4096, 16, '\x56\xfa\x6a\xa7\x55\x48\x09\x9d\xcc\x37\xd7\xf0\x34' + '\x25\xe0\xc3'); node-v0.10.25~dfsg2/test/simple/test-tls-pause.js0000644000000000000000000000555712270121457020331 0ustar rootroot// Copyright Joyent, Inc. and other Node contributors. // // Permission is hereby granted, free of charge, to any person obtaining a // copy of this software and associated documentation files (the // "Software"), to deal in the Software without restriction, including // without limitation the rights to use, copy, modify, merge, publish, // distribute, sublicense, and/or sell copies of the Software, and to permit // persons to whom the Software is furnished to do so, subject to the // following conditions: // // The above copyright notice and this permission notice shall be included // in all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS // OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF // MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN // NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, // DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR // OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE // USE OR OTHER DEALINGS IN THE SOFTWARE. if (!process.versions.openssl) { console.error('Skipping because node compiled without OpenSSL.'); process.exit(0); } var common = require('../common'); var assert = require('assert'); var tls = require('tls'); var fs = require('fs'); var path = require('path'); var options = { key: fs.readFileSync(path.join(common.fixturesDir, 'test_key.pem')), cert: fs.readFileSync(path.join(common.fixturesDir, 'test_cert.pem')) }; var bufSize = 1024 * 1024; var sent = 0; var received = 0; var server = tls.Server(options, function(socket) { socket.pipe(socket); socket.on('data', function(c) { console.error('data', c.length); }); }); server.listen(common.PORT, function() { var resumed = false; var client = tls.connect({ port: common.PORT, rejectUnauthorized: false }, function() { console.error('connected'); client.pause(); common.debug('paused'); send(); function send() { console.error('sending'); var ret = client.write(new Buffer(bufSize)); console.error('write => %j', ret); if (false !== ret) { console.error('write again'); sent += bufSize; assert.ok(sent < 100 * 1024 * 1024); // max 100MB return process.nextTick(send); } sent += bufSize; common.debug('sent: ' + sent); resumed = true; client.resume(); console.error('resumed', client); } }); client.on('data', function(data) { console.error('data'); assert.ok(resumed); received += data.length; console.error('received', received); console.error('sent', sent); if (received >= sent) { common.debug('received: ' + received); client.end(); server.close(); } }); }); process.on('exit', function() { assert.equal(sent, received); }); node-v0.10.25~dfsg2/test/simple/test-child-process-fork-getconnections.js0000644000000000000000000000654012270121457025123 0ustar rootroot// Copyright Joyent, Inc. and other Node contributors. // // Permission is hereby granted, free of charge, to any person obtaining a // copy of this software and associated documentation files (the // "Software"), to deal in the Software without restriction, including // without limitation the rights to use, copy, modify, merge, publish, // distribute, sublicense, and/or sell copies of the Software, and to permit // persons to whom the Software is furnished to do so, subject to the // following conditions: // // The above copyright notice and this permission notice shall be included // in all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS // OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF // MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN // NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, // DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR // OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE // USE OR OTHER DEALINGS IN THE SOFTWARE. var assert = require('assert'); var common = require('../common'); var fork = require('child_process').fork; var net = require('net'); var count = 12; if (process.argv[2] === 'child') { var sockets = []; var id = process.argv[3]; process.on('message', function(m, socket) { if (m.cmd === 'new') { assert(socket); assert(socket instanceof net.Socket, 'should be a net.Socket'); sockets.push(socket); socket.on('end', function() { if (!this.closingOnPurpose) throw new Error('[c] closing by accident! ' + process._errno); }); } if (m.cmd === 'close') { assert.equal(socket, undefined); sockets[m.id].once('close', function() { process.send({ id: m.id, status: 'closed' }); }); sockets[m.id].destroy(); } }); } else { var child = fork(process.argv[1], ['child']); child.on('exit', function(code, signal) { if (!childKilled) throw new Error('child died unexpectedly!'); }); var server = net.createServer(); var sockets = []; var sent = 0; server.on('connection', function(socket) { child.send({ cmd: 'new' }, socket, { track: false }); sockets.push(socket); if (sockets.length === count) { closeSockets(0); } }); var disconnected = 0; var clients = []; server.on('listening', function() { var j = count, client; while (j--) { client = net.connect(common.PORT, '127.0.0.1'); client.id = j; client.on('close', function() { disconnected += 1; }); clients.push(client); } }); var childKilled = false; function closeSockets(i) { if (i === count) { childKilled = true; server.close(); child.kill(); return; } sent++; child.send({ id: i, cmd: 'close' }); child.once('message', function(m) { assert(m.status === 'closed'); server.getConnections(function(err, num) { closeSockets(i + 1); }); }); }; var closeEmitted = false; server.on('close', function() { closeEmitted = true; }); server.listen(common.PORT, '127.0.0.1'); process.on('exit', function() { assert.equal(sent, count); assert.equal(disconnected, count); assert.ok(closeEmitted); console.log('ok'); }); } node-v0.10.25~dfsg2/test/simple/test-next-tick.js0000644000000000000000000000320512270121457020306 0ustar rootroot// Copyright Joyent, Inc. and other Node contributors. // // Permission is hereby granted, free of charge, to any person obtaining a // copy of this software and associated documentation files (the // "Software"), to deal in the Software without restriction, including // without limitation the rights to use, copy, modify, merge, publish, // distribute, sublicense, and/or sell copies of the Software, and to permit // persons to whom the Software is furnished to do so, subject to the // following conditions: // // The above copyright notice and this permission notice shall be included // in all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS // OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF // MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN // NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, // DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR // OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE // USE OR OTHER DEALINGS IN THE SOFTWARE. var common = require('../common'); var assert = require('assert'); var complete = 0; process.nextTick(function() { complete++; process.nextTick(function() { complete++; process.nextTick(function() { complete++; }); }); }); setTimeout(function() { process.nextTick(function() { complete++; }); }, 50); process.nextTick(function() { complete++; }); process.on('exit', function() { assert.equal(5, complete); process.nextTick(function() { throw new Error('this should not occur'); }); }); node-v0.10.25~dfsg2/test/simple/test-http-head-response-has-no-body.js0000644000000000000000000000372412270121457024236 0ustar rootroot// Copyright Joyent, Inc. and other Node contributors. // // Permission is hereby granted, free of charge, to any person obtaining a // copy of this software and associated documentation files (the // "Software"), to deal in the Software without restriction, including // without limitation the rights to use, copy, modify, merge, publish, // distribute, sublicense, and/or sell copies of the Software, and to permit // persons to whom the Software is furnished to do so, subject to the // following conditions: // // The above copyright notice and this permission notice shall be included // in all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS // OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF // MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN // NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, // DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR // OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE // USE OR OTHER DEALINGS IN THE SOFTWARE. var common = require('../common'); var assert = require('assert'); var http = require('http'); // This test is to make sure that when the HTTP server // responds to a HEAD request, it does not send any body. // In this case it was sending '0\r\n\r\n' var server = http.createServer(function(req, res) { res.writeHead(200); // broken: defaults to TE chunked res.end(); }); server.listen(common.PORT); var responseComplete = false; server.on('listening', function() { var req = http.request({ port: common.PORT, method: 'HEAD', path: '/' }, function(res) { common.error('response'); res.on('end', function() { common.error('response end'); server.close(); responseComplete = true; }); res.resume(); }); common.error('req'); req.end(); }); process.on('exit', function() { assert.ok(responseComplete); }); node-v0.10.25~dfsg2/test/simple/test-cluster-message.js0000644000000000000000000000752112270121457021510 0ustar rootroot// Copyright Joyent, Inc. and other Node contributors. // // Permission is hereby granted, free of charge, to any person obtaining a // copy of this software and associated documentation files (the // "Software"), to deal in the Software without restriction, including // without limitation the rights to use, copy, modify, merge, publish, // distribute, sublicense, and/or sell copies of the Software, and to permit // persons to whom the Software is furnished to do so, subject to the // following conditions: // // The above copyright notice and this permission notice shall be included // in all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS // OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF // MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN // NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, // DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR // OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE // USE OR OTHER DEALINGS IN THE SOFTWARE. var common = require('../common'); var assert = require('assert'); var cluster = require('cluster'); var net = require('net'); function forEach(obj, fn) { Object.keys(obj).forEach(function(name, index) { fn(obj[name], name, index); }); } if (cluster.isWorker) { // Create a tcp server. This will be used as cluster-shared-server and as an // alternative IPC channel. var server = net.Server(); var socket, message; function maybeReply() { if (!socket || !message) return; // Tell master using TCP socket that a message is received. socket.write(JSON.stringify({ code: 'received message', echo: message })); } server.on('connection', function(socket_) { socket = socket_; maybeReply(); // Send a message back over the IPC channel. process.send('message from worker'); }); process.on('message', function(message_) { message = message_; maybeReply(); }); server.listen(common.PORT, '127.0.0.1'); } else if (cluster.isMaster) { var checks = { master: { 'receive': false, 'correct': false }, worker: { 'receive': false, 'correct': false } }; var client; var check = function(type, result) { checks[type].receive = true; checks[type].correct = result; console.error('check', checks); var missing = false; forEach(checks, function(type) { if (type.receive === false) missing = true; }); if (missing === false) { console.error('end client'); client.end(); } }; // Spawn worker var worker = cluster.fork(); // When a IPC message is resicved form the worker worker.on('message', function(message) { check('master', message === 'message from worker'); }); // When a TCP connection is made with the worker connect to it worker.on('listening', function() { client = net.connect(common.PORT, function() { // Send message to worker. worker.send('message from master'); }); client.on('data', function(data) { // All data is JSON data = JSON.parse(data.toString()); if (data.code === 'received message') { check('worker', data.echo === 'message from master'); } else { throw new Error('wrong TCP message recived: ' + data); } }); // When the connection ends kill worker and shutdown process client.on('end', function() { worker.kill(); }); worker.on('exit', function() { process.exit(0); }); }); process.once('exit', function() { forEach(checks, function(check, type) { assert.ok(check.receive, 'The ' + type + ' did not receive any message'); assert.ok(check.correct, 'The ' + type + ' did not get the correct message'); }); }); } node-v0.10.25~dfsg2/test/simple/test-http-server-stale-close.js0000644000000000000000000000352612270121457023102 0ustar rootroot// Copyright Joyent, Inc. and other Node contributors. // // Permission is hereby granted, free of charge, to any person obtaining a // copy of this software and associated documentation files (the // "Software"), to deal in the Software without restriction, including // without limitation the rights to use, copy, modify, merge, publish, // distribute, sublicense, and/or sell copies of the Software, and to permit // persons to whom the Software is furnished to do so, subject to the // following conditions: // // The above copyright notice and this permission notice shall be included // in all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS // OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF // MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN // NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, // DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR // OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE // USE OR OTHER DEALINGS IN THE SOFTWARE. var common = require('../common'); var assert = require('assert'); var http = require('http'); var util = require('util'); var fork = require('child_process').fork; if (process.env.NODE_TEST_FORK) { var req = http.request({ headers: {'Content-Length': '42'}, method: 'POST', host: '127.0.0.1', port: common.PORT, }, process.exit); req.write('BAM'); req.end(); } else { var server = http.createServer(function(req, res) { res.writeHead(200, {'Content-Length': '42'}); req.pipe(res); req.on('close', function() { server.close(); res.end(); }); }); server.listen(common.PORT, function() { fork(__filename, { env: util._extend(process.env, {NODE_TEST_FORK: '1'}) }); }); } node-v0.10.25~dfsg2/test/simple/test-http-client-upload.js0000644000000000000000000000460512270121457022122 0ustar rootroot// Copyright Joyent, Inc. and other Node contributors. // // Permission is hereby granted, free of charge, to any person obtaining a // copy of this software and associated documentation files (the // "Software"), to deal in the Software without restriction, including // without limitation the rights to use, copy, modify, merge, publish, // distribute, sublicense, and/or sell copies of the Software, and to permit // persons to whom the Software is furnished to do so, subject to the // following conditions: // // The above copyright notice and this permission notice shall be included // in all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS // OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF // MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN // NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, // DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR // OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE // USE OR OTHER DEALINGS IN THE SOFTWARE. var common = require('../common'); var assert = require('assert'); var http = require('http'); var sent_body = ''; var server_req_complete = false; var client_res_complete = false; var server = http.createServer(function(req, res) { assert.equal('POST', req.method); req.setEncoding('utf8'); req.on('data', function(chunk) { console.log('server got: ' + JSON.stringify(chunk)); sent_body += chunk; }); req.on('end', function() { server_req_complete = true; console.log('request complete from server'); res.writeHead(200, {'Content-Type': 'text/plain'}); res.write('hello\n'); res.end(); }); }); server.listen(common.PORT); server.on('listening', function() { var req = http.request({ port: common.PORT, method: 'POST', path: '/' }, function(res) { res.setEncoding('utf8'); res.on('data', function(chunk) { console.log(chunk); }); res.on('end', function() { client_res_complete = true; server.close(); }); }); req.write('1\n'); req.write('2\n'); req.write('3\n'); req.end(); common.error('client finished sending request'); }); process.on('exit', function() { assert.equal('1\n2\n3\n', sent_body); assert.equal(true, server_req_complete); assert.equal(true, client_res_complete); }); node-v0.10.25~dfsg2/test/simple/test-http-upgrade-client2.js0000644000000000000000000000510412270121457022342 0ustar rootroot// Copyright Joyent, Inc. and other Node contributors. // // Permission is hereby granted, free of charge, to any person obtaining a // copy of this software and associated documentation files (the // "Software"), to deal in the Software without restriction, including // without limitation the rights to use, copy, modify, merge, publish, // distribute, sublicense, and/or sell copies of the Software, and to permit // persons to whom the Software is furnished to do so, subject to the // following conditions: // // The above copyright notice and this permission notice shall be included // in all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS // OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF // MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN // NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, // DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR // OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE // USE OR OTHER DEALINGS IN THE SOFTWARE. var common = require('../common'); var assert = require('assert'); var http = require('http'); var CRLF = '\r\n'; var server = http.createServer(); server.on('upgrade', function(req, socket, head) { socket.write('HTTP/1.1 101 Ok' + CRLF + 'Connection: Upgrade' + CRLF + 'Upgrade: Test' + CRLF + CRLF + 'head'); socket.on('end', function() { socket.end(); }); }); var successCount = 0; server.listen(common.PORT, function() { function upgradeRequest(fn) { console.log('req'); var header = { 'Connection': 'Upgrade', 'Upgrade': 'Test' }; var request = http.request({ port: common.PORT, headers: header }); var wasUpgrade = false; function onUpgrade(res, socket, head) { console.log('client upgraded'); wasUpgrade = true; request.removeListener('upgrade', onUpgrade); socket.end(); } request.on('upgrade', onUpgrade); function onEnd() { console.log('client end'); request.removeListener('end', onEnd); if (!wasUpgrade) { throw new Error('hasn\'t received upgrade event'); } else { fn && process.nextTick(fn); } } request.on('close', onEnd); request.write('head'); } upgradeRequest(function() { successCount++; upgradeRequest(function() { successCount++; // Test pass console.log('Pass!'); server.close(); }); }); }); process.on('exit', function() { assert.equal(2, successCount); }); node-v0.10.25~dfsg2/test/simple/test-path-makelong.js0000644000000000000000000000404412270121457021131 0ustar rootroot// Copyright Joyent, Inc. and other Node contributors. // // Permission is hereby granted, free of charge, to any person obtaining a // copy of this software and associated documentation files (the // "Software"), to deal in the Software without restriction, including // without limitation the rights to use, copy, modify, merge, publish, // distribute, sublicense, and/or sell copies of the Software, and to permit // persons to whom the Software is furnished to do so, subject to the // following conditions: // // The above copyright notice and this permission notice shall be included // in all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS // OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF // MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN // NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, // DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR // OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE // USE OR OTHER DEALINGS IN THE SOFTWARE. var assert = require('assert'); var path = require('path'); var common = require('../common'); if (process.platform === 'win32') { var file = path.join(common.fixturesDir, 'a.js'); var resolvedFile = path.resolve(file); assert.equal('\\\\?\\' + resolvedFile, path._makeLong(file)); assert.equal('\\\\?\\' + resolvedFile, path._makeLong('\\\\?\\' + file)); assert.equal('\\\\?\\UNC\\someserver\\someshare\\somefile', path._makeLong('\\\\someserver\\someshare\\somefile')); assert.equal('\\\\?\\UNC\\someserver\\someshare\\somefile', path._makeLong('\\\\?\\UNC\\someserver\\someshare\\somefile')); assert.equal('\\\\.\\pipe\\somepipe', path._makeLong('\\\\.\\pipe\\somepipe')); } assert.equal(path._makeLong(null), null); assert.equal(path._makeLong(100), 100); assert.equal(path._makeLong(path), path); assert.equal(path._makeLong(false), false); assert.equal(path._makeLong(true), true); node-v0.10.25~dfsg2/test/simple/test-event-emitter-listeners-side-effects.js0000644000000000000000000000401312270121457025533 0ustar rootroot // Copyright Joyent, Inc. and other Node contributors. // // Permission is hereby granted, free of charge, to any person obtaining a // copy of this software and associated documentation files (the // "Software"), to deal in the Software without restriction, including // without limitation the rights to use, copy, modify, merge, publish, // distribute, sublicense, and/or sell copies of the Software, and to permit // persons to whom the Software is furnished to do so, subject to the // following conditions: // // The above copyright notice and this permission notice shall be included // in all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS // OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF // MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN // NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, // DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR // OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE // USE OR OTHER DEALINGS IN THE SOFTWARE. var common = require('../common'); var assert = require('assert'); var events = require('events'); var EventEmitter = require('events').EventEmitter; var assert = require('assert'); var e = new EventEmitter; var fl; // foo listeners fl = e.listeners('foo'); assert(Array.isArray(fl)); assert(fl.length === 0); assert.deepEqual(e._events, {}); e.on('foo', assert.fail); fl = e.listeners('foo'); assert(e._events.foo === assert.fail); assert(Array.isArray(fl)); assert(fl.length === 1); assert(fl[0] === assert.fail); e.listeners('bar'); assert(!e._events.hasOwnProperty('bar')); e.on('foo', assert.ok); fl = e.listeners('foo'); assert(Array.isArray(e._events.foo)); assert(e._events.foo.length === 2); assert(e._events.foo[0] === assert.fail); assert(e._events.foo[1] === assert.ok); assert(Array.isArray(fl)); assert(fl.length === 2); assert(fl[0] === assert.fail); assert(fl[1] === assert.ok); console.log('ok'); node-v0.10.25~dfsg2/test/simple/test-next-tick-ordering.js0000644000000000000000000000337712270121457022127 0ustar rootroot// Copyright Joyent, Inc. and other Node contributors. // // Permission is hereby granted, free of charge, to any person obtaining a // copy of this software and associated documentation files (the // "Software"), to deal in the Software without restriction, including // without limitation the rights to use, copy, modify, merge, publish, // distribute, sublicense, and/or sell copies of the Software, and to permit // persons to whom the Software is furnished to do so, subject to the // following conditions: // // The above copyright notice and this permission notice shall be included // in all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS // OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF // MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN // NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, // DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR // OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE // USE OR OTHER DEALINGS IN THE SOFTWARE. var common = require('../common'); var assert = require('assert'); var i; var N = 30; var done = []; function get_printer(timeout) { return function() { console.log('Running from setTimeout ' + timeout); done.push(timeout); }; } process.nextTick(function() { console.log('Running from nextTick'); done.push('nextTick'); }); for (i = 0; i < N; i += 1) { setTimeout(get_printer(i), i); } console.log('Running from main.'); process.on('exit', function() { assert.equal('nextTick', done[0]); /* Disabling this test. I don't think we can ensure the order for (i = 0; i < N; i += 1) { assert.equal(i, done[i + 1]); } */ }); node-v0.10.25~dfsg2/test/simple/test-http-buffer-sanity.js0000644000000000000000000000475712270121457022150 0ustar rootroot// Copyright Joyent, Inc. and other Node contributors. // // Permission is hereby granted, free of charge, to any person obtaining a // copy of this software and associated documentation files (the // "Software"), to deal in the Software without restriction, including // without limitation the rights to use, copy, modify, merge, publish, // distribute, sublicense, and/or sell copies of the Software, and to permit // persons to whom the Software is furnished to do so, subject to the // following conditions: // // The above copyright notice and this permission notice shall be included // in all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS // OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF // MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN // NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, // DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR // OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE // USE OR OTHER DEALINGS IN THE SOFTWARE. var common = require('../common'); var assert = require('assert'); var http = require('http'); var util = require('util'); var bufferSize = 5 * 1024 * 1024; var measuredSize = 0; var buffer = Buffer(bufferSize); for (var i = 0; i < buffer.length; i++) { buffer[i] = i % 256; } var web = http.Server(function(req, res) { web.close(); console.log(req.headers); var i = 0; req.on('data', function(d) { process.stdout.write(','); measuredSize += d.length; for (var j = 0; j < d.length; j++) { assert.equal(buffer[i], d[j]); i++; } }); req.on('end', function() { res.writeHead(200); res.write('thanks'); res.end(); console.log('response with \'thanks\''); }); req.connection.on('error', function(e) { console.log('http server-side error: ' + e.message); process.exit(1); }); }); var gotThanks = false; web.listen(common.PORT, function() { console.log('Making request'); var req = http.request({ port: common.PORT, method: 'GET', path: '/', headers: { 'content-length': buffer.length } }, function(res) { console.log('Got response'); res.setEncoding('utf8'); res.on('data', function(string) { assert.equal('thanks', string); gotThanks = true; }); }); req.end(buffer); }); process.on('exit', function() { assert.equal(bufferSize, measuredSize); assert.ok(gotThanks); }); node-v0.10.25~dfsg2/test/simple/test-fs-chmod.js0000644000000000000000000001023312270121457020077 0ustar rootroot// Copyright Joyent, Inc. and other Node contributors. // // Permission is hereby granted, free of charge, to any person obtaining a // copy of this software and associated documentation files (the // "Software"), to deal in the Software without restriction, including // without limitation the rights to use, copy, modify, merge, publish, // distribute, sublicense, and/or sell copies of the Software, and to permit // persons to whom the Software is furnished to do so, subject to the // following conditions: // // The above copyright notice and this permission notice shall be included // in all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS // OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF // MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN // NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, // DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR // OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE // USE OR OTHER DEALINGS IN THE SOFTWARE. var common = require('../common'); var assert = require('assert'); var path = require('path'); var fs = require('fs'); var got_error = false; var success_count = 0; var mode_async; var mode_sync; var is_windows = process.platform === 'win32'; // Need to hijack fs.open/close to make sure that things // get closed once they're opened. fs._open = fs.open; fs._openSync = fs.openSync; fs.open = open; fs.openSync = openSync; fs._close = fs.close; fs._closeSync = fs.closeSync; fs.close = close; fs.closeSync = closeSync; var openCount = 0; function open() { openCount++; return fs._open.apply(fs, arguments); } function openSync() { openCount++; return fs._openSync.apply(fs, arguments); } function close() { openCount--; return fs._close.apply(fs, arguments); } function closeSync() { openCount--; return fs._closeSync.apply(fs, arguments); } // On Windows chmod is only able to manipulate read-only bit if (is_windows) { mode_async = 0400; // read-only mode_sync = 0600; // read-write } else { mode_async = 0777; mode_sync = 0644; } var file1 = path.join(common.fixturesDir, 'a.js'), file2 = path.join(common.fixturesDir, 'a1.js'); fs.chmod(file1, mode_async.toString(8), function(err) { if (err) { got_error = true; } else { console.log(fs.statSync(file1).mode); if (is_windows) { assert.ok((fs.statSync(file1).mode & 0777) & mode_async); } else { assert.equal(mode_async, fs.statSync(file1).mode & 0777); } fs.chmodSync(file1, mode_sync); if (is_windows) { assert.ok((fs.statSync(file1).mode & 0777) & mode_sync); } else { assert.equal(mode_sync, fs.statSync(file1).mode & 0777); } success_count++; } }); fs.open(file2, 'a', function(err, fd) { if (err) { got_error = true; console.error(err.stack); return; } fs.fchmod(fd, mode_async.toString(8), function(err) { if (err) { got_error = true; } else { console.log(fs.fstatSync(fd).mode); if (is_windows) { assert.ok((fs.fstatSync(fd).mode & 0777) & mode_async); } else { assert.equal(mode_async, fs.fstatSync(fd).mode & 0777); } fs.fchmodSync(fd, mode_sync); if (is_windows) { assert.ok((fs.fstatSync(fd).mode & 0777) & mode_sync); } else { assert.equal(mode_sync, fs.fstatSync(fd).mode & 0777); } success_count++; fs.close(fd); } }); }); // lchmod if (fs.lchmod) { var link = path.join(common.tmpDir, 'symbolic-link'); try { fs.unlinkSync(link); } catch (er) {} fs.symlinkSync(file2, link); fs.lchmod(link, mode_async, function(err) { if (err) { got_error = true; } else { console.log(fs.lstatSync(link).mode); assert.equal(mode_async, fs.lstatSync(link).mode & 0777); fs.lchmodSync(link, mode_sync); assert.equal(mode_sync, fs.lstatSync(link).mode & 0777); success_count++; } }); } else { success_count++; } process.on('exit', function() { assert.equal(3, success_count); assert.equal(0, openCount); assert.equal(false, got_error); }); node-v0.10.25~dfsg2/test/simple/test-cluster-worker-disconnect.js0000644000000000000000000000623012270121457023520 0ustar rootroot// Copyright Joyent, Inc. and other Node contributors. // // Permission is hereby granted, free of charge, to any person obtaining a // copy of this software and associated documentation files (the // "Software"), to deal in the Software without restriction, including // without limitation the rights to use, copy, modify, merge, publish, // distribute, sublicense, and/or sell copies of the Software, and to permit // persons to whom the Software is furnished to do so, subject to the // following conditions: // // The above copyright notice and this permission notice shall be included // in all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS // OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF // MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN // NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, // DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR // OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE // USE OR OTHER DEALINGS IN THE SOFTWARE. var common = require('../common'); var assert = require('assert'); var cluster = require('cluster'); if (cluster.isWorker) { var http = require('http'); http.Server(function() { }).listen(common.PORT, '127.0.0.1'); } else if (cluster.isMaster) { var checks = { cluster: { emitDisconnect: false, emitExit: false, callback: false }, worker: { emitDisconnect: false, emitExit: false, state: false, suicideMode: false, died: false } }; // helper function to check if a process is alive var alive = function(pid) { try { process.kill(pid, 0); return true; } catch (e) { return false; } }; // start worker var worker = cluster.fork(); // Disconnect worker when it is ready worker.once('listening', function() { worker.disconnect(); }); // Check cluster events cluster.once('disconnect', function() { checks.cluster.emitDisconnect = true; }); cluster.once('exit', function() { checks.cluster.emitExit = true; }); // Check worker eventes and properties worker.once('disconnect', function() { checks.worker.emitDisconnect = true; checks.worker.suicideMode = worker.suicide; checks.worker.state = worker.state; }); // Check that the worker died worker.once('exit', function() { checks.worker.emitExit = true; checks.worker.died = !alive(worker.process.pid); process.nextTick(function() { process.exit(0); }); }); process.once('exit', function() { var w = checks.worker; var c = checks.cluster; // events assert.ok(w.emitDisconnect, 'Disconnect event did not emit'); assert.ok(c.emitDisconnect, 'Disconnect event did not emit'); assert.ok(w.emitExit, 'Exit event did not emit'); assert.ok(c.emitExit, 'Exit event did not emit'); // flags assert.equal(w.state, 'disconnected', 'The state property was not set'); assert.equal(w.suicideMode, true, 'Suicide mode was not set'); // is process alive assert.ok(w.died, 'The worker did not die'); }); } node-v0.10.25~dfsg2/test/simple/test-http-client-agent.js0000644000000000000000000000434412270121457021734 0ustar rootroot// Copyright Joyent, Inc. and other Node contributors. // // Permission is hereby granted, free of charge, to any person obtaining a // copy of this software and associated documentation files (the // "Software"), to deal in the Software without restriction, including // without limitation the rights to use, copy, modify, merge, publish, // distribute, sublicense, and/or sell copies of the Software, and to permit // persons to whom the Software is furnished to do so, subject to the // following conditions: // // The above copyright notice and this permission notice shall be included // in all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS // OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF // MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN // NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, // DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR // OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE // USE OR OTHER DEALINGS IN THE SOFTWARE. var common = require('../common'); var assert = require('assert'); var http = require('http'); var name = 'localhost:' + common.PORT; var max = 3; var count = 0; var server = http.Server(function(req, res) { if (req.url === '/0') { setTimeout(function() { res.writeHead(200); res.end('Hello, World!'); }, 100); } else { res.writeHead(200); res.end('Hello, World!'); } }); server.listen(common.PORT, function() { for (var i = 0; i < max; ++i) { request(i); } }); function request(i) { var req = http.get({ port: common.PORT, path: '/' + i }, function(res) { var socket = req.socket; socket.on('close', function() { ++count; if (count < max) { assert.equal(http.globalAgent.sockets[name].length, max - count); assert.equal(http.globalAgent.sockets[name].indexOf(socket), -1); } else { assert(!http.globalAgent.sockets.hasOwnProperty(name)); assert(!http.globalAgent.requests.hasOwnProperty(name)); server.close(); } }); res.resume(); }); } process.on('exit', function() { assert.equal(count, max); }); node-v0.10.25~dfsg2/test/simple/test-event-emitter-check-listener-leaks.js0000644000000000000000000000407012270121457025164 0ustar rootroot// Copyright Joyent, Inc. and other Node contributors. // // Permission is hereby granted, free of charge, to any person obtaining a // copy of this software and associated documentation files (the // "Software"), to deal in the Software without restriction, including // without limitation the rights to use, copy, modify, merge, publish, // distribute, sublicense, and/or sell copies of the Software, and to permit // persons to whom the Software is furnished to do so, subject to the // following conditions: // // The above copyright notice and this permission notice shall be included // in all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS // OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF // MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN // NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, // DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR // OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE // USE OR OTHER DEALINGS IN THE SOFTWARE. var common = require('../common'); var assert = require('assert'); var events = require('events'); var e = new events.EventEmitter(); // default for (var i = 0; i < 10; i++) { e.on('default', function() {}); } assert.ok(!e._events['default'].hasOwnProperty('warned')); e.on('default', function() {}); assert.ok(e._events['default'].warned); // specific e.setMaxListeners(5); for (var i = 0; i < 5; i++) { e.on('specific', function() {}); } assert.ok(!e._events['specific'].hasOwnProperty('warned')); e.on('specific', function() {}); assert.ok(e._events['specific'].warned); // only one e.setMaxListeners(1); e.on('only one', function() {}); assert.ok(!e._events['only one'].hasOwnProperty('warned')); e.on('only one', function() {}); assert.ok(e._events['only one'].hasOwnProperty('warned')); // unlimited e.setMaxListeners(0); for (var i = 0; i < 1000; i++) { e.on('unlimited', function() {}); } assert.ok(!e._events['unlimited'].hasOwnProperty('warned')); node-v0.10.25~dfsg2/test/simple/test-next-tick-starvation.js0000644000000000000000000000310112270121457022471 0ustar rootroot// Copyright Joyent, Inc. and other Node contributors. // // Permission is hereby granted, free of charge, to any person obtaining a // copy of this software and associated documentation files (the // "Software"), to deal in the Software without restriction, including // without limitation the rights to use, copy, modify, merge, publish, // distribute, sublicense, and/or sell copies of the Software, and to permit // persons to whom the Software is furnished to do so, subject to the // following conditions: // // The above copyright notice and this permission notice shall be included // in all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS // OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF // MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN // NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, // DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR // OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE // USE OR OTHER DEALINGS IN THE SOFTWARE. var common = require('../common'); var assert = require('assert'); var ran = false; var stop = false; var start = +new Date(); function spin() { var now = +new Date(); if (now - start > 100) { throw new Error('The timer is starving'); } if (!stop) { ran = true; process.nextTick(spin); } } function onTimeout() { stop = true; } spin(); setTimeout(onTimeout, 50); process.on('exit', function() { assert.ok(ran); assert.ok(stop); }); node-v0.10.25~dfsg2/test/simple/test-require-exceptions.js0000644000000000000000000000330212270121457022231 0ustar rootroot// Copyright Joyent, Inc. and other Node contributors. // // Permission is hereby granted, free of charge, to any person obtaining a // copy of this software and associated documentation files (the // "Software"), to deal in the Software without restriction, including // without limitation the rights to use, copy, modify, merge, publish, // distribute, sublicense, and/or sell copies of the Software, and to permit // persons to whom the Software is furnished to do so, subject to the // following conditions: // // The above copyright notice and this permission notice shall be included // in all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS // OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF // MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN // NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, // DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR // OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE // USE OR OTHER DEALINGS IN THE SOFTWARE. var common = require('../common'); var assert = require('assert'); // A module with an error in it should throw assert.throws(function() { require(common.fixturesDir + '/throws_error'); }); // Requiring the same module again should throw as well assert.throws(function() { require(common.fixturesDir + '/throws_error'); }); // Requiring a module that does not exist should throw an // error with its `code` set to MODULE_NOT_FOUND assert.throws(function() { require(common.fixturesDir + '/DOES_NOT_EXIST'); }, function(e) { assert.equal('MODULE_NOT_FOUND', e.code); return true; }); node-v0.10.25~dfsg2/test/simple/test-fs-read-stream-err.js0000644000000000000000000000407112270121457022002 0ustar rootroot// Copyright Joyent, Inc. and other Node contributors. // // Permission is hereby granted, free of charge, to any person obtaining a // copy of this software and associated documentation files (the // "Software"), to deal in the Software without restriction, including // without limitation the rights to use, copy, modify, merge, publish, // distribute, sublicense, and/or sell copies of the Software, and to permit // persons to whom the Software is furnished to do so, subject to the // following conditions: // // The above copyright notice and this permission notice shall be included // in all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS // OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF // MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN // NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, // DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR // OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE // USE OR OTHER DEALINGS IN THE SOFTWARE. var common = require('../common'); var assert = require('assert'); var fs = require('fs'); var stream = fs.createReadStream(__filename, { bufferSize: 64 }); var err = new Error('BAM'); stream.on('error', common.mustCall(function errorHandler(err_) { console.error('error event'); process.nextTick(function() { assert.equal(stream.fd, null); assert.equal(err_, err); }); })); fs.close = common.mustCall(function(fd_, cb) { assert.equal(fd_, stream.fd); process.nextTick(cb); }); var read = fs.read; fs.read = function() { // first time is ok. read.apply(fs, arguments); // then it breaks fs.read = function() { var cb = arguments[arguments.length - 1]; process.nextTick(function() { cb(err); }); // and should not be called again! fs.read = function() { throw new Error('BOOM!'); }; }; }; stream.on('data', function(buf) { stream.on('data', assert.fail); // no more 'data' events should follow }); node-v0.10.25~dfsg2/test/simple/test-http-agent-destroyed-socket.js0000644000000000000000000000730012270121457023741 0ustar rootroot// Copyright Joyent, Inc. and other Node contributors. // // Permission is hereby granted, free of charge, to any person obtaining a // copy of this software and associated documentation files (the // "Software"), to deal in the Software without restriction, including // without limitation the rights to use, copy, modify, merge, publish, // distribute, sublicense, and/or sell copies of the Software, and to permit // persons to whom the Software is furnished to do so, subject to the // following conditions: // // The above copyright notice and this permission notice shall be included // in all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS // OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF // MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN // NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, // DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR // OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE // USE OR OTHER DEALINGS IN THE SOFTWARE. var common = require('../common'); var assert = require('assert'); var http = require('http'); var server = http.createServer(function(req, res) { res.writeHead(200, {'Content-Type': 'text/plain'}); res.end('Hello World\n'); }).listen(common.PORT); var agent = new http.Agent({maxSockets: 1}); agent.on('free', function(socket, host, port) { console.log('freeing socket. destroyed? ', socket.destroyed); }); var requestOptions = { agent: agent, host: 'localhost', port: common.PORT, path: '/' }; var request1 = http.get(requestOptions, function(response) { // assert request2 is queued in the agent var key = 'localhost:' + common.PORT; assert(agent.requests[key].length === 1); console.log('got response1'); request1.socket.on('close', function() { console.log('request1 socket closed'); }); response.pipe(process.stdout); response.on('end', function() { console.log('response1 done'); ///////////////////////////////// // // THE IMPORTANT PART // // It is possible for the socket to get destroyed and other work // to run before the 'close' event fires because it happens on // nextTick. This example is contrived because it destroys the // socket manually at just the right time, but at Voxer we have // seen cases where the socket is destroyed by non-user code // then handed out again by an agent *before* the 'close' event // is triggered. request1.socket.destroy(); response.once('close', function() { // assert request2 was removed from the queue assert(!agent.requests[key]); console.log("waiting for request2.onSocket's nextTick"); process.nextTick(function() { // assert that the same socket was not assigned to request2, // since it was destroyed. assert(request1.socket !== request2.socket); assert(!request2.socket.destroyed, 'the socket is destroyed'); }); }); }); }); var request2 = http.get(requestOptions, function(response) { assert(!request2.socket.destroyed); assert(request1.socket.destroyed); // assert not reusing the same socket, since it was destroyed. assert(request1.socket !== request2.socket); console.log('got response2'); var gotClose = false; var gotResponseEnd = false; request2.socket.on('close', function() { console.log('request2 socket closed'); gotClose = true; done(); }); response.pipe(process.stdout); response.on('end', function() { console.log('response2 done'); gotResponseEnd = true; done(); }); function done() { if (gotResponseEnd && gotClose) server.close(); } }); node-v0.10.25~dfsg2/test/simple/test-http-abort-before-end.js0000644000000000000000000000325412270121457022474 0ustar rootroot// Copyright Joyent, Inc. and other Node contributors. // // Permission is hereby granted, free of charge, to any person obtaining a // copy of this software and associated documentation files (the // "Software"), to deal in the Software without restriction, including // without limitation the rights to use, copy, modify, merge, publish, // distribute, sublicense, and/or sell copies of the Software, and to permit // persons to whom the Software is furnished to do so, subject to the // following conditions: // // The above copyright notice and this permission notice shall be included // in all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS // OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF // MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN // NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, // DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR // OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE // USE OR OTHER DEALINGS IN THE SOFTWARE. var common = require('../common'); var http = require('http'); var assert = require('assert'); var server = http.createServer(function(req, res) { assert(false); // should not be called }); server.listen(common.PORT, function() { var req = http.request({method: 'GET', host: '127.0.0.1', port: common.PORT}); req.on('error', function(ex) { // https://github.com/joyent/node/issues/1399#issuecomment-2597359 // abort() should emit an Error, not the net.Socket object assert(ex instanceof Error); }); req.abort(); req.end(); server.close(); }); node-v0.10.25~dfsg2/test/simple/test-http-timeout.js0000644000000000000000000000362512270121457021051 0ustar rootroot// Copyright Joyent, Inc. and other Node contributors. // // Permission is hereby granted, free of charge, to any person obtaining a // copy of this software and associated documentation files (the // "Software"), to deal in the Software without restriction, including // without limitation the rights to use, copy, modify, merge, publish, // distribute, sublicense, and/or sell copies of the Software, and to permit // persons to whom the Software is furnished to do so, subject to the // following conditions: // // The above copyright notice and this permission notice shall be included // in all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS // OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF // MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN // NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, // DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR // OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE // USE OR OTHER DEALINGS IN THE SOFTWARE. var common = require('../common'); var assert = require('assert'); var http = require('http'); var port = common.PORT; var server = http.createServer(function(req, res) { res.writeHead(200, {'Content-Type': 'text/plain'}); res.end('OK'); }); var agent = new http.Agent({maxSockets: 1}); server.listen(port, function() { for (var i = 0; i < 11; ++i) { createRequest().end(); } function callback(){} var count = 0; function createRequest() { var req = http.request({port: port, path: '/', agent: agent}, function(res) { req.clearTimeout(callback); res.on('end', function() { count++; if (count == 11) { server.close(); } }) res.resume(); }); req.setTimeout(1000, callback); return req; } }); node-v0.10.25~dfsg2/test/simple/test-zlib-from-gzip.js0000644000000000000000000000376612270121457021264 0ustar rootroot// Copyright Joyent, Inc. and other Node contributors. // // Permission is hereby granted, free of charge, to any person obtaining a // copy of this software and associated documentation files (the // "Software"), to deal in the Software without restriction, including // without limitation the rights to use, copy, modify, merge, publish, // distribute, sublicense, and/or sell copies of the Software, and to permit // persons to whom the Software is furnished to do so, subject to the // following conditions: // // The above copyright notice and this permission notice shall be included // in all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS // OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF // MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN // NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, // DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR // OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE // USE OR OTHER DEALINGS IN THE SOFTWARE. // test unzipping a file that was created with a non-node gzip lib, // piped in as fast as possible. var common = require('../common.js'); var assert = require('assert'); var zlib = require('zlib'); var path = require('path'); var gunzip = zlib.createGunzip(); var fs = require('fs'); var fixture = path.resolve(common.fixturesDir, 'person.jpg.gz'); var unzippedFixture = path.resolve(common.fixturesDir, 'person.jpg'); var outputFile = path.resolve(common.tmpDir, 'person.jpg'); var expect = fs.readFileSync(unzippedFixture); var inp = fs.createReadStream(fixture); var out = fs.createWriteStream(outputFile); inp.pipe(gunzip).pipe(out); out.on('close', function() { var actual = fs.readFileSync(outputFile); assert.equal(actual.length, expect.length, 'length should match'); for (var i = 0, l = actual.length; i < l; i++) { assert.equal(actual[i], expect[i], 'byte[' + i + ']'); } }); node-v0.10.25~dfsg2/test/simple/test-child-process-double-pipe.js0000644000000000000000000000616312270121457023350 0ustar rootroot// Copyright Joyent, Inc. and other Node contributors. // // Permission is hereby granted, free of charge, to any person obtaining a // copy of this software and associated documentation files (the // "Software"), to deal in the Software without restriction, including // without limitation the rights to use, copy, modify, merge, publish, // distribute, sublicense, and/or sell copies of the Software, and to permit // persons to whom the Software is furnished to do so, subject to the // following conditions: // // The above copyright notice and this permission notice shall be included // in all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS // OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF // MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN // NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, // DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR // OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE // USE OR OTHER DEALINGS IN THE SOFTWARE. var is_windows = process.platform === 'win32'; var common = require('../common'); var assert = require('assert'), util = require('util'), spawn = require('child_process').spawn; // We're trying to reproduce: // $ echo "hello\nnode\nand\nworld" | grep o | sed s/o/a/ var grep = spawn('grep', ['o']), sed = spawn('sed', ['s/o/O/']), echo; if (is_windows) { echo = spawn('cmd.exe', ['/c', 'echo', 'hello&&', 'echo', 'node&&', 'echo', 'and&&', 'echo', 'world']); } else { echo = spawn('echo', ['hello\nnode\nand\nworld\n']); } /* * grep and sed hang if the spawn function leaks file descriptors to child * processes. * This happens when calling pipe(2) and then forgetting to set the * FD_CLOEXEC flag on the resulting file descriptors. * * This test checks child processes exit, meaning they don't hang like * explained above. */ // pipe echo | grep echo.stdout.on('data', function(data) { console.error('grep stdin write ' + data.length); if (!grep.stdin.write(data)) { echo.stdout.pause(); } }); grep.stdin.on('drain', function(data) { echo.stdout.resume(); }); // propagate end from echo to grep echo.stdout.on('end', function(code) { grep.stdin.end(); }); echo.on('exit', function() { console.error('echo exit'); }); grep.on('exit', function() { console.error('grep exit'); }); sed.on('exit', function() { console.error('sed exit'); }); // pipe grep | sed grep.stdout.on('data', function(data) { console.error('grep stdout ' + data.length); if (!sed.stdin.write(data)) { grep.stdout.pause(); } }); sed.stdin.on('drain', function(data) { grep.stdout.resume(); }); // propagate end from grep to sed grep.stdout.on('end', function(code) { console.error('grep stdout end'); sed.stdin.end(); }); var result = ''; // print sed's output sed.stdout.on('data', function(data) { result += data.toString('utf8', 0, data.length); util.print(data); }); sed.stdout.on('end', function(code) { assert.equal(result, 'hellO\nnOde\nwOrld\n'); }); node-v0.10.25~dfsg2/test/simple/test-tls-remote.js0000644000000000000000000000457212270121457020503 0ustar rootroot// Copyright Joyent, Inc. and other Node contributors. // // Permission is hereby granted, free of charge, to any person obtaining a // copy of this software and associated documentation files (the // "Software"), to deal in the Software without restriction, including // without limitation the rights to use, copy, modify, merge, publish, // distribute, sublicense, and/or sell copies of the Software, and to permit // persons to whom the Software is furnished to do so, subject to the // following conditions: // // The above copyright notice and this permission notice shall be included // in all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS // OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF // MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN // NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, // DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR // OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE // USE OR OTHER DEALINGS IN THE SOFTWARE. if (!process.versions.openssl) { console.error('Skipping because node compiled without OpenSSL.'); process.exit(0); } var common = require('../common'); var assert = require('assert'); var tls = require('tls'); var fs = require('fs'); var path = require('path'); var options = { key: fs.readFileSync(path.join(common.fixturesDir, 'test_key.pem')), cert: fs.readFileSync(path.join(common.fixturesDir, 'test_cert.pem')) }; var server = tls.Server(options, function(s) { assert.equal(s.address().address, s.socket.address().address); assert.equal(s.address().port, s.socket.address().port); assert.equal(s.remoteAddress, s.socket.remoteAddress); assert.equal(s.remotePort, s.socket.remotePort); s.end(); }); server.listen(common.PORT, '127.0.0.1', function() { assert.equal(server.address().address, '127.0.0.1'); assert.equal(server.address().port, common.PORT); var c = tls.connect({ host: '127.0.0.1', port: common.PORT, rejectUnauthorized: false }, function() { assert.equal(c.address().address, c.socket.address().address); assert.equal(c.address().port, c.socket.address().port); assert.equal(c.remoteAddress, '127.0.0.1'); assert.equal(c.remotePort, common.PORT); }); c.on('end', function() { server.close(); }); }); node-v0.10.25~dfsg2/test/simple/test-stdout-to-file.js0000644000000000000000000000457312270121457021270 0ustar rootroot// Copyright Joyent, Inc. and other Node contributors. // // Permission is hereby granted, free of charge, to any person obtaining a // copy of this software and associated documentation files (the // "Software"), to deal in the Software without restriction, including // without limitation the rights to use, copy, modify, merge, publish, // distribute, sublicense, and/or sell copies of the Software, and to permit // persons to whom the Software is furnished to do so, subject to the // following conditions: // // The above copyright notice and this permission notice shall be included // in all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS // OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF // MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN // NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, // DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR // OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE // USE OR OTHER DEALINGS IN THE SOFTWARE. var common = require('../common'); var assert = require('assert'); var path = require('path'); var childProccess = require('child_process'); var fs = require('fs'); var scriptString = path.join(common.fixturesDir, 'print-chars.js'); var scriptBuffer = path.join(common.fixturesDir, 'print-chars-from-buffer.js'); var tmpFile = path.join(common.tmpDir, 'stdout.txt'); function test(size, useBuffer, cb) { var cmd = '"' + process.argv[0] + '"' + ' ' + '"' + (useBuffer ? scriptBuffer : scriptString) + '"' + ' ' + size + ' > ' + '"' + tmpFile + '"'; try { fs.unlinkSync(tmpFile); } catch (e) {} common.print(size + ' chars to ' + tmpFile + '...'); childProccess.exec(cmd, function(err) { if (err) throw err; console.log('done!'); var stat = fs.statSync(tmpFile); console.log(tmpFile + ' has ' + stat.size + ' bytes'); assert.equal(size, stat.size); fs.unlinkSync(tmpFile); cb(); }); } var finished = false; test(1024 * 1024, false, function() { console.log('Done printing with string'); test(1024 * 1024, true, function() { console.log('Done printing with buffer'); finished = true; }); }); process.on('exit', function() { assert.ok(finished); }); node-v0.10.25~dfsg2/test/simple/test-cluster-master-kill.js0000644000000000000000000000524412270121457022310 0ustar rootroot// Copyright Joyent, Inc. and other Node contributors. // // Permission is hereby granted, free of charge, to any person obtaining a // copy of this software and associated documentation files (the // "Software"), to deal in the Software without restriction, including // without limitation the rights to use, copy, modify, merge, publish, // distribute, sublicense, and/or sell copies of the Software, and to permit // persons to whom the Software is furnished to do so, subject to the // following conditions: // // The above copyright notice and this permission notice shall be included // in all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS // OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF // MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN // NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, // DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR // OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE // USE OR OTHER DEALINGS IN THE SOFTWARE. var common = require('../common'); var assert = require('assert'); var cluster = require('cluster'); if (cluster.isWorker) { // keep the worker alive var http = require('http'); http.Server().listen(common.PORT, '127.0.0.1'); } else if (process.argv[2] === 'cluster') { var worker = cluster.fork(); // send PID info to testcase process process.send({ pid: worker.process.pid }); // terminate the cluster process worker.once('listening', function() { setTimeout(function() { process.exit(0); }, 1000); }); } else { // This is the testcase var fork = require('child_process').fork; // is process alive helper var isAlive = function(pid) { try { //this will throw an error if the process is dead process.kill(pid, 0); return true; } catch (e) { return false; } }; // Spawn a cluster process var master = fork(process.argv[1], ['cluster']); // get pid info var pid = null; master.once('message', function(data) { pid = data.pid; }); // When master is dead var alive = true; master.on('exit', function(code) { // make sure that the master died by purpose assert.equal(code, 0); // check worker process status setTimeout(function() { alive = isAlive(pid); }, 200); }); process.once('exit', function() { // cleanup: kill the worker if alive if (alive) { process.kill(pid); } assert.equal(typeof pid, 'number', 'did not get worker pid info'); assert.equal(alive, false, 'worker was alive after master died'); }); } node-v0.10.25~dfsg2/test/simple/test-stream2-basic.js0000644000000000000000000002364212270121457021043 0ustar rootroot// Copyright Joyent, Inc. and other Node contributors. // // Permission is hereby granted, free of charge, to any person obtaining a // copy of this software and associated documentation files (the // "Software"), to deal in the Software without restriction, including // without limitation the rights to use, copy, modify, merge, publish, // distribute, sublicense, and/or sell copies of the Software, and to permit // persons to whom the Software is furnished to do so, subject to the // following conditions: // // The above copyright notice and this permission notice shall be included // in all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS // OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF // MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN // NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, // DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR // OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE // USE OR OTHER DEALINGS IN THE SOFTWARE. var common = require('../common.js'); var R = require('_stream_readable'); var assert = require('assert'); var util = require('util'); var EE = require('events').EventEmitter; function TestReader(n) { R.apply(this); this._buffer = new Buffer(n || 100); this._buffer.fill('x'); this._pos = 0; this._bufs = 10; } util.inherits(TestReader, R); TestReader.prototype.read = function(n) { if (n === 0) return null; var max = this._buffer.length - this._pos; n = n || max; n = Math.max(n, 0); var toRead = Math.min(n, max); if (toRead === 0) { // simulate the read buffer filling up with some more bytes some time // in the future. setTimeout(function() { this._pos = 0; this._bufs -= 1; if (this._bufs <= 0) { // read them all! if (!this.ended) { this.emit('end'); this.ended = true; } } else { this.emit('readable'); } }.bind(this), 10); return null; } var ret = this._buffer.slice(this._pos, this._pos + toRead); this._pos += toRead; return ret; }; ///// function TestWriter() { EE.apply(this); this.received = []; this.flush = false; } util.inherits(TestWriter, EE); TestWriter.prototype.write = function(c) { this.received.push(c.toString()); this.emit('write', c); return true; }; TestWriter.prototype.end = function(c) { if (c) this.write(c); this.emit('end', this.received); }; //////// // tiny node-tap lookalike. var tests = []; var count = 0; function test(name, fn) { count++; tests.push([name, fn]); } function run() { var next = tests.shift(); if (!next) return console.error('ok'); var name = next[0]; var fn = next[1]; console.log('# %s', name); fn({ same: assert.deepEqual, ok: assert, equal: assert.equal, end: function () { count--; run(); } }); } // ensure all tests have run process.on("exit", function () { assert.equal(count, 0); }); process.nextTick(run); test('a most basic test', function(t) { var r = new TestReader(20); var reads = []; var expect = [ 'x', 'xx', 'xxx', 'xxxx', 'xxxxx', 'xxxxx', 'xxxxxxxx', 'xxxxxxxxx', 'xxx', 'xxxxxxxxxxxx', 'xxxxxxxx', 'xxxxxxxxxxxxxxx', 'xxxxx', 'xxxxxxxxxxxxxxxxxx', 'xx', 'xxxxxxxxxxxxxxxxxxxx', 'xxxxxxxxxxxxxxxxxxxx', 'xxxxxxxxxxxxxxxxxxxx', 'xxxxxxxxxxxxxxxxxxxx', 'xxxxxxxxxxxxxxxxxxxx' ]; r.on('end', function() { t.same(reads, expect); t.end(); }); var readSize = 1; function flow() { var res; while (null !== (res = r.read(readSize++))) { reads.push(res.toString()); } r.once('readable', flow); } flow(); }); test('pipe', function(t) { var r = new TestReader(5); var expect = [ 'xxxxx', 'xxxxx', 'xxxxx', 'xxxxx', 'xxxxx', 'xxxxx', 'xxxxx', 'xxxxx', 'xxxxx', 'xxxxx' ] var w = new TestWriter; var flush = true; w.on('end', function(received) { t.same(received, expect); t.end(); }); r.pipe(w); }); [1,2,3,4,5,6,7,8,9].forEach(function(SPLIT) { test('unpipe', function(t) { var r = new TestReader(5); // unpipe after 3 writes, then write to another stream instead. var expect = [ 'xxxxx', 'xxxxx', 'xxxxx', 'xxxxx', 'xxxxx', 'xxxxx', 'xxxxx', 'xxxxx', 'xxxxx', 'xxxxx' ]; expect = [ expect.slice(0, SPLIT), expect.slice(SPLIT) ]; var w = [ new TestWriter(), new TestWriter() ]; var writes = SPLIT; w[0].on('write', function() { if (--writes === 0) { r.unpipe(); t.equal(r._readableState.pipes, null); w[0].end(); r.pipe(w[1]); t.equal(r._readableState.pipes, w[1]); } }); var ended = 0; var ended0 = false; var ended1 = false; w[0].on('end', function(results) { t.equal(ended0, false); ended0 = true; ended++; t.same(results, expect[0]); }); w[1].on('end', function(results) { t.equal(ended1, false); ended1 = true; ended++; t.equal(ended, 2); t.same(results, expect[1]); t.end(); }); r.pipe(w[0]); }); }); // both writers should get the same exact data. test('multipipe', function(t) { var r = new TestReader(5); var w = [ new TestWriter, new TestWriter ]; var expect = [ 'xxxxx', 'xxxxx', 'xxxxx', 'xxxxx', 'xxxxx', 'xxxxx', 'xxxxx', 'xxxxx', 'xxxxx', 'xxxxx' ]; var c = 2; w[0].on('end', function(received) { t.same(received, expect, 'first'); if (--c === 0) t.end(); }); w[1].on('end', function(received) { t.same(received, expect, 'second'); if (--c === 0) t.end(); }); r.pipe(w[0]); r.pipe(w[1]); }); [1,2,3,4,5,6,7,8,9].forEach(function(SPLIT) { test('multi-unpipe', function(t) { var r = new TestReader(5); // unpipe after 3 writes, then write to another stream instead. var expect = [ 'xxxxx', 'xxxxx', 'xxxxx', 'xxxxx', 'xxxxx', 'xxxxx', 'xxxxx', 'xxxxx', 'xxxxx', 'xxxxx' ]; expect = [ expect.slice(0, SPLIT), expect.slice(SPLIT) ]; var w = [ new TestWriter(), new TestWriter(), new TestWriter() ]; var writes = SPLIT; w[0].on('write', function() { if (--writes === 0) { r.unpipe(); w[0].end(); r.pipe(w[1]); } }); var ended = 0; w[0].on('end', function(results) { ended++; t.same(results, expect[0]); }); w[1].on('end', function(results) { ended++; t.equal(ended, 2); t.same(results, expect[1]); t.end(); }); r.pipe(w[0]); r.pipe(w[2]); }); }); test('back pressure respected', function (t) { function noop() {} var r = new R({ objectMode: true }); r._read = noop; var counter = 0; r.push(["one"]); r.push(["two"]); r.push(["three"]); r.push(["four"]); r.push(null); var w1 = new R(); w1.write = function (chunk) { assert.equal(chunk[0], "one"); w1.emit("close"); process.nextTick(function () { r.pipe(w2); r.pipe(w3); }) }; w1.end = noop; r.pipe(w1); var expected = ["two", "two", "three", "three", "four", "four"]; var w2 = new R(); w2.write = function (chunk) { assert.equal(chunk[0], expected.shift()); assert.equal(counter, 0); counter++; if (chunk[0] === "four") { return true; } setTimeout(function () { counter--; w2.emit("drain"); }, 10); return false; } w2.end = noop; var w3 = new R(); w3.write = function (chunk) { assert.equal(chunk[0], expected.shift()); assert.equal(counter, 1); counter++; if (chunk[0] === "four") { return true; } setTimeout(function () { counter--; w3.emit("drain"); }, 50); return false; }; w3.end = function () { assert.equal(counter, 2); assert.equal(expected.length, 0); t.end(); }; }); test('read(0) for ended streams', function (t) { var r = new R(); var written = false; var ended = false; r._read = function (n) {}; r.push(new Buffer("foo")); r.push(null); var v = r.read(0); assert.equal(v, null); var w = new R(); w.write = function (buffer) { written = true; assert.equal(ended, false); assert.equal(buffer.toString(), "foo") }; w.end = function () { ended = true; assert.equal(written, true); t.end(); }; r.pipe(w); }) test('sync _read ending', function (t) { var r = new R(); var called = false; r._read = function (n) { r.push(null); }; r.once('end', function () { called = true; }) r.read(); process.nextTick(function () { assert.equal(called, true); t.end(); }) }); test('adding readable triggers data flow', function(t) { var r = new R({ highWaterMark: 5 }); var onReadable = false; var readCalled = 0; r._read = function(n) { if (readCalled++ === 2) r.push(null); else r.push(new Buffer('asdf')); }; var called = false; r.on('readable', function() { onReadable = true; r.read(); }); r.on('end', function() { t.equal(readCalled, 3); t.ok(onReadable); t.end(); }); }); node-v0.10.25~dfsg2/test/simple/test-file-write-stream.js0000644000000000000000000000516212270121457021744 0ustar rootroot// Copyright Joyent, Inc. and other Node contributors. // // Permission is hereby granted, free of charge, to any person obtaining a // copy of this software and associated documentation files (the // "Software"), to deal in the Software without restriction, including // without limitation the rights to use, copy, modify, merge, publish, // distribute, sublicense, and/or sell copies of the Software, and to permit // persons to whom the Software is furnished to do so, subject to the // following conditions: // // The above copyright notice and this permission notice shall be included // in all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS // OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF // MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN // NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, // DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR // OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE // USE OR OTHER DEALINGS IN THE SOFTWARE. var common = require('../common'); var assert = require('assert'); var path = require('path'); var fs = require('fs'); var fn = path.join(common.tmpDir, 'write.txt'); var file = fs.createWriteStream(fn, { highWaterMark: 10 }); var EXPECTED = '012345678910'; var callbacks = { open: -1, drain: -2, close: -1 }; file .on('open', function(fd) { console.error('open!'); callbacks.open++; assert.equal('number', typeof fd); }) .on('error', function(err) { throw err; console.error('error!', err.stack); }) .on('drain', function() { console.error('drain!', callbacks.drain); callbacks.drain++; if (callbacks.drain == -1) { assert.equal(EXPECTED, fs.readFileSync(fn, 'utf8')); file.write(EXPECTED); } else if (callbacks.drain == 0) { assert.equal(EXPECTED + EXPECTED, fs.readFileSync(fn, 'utf8')); file.end(); } }) .on('close', function() { console.error('close!'); assert.strictEqual(file.bytesWritten, EXPECTED.length * 2); callbacks.close++; assert.throws(function() { console.error('write after end should not be allowed'); file.write('should not work anymore'); }); fs.unlinkSync(fn); }); for (var i = 0; i < 11; i++) { (function(i) { file.write('' + i); })(i); } process.on('exit', function() { for (var k in callbacks) { assert.equal(0, callbacks[k], k + ' count off by ' + callbacks[k]); } console.log('ok'); }); node-v0.10.25~dfsg2/test/simple/test-buffer-ascii.js0000644000000000000000000000367312270121457020750 0ustar rootroot// Copyright Joyent, Inc. and other Node contributors. // // Permission is hereby granted, free of charge, to any person obtaining a // copy of this software and associated documentation files (the // "Software"), to deal in the Software without restriction, including // without limitation the rights to use, copy, modify, merge, publish, // distribute, sublicense, and/or sell copies of the Software, and to permit // persons to whom the Software is furnished to do so, subject to the // following conditions: // // The above copyright notice and this permission notice shall be included // in all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS // OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF // MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN // NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, // DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR // OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE // USE OR OTHER DEALINGS IN THE SOFTWARE. var common = require('../common'); var assert = require('assert'); // ASCII conversion in node.js simply masks off the high bits, // it doesn't do transliteration. assert.equal(Buffer('hérité').toString('ascii'), 'hC)ritC)'); // 71 characters, 78 bytes. The ’ character is a triple-byte sequence. var input = 'C’est, graphiquement, la réunion d’un accent aigu ' + 'et d’un accent grave.'; var expected = 'Cb\u0000\u0019est, graphiquement, la rC)union ' + 'db\u0000\u0019un accent aigu et db\u0000\u0019un ' + 'accent grave.'; var buf = Buffer(input); for (var i = 0; i < expected.length; ++i) { assert.equal(buf.slice(i).toString('ascii'), expected.slice(i)); // Skip remainder of multi-byte sequence. if (input.charCodeAt(i) > 65535) ++i; if (input.charCodeAt(i) > 127) ++i; } node-v0.10.25~dfsg2/test/simple/test-domain-stack.js0000644000000000000000000000325012270121457020752 0ustar rootroot// Copyright Joyent, Inc. and other Node contributors. // // Permission is hereby granted, free of charge, to any person obtaining a // copy of this software and associated documentation files (the // "Software"), to deal in the Software without restriction, including // without limitation the rights to use, copy, modify, merge, publish, // distribute, sublicense, and/or sell copies of the Software, and to permit // persons to whom the Software is furnished to do so, subject to the // following conditions: // // The above copyright notice and this permission notice shall be included // in all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS // OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF // MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN // NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, // DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR // OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE // USE OR OTHER DEALINGS IN THE SOFTWARE. // Make sure that the domain stack doesn't get out of hand. var common = require('../common'); var assert = require('assert'); var domain = require('domain'); var events = require('events'); var a = domain.create(); a.name = 'a'; a.on('error', function() { if (domain._stack.length > 5) { console.error('leaking!', domain._stack); process.exit(1); } }); var foo = a.bind(function() { throw new Error('error from foo'); }); for (var i = 0; i < 1000; i++) { process.nextTick(foo); } process.on('exit', function(c) { if (!c) console.log('ok'); }); node-v0.10.25~dfsg2/test/simple/test-http-set-timeout.js0000644000000000000000000000357712270121457021650 0ustar rootroot// Copyright Joyent, Inc. and other Node contributors. // // Permission is hereby granted, free of charge, to any person obtaining a // copy of this software and associated documentation files (the // "Software"), to deal in the Software without restriction, including // without limitation the rights to use, copy, modify, merge, publish, // distribute, sublicense, and/or sell copies of the Software, and to permit // persons to whom the Software is furnished to do so, subject to the // following conditions: // // The above copyright notice and this permission notice shall be included // in all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS // OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF // MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN // NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, // DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR // OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE // USE OR OTHER DEALINGS IN THE SOFTWARE. var common = require('../common'); var assert = require('assert'); var http = require('http'); var server = http.createServer(function(req, res) { console.log('got request. setting 1 second timeout'); req.connection.setTimeout(500); req.connection.on('timeout', function() { req.connection.destroy(); common.debug('TIMEOUT'); server.close(); }); }); server.listen(common.PORT, function() { console.log('Server running at http://127.0.0.1:' + common.PORT + '/'); var errorTimer = setTimeout(function() { throw new Error('Timeout was not successful'); }, 2000); var x = http.get({port: common.PORT, path: '/'}); x.on('error', function() { clearTimeout(errorTimer); console.log('HTTP REQUEST COMPLETE (this is good)'); }); x.end(); }); node-v0.10.25~dfsg2/test/simple/test-child-process-fork-net.js0000644000000000000000000001400012270121457022655 0ustar rootroot// Copyright Joyent, Inc. and other Node contributors. // // Permission is hereby granted, free of charge, to any person obtaining a // copy of this software and associated documentation files (the // "Software"), to deal in the Software without restriction, including // without limitation the rights to use, copy, modify, merge, publish, // distribute, sublicense, and/or sell copies of the Software, and to permit // persons to whom the Software is furnished to do so, subject to the // following conditions: // // The above copyright notice and this permission notice shall be included // in all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS // OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF // MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN // NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, // DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR // OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE // USE OR OTHER DEALINGS IN THE SOFTWARE. var assert = require('assert'); var common = require('../common'); var fork = require('child_process').fork; var net = require('net'); // progress tracker function ProgressTracker(missing, callback) { this.missing = missing; this.callback = callback; } ProgressTracker.prototype.done = function() { this.missing -= 1; this.check(); }; ProgressTracker.prototype.check = function() { if (this.missing === 0) this.callback(); }; if (process.argv[2] === 'child') { var serverScope; process.on('message', function onServer(msg, server) { if (msg.what !== 'server') return; process.removeListener('message', onServer); serverScope = server; server.on('connection', function(socket) { console.log('CHILD: got connection'); process.send({what: 'connection'}); socket.destroy(); }); // start making connection from parent console.log('CHILD: server listening'); process.send({what: 'listening'}); }); process.on('message', function onClose(msg) { if (msg.what !== 'close') return; process.removeListener('message', onClose); serverScope.on('close', function() { process.send({what: 'close'}); }); serverScope.close(); }); process.on('message', function onSocket(msg, socket) { if (msg.what !== 'socket') return; process.removeListener('message', onSocket); socket.end('echo'); console.log('CHILD: got socket'); }); process.send({what: 'ready'}); } else { var child = fork(process.argv[1], ['child']); child.on('exit', function() { console.log('CHILD: died'); }); // send net.Server to child and test by connecting var testServer = function(callback) { // destroy server execute callback when done var progress = new ProgressTracker(2, function() { server.on('close', function() { console.log('PARENT: server closed'); child.send({what: 'close'}); }); server.close(); }); // we expect 10 connections and close events var connections = new ProgressTracker(10, progress.done.bind(progress)); var closed = new ProgressTracker(10, progress.done.bind(progress)); // create server and send it to child var server = net.createServer(); server.on('connection', function(socket) { console.log('PARENT: got connection'); socket.destroy(); connections.done(); }); server.on('listening', function() { console.log('PARENT: server listening'); child.send({what: 'server'}, server); }); server.listen(common.PORT); // handle client messages var messageHandlers = function(msg) { if (msg.what === 'listening') { // make connections var socket; for (var i = 0; i < 10; i++) { socket = net.connect(common.PORT, function() { console.log('CLIENT: connected'); }); socket.on('close', function() { closed.done(); console.log('CLIENT: closed'); }); } } else if (msg.what === 'connection') { // child got connection connections.done(); } else if (msg.what === 'close') { child.removeListener('message', messageHandlers); callback(); } }; child.on('message', messageHandlers); }; // send net.Socket to child var testSocket = function(callback) { // create a new server and connect to it, // but the socket will be handled by the child var server = net.createServer(); server.on('connection', function(socket) { socket.on('close', function() { console.log('CLIENT: socket closed'); }); child.send({what: 'socket'}, socket); }); server.on('close', function() { console.log('PARENT: server closed'); callback(); }); // don't listen on the same port, because SmartOS sometimes says // that the server's fd is closed, but it still cannot listen // on the same port again. // // An isolated test for this would be lovely, but for now, this // will have to do. server.listen(common.PORT + 1, function() { console.error('testSocket, listening'); var connect = net.connect(common.PORT + 1); var store = ''; connect.on('data', function(chunk) { store += chunk; console.log('CLIENT: got data'); }); connect.on('close', function() { console.log('CLIENT: closed'); assert.equal(store, 'echo'); server.close(); }); }); }; // create server and send it to child var serverSuccess = false; var socketSuccess = false; child.on('message', function onReady(msg) { if (msg.what !== 'ready') return; child.removeListener('message', onReady); testServer(function() { serverSuccess = true; testSocket(function() { socketSuccess = true; child.kill(); }); }); }); process.on('exit', function() { assert.ok(serverSuccess); assert.ok(socketSuccess); }); } node-v0.10.25~dfsg2/test/simple/test-regress-GH-1899.js0000644000000000000000000000303512270121457020757 0ustar rootroot// Copyright Joyent, Inc. and other Node contributors. // // Permission is hereby granted, free of charge, to any person obtaining a // copy of this software and associated documentation files (the // "Software"), to deal in the Software without restriction, including // without limitation the rights to use, copy, modify, merge, publish, // distribute, sublicense, and/or sell copies of the Software, and to permit // persons to whom the Software is furnished to do so, subject to the // following conditions: // // The above copyright notice and this permission notice shall be included // in all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS // OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF // MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN // NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, // DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR // OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE // USE OR OTHER DEALINGS IN THE SOFTWARE. var path = require('path'); var assert = require('assert'); var spawn = require('child_process').spawn; var common = require('../common'); var child = spawn(process.argv[0], [ path.join(common.fixturesDir, 'GH-1899-output.js') ]); var output = ''; child.stdout.on('data', function(data) { output += data; }); child.on('exit', function(code, signal) { assert.equal(code, 0); assert.equal(output, 'hello, world!\n'); }); node-v0.10.25~dfsg2/test/simple/test-net-socket-timeout-unref.js0000644000000000000000000000334512270121457023262 0ustar rootroot// Copyright Joyent, Inc. and other Node contributors. // // Permission is hereby granted, free of charge, to any person obtaining a // copy of this software and associated documentation files (the // "Software"), to deal in the Software without restriction, including // without limitation the rights to use, copy, modify, merge, publish, // distribute, sublicense, and/or sell copies of the Software, and to permit // persons to whom the Software is furnished to do so, subject to the // following conditions: // // The above copyright notice and this permission notice shall be included // in all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS // OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF // MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN // NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, // DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR // OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE // USE OR OTHER DEALINGS IN THE SOFTWARE. var common = require('../common'); var assert = require('assert'); var net = require('net'); var server = net.createServer(function (c) { c.write('hello'); c.unref(); }); server.listen(common.PORT); server.unref(); var timedout = false; [8, 5, 3, 6, 2, 4].forEach(function (T) { var socket = net.createConnection(common.PORT, 'localhost'); socket.setTimeout(T * 1000, function () { console.log(process._getActiveHandles()); timedout = true; socket.destroy(); }); socket.unref(); }); process.on('exit', function () { assert.strictEqual(timedout, false, 'Socket timeout should not hold loop open'); }); node-v0.10.25~dfsg2/test/simple/test-tls-server-large-request.js0000644000000000000000000000450312270121457023266 0ustar rootroot// Copyright Joyent, Inc. and other Node contributors. // // Permission is hereby granted, free of charge, to any person obtaining a // copy of this software and associated documentation files (the // "Software"), to deal in the Software without restriction, including // without limitation the rights to use, copy, modify, merge, publish, // distribute, sublicense, and/or sell copies of the Software, and to permit // persons to whom the Software is furnished to do so, subject to the // following conditions: // // The above copyright notice and this permission notice shall be included // in all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS // OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF // MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN // NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, // DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR // OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE // USE OR OTHER DEALINGS IN THE SOFTWARE. var common = require('../common'); var assert = require('assert'); var tls = require('tls'); var fs = require('fs'); var stream = require('stream'); var util = require('util'); var clientConnected = 0; var serverConnected = 0; var request = new Buffer(new Array(1024 * 256).join('ABCD')); // 1mb var options = { key: fs.readFileSync(common.fixturesDir + '/keys/agent1-key.pem'), cert: fs.readFileSync(common.fixturesDir + '/keys/agent1-cert.pem') }; function Mediator() { stream.Writable.call(this); this.buf = ''; }; util.inherits(Mediator, stream.Writable); Mediator.prototype._write = function write(data, enc, cb) { this.buf += data; setTimeout(cb, 0); if (this.buf.length >= request.length) { assert.equal(this.buf, request.toString()); server.close(); } }; var mediator = new Mediator(); var server = tls.Server(options, function(socket) { socket.pipe(mediator); serverConnected++; }); server.listen(common.PORT, function() { var client1 = tls.connect({ port: common.PORT, rejectUnauthorized: false }, function() { ++clientConnected; client1.end(request); }); }); process.on('exit', function() { assert.equal(clientConnected, 1); assert.equal(serverConnected, 1); }); node-v0.10.25~dfsg2/test/simple/testcfg.py0000644000000000000000000001042212270121457017075 0ustar rootroot# Copyright 2008 the V8 project authors. All rights reserved. # Redistribution and use in source and binary forms, with or without # modification, are permitted provided that the following conditions are # met: # # * Redistributions of source code must retain the above copyright # notice, this list of conditions and the following disclaimer. # * Redistributions in binary form must reproduce the above # copyright notice, this list of conditions and the following # disclaimer in the documentation and/or other materials provided # with the distribution. # * Neither the name of Google Inc. nor the names of its # contributors may be used to endorse or promote products derived # from this software without specific prior written permission. # # THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS # "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT # LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR # A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT # OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, # SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT # LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, # DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY # THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT # (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE # OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. import test import os import shutil from shutil import rmtree from os import mkdir from glob import glob from os.path import join, dirname, exists import re FLAGS_PATTERN = re.compile(r"//\s+Flags:(.*)") FILES_PATTERN = re.compile(r"//\s+Files:(.*)") class SimpleTestCase(test.TestCase): def __init__(self, path, file, mode, context, config): super(SimpleTestCase, self).__init__(context, path, mode) self.file = file self.config = config self.mode = mode self.tmpdir = join(dirname(self.config.root), 'tmp') def AfterRun(self, result): # delete the whole tmp dir try: rmtree(self.tmpdir) except: pass # make it again. try: mkdir(self.tmpdir) except: pass def BeforeRun(self): # delete the whole tmp dir try: rmtree(self.tmpdir) except: pass # make it again. # intermittently fails on win32, so keep trying while not os.path.exists(self.tmpdir): try: mkdir(self.tmpdir) except: pass def GetLabel(self): return "%s %s" % (self.mode, self.GetName()) def GetName(self): return self.path[-1] def GetCommand(self): result = [self.config.context.GetVm(self.mode)] source = open(self.file).read() flags_match = FLAGS_PATTERN.search(source) if flags_match: result += flags_match.group(1).strip().split() files_match = FILES_PATTERN.search(source); additional_files = [] if files_match: additional_files += files_match.group(1).strip().split() for a_file in additional_files: result.append(join(dirname(self.config.root), '..', a_file)) result += [self.file] return result def GetSource(self): return open(self.file).read() class SimpleTestConfiguration(test.TestConfiguration): def __init__(self, context, root): super(SimpleTestConfiguration, self).__init__(context, root) def Ls(self, path): def SelectTest(name): return name.startswith('test-') and name.endswith('.js') return [f[:-3] for f in os.listdir(path) if SelectTest(f)] def ListTests(self, current_path, path, mode): all_tests = [current_path + [t] for t in self.Ls(join(self.root))] result = [] for test in all_tests: if self.Contains(path, test): file_path = join(self.root, reduce(join, test[1:], "") + ".js") result.append(SimpleTestCase(test, file_path, mode, self.context, self)) return result def GetBuildRequirements(self): return ['sample', 'sample=shell'] def GetTestStatus(self, sections, defs): status_file = join(self.root, 'simple.status') if exists(status_file): test.ReadConfigurationInto(status_file, sections, defs) def GetConfiguration(context, root): return SimpleTestConfiguration(context, root) node-v0.10.25~dfsg2/test/simple/test-https-req-split.js0000644000000000000000000000452212270121457021463 0ustar rootroot// Copyright Joyent, Inc. and other Node contributors. // // Permission is hereby granted, free of charge, to any person obtaining a // copy of this software and associated documentation files (the // "Software"), to deal in the Software without restriction, including // without limitation the rights to use, copy, modify, merge, publish, // distribute, sublicense, and/or sell copies of the Software, and to permit // persons to whom the Software is furnished to do so, subject to the // following conditions: // // The above copyright notice and this permission notice shall be included // in all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS // OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF // MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN // NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, // DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR // OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE // USE OR OTHER DEALINGS IN THE SOFTWARE. if (!process.versions.openssl) { console.error('Skipping because node compiled without OpenSSL.'); process.exit(0); } // disable strict server certificate validation by the client process.env.NODE_TLS_REJECT_UNAUTHORIZED = '0'; var common = require('../common'); var assert = require('assert'); var https = require('https'); var tls = require('tls'); var fs = require('fs'); var seen_req = false; var options = { key: fs.readFileSync(common.fixturesDir + '/keys/agent1-key.pem'), cert: fs.readFileSync(common.fixturesDir + '/keys/agent1-cert.pem') }; // Force splitting incoming data tls.SLAB_BUFFER_SIZE = 1; var server = https.createServer(options); server.on('upgrade', function(req, socket, upgrade) { socket.on('data', function(data) { throw new Error('Unexpected data: ' + data); }); socket.end('HTTP/1.1 200 Ok\r\n\r\n'); seen_req = true; }); server.listen(common.PORT, function() { var req = https.request({ host: '127.0.0.1', port: common.PORT, agent: false, headers: { Connection: 'Upgrade', Upgrade: 'Websocket' } }, function() { req.socket.destroy(); server.close(); }); req.end(); }); process.on('exit', function() { assert(seen_req); console.log('ok'); }); node-v0.10.25~dfsg2/test/simple/test-pipe-address.js0000644000000000000000000000274112270121457020764 0ustar rootroot// Copyright Joyent, Inc. and other Node contributors. // // Permission is hereby granted, free of charge, to any person obtaining a // copy of this software and associated documentation files (the // "Software"), to deal in the Software without restriction, including // without limitation the rights to use, copy, modify, merge, publish, // distribute, sublicense, and/or sell copies of the Software, and to permit // persons to whom the Software is furnished to do so, subject to the // following conditions: // // The above copyright notice and this permission notice shall be included // in all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS // OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF // MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN // NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, // DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR // OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE // USE OR OTHER DEALINGS IN THE SOFTWARE. var common = require('../common'); var assert = require('assert'); var net = require('net'); var address = null; var server = net.createServer(function() { assert(false); // should not be called }); server.listen(common.PIPE, function() { address = server.address(); server.close(); }); process.on('exit', function() { assert.equal(address, common.PIPE); }); node-v0.10.25~dfsg2/test/simple/test-stream2-readable-non-empty-end.js0000644000000000000000000000436512270121457024212 0ustar rootroot// Copyright Joyent, Inc. and other Node contributors. // // Permission is hereby granted, free of charge, to any person obtaining a // copy of this software and associated documentation files (the // "Software"), to deal in the Software without restriction, including // without limitation the rights to use, copy, modify, merge, publish, // distribute, sublicense, and/or sell copies of the Software, and to permit // persons to whom the Software is furnished to do so, subject to the // following conditions: // // The above copyright notice and this permission notice shall be included // in all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS // OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF // MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN // NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, // DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR // OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE // USE OR OTHER DEALINGS IN THE SOFTWARE. var assert = require('assert'); var common = require('../common.js'); var Readable = require('_stream_readable'); var len = 0; var chunks = new Array(10); for (var i = 1; i <= 10; i++) { chunks[i-1] = new Buffer(i); len += i; } var test = new Readable(); var n = 0; test._read = function(size) { var chunk = chunks[n++]; setTimeout(function() { test.push(chunk); }); }; test.on('end', thrower); function thrower() { throw new Error('this should not happen!'); } var bytesread = 0; test.on('readable', function() { var b = len - bytesread - 1; var res = test.read(b); if (res) { bytesread += res.length; console.error('br=%d len=%d', bytesread, len); setTimeout(next); } test.read(0); }); test.read(0); function next() { // now let's make 'end' happen test.removeListener('end', thrower); var endEmitted = false; process.on('exit', function() { assert(endEmitted, 'end should be emitted by now'); }); test.on('end', function() { endEmitted = true; }); // one to get the last byte var r = test.read(); assert(r); assert.equal(r.length, 1); r = test.read(); assert.equal(r, null); } node-v0.10.25~dfsg2/test/simple/test-init.js0000644000000000000000000000547612270121457017357 0ustar rootroot// Copyright Joyent, Inc. and other Node contributors. // // Permission is hereby granted, free of charge, to any person obtaining a // copy of this software and associated documentation files (the // "Software"), to deal in the Software without restriction, including // without limitation the rights to use, copy, modify, merge, publish, // distribute, sublicense, and/or sell copies of the Software, and to permit // persons to whom the Software is furnished to do so, subject to the // following conditions: // // The above copyright notice and this permission notice shall be included // in all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS // OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF // MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN // NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, // DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR // OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE // USE OR OTHER DEALINGS IN THE SOFTWARE. (function() { var assert = require('assert'), child = require('child_process'), util = require('util'), common = require('../common'); if (process.env['TEST_INIT']) { util.print('Loaded successfully!'); } else { // change CWD as we do this test so its not dependant on current CWD // being in the test folder process.chdir(__dirname); // slow but simple var envCopy = JSON.parse(JSON.stringify(process.env)); envCopy.TEST_INIT = 1; child.exec(process.execPath + ' test-init', {env: envCopy}, function(err, stdout, stderr) { assert.equal(stdout, 'Loaded successfully!', '`node test-init` failed!'); }); child.exec(process.execPath + ' test-init.js', {env: envCopy}, function(err, stdout, stderr) { assert.equal(stdout, 'Loaded successfully!', '`node test-init.js` failed!'); }); // test-init-index is in fixtures dir as requested by ry, so go there process.chdir(common.fixturesDir); child.exec(process.execPath + ' test-init-index', {env: envCopy}, function(err, stdout, stderr) { assert.equal(stdout, 'Loaded successfully!', '`node test-init-index failed!'); }); // ensures that `node fs` does not mistakenly load the native 'fs' module // instead of the desired file and that the fs module loads as // expected in node process.chdir(common.fixturesDir + '/test-init-native/'); child.exec(process.execPath + ' fs', {env: envCopy}, function(err, stdout, stderr) { assert.equal(stdout, 'fs loaded successfully', '`node fs` failed!'); }); } })(); node-v0.10.25~dfsg2/test/simple/test-domain-multi.js0000644000000000000000000000566612270121457021014 0ustar rootroot// Copyright Joyent, Inc. and other Node contributors. // // Permission is hereby granted, free of charge, to any person obtaining a // copy of this software and associated documentation files (the // "Software"), to deal in the Software without restriction, including // without limitation the rights to use, copy, modify, merge, publish, // distribute, sublicense, and/or sell copies of the Software, and to permit // persons to whom the Software is furnished to do so, subject to the // following conditions: // // The above copyright notice and this permission notice shall be included // in all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS // OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF // MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN // NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, // DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR // OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE // USE OR OTHER DEALINGS IN THE SOFTWARE. // Tests of multiple domains happening at once. var common = require('../common'); var assert = require('assert'); var domain = require('domain'); var events = require('events'); var caughtA = false; var caughtB = false; var caughtC = false; var a = domain.create(); a.enter(); // this will be our "root" domain a.on('error', function(er) { caughtA = true; console.log('This should not happen'); throw er; }); var http = require('http'); var server = http.createServer(function (req, res) { // child domain of a. var b = domain.create(); a.add(b); // treat these EE objects as if they are a part of the b domain // so, an 'error' event on them propagates to the domain, rather // than being thrown. b.add(req); b.add(res); b.on('error', function (er) { caughtB = true; console.error('Error encountered', er) if (res) { res.writeHead(500); res.end('An error occurred'); } // res.writeHead(500), res.destroy, etc. server.close(); }); // XXX this bind should not be necessary. // the write cb behavior in http/net should use an // event so that it picks up the domain handling. res.write('HELLO\n', b.bind(function() { throw new Error('this kills domain B, not A'); })); }).listen(common.PORT); var c = domain.create(); var req = http.get({ host: 'localhost', port: common.PORT }) // add the request to the C domain c.add(req); req.on('response', function(res) { console.error('got response'); // add the response object to the C domain c.add(res); res.pipe(process.stdout); }); c.on('error', function(er) { caughtC = true; console.error('Error on c', er.message); }); process.on('exit', function() { assert.equal(caughtA, false); assert.equal(caughtB, true) assert.equal(caughtC, true) console.log('ok - Errors went where they were supposed to go'); }); node-v0.10.25~dfsg2/test/simple/test-cluster-worker-kill.js0000644000000000000000000001171512270121457022326 0ustar rootroot// Copyright Joyent, Inc. and other Node contributors. // // Permission is hereby granted, free of charge, to any person obtaining a // copy of this software and associated documentation files (the // "Software"), to deal in the Software without restriction, including // without limitation the rights to use, copy, modify, merge, publish, // distribute, sublicense, and/or sell copies of the Software, and to permit // persons to whom the Software is furnished to do so, subject to the // following conditions: // // The above copyright notice and this permission notice shall be included // in all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS // OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF // MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN // NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, // DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR // OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE // USE OR OTHER DEALINGS IN THE SOFTWARE. // test-cluster-worker-kill.js // verifies that, when a child process is killed (we use SIGKILL) // - the parent receives the proper events in the proper order, no duplicates // - the exitCode and signalCode are correct in the 'exit' event // - the worker.suicide flag, and worker.state are correct // - the worker process actually goes away var common = require('../common'); var assert = require('assert'); var cluster = require('cluster'); if (cluster.isWorker) { var http = require('http'); var server = http.Server(function() { }); server.once('listening', function() { }); server.listen(common.PORT, '127.0.0.1'); } else if (cluster.isMaster) { var KILL_SIGNAL = 'SIGKILL', expected_results = { cluster_emitDisconnect: [1, "the cluster did not emit 'disconnect'"], cluster_emitExit: [1, "the cluster did not emit 'exit'"], cluster_exitCode: [null, 'the cluster exited w/ incorrect exitCode'], cluster_signalCode: [KILL_SIGNAL, 'the cluster exited w/ incorrect signalCode'], worker_emitDisconnect: [1, "the worker did not emit 'disconnect'"], worker_emitExit: [1, "the worker did not emit 'exit'"], worker_state: ['disconnected', 'the worker state is incorrect'], worker_suicideMode: [false, 'the worker.suicide flag is incorrect'], worker_died: [true, 'the worker is still running'], worker_exitCode: [null, 'the worker exited w/ incorrect exitCode'], worker_signalCode: [KILL_SIGNAL, 'the worker exited w/ incorrect signalCode'] }, results = { cluster_emitDisconnect: 0, cluster_emitExit: 0, worker_emitDisconnect: 0, worker_emitExit: 0 }; // start worker var worker = cluster.fork(); // when the worker is up and running, kill it worker.once('listening', function() { worker.process.kill(KILL_SIGNAL); }); // Check cluster events cluster.on('disconnect', function() { results.cluster_emitDisconnect += 1; }); cluster.on('exit', function(worker) { results.cluster_exitCode = worker.process.exitCode; results.cluster_signalCode = worker.process.signalCode; results.cluster_emitExit += 1; assert.ok(results.cluster_emitDisconnect, "cluster: 'exit' event before 'disconnect' event"); }); // Check worker eventes and properties worker.on('disconnect', function() { results.worker_emitDisconnect += 1; results.worker_suicideMode = worker.suicide; results.worker_state = worker.state; }); // Check that the worker died worker.once('exit', function(exitCode, signalCode) { results.worker_exitCode = exitCode; results.worker_signalCode = signalCode; results.worker_emitExit += 1; results.worker_died = !alive(worker.process.pid); assert.ok(results.worker_emitDisconnect, "worker: 'exit' event before 'disconnect' event"); process.nextTick(function() { finish_test(); }); }); var finish_test = function() { try { checkResults(expected_results, results); } catch (exc) { console.error('FAIL: ' + exc.message); if (exc.name != 'AssertionError') { console.trace(exc); } process.exit(1); return; } process.exit(0); }; } // some helper functions ... function checkResults(expected_results, results) { for (var k in expected_results) { var actual = results[k], expected = expected_results[k]; if (typeof expected === 'function') { expected(r[k]); } else { var msg = (expected[1] || '') + (' [expected: ' + expected[0] + ' / actual: ' + actual + ']'); if (expected && expected.length) { assert.equal(actual, expected[0], msg); } else { assert.equal(actual, expected, msg); } } } } function alive(pid) { try { process.kill(pid, 'SIGCONT'); return true; } catch (e) { return false; } } node-v0.10.25~dfsg2/test/simple/test-http-abort-client.js0000644000000000000000000000440512270121457021743 0ustar rootroot// Copyright Joyent, Inc. and other Node contributors. // // Permission is hereby granted, free of charge, to any person obtaining a // copy of this software and associated documentation files (the // "Software"), to deal in the Software without restriction, including // without limitation the rights to use, copy, modify, merge, publish, // distribute, sublicense, and/or sell copies of the Software, and to permit // persons to whom the Software is furnished to do so, subject to the // following conditions: // // The above copyright notice and this permission notice shall be included // in all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS // OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF // MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN // NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, // DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR // OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE // USE OR OTHER DEALINGS IN THE SOFTWARE. var common = require('../common'); var http = require('http'); var assert = require('assert'); var server = http.Server(function(req, res) { console.log('Server accepted request.'); res.writeHead(200); res.write('Part of my res.'); res.destroy(); }); var responseClose = false; server.listen(common.PORT, function() { var client = http.get({ port: common.PORT, headers: { connection: 'keep-alive' } }, function(res) { server.close(); console.log('Got res: ' + res.statusCode); console.dir(res.headers); res.on('data', function(chunk) { console.log('Read ' + chunk.length + ' bytes'); console.log(' chunk=%j', chunk.toString()); }); res.on('end', function() { console.log('Response ended.'); }); res.on('aborted', function() { console.log('Response aborted.'); }); res.socket.on('close', function() { console.log('socket closed, but not res'); }) // it would be nice if this worked: res.on('close', function() { console.log('Response aborted'); responseClose = true; }); }); }); process.on('exit', function() { assert.ok(responseClose); }); node-v0.10.25~dfsg2/test/simple/test-sync-fileread.js0000644000000000000000000000252412270121457021130 0ustar rootroot// Copyright Joyent, Inc. and other Node contributors. // // Permission is hereby granted, free of charge, to any person obtaining a // copy of this software and associated documentation files (the // "Software"), to deal in the Software without restriction, including // without limitation the rights to use, copy, modify, merge, publish, // distribute, sublicense, and/or sell copies of the Software, and to permit // persons to whom the Software is furnished to do so, subject to the // following conditions: // // The above copyright notice and this permission notice shall be included // in all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS // OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF // MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN // NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, // DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR // OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE // USE OR OTHER DEALINGS IN THE SOFTWARE. var common = require('../common'); var assert = require('assert'); var path = require('path'); var fs = require('fs'); var fixture = path.join(__dirname, '../fixtures/x.txt'); assert.equal('xyz\n', fs.readFileSync(fixture)); node-v0.10.25~dfsg2/test/simple/test-stream-writable-decoded-encoding.js0000644000000000000000000000420112270121457024650 0ustar rootroot// Copyright Joyent, Inc. and other Node contributors. // // Permission is hereby granted, free of charge, to any person obtaining a // copy of this software and associated documentation files (the // "Software"), to deal in the Software without restriction, including // without limitation the rights to use, copy, modify, merge, publish, // distribute, sublicense, and/or sell copies of the Software, and to permit // persons to whom the Software is furnished to do so, subject to the // following conditions: // // The above copyright notice and this permission notice shall be included // in all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS // OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF // MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN // NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, // DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR // OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE // USE OR OTHER DEALINGS IN THE SOFTWARE. var common = require('../common'); var assert = require('assert'); var stream = require('stream'); var util = require('util'); function MyWritable(fn, options) { stream.Writable.call(this, options); this.fn = fn; }; util.inherits(MyWritable, stream.Writable); MyWritable.prototype._write = function (chunk, encoding, callback) { this.fn(Buffer.isBuffer(chunk), typeof chunk, encoding); callback(); }; ;(function decodeStringsTrue() { var m = new MyWritable(function(isBuffer, type, enc) { assert(isBuffer); assert.equal(type, 'object'); assert.equal(enc, 'buffer'); console.log('ok - decoded string is decoded'); }, { decodeStrings: true }); m.write('some-text', 'utf8'); m.end(); })(); ;(function decodeStringsFalse() { var m = new MyWritable(function(isBuffer, type, enc) { assert(!isBuffer); assert.equal(type, 'string'); assert.equal(enc, 'utf8'); console.log('ok - un-decoded string is not decoded'); }, { decodeStrings: false }); m.write('some-text', 'utf8'); m.end(); })(); node-v0.10.25~dfsg2/test/simple/test-dgram-oob-buffer.js0000644000000000000000000000422512270121457021521 0ustar rootroot// Copyright Joyent, Inc. and other Node contributors. // // Permission is hereby granted, free of charge, to any person obtaining a // copy of this software and associated documentation files (the // "Software"), to deal in the Software without restriction, including // without limitation the rights to use, copy, modify, merge, publish, // distribute, sublicense, and/or sell copies of the Software, and to permit // persons to whom the Software is furnished to do so, subject to the // following conditions: // // The above copyright notice and this permission notice shall be included // in all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS // OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF // MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN // NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, // DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR // OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE // USE OR OTHER DEALINGS IN THE SOFTWARE. // Some operating systems report errors when an UDP message is sent to an // unreachable host. This error can be reported by sendto() and even by // recvfrom(). Node should not propagate this error to the user. var common = require('../common'); var assert = require('assert'); var dgram = require('dgram'); var socket = dgram.createSocket('udp4'); var buf = Buffer([1,2,3,4]); function ok() {} socket.send(buf, 0, 0, common.PORT, '127.0.0.1', ok); // useful? no socket.send(buf, 0, 4, common.PORT, '127.0.0.1', ok); socket.send(buf, 1, 3, common.PORT, '127.0.0.1', ok); socket.send(buf, 3, 1, common.PORT, '127.0.0.1', ok); assert.throws(function() { socket.send(buf, 0, 5, common.PORT, '127.0.0.1', assert.fail); }); assert.throws(function() { socket.send(buf, 2, 3, common.PORT, '127.0.0.1', assert.fail); }); assert.throws(function() { socket.send(buf, 4, 0, common.PORT, '127.0.0.1', assert.fail); }); assert.throws(function() { socket.send(buf, 4, 4, common.PORT, '127.0.0.1', assert.fail); }); socket.close(); // FIXME should not be necessary node-v0.10.25~dfsg2/test/simple/test-net-server-bind.js0000644000000000000000000000533112270121457021406 0ustar rootroot// Copyright Joyent, Inc. and other Node contributors. // // Permission is hereby granted, free of charge, to any person obtaining a // copy of this software and associated documentation files (the // "Software"), to deal in the Software without restriction, including // without limitation the rights to use, copy, modify, merge, publish, // distribute, sublicense, and/or sell copies of the Software, and to permit // persons to whom the Software is furnished to do so, subject to the // following conditions: // // The above copyright notice and this permission notice shall be included // in all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS // OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF // MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN // NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, // DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR // OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE // USE OR OTHER DEALINGS IN THE SOFTWARE. var common = require('../common'); var assert = require('assert'); var net = require('net'); // With only a callback, server should get a port assigned by the OS var address0; var server0 = net.createServer(function(socket) { }); server0.listen(function() { address0 = server0.address(); console.log('address0 %j', address0); server0.close(); }); // No callback to listen(), assume we can bind in 100 ms var address1; var server1 = net.createServer(function(socket) { }); server1.listen(common.PORT); setTimeout(function() { address1 = server1.address(); console.log('address1 %j', address1); server1.close(); }, 100); // Callback to listen() var address2; var server2 = net.createServer(function(socket) { }); server2.listen(common.PORT + 1, function() { address2 = server2.address(); console.log('address2 %j', address2); server2.close(); }); // Backlog argument var address3; var server3 = net.createServer(function(socket) { }); server3.listen(common.PORT + 2, '0.0.0.0', 127, function() { address3 = server3.address(); console.log('address3 %j', address3); server3.close(); }); // Backlog argument without host argument var address4; var server4 = net.createServer(function(socket) { }); server4.listen(common.PORT + 3, 127, function() { address4 = server4.address(); console.log('address4 %j', address4); server4.close(); }); process.on('exit', function() { assert.ok(address0.port > 100); assert.equal(common.PORT, address1.port); assert.equal(common.PORT + 1, address2.port); assert.equal(common.PORT + 2, address3.port); assert.equal(common.PORT + 3, address4.port); }); node-v0.10.25~dfsg2/test/simple/test-signal-handler.js0000644000000000000000000000423312270121457021272 0ustar rootroot// Copyright Joyent, Inc. and other Node contributors. // // Permission is hereby granted, free of charge, to any person obtaining a // copy of this software and associated documentation files (the // "Software"), to deal in the Software without restriction, including // without limitation the rights to use, copy, modify, merge, publish, // distribute, sublicense, and/or sell copies of the Software, and to permit // persons to whom the Software is furnished to do so, subject to the // following conditions: // // The above copyright notice and this permission notice shall be included // in all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS // OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF // MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN // NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, // DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR // OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE // USE OR OTHER DEALINGS IN THE SOFTWARE. // SIGUSR1 and SIGHUP are not supported on Windows if (process.platform === 'win32') { process.exit(0); } var common = require('../common'); var assert = require('assert'); console.log('process.pid: ' + process.pid); var first = 0, second = 0; var sighup = false; process.on('SIGUSR1', function() { console.log('Interrupted by SIGUSR1'); first += 1; }); process.on('SIGUSR1', function() { second += 1; setTimeout(function() { console.log('End.'); process.exit(0); }, 5); }); var i = 0; setInterval(function() { console.log('running process...' + ++i); if (i == 5) { process.kill(process.pid, 'SIGUSR1'); } }, 1); // Test on condition where a watcher for SIGNAL // has been previously registered, and `process.listeners(SIGNAL).length === 1` process.on('SIGHUP', function() {}); process.removeAllListeners('SIGHUP'); process.on('SIGHUP', function() { sighup = true }); process.kill(process.pid, 'SIGHUP'); process.on('exit', function() { assert.equal(1, first); assert.equal(1, second); assert.equal(true, sighup); }); node-v0.10.25~dfsg2/test/simple/test-tls-client-abort3.js0000644000000000000000000000422712270121457021653 0ustar rootroot// Copyright Joyent, Inc. and other Node contributors. // // Permission is hereby granted, free of charge, to any person obtaining a // copy of this software and associated documentation files (the // "Software"), to deal in the Software without restriction, including // without limitation the rights to use, copy, modify, merge, publish, // distribute, sublicense, and/or sell copies of the Software, and to permit // persons to whom the Software is furnished to do so, subject to the // following conditions: // // The above copyright notice and this permission notice shall be included // in all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS // OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF // MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN // NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, // DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR // OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE // USE OR OTHER DEALINGS IN THE SOFTWARE. if (!process.versions.openssl) { console.error('Skipping because node compiled without OpenSSL.'); process.exit(0); } var common = require('../common'); var common = require('../common'); var tls = require('tls'); var fs = require('fs'); var assert = require('assert'); var options = { key: fs.readFileSync(common.fixturesDir + '/test_key.pem'), cert: fs.readFileSync(common.fixturesDir + '/test_cert.pem') }; var gotError = 0, gotRequest = 0, connected = 0; var server = tls.createServer(options, function(c) { gotRequest++; c.on('data', function(data) { console.log(data.toString()); }); c.on('close', function() { server.close(); }); }).listen(common.PORT, function() { var c = tls.connect(common.PORT, { rejectUnauthorized: false }, function() { connected++; c.pair.ssl.shutdown(); c.write('123'); c.destroy(); }); c.once('error', function() { gotError++; }); }); process.once('exit', function() { assert.equal(gotError, 1); assert.equal(gotRequest, 1); assert.equal(connected, 1); }); node-v0.10.25~dfsg2/test/simple/test-repl-end-emits-exit.js0000644000000000000000000000433212270121457022176 0ustar rootroot// Copyright Joyent, Inc. and other Node contributors. // // Permission is hereby granted, free of charge, to any person obtaining a // copy of this software and associated documentation files (the // "Software"), to deal in the Software without restriction, including // without limitation the rights to use, copy, modify, merge, publish, // distribute, sublicense, and/or sell copies of the Software, and to permit // persons to whom the Software is furnished to do so, subject to the // following conditions: // // The above copyright notice and this permission notice shall be included // in all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS // OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF // MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN // NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, // DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR // OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE // USE OR OTHER DEALINGS IN THE SOFTWARE. var common = require('../common'), assert = require('assert'), Stream = require('stream'), repl = require('repl'), terminalExit = 0, regularExit = 0; // create a dummy stream that does nothing var stream = new Stream(); stream.write = stream.pause = stream.resume = function(){}; stream.readable = stream.writable = true; function testTerminalMode() { var r1 = repl.start({ input: stream, output: stream, terminal: true }); process.nextTick(function() { // manually fire a ^D keypress stream.emit('data', '\u0004'); }); r1.on('exit', function() { // should be fired from the simulated ^D keypress terminalExit++; testRegularMode(); }); } function testRegularMode() { var r2 = repl.start({ input: stream, output: stream, terminal: false }); process.nextTick(function() { stream.emit('end'); }); r2.on('exit', function() { // should be fired from the simulated 'end' event regularExit++; }); } process.on('exit', function() { assert.equal(terminalExit, 1); assert.equal(regularExit, 1); }); // start testTerminalMode(); node-v0.10.25~dfsg2/test/simple/test-https-connecting-to-http.js0000644000000000000000000000377112270121457023274 0ustar rootroot// Copyright Joyent, Inc. and other Node contributors. // // Permission is hereby granted, free of charge, to any person obtaining a // copy of this software and associated documentation files (the // "Software"), to deal in the Software without restriction, including // without limitation the rights to use, copy, modify, merge, publish, // distribute, sublicense, and/or sell copies of the Software, and to permit // persons to whom the Software is furnished to do so, subject to the // following conditions: // // The above copyright notice and this permission notice shall be included // in all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS // OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF // MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN // NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, // DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR // OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE // USE OR OTHER DEALINGS IN THE SOFTWARE. // This tests the situation where you try to connect a https client // to an http server. You should get an error and exit. var common = require('../common'); var assert = require('assert'); var https = require('https'); var http = require('http'); var reqCount = 0; var resCount = 0; var reqErrorCount = 0; var body = 'hello world\n'; var server = http.createServer(function(req, res) { reqCount++; console.log('got request'); res.writeHead(200, { 'content-type': 'text/plain' }); res.end(body); }); server.listen(common.PORT, function() { var req = https.get({ port: common.PORT }, function(res) { resCount++; }); req.on('error', function(e) { console.log('Got expected error: ', e.message); server.close(); reqErrorCount++; }); }); process.on('exit', function() { assert.equal(0, reqCount); assert.equal(0, resCount); assert.equal(1, reqErrorCount); }); node-v0.10.25~dfsg2/test/simple/test-net-end-without-connect.js0000644000000000000000000000235112270121457023063 0ustar rootroot// Copyright Joyent, Inc. and other Node contributors. // // Permission is hereby granted, free of charge, to any person obtaining a // copy of this software and associated documentation files (the // "Software"), to deal in the Software without restriction, including // without limitation the rights to use, copy, modify, merge, publish, // distribute, sublicense, and/or sell copies of the Software, and to permit // persons to whom the Software is furnished to do so, subject to the // following conditions: // // The above copyright notice and this permission notice shall be included // in all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS // OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF // MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN // NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, // DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR // OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE // USE OR OTHER DEALINGS IN THE SOFTWARE. var common = require('../common'); var net = require('net'); var sock = new net.Socket; sock.end(); // Should not throw. node-v0.10.25~dfsg2/test/simple/test-http-url.parse-path.js0000644000000000000000000000330212270121457022220 0ustar rootroot// Copyright Joyent, Inc. and other Node contributors. // // Permission is hereby granted, free of charge, to any person obtaining a // copy of this software and associated documentation files (the // "Software"), to deal in the Software without restriction, including // without limitation the rights to use, copy, modify, merge, publish, // distribute, sublicense, and/or sell copies of the Software, and to permit // persons to whom the Software is furnished to do so, subject to the // following conditions: // // The above copyright notice and this permission notice shall be included // in all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS // OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF // MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN // NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, // DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR // OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE // USE OR OTHER DEALINGS IN THE SOFTWARE. var common = require('../common'); var assert = require('assert'); var http = require('http'); var url = require('url'); var testURL = url.parse('http://localhost:' + common.PORT + '/asdf'); function check(request) { // a path should come over assert.strictEqual(request.url, '/asdf'); } var server = http.createServer(function(request, response) { // run the check function check.call(this, request, response); response.writeHead(200, {}); response.end('ok'); server.close(); }); server.listen(common.PORT, function() { // make the request http.request(testURL).end(); }); node-v0.10.25~dfsg2/test/simple/test-http-connect.js0000644000000000000000000000714412270121457021014 0ustar rootroot// Copyright Joyent, Inc. and other Node contributors. // // Permission is hereby granted, free of charge, to any person obtaining a // copy of this software and associated documentation files (the // "Software"), to deal in the Software without restriction, including // without limitation the rights to use, copy, modify, merge, publish, // distribute, sublicense, and/or sell copies of the Software, and to permit // persons to whom the Software is furnished to do so, subject to the // following conditions: // // The above copyright notice and this permission notice shall be included // in all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS // OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF // MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN // NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, // DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR // OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE // USE OR OTHER DEALINGS IN THE SOFTWARE. var common = require('../common'); var assert = require('assert'); var http = require('http'); var serverGotConnect = false; var clientGotConnect = false; var server = http.createServer(function(req, res) { assert(false); }); server.on('connect', function(req, socket, firstBodyChunk) { assert.equal(req.method, 'CONNECT'); assert.equal(req.url, 'google.com:443'); common.debug('Server got CONNECT request'); serverGotConnect = true; socket.write('HTTP/1.1 200 Connection established\r\n\r\n'); var data = firstBodyChunk.toString(); socket.on('data', function(buf) { data += buf.toString(); }); socket.on('end', function() { socket.end(data); }); }); server.listen(common.PORT, function() { var req = http.request({ port: common.PORT, method: 'CONNECT', path: 'google.com:443' }, function(res) { assert(false); }); var clientRequestClosed = false; req.on('close', function() { clientRequestClosed = true; }); req.on('connect', function(res, socket, firstBodyChunk) { common.debug('Client got CONNECT request'); clientGotConnect = true; // Make sure this request got removed from the pool. var name = 'localhost:' + common.PORT; assert(!http.globalAgent.sockets.hasOwnProperty(name)); assert(!http.globalAgent.requests.hasOwnProperty(name)); // Make sure this socket has detached. assert(!socket.ondata); assert(!socket.onend); assert.equal(socket.listeners('connect').length, 0); assert.equal(socket.listeners('data').length, 0); // the stream.Duplex onend listener // allow 0 here, so that i can run the same test on streams1 impl assert(socket.listeners('end').length <= 1); assert.equal(socket.listeners('free').length, 0); assert.equal(socket.listeners('close').length, 0); assert.equal(socket.listeners('error').length, 0); assert.equal(socket.listeners('agentRemove').length, 0); var data = firstBodyChunk.toString(); socket.on('data', function(buf) { data += buf.toString(); }); socket.on('end', function() { assert.equal(data, 'HeadBody'); assert(clientRequestClosed); server.close(); }); socket.write('Body'); socket.end(); }); // It is legal for the client to send some data intended for the server // before the "200 Connection established" (or any other success or // error code) is received. req.write('Head'); req.end(); }); process.on('exit', function() { assert.ok(serverGotConnect); assert.ok(clientGotConnect); }); node-v0.10.25~dfsg2/test/simple/test-http-byteswritten.js0000644000000000000000000000402412270121457022120 0ustar rootroot// Copyright Joyent, Inc. and other Node contributors. // // Permission is hereby granted, free of charge, to any person obtaining a // copy of this software and associated documentation files (the // "Software"), to deal in the Software without restriction, including // without limitation the rights to use, copy, modify, merge, publish, // distribute, sublicense, and/or sell copies of the Software, and to permit // persons to whom the Software is furnished to do so, subject to the // following conditions: // // The above copyright notice and this permission notice shall be included // in all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS // OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF // MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN // NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, // DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR // OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE // USE OR OTHER DEALINGS IN THE SOFTWARE. var common = require('../common'); var assert = require('assert'); var fs = require('fs'); var http = require('http'); var body = 'hello world\n'; var httpServer = http.createServer(function(req, res) { res.on('finish', function() { assert(typeof(req.connection.bytesWritten) === 'number'); assert(req.connection.bytesWritten > 0); httpServer.close(); console.log('ok'); }); res.writeHead(200, { 'Content-Type': 'text/plain' }); // Write 1.5mb to cause some requests to buffer // Also, mix up the encodings a bit. var chunk = new Array(1024 + 1).join('7'); var bchunk = new Buffer(chunk); for (var i = 0; i < 1024; i++) { res.write(chunk); res.write(bchunk); res.write(chunk, 'hex'); } // Get .bytesWritten while buffer is not empty assert(res.connection.bytesWritten > 0); res.end(body); }); httpServer.listen(common.PORT, function() { http.get({ port: common.PORT }); }); node-v0.10.25~dfsg2/test/simple/test-file-write-stream2.js0000644000000000000000000000625412270121457022031 0ustar rootroot// Copyright Joyent, Inc. and other Node contributors. // // Permission is hereby granted, free of charge, to any person obtaining a // copy of this software and associated documentation files (the // "Software"), to deal in the Software without restriction, including // without limitation the rights to use, copy, modify, merge, publish, // distribute, sublicense, and/or sell copies of the Software, and to permit // persons to whom the Software is furnished to do so, subject to the // following conditions: // // The above copyright notice and this permission notice shall be included // in all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS // OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF // MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN // NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, // DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR // OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE // USE OR OTHER DEALINGS IN THE SOFTWARE. var common = require('../common'); var assert = require('assert'); var path = require('path'); var fs = require('fs'); var util = require('util'); var filepath = path.join(common.tmpDir, 'write.txt'); var file; var EXPECTED = '012345678910'; var cb_expected = 'write open drain write drain close error '; var cb_occurred = ''; var countDrains = 0; process.on('exit', function() { removeTestFile(); if (cb_occurred !== cb_expected) { console.log(' Test callback events missing or out of order:'); console.log(' expected: %j', cb_expected); console.log(' occurred: %j', cb_occurred); assert.strictEqual(cb_occurred, cb_expected, 'events missing or out of order: "' + cb_occurred + '" !== "' + cb_expected + '"'); } else { console.log('ok'); } }); function removeTestFile() { try { fs.unlinkSync(filepath); } catch (e) {} } removeTestFile(); // drain at 0, return false at 10. file = fs.createWriteStream(filepath, { highWaterMark: 11 }); file.on('open', function(fd) { console.error('open'); cb_occurred += 'open '; assert.equal(typeof fd, 'number'); }); file.on('drain', function() { console.error('drain'); cb_occurred += 'drain '; ++countDrains; if (countDrains === 1) { console.error('drain=1, write again'); assert.equal(fs.readFileSync(filepath, 'utf8'), EXPECTED); console.error('ondrain write ret=%j', file.write(EXPECTED)); cb_occurred += 'write '; } else if (countDrains == 2) { console.error('second drain, end'); assert.equal(fs.readFileSync(filepath, 'utf8'), EXPECTED + EXPECTED); file.end(); } }); file.on('close', function() { cb_occurred += 'close '; assert.strictEqual(file.bytesWritten, EXPECTED.length * 2); file.write('should not work anymore'); }); file.on('error', function(err) { cb_occurred += 'error '; assert.ok(err.message.indexOf('write after end') >= 0); }); for (var i = 0; i < 11; i++) { var ret = file.write(i + ''); console.error('%d %j', i, ret); // return false when i hits 10 assert(ret === (i != 10)); } cb_occurred += 'write '; node-v0.10.25~dfsg2/test/simple/test-fs-append-file.js0000644000000000000000000001101212270121457021165 0ustar rootroot// Copyright Joyent, Inc. and other Node contributors. // // Permission is hereby granted, free of charge, to any person obtaining a // copy of this software and associated documentation files (the // "Software"), to deal in the Software without restriction, including // without limitation the rights to use, copy, modify, merge, publish, // distribute, sublicense, and/or sell copies of the Software, and to permit // persons to whom the Software is furnished to do so, subject to the // following conditions: // // The above copyright notice and this permission notice shall be included // in all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS // OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF // MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN // NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, // DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR // OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE // USE OR OTHER DEALINGS IN THE SOFTWARE. var common = require('../common'); var assert = require('assert'); var fs = require('fs'); var join = require('path').join; var filename = join(common.tmpDir, 'append.txt'); common.error('appending to ' + filename); var currentFileData = 'ABCD'; var n = 220; var s = '南越国是前203年至前111年存在于岭南地区的一个国家,国都位于番禺,疆域包括今天中国的广东、' + '广西两省区的大部份地区,福建省、湖南、贵州、云南的一小部份地区和越南的北部。' + '南越国是秦朝灭亡后,由南海郡尉赵佗于前203年起兵兼并桂林郡和象郡后建立。' + '前196年和前179年,南越国曾先后两次名义上臣属于西汉,成为西汉的“外臣”。前112年,' + '南越国末代君主赵建德与西汉发生战争,被汉武帝于前111年所灭。南越国共存在93年,' + '历经五代君主。南越国是岭南地区的第一个有记载的政权国家,采用封建制和郡县制并存的制度,' + '它的建立保证了秦末乱世岭南地区社会秩序的稳定,有效的改善了岭南地区落后的政治、##济现状。\n'; var ncallbacks = 0; // test that empty file will be created and have content added fs.appendFile(filename, s, function(e) { if (e) throw e; ncallbacks++; common.error('appended to file'); fs.readFile(filename, function(e, buffer) { if (e) throw e; common.error('file read'); ncallbacks++; assert.equal(Buffer.byteLength(s), buffer.length); }); }); // test that appends data to a non empty file var filename2 = join(common.tmpDir, 'append2.txt'); fs.writeFileSync(filename2, currentFileData); fs.appendFile(filename2, s, function(e) { if (e) throw e; ncallbacks++; common.error('appended to file2'); fs.readFile(filename2, function(e, buffer) { if (e) throw e; common.error('file2 read'); ncallbacks++; assert.equal(Buffer.byteLength(s) + currentFileData.length, buffer.length); }); }); // test that appendFile accepts buffers var filename3 = join(common.tmpDir, 'append3.txt'); fs.writeFileSync(filename3, currentFileData); var buf = new Buffer(s, 'utf8'); common.error('appending to ' + filename3); fs.appendFile(filename3, buf, function(e) { if (e) throw e; ncallbacks++; common.error('appended to file3'); fs.readFile(filename3, function(e, buffer) { if (e) throw e; common.error('file3 read'); ncallbacks++; assert.equal(buf.length + currentFileData.length, buffer.length); }); }); // test that appendFile accepts numbers. var filename4 = join(common.tmpDir, 'append4.txt'); fs.writeFileSync(filename4, currentFileData); common.error('appending to ' + filename4); var m = 0600; fs.appendFile(filename4, n, { mode: m }, function(e) { if (e) throw e; ncallbacks++; common.error('appended to file4'); // windows permissions aren't unix if (process.platform !== 'win32') { var st = fs.statSync(filename4); assert.equal(st.mode & 0700, m); } fs.readFile(filename4, function(e, buffer) { if (e) throw e; common.error('file4 read'); ncallbacks++; assert.equal(Buffer.byteLength('' + n) + currentFileData.length, buffer.length); }); }); process.on('exit', function() { common.error('done'); assert.equal(8, ncallbacks); fs.unlinkSync(filename); fs.unlinkSync(filename2); fs.unlinkSync(filename3); fs.unlinkSync(filename4); }); node-v0.10.25~dfsg2/test/simple/test-regress-GH-3542.js0000644000000000000000000000351512270121457020745 0ustar rootroot// Copyright Joyent, Inc. and other Node contributors. // // Permission is hereby granted, free of charge, to any person obtaining a // copy of this software and associated documentation files (the // "Software"), to deal in the Software without restriction, including // without limitation the rights to use, copy, modify, merge, publish, // distribute, sublicense, and/or sell copies of the Software, and to permit // persons to whom the Software is furnished to do so, subject to the // following conditions: // // The above copyright notice and this permission notice shall be included // in all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS // OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF // MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN // NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, // DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR // OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE // USE OR OTHER DEALINGS IN THE SOFTWARE. // This test is only relevant on Windows. if (process.platform !== 'win32') { return process.exit(0); } var common = require('../common.js'), assert = require('assert'), fs = require('fs'), path = require('path'), succeeded = 0; function test(p) { var result = fs.realpathSync(p); assert.strictEqual(result, path.resolve(p)); fs.realpath(p, function(err, result) { assert.ok(!err); assert.strictEqual(result, path.resolve(p)); succeeded++; }); } test('//localhost/c$/windows/system32'); test('//localhost/c$/windows'); test('//localhost/c$/') test('\\\\localhost\\c$') test('c:\\'); test('c:'); test(process.env.windir); process.on('exit', function() { assert.strictEqual(succeeded, 7); });node-v0.10.25~dfsg2/test/simple/test-fs-watch.js0000644000000000000000000001043312270121457020115 0ustar rootroot// Copyright Joyent, Inc. and other Node contributors. // // Permission is hereby granted, free of charge, to any person obtaining a // copy of this software and associated documentation files (the // "Software"), to deal in the Software without restriction, including // without limitation the rights to use, copy, modify, merge, publish, // distribute, sublicense, and/or sell copies of the Software, and to permit // persons to whom the Software is furnished to do so, subject to the // following conditions: // // The above copyright notice and this permission notice shall be included // in all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS // OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF // MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN // NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, // DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR // OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE // USE OR OTHER DEALINGS IN THE SOFTWARE. var common = require('../common'); var assert = require('assert'); var path = require('path'); var fs = require('fs'); var expectFilePath = process.platform === 'win32' || process.platform === 'linux' || process.platform === 'darwin'; var watchSeenOne = 0; var watchSeenTwo = 0; var watchSeenThree = 0; var testDir = common.tmpDir; var filenameOne = 'watch.txt'; var filepathOne = path.join(testDir, filenameOne); var filenameTwo = 'hasOwnProperty'; var filepathTwo = filenameTwo; var filepathTwoAbs = path.join(testDir, filenameTwo); var filenameThree = 'newfile.txt'; var testsubdir = path.join(testDir, 'testsubdir'); var filepathThree = path.join(testsubdir, filenameThree); process.on('exit', function() { assert.ok(watchSeenOne > 0); assert.ok(watchSeenTwo > 0); assert.ok(watchSeenThree > 0); }); // Clean up stale files (if any) from previous run. try { fs.unlinkSync(filepathOne); } catch (e) { } try { fs.unlinkSync(filepathTwoAbs); } catch (e) { } try { fs.unlinkSync(filepathThree); } catch (e) { } try { fs.rmdirSync(testsubdir); } catch (e) { } fs.writeFileSync(filepathOne, 'hello'); assert.doesNotThrow( function() { var watcher = fs.watch(filepathOne) watcher.on('change', function(event, filename) { assert.equal('change', event); // darwin only shows the file path for subdir watching, // not for individual file watching. if (expectFilePath && process.platform !== 'darwin') { assert.equal('watch.txt', filename); } else { assert.equal(null, filename); } watcher.close(); ++watchSeenOne; }); } ); setTimeout(function() { fs.writeFileSync(filepathOne, 'world'); }, 1000); process.chdir(testDir); fs.writeFileSync(filepathTwoAbs, 'howdy'); assert.doesNotThrow( function() { var watcher = fs.watch(filepathTwo, function(event, filename) { assert.equal('change', event); // darwin only shows the file path for subdir watching, // not for individual file watching. if (expectFilePath && process.platform !== 'darwin') { assert.equal('hasOwnProperty', filename); } else { assert.equal(null, filename); } watcher.close(); ++watchSeenTwo; }); } ); setTimeout(function() { fs.writeFileSync(filepathTwoAbs, 'pardner'); }, 1000); try { fs.unlinkSync(filepathThree); } catch (e) {} try { fs.mkdirSync(testsubdir, 0700); } catch (e) {} assert.doesNotThrow( function() { var watcher = fs.watch(testsubdir, function(event, filename) { var renameEv = process.platform === 'sunos' ? 'change' : 'rename'; assert.equal(renameEv, event); if (expectFilePath) { assert.equal('newfile.txt', filename); } else { assert.equal(null, filename); } watcher.close(); ++watchSeenThree; }); } ); setTimeout(function() { var fd = fs.openSync(filepathThree, 'w'); fs.closeSync(fd); }, 1000); // https://github.com/joyent/node/issues/2293 - non-persistent watcher should // not block the event loop fs.watch(__filename, {persistent: false}, function() { assert(0); }); node-v0.10.25~dfsg2/test/simple/test-net-stream.js0000644000000000000000000000304112270121457020455 0ustar rootroot// Copyright Joyent, Inc. and other Node contributors. // // Permission is hereby granted, free of charge, to any person obtaining a // copy of this software and associated documentation files (the // "Software"), to deal in the Software without restriction, including // without limitation the rights to use, copy, modify, merge, publish, // distribute, sublicense, and/or sell copies of the Software, and to permit // persons to whom the Software is furnished to do so, subject to the // following conditions: // // The above copyright notice and this permission notice shall be included // in all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS // OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF // MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN // NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, // DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR // OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE // USE OR OTHER DEALINGS IN THE SOFTWARE. var common = require('../common'); var assert = require('assert'); var net = require('net'); var s = new net.Stream(); // test that destroy called on a stream with a server only ever decrements the // server connection count once s.server = new net.Server(); s.server.connections = 10; assert.equal(10, s.server.connections); s.destroy(); assert.equal(9, s.server.connections); s.destroy(); assert.equal(9, s.server.connections); node-v0.10.25~dfsg2/test/simple/test-http-1.0.js0000644000000000000000000001260412270121457017656 0ustar rootroot// Copyright Joyent, Inc. and other Node contributors. // // Permission is hereby granted, free of charge, to any person obtaining a // copy of this software and associated documentation files (the // "Software"), to deal in the Software without restriction, including // without limitation the rights to use, copy, modify, merge, publish, // distribute, sublicense, and/or sell copies of the Software, and to permit // persons to whom the Software is furnished to do so, subject to the // following conditions: // // The above copyright notice and this permission notice shall be included // in all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS // OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF // MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN // NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, // DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR // OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE // USE OR OTHER DEALINGS IN THE SOFTWARE. var common = require('../common'); var assert = require('assert'); var net = require('net'); var http = require('http'); var body = 'hello world\n'; var common_port = common.PORT; function test(handler, request_generator, response_validator) { var port = common_port++; var server = http.createServer(handler); var client_got_eof = false; var server_response = { data: '', chunks: [] }; function cleanup() { server.close(); response_validator(server_response, client_got_eof, true); } var timer = setTimeout(cleanup, 1000); process.on('exit', cleanup); server.listen(port); server.on('listening', function() { var c = net.createConnection(port); c.setEncoding('utf8'); c.on('connect', function() { c.write(request_generator()); }); c.on('data', function(chunk) { server_response.data += chunk; server_response.chunks.push(chunk); }); c.on('end', function() { client_got_eof = true; c.end(); server.close(); clearTimeout(timer); process.removeListener('exit', cleanup); response_validator(server_response, client_got_eof, false); }); }); } (function() { function handler(req, res) { assert.equal('1.0', req.httpVersion); assert.equal(1, req.httpVersionMajor); assert.equal(0, req.httpVersionMinor); res.writeHead(200, {'Content-Type': 'text/plain'}); res.end(body); } function request_generator() { return 'GET / HTTP/1.0\r\n\r\n'; } function response_validator(server_response, client_got_eof, timed_out) { var m = server_response.data.split('\r\n\r\n'); assert.equal(m[1], body); assert.equal(true, client_got_eof); assert.equal(false, timed_out); } test(handler, request_generator, response_validator); })(); // // Don't send HTTP/1.1 status lines to HTTP/1.0 clients. // // https://github.com/joyent/node/issues/1234 // (function() { function handler(req, res) { assert.equal('1.0', req.httpVersion); assert.equal(1, req.httpVersionMajor); assert.equal(0, req.httpVersionMinor); res.sendDate = false; res.writeHead(200, {'Content-Type': 'text/plain'}); res.write('Hello, '); res._send(''); res.write('world!'); res._send(''); res.end(); } function request_generator() { return ('GET / HTTP/1.0\r\n' + 'User-Agent: curl/7.19.7 (x86_64-pc-linux-gnu) libcurl/7.19.7 ' + 'OpenSSL/0.9.8k zlib/1.2.3.3 libidn/1.15\r\n' + 'Host: 127.0.0.1:1337\r\n' + 'Accept: */*\r\n' + '\r\n'); } function response_validator(server_response, client_got_eof, timed_out) { var expected_response = ('HTTP/1.1 200 OK\r\n' + 'Content-Type: text/plain\r\n' + 'Connection: close\r\n' + '\r\n' + 'Hello, world!'); assert.equal(expected_response, server_response.data); assert.equal(1, server_response.chunks.length); assert.equal(true, client_got_eof); assert.equal(false, timed_out); } test(handler, request_generator, response_validator); })(); (function() { function handler(req, res) { assert.equal('1.1', req.httpVersion); assert.equal(1, req.httpVersionMajor); assert.equal(1, req.httpVersionMinor); res.sendDate = false; res.writeHead(200, {'Content-Type': 'text/plain'}); res.write('Hello, '); res._send(''); res.write('world!'); res._send(''); res.end(); } function request_generator() { return ('GET / HTTP/1.1\r\n' + 'User-Agent: curl/7.19.7 (x86_64-pc-linux-gnu) libcurl/7.19.7 ' + 'OpenSSL/0.9.8k zlib/1.2.3.3 libidn/1.15\r\n' + 'Connection: close\r\n' + 'Host: 127.0.0.1:1337\r\n' + 'Accept: */*\r\n' + '\r\n'); } function response_validator(server_response, client_got_eof, timed_out) { var expected_response = ('HTTP/1.1 200 OK\r\n' + 'Content-Type: text/plain\r\n' + 'Connection: close\r\n' + 'Transfer-Encoding: chunked\r\n' + '\r\n' + '7\r\n' + 'Hello, \r\n' + '6\r\n' + 'world!\r\n' + '0\r\n' + '\r\n'); assert.equal(expected_response, server_response.data); assert.equal(1, server_response.chunks.length); assert.equal(true, client_got_eof); assert.equal(false, timed_out); } test(handler, request_generator, response_validator); })(); node-v0.10.25~dfsg2/test/simple/test-http-304.js0000644000000000000000000000346212270121457017670 0ustar rootroot// Copyright Joyent, Inc. and other Node contributors. // // Permission is hereby granted, free of charge, to any person obtaining a // copy of this software and associated documentation files (the // "Software"), to deal in the Software without restriction, including // without limitation the rights to use, copy, modify, merge, publish, // distribute, sublicense, and/or sell copies of the Software, and to permit // persons to whom the Software is furnished to do so, subject to the // following conditions: // // The above copyright notice and this permission notice shall be included // in all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS // OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF // MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN // NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, // DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR // OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE // USE OR OTHER DEALINGS IN THE SOFTWARE. var common = require('../common'); var assert = require('assert'); var http = require('http'); var childProcess = require('child_process'); var s = http.createServer(function(request, response) { response.writeHead(304); response.end(); }); s.listen(common.PORT, function() { childProcess.exec('curl -i http://127.0.0.1:' + common.PORT + '/', function(err, stdout, stderr) { if (err) throw err; s.close(); common.error('curled response correctly'); common.error(common.inspect(stdout)); }); }); console.log('Server running at http://127.0.0.1:' + common.PORT + '/'); node-v0.10.25~dfsg2/test/simple/test-net-server-try-ports.js0000644000000000000000000000464212270121457022461 0ustar rootroot// Copyright Joyent, Inc. and other Node contributors. // // Permission is hereby granted, free of charge, to any person obtaining a // copy of this software and associated documentation files (the // "Software"), to deal in the Software without restriction, including // without limitation the rights to use, copy, modify, merge, publish, // distribute, sublicense, and/or sell copies of the Software, and to permit // persons to whom the Software is furnished to do so, subject to the // following conditions: // // The above copyright notice and this permission notice shall be included // in all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS // OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF // MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN // NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, // DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR // OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE // USE OR OTHER DEALINGS IN THE SOFTWARE. // This tests binds to one port, then attempts to start a server on that // port. It should be EADDRINUSE but be able to then bind to another port. var common = require('../common'); var assert = require('assert'); var net = require('net'); var connections = 0; var server1listening = false; var server2listening = false; var server1 = net.Server(function(socket) { connections++; socket.destroy(); }); var server2 = net.Server(function(socket) { connections++; socket.destroy(); }); var server2errors = 0; server2.on('error', function() { server2errors++; console.error('server2 error'); }); server1.listen(common.PORT, function() { console.error('server1 listening'); server1listening = true; // This should make server2 emit EADDRINUSE server2.listen(common.PORT); // Wait a bit, now try again. // TODO, the listen callback should report if there was an error. // Then we could avoid this very unlikely but potential race condition // here. setTimeout(function() { server2.listen(common.PORT + 1, function() { console.error('server2 listening'); server2listening = true; server1.close(); server2.close(); }); }, 100); }); process.on('exit', function() { assert.equal(1, server2errors); assert.ok(server2listening); assert.ok(server1listening); }); node-v0.10.25~dfsg2/test/simple/test-http-host-headers.js0000644000000000000000000001221112270121457021740 0ustar rootroot// Copyright Joyent, Inc. and other Node contributors. // // Permission is hereby granted, free of charge, to any person obtaining a // copy of this software and associated documentation files (the // "Software"), to deal in the Software without restriction, including // without limitation the rights to use, copy, modify, merge, publish, // distribute, sublicense, and/or sell copies of the Software, and to permit // persons to whom the Software is furnished to do so, subject to the // following conditions: // // The above copyright notice and this permission notice shall be included // in all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS // OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF // MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN // NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, // DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR // OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE // USE OR OTHER DEALINGS IN THE SOFTWARE. var http = require('http'), https = require('https'), fs = require('fs'), common = require('../common'), assert = require('assert'), options = { key: fs.readFileSync(common.fixturesDir + '/keys/agent1-key.pem'), cert: fs.readFileSync(common.fixturesDir + '/keys/agent1-cert.pem') }, httpServer = http.createServer(reqHandler), httpsServer = https.createServer(options, reqHandler); function reqHandler(req, res) { console.log('Got request: ' + req.headers.host + ' ' + req.url); if (req.url === '/setHostFalse5') { assert.equal(req.headers.host, undefined); } else { assert.equal(req.headers.host, 'localhost:' + common.PORT, 'Wrong host header for req[' + req.url + ']: ' + req.headers.host); } res.writeHead(200, {}); //process.nextTick(function() { res.end('ok'); }); res.end('ok'); } function thrower(er) { throw er; } testHttp(); function testHttp() { console.log('testing http on port ' + common.PORT); var counter = 0; function cb(res) { counter--; console.log('back from http request. counter = ' + counter); if (counter === 0) { httpServer.close(); testHttps(); } res.resume(); } httpServer.listen(common.PORT, function(er) { console.error('listening on ' + common.PORT); if (er) throw er; http.get({ method: 'GET', path: '/' + (counter++), host: 'localhost', //agent: false, port: common.PORT, rejectUnauthorized: false }, cb).on('error', thrower); http.request({ method: 'GET', path: '/' + (counter++), host: 'localhost', //agent: false, port: common.PORT, rejectUnauthorized: false }, cb).on('error', thrower).end(); http.request({ method: 'POST', path: '/' + (counter++), host: 'localhost', //agent: false, port: common.PORT, rejectUnauthorized: false }, cb).on('error', thrower).end(); http.request({ method: 'PUT', path: '/' + (counter++), host: 'localhost', //agent: false, port: common.PORT, rejectUnauthorized: false }, cb).on('error', thrower).end(); http.request({ method: 'DELETE', path: '/' + (counter++), host: 'localhost', //agent: false, port: common.PORT, rejectUnauthorized: false }, cb).on('error', thrower).end(); }); } function testHttps() { console.log('testing https on port ' + common.PORT); var counter = 0; function cb(res) { counter--; console.log('back from https request. counter = ' + counter); if (counter === 0) { httpsServer.close(); console.log('ok'); } res.resume(); } httpsServer.listen(common.PORT, function(er) { if (er) throw er; https.get({ method: 'GET', path: '/' + (counter++), host: 'localhost', //agent: false, port: common.PORT, rejectUnauthorized: false }, cb).on('error', thrower); https.request({ method: 'GET', path: '/' + (counter++), host: 'localhost', //agent: false, port: common.PORT, rejectUnauthorized: false }, cb).on('error', thrower).end(); https.request({ method: 'POST', path: '/' + (counter++), host: 'localhost', //agent: false, port: common.PORT, rejectUnauthorized: false }, cb).on('error', thrower).end(); https.request({ method: 'PUT', path: '/' + (counter++), host: 'localhost', //agent: false, port: common.PORT, rejectUnauthorized: false }, cb).on('error', thrower).end(); https.request({ method: 'DELETE', path: '/' + (counter++), host: 'localhost', //agent: false, port: common.PORT, rejectUnauthorized: false }, cb).on('error', thrower).end(); https.get({ method: 'GET', path: '/setHostFalse' + (counter++), host: 'localhost', setHost: false, port: common.PORT, rejectUnauthorized: false }, cb).on('error', thrower).end(); }); } node-v0.10.25~dfsg2/test/simple/test-console-instance.js0000644000000000000000000000470112270121457021646 0ustar rootroot// Copyright Joyent, Inc. and other Node contributors. // // Permission is hereby granted, free of charge, to any person obtaining a // copy of this software and associated documentation files (the // "Software"), to deal in the Software without restriction, including // without limitation the rights to use, copy, modify, merge, publish, // distribute, sublicense, and/or sell copies of the Software, and to permit // persons to whom the Software is furnished to do so, subject to the // following conditions: // // The above copyright notice and this permission notice shall be included // in all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS // OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF // MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN // NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, // DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR // OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE // USE OR OTHER DEALINGS IN THE SOFTWARE. var common = require('../common'); var assert = require('assert'); var Stream = require('stream'); var Console = require('console').Console; var called = false; // ensure the Console instance doesn't write to the // process' "stdout" or "stderr" streams process.stdout.write = process.stderr.write = function() { throw new Error('write() should not be called!'); }; // make sure that the "Console" function exists assert.equal('function', typeof Console); // make sure that the Console constructor throws // when not given a writable stream instance assert.throws(function () { new Console(); }, /Console expects a writable stream/); var out = new Stream(); var err = new Stream(); out.writable = err.writable = true; out.write = err.write = function(d) {}; var c = new Console(out, err); out.write = err.write = function(d) { assert.equal(d, 'test\n'); called = true; }; assert(!called); c.log('test'); assert(called); called = false; c.error('test'); assert(called); out.write = function(d) { assert.equal('{ foo: 1 }\n', d); called = true; }; called = false; c.dir({ foo: 1 }); assert(called); // ensure that the console functions are bound to the console instance called = 0; out.write = function(d) { called++; assert.equal(d, called + ' ' + (called - 1) + ' [ 1, 2, 3 ]\n'); }; [1, 2, 3].forEach(c.log); assert.equal(3, called); node-v0.10.25~dfsg2/test/simple/test-crypto.js0000644000000000000000000010231412270121457017721 0ustar rootroot// Copyright Joyent, Inc. and other Node contributors. // // Permission is hereby granted, free of charge, to any person obtaining a // copy of this software and associated documentation files (the // "Software"), to deal in the Software without restriction, including // without limitation the rights to use, copy, modify, merge, publish, // distribute, sublicense, and/or sell copies of the Software, and to permit // persons to whom the Software is furnished to do so, subject to the // following conditions: // // The above copyright notice and this permission notice shall be included // in all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS // OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF // MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN // NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, // DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR // OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE // USE OR OTHER DEALINGS IN THE SOFTWARE. var common = require('../common'); var assert = require('assert'); try { var crypto = require('crypto'); } catch (e) { console.log('Not compiled with OPENSSL support.'); process.exit(); } crypto.DEFAULT_ENCODING = 'buffer'; var fs = require('fs'); var path = require('path'); // Test Certificates var caPem = fs.readFileSync(common.fixturesDir + '/test_ca.pem', 'ascii'); var certPem = fs.readFileSync(common.fixturesDir + '/test_cert.pem', 'ascii'); var certPfx = fs.readFileSync(common.fixturesDir + '/test_cert.pfx'); var keyPem = fs.readFileSync(common.fixturesDir + '/test_key.pem', 'ascii'); var rsaPubPem = fs.readFileSync(common.fixturesDir + '/test_rsa_pubkey.pem', 'ascii'); var rsaKeyPem = fs.readFileSync(common.fixturesDir + '/test_rsa_privkey.pem', 'ascii'); try { var credentials = crypto.createCredentials( {key: keyPem, cert: certPem, ca: caPem}); } catch (e) { console.log('Not compiled with OPENSSL support.'); process.exit(); } // PFX tests assert.doesNotThrow(function() { crypto.createCredentials({pfx:certPfx, passphrase:'sample'}); }); assert.throws(function() { crypto.createCredentials({pfx:certPfx}); }, 'mac verify failure'); assert.throws(function() { crypto.createCredentials({pfx:certPfx, passphrase:'test'}); }, 'mac verify failure'); assert.throws(function() { crypto.createCredentials({pfx:'sample', passphrase:'test'}); }, 'not enough data'); // Test HMAC var h1 = crypto.createHmac('sha1', 'Node') .update('some data') .update('to hmac') .digest('hex'); assert.equal(h1, '19fd6e1ba73d9ed2224dd5094a71babe85d9a892', 'test HMAC'); // Test HMAC (Wikipedia Test Cases) var wikipedia = [ { key: 'key', data: 'The quick brown fox jumps over the lazy dog', hmac: { // HMACs lifted from Wikipedia. md5: '80070713463e7749b90c2dc24911e275', sha1: 'de7c9b85b8b78aa6bc8a7a36f70a90701c9db4d9', sha256: 'f7bc83f430538424b13298e6aa6fb143ef4d59a14946175997479dbc' + '2d1a3cd8' } }, { key: 'key', data: '', hmac: { // Intermediate test to help debugging. md5: '63530468a04e386459855da0063b6596', sha1: 'f42bb0eeb018ebbd4597ae7213711ec60760843f', sha256: '5d5d139563c95b5967b9bd9a8c9b233a9dedb45072794cd232dc1b74' + '832607d0' } }, { key: '', data: 'The quick brown fox jumps over the lazy dog', hmac: { // Intermediate test to help debugging. md5: 'ad262969c53bc16032f160081c4a07a0', sha1: '2ba7f707ad5f187c412de3106583c3111d668de8', sha256: 'fb011e6154a19b9a4c767373c305275a5a69e8b68b0b4c9200c383dc' + 'ed19a416' } }, { key: '', data: '', hmac: { // HMACs lifted from Wikipedia. md5: '74e6f7298a9c2d168935f58c001bad88', sha1: 'fbdb1d1b18aa6c08324b7d64b71fb76370690e1d', sha256: 'b613679a0814d9ec772f95d778c35fc5ff1697c493715653c6c71214' + '4292c5ad' } }, ] for (var i = 0, l = wikipedia.length; i < l; i++) { for (var hash in wikipedia[i]['hmac']) { var result = crypto.createHmac(hash, wikipedia[i]['key']) .update(wikipedia[i]['data']) .digest('hex'); assert.equal(wikipedia[i]['hmac'][hash], result, 'Test HMAC-' + hash + ': Test case ' + (i + 1) + ' wikipedia'); } } // Test HMAC-SHA-* (rfc 4231 Test Cases) var rfc4231 = [ { key: new Buffer('0b0b0b0b0b0b0b0b0b0b0b0b0b0b0b0b0b0b0b0b', 'hex'), data: new Buffer('4869205468657265', 'hex'), // 'Hi There' hmac: { sha224: '896fb1128abbdf196832107cd49df33f47b4b1169912ba4f53684b22', sha256: 'b0344c61d8db38535ca8afceaf0bf12b881dc200c9833da726e9376c' + '2e32cff7', sha384: 'afd03944d84895626b0825f4ab46907f15f9dadbe4101ec682aa034c' + '7cebc59cfaea9ea9076ede7f4af152e8b2fa9cb6', sha512: '87aa7cdea5ef619d4ff0b4241a1d6cb02379f4e2ce4ec2787ad0b305' + '45e17cdedaa833b7d6b8a702038b274eaea3f4e4be9d914eeb61f170' + '2e696c203a126854' } }, { key: new Buffer('4a656665', 'hex'), // 'Jefe' data: new Buffer('7768617420646f2079612077616e7420666f72206e6f74686' + '96e673f', 'hex'), // 'what do ya want for nothing?' hmac: { sha224: 'a30e01098bc6dbbf45690f3a7e9e6d0f8bbea2a39e6148008fd05e44', sha256: '5bdcc146bf60754e6a042426089575c75a003f089d2739839dec58b9' + '64ec3843', sha384: 'af45d2e376484031617f78d2b58a6b1b9c7ef464f5a01b47e42ec373' + '6322445e8e2240ca5e69e2c78b3239ecfab21649', sha512: '164b7a7bfcf819e2e395fbe73b56e0a387bd64222e831fd610270cd7' + 'ea2505549758bf75c05a994a6d034f65f8f0e6fdcaeab1a34d4a6b4b' + '636e070a38bce737' } }, { key: new Buffer('aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa', 'hex'), data: new Buffer('ddddddddddddddddddddddddddddddddddddddddddddddddd' + 'ddddddddddddddddddddddddddddddddddddddddddddddddddd', 'hex'), hmac: { sha224: '7fb3cb3588c6c1f6ffa9694d7d6ad2649365b0c1f65d69d1ec8333ea', sha256: '773ea91e36800e46854db8ebd09181a72959098b3ef8c122d9635514' + 'ced565fe', sha384: '88062608d3e6ad8a0aa2ace014c8a86f0aa635d947ac9febe83ef4e5' + '5966144b2a5ab39dc13814b94e3ab6e101a34f27', sha512: 'fa73b0089d56a284efb0f0756c890be9b1b5dbdd8ee81a3655f83e33' + 'b2279d39bf3e848279a722c806b485a47e67c807b946a337bee89426' + '74278859e13292fb' } }, { key: new Buffer('0102030405060708090a0b0c0d0e0f10111213141516171819', 'hex'), data: new Buffer('cdcdcdcdcdcdcdcdcdcdcdcdcdcdcdcdcdcdcdcdcdcdcdcdc' + 'dcdcdcdcdcdcdcdcdcdcdcdcdcdcdcdcdcdcdcdcdcdcdcdcdcd', 'hex'), hmac: { sha224: '6c11506874013cac6a2abc1bb382627cec6a90d86efc012de7afec5a', sha256: '82558a389a443c0ea4cc819899f2083a85f0faa3e578f8077a2e3ff4' + '6729665b', sha384: '3e8a69b7783c25851933ab6290af6ca77a9981480850009cc5577c6e' + '1f573b4e6801dd23c4a7d679ccf8a386c674cffb', sha512: 'b0ba465637458c6990e5a8c5f61d4af7e576d97ff94b872de76f8050' + '361ee3dba91ca5c11aa25eb4d679275cc5788063a5f19741120c4f2d' + 'e2adebeb10a298dd' } }, { key: new Buffer('0c0c0c0c0c0c0c0c0c0c0c0c0c0c0c0c0c0c0c0c', 'hex'), // 'Test With Truncation' data: new Buffer('546573742057697468205472756e636174696f6e', 'hex'), hmac: { sha224: '0e2aea68a90c8d37c988bcdb9fca6fa8', sha256: 'a3b6167473100ee06e0c796c2955552b', sha384: '3abf34c3503b2a23a46efc619baef897', sha512: '415fad6271580a531d4179bc891d87a6' }, truncate: true }, { key: new Buffer('aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa' + 'aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa' + 'aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa' + 'aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa' + 'aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa' + 'aaaaaaaaaaaa', 'hex'), // 'Test Using Larger Than Block-Size Key - Hash Key First' data: new Buffer('54657374205573696e67204c6172676572205468616e20426' + 'c6f636b2d53697a65204b6579202d2048617368204b657920' + '4669727374', 'hex'), hmac: { sha224: '95e9a0db962095adaebe9b2d6f0dbce2d499f112f2d2b7273fa6870e', sha256: '60e431591ee0b67f0d8a26aacbf5b77f8e0bc6213728c5140546040f' + '0ee37f54', sha384: '4ece084485813e9088d2c63a041bc5b44f9ef1012a2b588f3cd11f05' + '033ac4c60c2ef6ab4030fe8296248df163f44952', sha512: '80b24263c7c1a3ebb71493c1dd7be8b49b46d1f41b4aeec1121b0137' + '83f8f3526b56d037e05f2598bd0fd2215d6a1e5295e64f73f63f0aec' + '8b915a985d786598' } }, { key: new Buffer('aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa' + 'aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa' + 'aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa' + 'aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa' + 'aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa' + 'aaaaaaaaaaaa', 'hex'), // 'This is a test using a larger than block-size key and a larger ' + // 'than block-size data. The key needs to be hashed before being ' + // 'used by the HMAC algorithm.' data: new Buffer('5468697320697320612074657374207573696e672061206c6' + '172676572207468616e20626c6f636b2d73697a65206b6579' + '20616e642061206c6172676572207468616e20626c6f636b2' + 'd73697a6520646174612e20546865206b6579206e65656473' + '20746f20626520686173686564206265666f7265206265696' + 'e6720757365642062792074686520484d414320616c676f72' + '6974686d2e', 'hex'), hmac: { sha224: '3a854166ac5d9f023f54d517d0b39dbd946770db9c2b95c9f6f565d1', sha256: '9b09ffa71b942fcb27635fbcd5b0e944bfdc63644f0713938a7f5153' + '5c3a35e2', sha384: '6617178e941f020d351e2f254e8fd32c602420feb0b8fb9adccebb82' + '461e99c5a678cc31e799176d3860e6110c46523e', sha512: 'e37b6a775dc87dbaa4dfa9f96e5e3ffddebd71f8867289865df5a32d' + '20cdc944b6022cac3c4982b10d5eeb55c3e4de15134676fb6de04460' + '65c97440fa8c6a58' } } ]; for (var i = 0, l = rfc4231.length; i < l; i++) { for (var hash in rfc4231[i]['hmac']) { var str = crypto.createHmac(hash, rfc4231[i].key); str.end(rfc4231[i].data); var strRes = str.read().toString('hex'); var result = crypto.createHmac(hash, rfc4231[i]['key']) .update(rfc4231[i]['data']) .digest('hex'); if (rfc4231[i]['truncate']) { result = result.substr(0, 32); // first 128 bits == 32 hex chars strRes = strRes.substr(0, 32); } assert.equal(rfc4231[i]['hmac'][hash], result, 'Test HMAC-' + hash + ': Test case ' + (i + 1) + ' rfc 4231'); assert.equal(strRes, result, 'Should get same result from stream'); } } // Test HMAC-MD5/SHA1 (rfc 2202 Test Cases) var rfc2202_md5 = [ { key: new Buffer('0b0b0b0b0b0b0b0b0b0b0b0b0b0b0b0b', 'hex'), data: 'Hi There', hmac: '9294727a3638bb1c13f48ef8158bfc9d' }, { key: 'Jefe', data: 'what do ya want for nothing?', hmac: '750c783e6ab0b503eaa86e310a5db738' }, { key: new Buffer('aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa', 'hex'), data: new Buffer('ddddddddddddddddddddddddddddddddddddddddddddddddd' + 'ddddddddddddddddddddddddddddddddddddddddddddddddddd', 'hex'), hmac: '56be34521d144c88dbb8c733f0e8b3f6' }, { key: new Buffer('0102030405060708090a0b0c0d0e0f10111213141516171819', 'hex'), data: new Buffer('cdcdcdcdcdcdcdcdcdcdcdcdcdcdcdcdcdcdcdcdcdcdc' + 'dcdcdcdcdcdcdcdcdcdcdcdcdcdcdcdcdcdcdcdcdcdcd' + 'cdcdcdcdcd', 'hex'), hmac: '697eaf0aca3a3aea3a75164746ffaa79' }, { key: new Buffer('0c0c0c0c0c0c0c0c0c0c0c0c0c0c0c0c', 'hex'), data: 'Test With Truncation', hmac: '56461ef2342edc00f9bab995690efd4c' }, { key: new Buffer('aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa' + 'aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa' + 'aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa' + 'aaaaaaaaaaaaaaaaaaaaaa', 'hex'), data: 'Test Using Larger Than Block-Size Key - Hash Key First', hmac: '6b1ab7fe4bd7bf8f0b62e6ce61b9d0cd' }, { key: new Buffer('aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa' + 'aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa' + 'aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa' + 'aaaaaaaaaaaaaaaaaaaaaa', 'hex'), data: 'Test Using Larger Than Block-Size Key and Larger Than One ' + 'Block-Size Data', hmac: '6f630fad67cda0ee1fb1f562db3aa53e' } ]; var rfc2202_sha1 = [ { key: new Buffer('0b0b0b0b0b0b0b0b0b0b0b0b0b0b0b0b0b0b0b0b', 'hex'), data: 'Hi There', hmac: 'b617318655057264e28bc0b6fb378c8ef146be00' }, { key: 'Jefe', data: 'what do ya want for nothing?', hmac: 'effcdf6ae5eb2fa2d27416d5f184df9c259a7c79' }, { key: new Buffer('aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa', 'hex'), data: new Buffer('ddddddddddddddddddddddddddddddddddddddddddddd' + 'ddddddddddddddddddddddddddddddddddddddddddddd' + 'dddddddddd', 'hex'), hmac: '125d7342b9ac11cd91a39af48aa17b4f63f175d3' }, { key: new Buffer('0102030405060708090a0b0c0d0e0f10111213141516171819', 'hex'), data: new Buffer('cdcdcdcdcdcdcdcdcdcdcdcdcdcdcdcdcdcdcdcdcdcdc' + 'dcdcdcdcdcdcdcdcdcdcdcdcdcdcdcdcdcdcdcdcdcdcd' + 'cdcdcdcdcd', 'hex'), hmac: '4c9007f4026250c6bc8414f9bf50c86c2d7235da' }, { key: new Buffer('0c0c0c0c0c0c0c0c0c0c0c0c0c0c0c0c0c0c0c0c', 'hex'), data: 'Test With Truncation', hmac: '4c1a03424b55e07fe7f27be1d58bb9324a9a5a04' }, { key: new Buffer('aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa' + 'aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa' + 'aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa' + 'aaaaaaaaaaaaaaaaaaaaaa', 'hex'), data: 'Test Using Larger Than Block-Size Key - Hash Key First', hmac: 'aa4ae5e15272d00e95705637ce8a3b55ed402112' }, { key: new Buffer('aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa' + 'aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa' + 'aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa' + 'aaaaaaaaaaaaaaaaaaaaaa', 'hex'), data: 'Test Using Larger Than Block-Size Key and Larger Than One ' + 'Block-Size Data', hmac: 'e8e99d0f45237d786d6bbaa7965c7808bbff1a91' } ]; for (var i = 0, l = rfc2202_md5.length; i < l; i++) { assert.equal(rfc2202_md5[i]['hmac'], crypto.createHmac('md5', rfc2202_md5[i]['key']) .update(rfc2202_md5[i]['data']) .digest('hex'), 'Test HMAC-MD5 : Test case ' + (i + 1) + ' rfc 2202'); } for (var i = 0, l = rfc2202_sha1.length; i < l; i++) { assert.equal(rfc2202_sha1[i]['hmac'], crypto.createHmac('sha1', rfc2202_sha1[i]['key']) .update(rfc2202_sha1[i]['data']) .digest('hex'), 'Test HMAC-SHA1 : Test case ' + (i + 1) + ' rfc 2202'); } // Test hashing var a0 = crypto.createHash('sha1').update('Test123').digest('hex'); var a1 = crypto.createHash('md5').update('Test123').digest('binary'); var a2 = crypto.createHash('sha256').update('Test123').digest('base64'); var a3 = crypto.createHash('sha512').update('Test123').digest(); // binary var a4 = crypto.createHash('sha1').update('Test123').digest('buffer'); // stream interface var a5 = crypto.createHash('sha512'); a5.end('Test123'); a5 = a5.read(); var a6 = crypto.createHash('sha512'); a6.write('Te'); a6.write('st'); a6.write('123'); a6.end(); a6 = a6.read(); assert.equal(a0, '8308651804facb7b9af8ffc53a33a22d6a1c8ac2', 'Test SHA1'); assert.equal(a1, 'h\u00ea\u00cb\u0097\u00d8o\fF!\u00fa+\u000e\u0017\u00ca' + '\u00bd\u008c', 'Test MD5 as binary'); assert.equal(a2, '2bX1jws4GYKTlxhloUB09Z66PoJZW+y+hq5R8dnx9l4=', 'Test SHA256 as base64'); assert.deepEqual( a3, new Buffer( '\u00c1(4\u00f1\u0003\u001fd\u0097!O\'\u00d4C/&Qz\u00d4' + '\u0094\u0015l\u00b8\u008dQ+\u00db\u001d\u00c4\u00b5}\u00b2' + '\u00d6\u0092\u00a3\u00df\u00a2i\u00a1\u009b\n\n*\u000f' + '\u00d7\u00d6\u00a2\u00a8\u0085\u00e3<\u0083\u009c\u0093' + '\u00c2\u0006\u00da0\u00a1\u00879(G\u00ed\'', 'binary'), 'Test SHA512 as assumed buffer'); assert.deepEqual(a4, new Buffer('8308651804facb7b9af8ffc53a33a22d6a1c8ac2', 'hex'), 'Test SHA1'); // stream interface should produce the same result. assert.deepEqual(a5, a3, 'stream interface is consistent'); assert.deepEqual(a6, a3, 'stream interface is consistent'); // Test multiple updates to same hash var h1 = crypto.createHash('sha1').update('Test123').digest('hex'); var h2 = crypto.createHash('sha1').update('Test').update('123').digest('hex'); assert.equal(h1, h2, 'multipled updates'); // Test hashing for binary files var fn = path.join(common.fixturesDir, 'sample.png'); var sha1Hash = crypto.createHash('sha1'); var fileStream = fs.createReadStream(fn); fileStream.on('data', function(data) { sha1Hash.update(data); }); fileStream.on('close', function() { assert.equal(sha1Hash.digest('hex'), '22723e553129a336ad96e10f6aecdf0f45e4149e', 'Test SHA1 of sample.png'); }); // Issue #2227: unknown digest method should throw an error. assert.throws(function() { crypto.createHash('xyzzy'); }); // Test signing and verifying var s1 = crypto.createSign('RSA-SHA1') .update('Test123') .sign(keyPem, 'base64'); var s1stream = crypto.createSign('RSA-SHA1'); s1stream.end('Test123'); s1stream = s1stream.sign(keyPem, 'base64'); assert.equal(s1, s1stream, 'Stream produces same output'); var verified = crypto.createVerify('RSA-SHA1') .update('Test') .update('123') .verify(certPem, s1, 'base64'); assert.strictEqual(verified, true, 'sign and verify (base 64)'); var s2 = crypto.createSign('RSA-SHA256') .update('Test123') .sign(keyPem, 'binary'); var s2stream = crypto.createSign('RSA-SHA256'); s2stream.end('Test123'); s2stream = s2stream.sign(keyPem, 'binary'); assert.equal(s2, s2stream, 'Stream produces same output'); var verified = crypto.createVerify('RSA-SHA256') .update('Test') .update('123') .verify(certPem, s2, 'binary'); assert.strictEqual(verified, true, 'sign and verify (binary)'); var verStream = crypto.createVerify('RSA-SHA256'); verStream.write('Tes'); verStream.write('t12'); verStream.end('3'); verified = verStream.verify(certPem, s2, 'binary'); assert.strictEqual(verified, true, 'sign and verify (stream)'); var s3 = crypto.createSign('RSA-SHA1') .update('Test123') .sign(keyPem, 'buffer'); var verified = crypto.createVerify('RSA-SHA1') .update('Test') .update('123') .verify(certPem, s3); assert.strictEqual(verified, true, 'sign and verify (buffer)'); var verStream = crypto.createVerify('RSA-SHA1'); verStream.write('Tes'); verStream.write('t12'); verStream.end('3'); verified = verStream.verify(certPem, s3); assert.strictEqual(verified, true, 'sign and verify (stream)'); function testCipher1(key) { // Test encryption and decryption var plaintext = 'Keep this a secret? No! Tell everyone about node.js!'; var cipher = crypto.createCipher('aes192', key); // encrypt plaintext which is in utf8 format // to a ciphertext which will be in hex var ciph = cipher.update(plaintext, 'utf8', 'hex'); // Only use binary or hex, not base64. ciph += cipher.final('hex'); var decipher = crypto.createDecipher('aes192', key); var txt = decipher.update(ciph, 'hex', 'utf8'); txt += decipher.final('utf8'); assert.equal(txt, plaintext, 'encryption and decryption'); // streaming cipher interface // NB: In real life, it's not guaranteed that you can get all of it // in a single read() like this. But in this case, we know it's // quite small, so there's no harm. var cStream = crypto.createCipher('aes192', key); cStream.end(plaintext); ciph = cStream.read(); var dStream = crypto.createDecipher('aes192', key); dStream.end(ciph); txt = dStream.read().toString('utf8'); assert.equal(txt, plaintext, 'encryption and decryption with streams'); } function testCipher2(key) { // encryption and decryption with Base64 // reported in https://github.com/joyent/node/issues/738 var plaintext = '32|RmVZZkFUVmpRRkp0TmJaUm56ZU9qcnJkaXNNWVNpTTU*|iXmckfRWZBGWWELw' + 'eCBsThSsfUHLeRe0KCsK8ooHgxie0zOINpXxfZi/oNG7uq9JWFVCk70gfzQH8ZUJ' + 'jAfaFg**'; var cipher = crypto.createCipher('aes256', key); // encrypt plaintext which is in utf8 format // to a ciphertext which will be in Base64 var ciph = cipher.update(plaintext, 'utf8', 'base64'); ciph += cipher.final('base64'); var decipher = crypto.createDecipher('aes256', key); var txt = decipher.update(ciph, 'base64', 'utf8'); txt += decipher.final('utf8'); assert.equal(txt, plaintext, 'encryption and decryption with Base64'); } function testCipher3(key, iv) { // Test encyrption and decryption with explicit key and iv var plaintext = '32|RmVZZkFUVmpRRkp0TmJaUm56ZU9qcnJkaXNNWVNpTTU*|iXmckfRWZBGWWELw' + 'eCBsThSsfUHLeRe0KCsK8ooHgxie0zOINpXxfZi/oNG7uq9JWFVCk70gfzQH8ZUJ' + 'jAfaFg**'; var cipher = crypto.createCipheriv('des-ede3-cbc', key, iv); var ciph = cipher.update(plaintext, 'utf8', 'hex'); ciph += cipher.final('hex'); var decipher = crypto.createDecipheriv('des-ede3-cbc', key, iv); var txt = decipher.update(ciph, 'hex', 'utf8'); txt += decipher.final('utf8'); assert.equal(txt, plaintext, 'encryption and decryption with key and iv'); // streaming cipher interface // NB: In real life, it's not guaranteed that you can get all of it // in a single read() like this. But in this case, we know it's // quite small, so there's no harm. var cStream = crypto.createCipheriv('des-ede3-cbc', key, iv); cStream.end(plaintext); ciph = cStream.read(); var dStream = crypto.createDecipheriv('des-ede3-cbc', key, iv); dStream.end(ciph); txt = dStream.read().toString('utf8'); assert.equal(txt, plaintext, 'streaming cipher iv'); } function testCipher4(key, iv) { // Test encyrption and decryption with explicit key and iv var plaintext = '32|RmVZZkFUVmpRRkp0TmJaUm56ZU9qcnJkaXNNWVNpTTU*|iXmckfRWZBGWWELw' + 'eCBsThSsfUHLeRe0KCsK8ooHgxie0zOINpXxfZi/oNG7uq9JWFVCk70gfzQH8ZUJ' + 'jAfaFg**'; var cipher = crypto.createCipheriv('des-ede3-cbc', key, iv); var ciph = cipher.update(plaintext, 'utf8', 'buffer'); ciph = Buffer.concat([ciph, cipher.final('buffer')]); var decipher = crypto.createDecipheriv('des-ede3-cbc', key, iv); var txt = decipher.update(ciph, 'buffer', 'utf8'); txt += decipher.final('utf8'); assert.equal(txt, plaintext, 'encryption and decryption with key and iv'); } testCipher1('MySecretKey123'); testCipher1(new Buffer('MySecretKey123')); testCipher2('0123456789abcdef'); testCipher2(new Buffer('0123456789abcdef')); testCipher3('0123456789abcd0123456789', '12345678'); testCipher3('0123456789abcd0123456789', new Buffer('12345678')); testCipher3(new Buffer('0123456789abcd0123456789'), '12345678'); testCipher3(new Buffer('0123456789abcd0123456789'), new Buffer('12345678')); testCipher4(new Buffer('0123456789abcd0123456789'), new Buffer('12345678')); // update() should only take buffers / strings assert.throws(function() { crypto.createHash('sha1').update({foo: 'bar'}); }, /buffer/); // Test Diffie-Hellman with two parties sharing a secret, // using various encodings as we go along var dh1 = crypto.createDiffieHellman(256); var p1 = dh1.getPrime('buffer'); var dh2 = crypto.createDiffieHellman(p1, 'base64'); var key1 = dh1.generateKeys(); var key2 = dh2.generateKeys('hex'); var secret1 = dh1.computeSecret(key2, 'hex', 'base64'); var secret2 = dh2.computeSecret(key1, 'binary', 'buffer'); assert.equal(secret1, secret2.toString('base64')); // Create "another dh1" using generated keys from dh1, // and compute secret again var dh3 = crypto.createDiffieHellman(p1, 'buffer'); var privkey1 = dh1.getPrivateKey(); dh3.setPublicKey(key1); dh3.setPrivateKey(privkey1); assert.deepEqual(dh1.getPrime(), dh3.getPrime()); assert.deepEqual(dh1.getGenerator(), dh3.getGenerator()); assert.deepEqual(dh1.getPublicKey(), dh3.getPublicKey()); assert.deepEqual(dh1.getPrivateKey(), dh3.getPrivateKey()); var secret3 = dh3.computeSecret(key2, 'hex', 'base64'); assert.equal(secret1, secret3); // Run this one twice to make sure that the dh3 clears its error properly (function() { var c = crypto.createDecipher('aes-128-ecb', ''); assert.throws(function() { c.final('utf8') }, /wrong final block length/); })(); assert.throws(function() { dh3.computeSecret(''); }, /key is too small/i); (function() { var c = crypto.createDecipher('aes-128-ecb', ''); assert.throws(function() { c.final('utf8') }, /wrong final block length/); })(); // Create a shared using a DH group. var alice = crypto.createDiffieHellmanGroup('modp5'); var bob = crypto.createDiffieHellmanGroup('modp5'); alice.generateKeys(); bob.generateKeys(); var aSecret = alice.computeSecret(bob.getPublicKey()).toString('hex'); var bSecret = bob.computeSecret(alice.getPublicKey()).toString('hex'); assert.equal(aSecret, bSecret); // https://github.com/joyent/node/issues/2338 assert.throws(function() { var p = 'FFFFFFFFFFFFFFFFC90FDAA22168C234C4C6628B80DC1CD129024E088A67CC74' + '020BBEA63B139B22514A08798E3404DDEF9519B3CD3A431B302B0A6DF25F1437' + '4FE1356D6D51C245E485B576625E7EC6F44C42E9A637ED6B0BFF5CB6F406B7ED' + 'EE386BFB5A899FA5AE9F24117C4B1FE649286651ECE65381FFFFFFFFFFFFFFFF'; crypto.createDiffieHellman(p, 'hex'); }); // Test RSA key signing/verification var rsaSign = crypto.createSign('RSA-SHA1'); var rsaVerify = crypto.createVerify('RSA-SHA1'); assert.ok(rsaSign); assert.ok(rsaVerify); rsaSign.update(rsaPubPem); var rsaSignature = rsaSign.sign(rsaKeyPem, 'hex'); assert.equal(rsaSignature, '5c50e3145c4e2497aadb0eabc83b342d0b0021ece0d4c4a064b7c' + '8f020d7e2688b122bfb54c724ac9ee169f83f66d2fe90abeb95e8' + 'e1290e7e177152a4de3d944cf7d4883114a20ed0f78e70e25ef0f' + '60f06b858e6af42a2f276ede95bbc6bc9a9bbdda15bd663186a6f' + '40819a7af19e577bb2efa5e579a1f5ce8a0d4ca8b8f6'); rsaVerify.update(rsaPubPem); assert.strictEqual(rsaVerify.verify(rsaPubPem, rsaSignature, 'hex'), true); // // Test RSA signing and verification // (function() { var privateKey = fs.readFileSync( common.fixturesDir + '/test_rsa_privkey_2.pem'); var publicKey = fs.readFileSync( common.fixturesDir + '/test_rsa_pubkey_2.pem'); var input = 'I AM THE WALRUS'; var signature = '79d59d34f56d0e94aa6a3e306882b52ed4191f07521f25f505a078dc2f89' + '396e0c8ac89e996fde5717f4cb89199d8fec249961fcb07b74cd3d2a4ffa' + '235417b69618e4bcd76b97e29975b7ce862299410e1b522a328e44ac9bb2' + '8195e0268da7eda23d9825ac43c724e86ceeee0d0d4465678652ccaf6501' + '0ddfb299bedeb1ad'; var sign = crypto.createSign('RSA-SHA256'); sign.update(input); var output = sign.sign(privateKey, 'hex'); assert.equal(output, signature); var verify = crypto.createVerify('RSA-SHA256'); verify.update(input); assert.strictEqual(verify.verify(publicKey, signature, 'hex'), true); })(); // // Test DSA signing and verification // (function() { var privateKey = fs.readFileSync( common.fixturesDir + '/test_dsa_privkey.pem'); var publicKey = fs.readFileSync( common.fixturesDir + '/test_dsa_pubkey.pem'); var input = 'I AM THE WALRUS'; // DSA signatures vary across runs so there is no static string to verify // against var sign = crypto.createSign('DSS1'); sign.update(input); var signature = sign.sign(privateKey, 'hex'); var verify = crypto.createVerify('DSS1'); verify.update(input); assert.strictEqual(verify.verify(publicKey, signature, 'hex'), true); })(); // // Test PBKDF2 with RFC 6070 test vectors (except #4) // function testPBKDF2(password, salt, iterations, keylen, expected) { var actual = crypto.pbkdf2Sync(password, salt, iterations, keylen); assert.equal(actual.toString('binary'), expected); crypto.pbkdf2(password, salt, iterations, keylen, function(err, actual) { assert.equal(actual.toString('binary'), expected); }); } testPBKDF2('password', 'salt', 1, 20, '\x0c\x60\xc8\x0f\x96\x1f\x0e\x71\xf3\xa9\xb5\x24' + '\xaf\x60\x12\x06\x2f\xe0\x37\xa6'); testPBKDF2('password', 'salt', 2, 20, '\xea\x6c\x01\x4d\xc7\x2d\x6f\x8c\xcd\x1e\xd9\x2a' + '\xce\x1d\x41\xf0\xd8\xde\x89\x57'); testPBKDF2('password', 'salt', 4096, 20, '\x4b\x00\x79\x01\xb7\x65\x48\x9a\xbe\xad\x49\xd9\x26' + '\xf7\x21\xd0\x65\xa4\x29\xc1'); testPBKDF2('passwordPASSWORDpassword', 'saltSALTsaltSALTsaltSALTsaltSALTsalt', 4096, 25, '\x3d\x2e\xec\x4f\xe4\x1c\x84\x9b\x80\xc8\xd8\x36\x62' + '\xc0\xe4\x4a\x8b\x29\x1a\x96\x4c\xf2\xf0\x70\x38'); testPBKDF2('pass\0word', 'sa\0lt', 4096, 16, '\x56\xfa\x6a\xa7\x55\x48\x09\x9d\xcc\x37\xd7\xf0\x34' + '\x25\xe0\xc3'); function assertSorted(list) { assert.deepEqual(list, list.sort()); } // Assume that we have at least AES-128-CBC. assert.notEqual(0, crypto.getCiphers().length); assert.notEqual(-1, crypto.getCiphers().indexOf('aes-128-cbc')); assert.equal(-1, crypto.getCiphers().indexOf('AES-128-CBC')); assertSorted(crypto.getCiphers()); // Assume that we have at least AES256-SHA. var tls = require('tls'); assert.notEqual(0, tls.getCiphers().length); assert.notEqual(-1, tls.getCiphers().indexOf('aes256-sha')); assert.equal(-1, tls.getCiphers().indexOf('AES256-SHA')); assertSorted(tls.getCiphers()); // Assert that we have sha and sha1 but not SHA and SHA1. assert.notEqual(0, crypto.getHashes().length); assert.notEqual(-1, crypto.getHashes().indexOf('sha1')); assert.notEqual(-1, crypto.getHashes().indexOf('sha')); assert.equal(-1, crypto.getHashes().indexOf('SHA1')); assert.equal(-1, crypto.getHashes().indexOf('SHA')); assertSorted(crypto.getHashes()); // Base64 padding regression test, see #4837. (function() { var c = crypto.createCipher('aes-256-cbc', 'secret'); var s = c.update('test', 'utf8', 'base64') + c.final('base64'); assert.equal(s, '375oxUQCIocvxmC5At+rvA=='); })(); // Error path should not leak memory (check with valgrind). assert.throws(function() { crypto.pbkdf2('password', 'salt', 1, 20, null); }); // Calling Cipher.final() or Decipher.final() twice should error but // not assert. See #4886. (function() { var c = crypto.createCipher('aes-256-cbc', 'secret'); try { c.final('xxx') } catch (e) { /* Ignore. */ } try { c.final('xxx') } catch (e) { /* Ignore. */ } try { c.final('xxx') } catch (e) { /* Ignore. */ } var d = crypto.createDecipher('aes-256-cbc', 'secret'); try { d.final('xxx') } catch (e) { /* Ignore. */ } try { d.final('xxx') } catch (e) { /* Ignore. */ } try { d.final('xxx') } catch (e) { /* Ignore. */ } })(); // Regression test for #5482: string to Cipher#update() should not assert. (function() { var c = crypto.createCipher('aes192', '0123456789abcdef'); c.update('update'); c.final(); })(); // #5655 regression tests, 'utf-8' and 'utf8' are identical. (function() { var c = crypto.createCipher('aes192', '0123456789abcdef'); c.update('update', ''); // Defaults to "utf8". c.final('utf-8'); // Should not throw. c = crypto.createCipher('aes192', '0123456789abcdef'); c.update('update', 'utf8'); c.final('utf-8'); // Should not throw. c = crypto.createCipher('aes192', '0123456789abcdef'); c.update('update', 'utf-8'); c.final('utf8'); // Should not throw. })(); // Regression tests for #5725: hex input that's not a power of two should // throw, not assert in C++ land. assert.throws(function() { crypto.createCipher('aes192', 'test').update('0', 'hex'); }, /Bad input string/); assert.throws(function() { crypto.createDecipher('aes192', 'test').update('0', 'hex'); }, /Bad input string/); assert.throws(function() { crypto.createHash('sha1').update('0', 'hex'); }, /Bad input string/); assert.throws(function() { crypto.createSign('RSA-SHA1').update('0', 'hex'); }, /Bad input string/); assert.throws(function() { crypto.createVerify('RSA-SHA1').update('0', 'hex'); }, /Bad input string/); node-v0.10.25~dfsg2/test/simple/test-dgram-ref.js0000644000000000000000000000240612270121457020246 0ustar rootroot// Copyright Joyent, Inc. and other Node contributors. // // Permission is hereby granted, free of charge, to any person obtaining a // copy of this software and associated documentation files (the // "Software"), to deal in the Software without restriction, including // without limitation the rights to use, copy, modify, merge, publish, // distribute, sublicense, and/or sell copies of the Software, and to permit // persons to whom the Software is furnished to do so, subject to the // following conditions: // // The above copyright notice and this permission notice shall be included // in all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS // OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF // MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN // NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, // DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR // OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE // USE OR OTHER DEALINGS IN THE SOFTWARE. var common = require('../common'); var dgram = require('dgram'); // should not hang, see #1282 dgram.createSocket('udp4'); dgram.createSocket('udp6'); node-v0.10.25~dfsg2/test/simple/test-http-response-no-headers.js0000644000000000000000000000435012270121457023240 0ustar rootroot// Copyright Joyent, Inc. and other Node contributors. // // Permission is hereby granted, free of charge, to any person obtaining a // copy of this software and associated documentation files (the // "Software"), to deal in the Software without restriction, including // without limitation the rights to use, copy, modify, merge, publish, // distribute, sublicense, and/or sell copies of the Software, and to permit // persons to whom the Software is furnished to do so, subject to the // following conditions: // // The above copyright notice and this permission notice shall be included // in all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS // OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF // MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN // NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, // DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR // OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE // USE OR OTHER DEALINGS IN THE SOFTWARE. var common = require('../common'); var assert = require('assert'); var http = require('http'); var net = require('net'); var expected = { '0.9': 'I AM THE WALRUS', '1.0': 'I AM THE WALRUS', '1.1': '' }; var gotExpected = false; function test(httpVersion, callback) { process.on('exit', function() { assert(gotExpected); }); var server = net.createServer(function(conn) { var reply = 'HTTP/' + httpVersion + ' 200 OK\r\n\r\n' + expected[httpVersion]; conn.end(reply); }); server.listen(common.PORT, '127.0.0.1', function() { var options = { host: '127.0.0.1', port: common.PORT }; var req = http.get(options, function(res) { var body = ''; res.on('data', function(data) { body += data; }); res.on('end', function() { assert.equal(body, expected[httpVersion]); gotExpected = true; server.close(); if (callback) process.nextTick(callback); }); }); req.on('error', function(err) { throw err; }); }); } test('0.9', function() { test('1.0', function() { test('1.1'); }); }); node-v0.10.25~dfsg2/test/simple/test-writefloat.js0000644000000000000000000001116112270121457020560 0ustar rootroot// Copyright Joyent, Inc. and other Node contributors. // // Permission is hereby granted, free of charge, to any person obtaining a // copy of this software and associated documentation files (the // "Software"), to deal in the Software without restriction, including // without limitation the rights to use, copy, modify, merge, publish, // distribute, sublicense, and/or sell copies of the Software, and to permit // persons to whom the Software is furnished to do so, subject to the // following conditions: // // The above copyright notice and this permission notice shall be included // in all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS // OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF // MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN // NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, // DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR // OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE // USE OR OTHER DEALINGS IN THE SOFTWARE. /* * Tests to verify we're writing floats correctly */ var SlowBuffer = process.binding('buffer').SlowBuffer; var common = require('../common'); var ASSERT = require('assert'); function test(clazz) { var buffer = new clazz(8); buffer.writeFloatBE(1, 0); buffer.writeFloatLE(1, 4); ASSERT.equal(0x3f, buffer[0]); ASSERT.equal(0x80, buffer[1]); ASSERT.equal(0x00, buffer[2]); ASSERT.equal(0x00, buffer[3]); ASSERT.equal(0x00, buffer[4]); ASSERT.equal(0x00, buffer[5]); ASSERT.equal(0x80, buffer[6]); ASSERT.equal(0x3f, buffer[7]); buffer.writeFloatBE(1 / 3, 0); buffer.writeFloatLE(1 / 3, 4); ASSERT.equal(0x3e, buffer[0]); ASSERT.equal(0xaa, buffer[1]); ASSERT.equal(0xaa, buffer[2]); ASSERT.equal(0xab, buffer[3]); ASSERT.equal(0xab, buffer[4]); ASSERT.equal(0xaa, buffer[5]); ASSERT.equal(0xaa, buffer[6]); ASSERT.equal(0x3e, buffer[7]); buffer.writeFloatBE(3.4028234663852886e+38, 0); buffer.writeFloatLE(3.4028234663852886e+38, 4); ASSERT.equal(0x7f, buffer[0]); ASSERT.equal(0x7f, buffer[1]); ASSERT.equal(0xff, buffer[2]); ASSERT.equal(0xff, buffer[3]); ASSERT.equal(0xff, buffer[4]); ASSERT.equal(0xff, buffer[5]); ASSERT.equal(0x7f, buffer[6]); ASSERT.equal(0x7f, buffer[7]); buffer.writeFloatLE(1.1754943508222875e-38, 0); buffer.writeFloatBE(1.1754943508222875e-38, 4); ASSERT.equal(0x00, buffer[0]); ASSERT.equal(0x00, buffer[1]); ASSERT.equal(0x80, buffer[2]); ASSERT.equal(0x00, buffer[3]); ASSERT.equal(0x00, buffer[4]); ASSERT.equal(0x80, buffer[5]); ASSERT.equal(0x00, buffer[6]); ASSERT.equal(0x00, buffer[7]); buffer.writeFloatBE(0 * -1, 0); buffer.writeFloatLE(0 * -1, 4); ASSERT.equal(0x80, buffer[0]); ASSERT.equal(0x00, buffer[1]); ASSERT.equal(0x00, buffer[2]); ASSERT.equal(0x00, buffer[3]); ASSERT.equal(0x00, buffer[4]); ASSERT.equal(0x00, buffer[5]); ASSERT.equal(0x00, buffer[6]); ASSERT.equal(0x80, buffer[7]); buffer.writeFloatBE(Infinity, 0); buffer.writeFloatLE(Infinity, 4); ASSERT.equal(0x7F, buffer[0]); ASSERT.equal(0x80, buffer[1]); ASSERT.equal(0x00, buffer[2]); ASSERT.equal(0x00, buffer[3]); ASSERT.equal(0x00, buffer[4]); ASSERT.equal(0x00, buffer[5]); ASSERT.equal(0x80, buffer[6]); ASSERT.equal(0x7F, buffer[7]); ASSERT.equal(Infinity, buffer.readFloatBE(0)); ASSERT.equal(Infinity, buffer.readFloatLE(4)); buffer.writeFloatBE(-Infinity, 0); buffer.writeFloatLE(-Infinity, 4); // Darwin ia32 does the other kind of NaN. // Compiler bug. No one really cares. ASSERT(0xFF === buffer[0] || 0x7F === buffer[0]); ASSERT.equal(0x80, buffer[1]); ASSERT.equal(0x00, buffer[2]); ASSERT.equal(0x00, buffer[3]); ASSERT.equal(0x00, buffer[4]); ASSERT.equal(0x00, buffer[5]); ASSERT.equal(0x80, buffer[6]); ASSERT.equal(0xFF, buffer[7]); ASSERT.equal(-Infinity, buffer.readFloatBE(0)); ASSERT.equal(-Infinity, buffer.readFloatLE(4)); buffer.writeFloatBE(NaN, 0); buffer.writeFloatLE(NaN, 4); // Darwin ia32 does the other kind of NaN. // Compiler bug. No one really cares. ASSERT(0x7F === buffer[0] || 0xFF === buffer[0]); ASSERT.equal(0xc0, buffer[1]); ASSERT.equal(0x00, buffer[2]); ASSERT.equal(0x00, buffer[3]); ASSERT.equal(0x00, buffer[4]); ASSERT.equal(0x00, buffer[5]); ASSERT.equal(0xc0, buffer[6]); // Darwin ia32 does the other kind of NaN. // Compiler bug. No one really cares. ASSERT(0x7F === buffer[7] || 0xFF === buffer[7]); ASSERT.ok(isNaN(buffer.readFloatBE(0))); ASSERT.ok(isNaN(buffer.readFloatLE(4))); } test(Buffer); test(SlowBuffer); node-v0.10.25~dfsg2/test/simple/test-pipe-unref.js0000644000000000000000000000272712270121457020462 0ustar rootroot// Copyright Joyent, Inc. and other Node contributors. // // Permission is hereby granted, free of charge, to any person obtaining a // copy of this software and associated documentation files (the // "Software"), to deal in the Software without restriction, including // without limitation the rights to use, copy, modify, merge, publish, // distribute, sublicense, and/or sell copies of the Software, and to permit // persons to whom the Software is furnished to do so, subject to the // following conditions: // // The above copyright notice and this permission notice shall be included // in all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS // OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF // MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN // NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, // DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR // OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE // USE OR OTHER DEALINGS IN THE SOFTWARE. var common = require('../common'); var assert = require('assert'); var net = require('net'); var closed = false; var s = net.Server(); s.listen(common.PIPE); s.unref(); setTimeout(function() { closed = true; s.close(); }, 1000).unref(); process.on('exit', function() { assert.strictEqual(closed, false, 'Unrefd socket should not hold loop open'); }); node-v0.10.25~dfsg2/test/simple/test-http-pause-resume-one-end.js0000644000000000000000000000345612270121457023323 0ustar rootroot// Copyright Joyent, Inc. and other Node contributors. // // Permission is hereby granted, free of charge, to any person obtaining a // copy of this software and associated documentation files (the // "Software"), to deal in the Software without restriction, including // without limitation the rights to use, copy, modify, merge, publish, // distribute, sublicense, and/or sell copies of the Software, and to permit // persons to whom the Software is furnished to do so, subject to the // following conditions: // // The above copyright notice and this permission notice shall be included // in all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS // OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF // MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN // NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, // DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR // OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE // USE OR OTHER DEALINGS IN THE SOFTWARE. var common = require('../common'); var assert = require('assert'); var http = require('http'); var server = http.Server(function(req, res) { res.writeHead(200, {'Content-Type': 'text/plain'}); res.end('Hello World\n'); server.close(); }); var dataCount = 0, endCount = 0; server.listen(common.PORT, function() { var opts = { port: common.PORT, headers: { connection: 'close' } }; http.get(opts, function(res) { res.on('data', function(chunk) { dataCount++; res.pause(); }); res.on('end', function() { endCount++; res.resume(); }); }); }); process.on('exit', function() { assert.equal(1, dataCount); assert.equal(1, endCount); }); node-v0.10.25~dfsg2/test/simple/test-cluster-eaddrinuse.js0000644000000000000000000000453412270121457022210 0ustar rootroot// Copyright Joyent, Inc. and other Node contributors. // // Permission is hereby granted, free of charge, to any person obtaining a // copy of this software and associated documentation files (the // "Software"), to deal in the Software without restriction, including // without limitation the rights to use, copy, modify, merge, publish, // distribute, sublicense, and/or sell copies of the Software, and to permit // persons to whom the Software is furnished to do so, subject to the // following conditions: // // The above copyright notice and this permission notice shall be included // in all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS // OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF // MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN // NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, // DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR // OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE // USE OR OTHER DEALINGS IN THE SOFTWARE. // Check that having a worker bind to a port that's already taken doesn't // leave the master process in a confused state. Releasing the port and // trying again should Just Work[TM]. var common = require('../common'); var assert = require('assert'); var cluster = require('cluster'); var fork = require('child_process').fork; var net = require('net'); var id = '' + process.argv[2]; if (id === 'undefined') { var server = net.createServer(assert.fail); server.listen(common.PORT, function() { var worker = fork(__filename, ['worker']); worker.on('message', function(msg) { if (msg !== 'stop-listening') return; server.close(function() { worker.send('stopped-listening'); }); }); }); } else if (id === 'worker') { var server = net.createServer(assert.fail); server.listen(common.PORT, assert.fail); server.on('error', common.mustCall(function(e) { assert(e.code, 'EADDRINUSE'); process.send('stop-listening'); process.once('message', function(msg) { if (msg !== 'stopped-listening') return; server = net.createServer(assert.fail); server.listen(common.PORT, common.mustCall(function() { server.close(); })); }); })); } else { assert(0); // Bad argument. } node-v0.10.25~dfsg2/test/simple/test-tls-npn-server-client.js0000644000000000000000000000714412270121457022561 0ustar rootroot// Copyright Joyent, Inc. and other Node contributors. // // Permission is hereby granted, free of charge, to any person obtaining a // copy of this software and associated documentation files (the // "Software"), to deal in the Software without restriction, including // without limitation the rights to use, copy, modify, merge, publish, // distribute, sublicense, and/or sell copies of the Software, and to permit // persons to whom the Software is furnished to do so, subject to the // following conditions: // // The above copyright notice and this permission notice shall be included // in all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS // OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF // MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN // NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, // DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR // OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE // USE OR OTHER DEALINGS IN THE SOFTWARE. if (!process.features.tls_npn) { console.error('Skipping because node compiled without OpenSSL or ' + 'with old OpenSSL version.'); process.exit(0); } var common = require('../common'), assert = require('assert'), fs = require('fs'), tls = require('tls'), crypto = require('crypto'); function filenamePEM(n) { return require('path').join(common.fixturesDir, 'keys', n + '.pem'); } function loadPEM(n) { return fs.readFileSync(filenamePEM(n)); } var serverOptions = { key: loadPEM('agent2-key'), cert: loadPEM('agent2-cert'), crl: loadPEM('ca2-crl'), SNICallback: function() { return crypto.createCredentials({ key: loadPEM('agent2-key'), cert: loadPEM('agent2-cert'), crl: loadPEM('ca2-crl'), }).context; }, NPNProtocols: ['a', 'b', 'c'] }; var serverPort = common.PORT; var clientsOptions = [{ port: serverPort, key: serverOptions.key, cert: serverOptions.cert, crl: serverOptions.crl, NPNProtocols: ['a', 'b', 'c'], rejectUnauthorized: false },{ port: serverPort, key: serverOptions.key, cert: serverOptions.cert, crl: serverOptions.crl, NPNProtocols: ['c', 'b', 'e'], rejectUnauthorized: false },{ port: serverPort, key: serverOptions.key, cert: serverOptions.cert, crl: serverOptions.crl, rejectUnauthorized: false },{ port: serverPort, key: serverOptions.key, cert: serverOptions.cert, crl: serverOptions.crl, NPNProtocols: ['first-priority-unsupported', 'x', 'y'], rejectUnauthorized: false }]; var serverResults = [], clientsResults = []; var server = tls.createServer(serverOptions, function(c) { serverResults.push(c.npnProtocol); }); server.listen(serverPort, startTest); function startTest() { function connectClient(options, callback) { var client = tls.connect(options, function() { clientsResults.push(client.npnProtocol); client.destroy(); callback(); }); }; connectClient(clientsOptions[0], function() { connectClient(clientsOptions[1], function() { connectClient(clientsOptions[2], function() { connectClient(clientsOptions[3], function() { server.close(); }); }); }); }); } process.on('exit', function() { assert.equal(serverResults[0], clientsResults[0]); assert.equal(serverResults[1], clientsResults[1]); assert.equal(serverResults[2], 'http/1.1'); assert.equal(clientsResults[2], false); assert.equal(serverResults[3], 'first-priority-unsupported'); assert.equal(clientsResults[3], false); }); node-v0.10.25~dfsg2/test/simple/test-http-no-content-length.js0000644000000000000000000000331212270121457022717 0ustar rootroot// Copyright Joyent, Inc. and other Node contributors. // // Permission is hereby granted, free of charge, to any person obtaining a // copy of this software and associated documentation files (the // "Software"), to deal in the Software without restriction, including // without limitation the rights to use, copy, modify, merge, publish, // distribute, sublicense, and/or sell copies of the Software, and to permit // persons to whom the Software is furnished to do so, subject to the // following conditions: // // The above copyright notice and this permission notice shall be included // in all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS // OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF // MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN // NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, // DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR // OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE // USE OR OTHER DEALINGS IN THE SOFTWARE. var common = require('../common'); var assert = require('assert'); var net = require('net'); var http = require('http'); var body = ''; var server = net.createServer(function(socket) { // Neither Content-Length nor Connection socket.end('HTTP/1.1 200 ok\r\n\r\nHello'); }).listen(common.PORT, function() { var req = http.get({port: common.PORT}, function(res) { res.setEncoding('utf8'); res.on('data', function(chunk) { body += chunk; }); res.on('end', function() { server.close(); }); }); }); process.on('exit', function() { assert.equal(body, 'Hello'); }); node-v0.10.25~dfsg2/test/simple/test-fs-empty-readStream.js0000644000000000000000000000417312270121457022236 0ustar rootroot// Copyright Joyent, Inc. and other Node contributors. // // Permission is hereby granted, free of charge, to any person obtaining a // copy of this software and associated documentation files (the // "Software"), to deal in the Software without restriction, including // without limitation the rights to use, copy, modify, merge, publish, // distribute, sublicense, and/or sell copies of the Software, and to permit // persons to whom the Software is furnished to do so, subject to the // following conditions: // // The above copyright notice and this permission notice shall be included // in all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS // OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF // MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN // NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, // DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR // OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE // USE OR OTHER DEALINGS IN THE SOFTWARE. var common = require('../common'); var assert = require('assert'); var path = require('path'); var fs = require('fs'); var emptyFile = path.join(common.fixturesDir, 'empty.txt'); fs.open(emptyFile, 'r', function (error, fd) { assert.ifError(error); var read = fs.createReadStream(emptyFile, { 'fd': fd }); read.once('data', function () { throw new Error('data event should not emit'); }); var readEmit = false; read.once('end', function () { readEmit = true; console.error('end event 1'); }); setTimeout(function () { assert.equal(readEmit, true); }, 50); }); fs.open(emptyFile, 'r', function (error, fd) { assert.ifError(error); var read = fs.createReadStream(emptyFile, { 'fd': fd }); read.pause(); read.once('data', function () { throw new Error('data event should not emit'); }); var readEmit = false; read.once('end', function () { readEmit = true; console.error('end event 2'); }); setTimeout(function () { assert.equal(readEmit, false); }, 50); }); node-v0.10.25~dfsg2/test/simple/test-net-server-unref.js0000644000000000000000000000272212270121457021612 0ustar rootroot// Copyright Joyent, Inc. and other Node contributors. // // Permission is hereby granted, free of charge, to any person obtaining a // copy of this software and associated documentation files (the // "Software"), to deal in the Software without restriction, including // without limitation the rights to use, copy, modify, merge, publish, // distribute, sublicense, and/or sell copies of the Software, and to permit // persons to whom the Software is furnished to do so, subject to the // following conditions: // // The above copyright notice and this permission notice shall be included // in all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS // OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF // MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN // NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, // DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR // OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE // USE OR OTHER DEALINGS IN THE SOFTWARE. var common = require('../common'); var assert = require('assert'); var net = require('net'); var closed = false; var s = net.createServer(); s.listen(); s.unref(); setTimeout(function() { closed = true; s.close(); }, 1000).unref(); process.on('exit', function() { assert.strictEqual(closed, false, 'Unrefd socket should not hold loop open'); }); node-v0.10.25~dfsg2/test/simple/test-next-tick-intentional-starvation.js0000644000000000000000000000400712270121457025021 0ustar rootroot// Copyright Joyent, Inc. and other Node contributors. // // Permission is hereby granted, free of charge, to any person obtaining a // copy of this software and associated documentation files (the // "Software"), to deal in the Software without restriction, including // without limitation the rights to use, copy, modify, merge, publish, // distribute, sublicense, and/or sell copies of the Software, and to permit // persons to whom the Software is furnished to do so, subject to the // following conditions: // // The above copyright notice and this permission notice shall be included // in all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS // OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF // MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN // NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, // DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR // OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE // USE OR OTHER DEALINGS IN THE SOFTWARE. var common = require('../common'); var assert = require('assert'); // this is the inverse of test-next-tick-starvation. // it verifies that process.nextTick will *always* come before other // events, up to the limit of the process.maxTickDepth value. // WARNING: unsafe! process.maxTickDepth = Infinity; var ran = false; var starved = false; var start = +new Date(); var timerRan = false; function spin() { ran = true; var now = +new Date(); if (now - start > 100) { console.log('The timer is starving, just as we planned.'); starved = true; // now let it out. return; } process.nextTick(spin); } function onTimeout() { if (!starved) throw new Error('The timer escaped!'); console.log('The timer ran once the ban was lifted'); timerRan = true; } spin(); setTimeout(onTimeout, 50); process.on('exit', function() { assert.ok(ran); assert.ok(starved); assert.ok(timerRan); }); node-v0.10.25~dfsg2/test/simple/test-next-tick-ordering2.js0000644000000000000000000000270412270121457022202 0ustar rootroot// Copyright Joyent, Inc. and other Node contributors. // // Permission is hereby granted, free of charge, to any person obtaining a // copy of this software and associated documentation files (the // "Software"), to deal in the Software without restriction, including // without limitation the rights to use, copy, modify, merge, publish, // distribute, sublicense, and/or sell copies of the Software, and to permit // persons to whom the Software is furnished to do so, subject to the // following conditions: // // The above copyright notice and this permission notice shall be included // in all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS // OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF // MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN // NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, // DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR // OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE // USE OR OTHER DEALINGS IN THE SOFTWARE. var common = require('../common'); var assert = require('assert'); var order = []; process.nextTick(function() { setTimeout(function() { order.push('setTimeout'); }, 0); process.nextTick(function() { order.push('nextTick'); }); }); process.on('exit', function() { assert.deepEqual(order, ['nextTick', 'setTimeout']); }); node-v0.10.25~dfsg2/test/simple/test-script-static-this.js0000644000000000000000000000370312270121457022141 0ustar rootroot// Copyright Joyent, Inc. and other Node contributors. // // Permission is hereby granted, free of charge, to any person obtaining a // copy of this software and associated documentation files (the // "Software"), to deal in the Software without restriction, including // without limitation the rights to use, copy, modify, merge, publish, // distribute, sublicense, and/or sell copies of the Software, and to permit // persons to whom the Software is furnished to do so, subject to the // following conditions: // // The above copyright notice and this permission notice shall be included // in all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS // OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF // MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN // NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, // DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR // OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE // USE OR OTHER DEALINGS IN THE SOFTWARE. var common = require('../common'); var assert = require('assert'); var Script = require('vm').Script; common.globalCheck = false; common.debug('run a string'); var result = Script.runInThisContext('\'passed\';'); assert.equal('passed', result); common.debug('thrown error'); assert.throws(function() { Script.runInThisContext('throw new Error(\'test\');'); }); hello = 5; Script.runInThisContext('hello = 2'); assert.equal(2, hello); common.debug('pass values'); code = 'foo = 1;' + 'bar = 2;' + 'if (typeof baz !== \'undefined\') throw new Error(\'test fail\');'; foo = 2; obj = { foo: 0, baz: 3 }; var baz = Script.runInThisContext(code); assert.equal(0, obj.foo); assert.equal(2, bar); assert.equal(1, foo); common.debug('call a function'); f = function() { foo = 100 }; Script.runInThisContext('f()'); assert.equal(100, foo); node-v0.10.25~dfsg2/test/simple/test-http-set-timeout-server.js0000644000000000000000000001235212270121457023143 0ustar rootroot// Copyright Joyent, Inc. and other Node contributors. // // Permission is hereby granted, free of charge, to any person obtaining a // copy of this software and associated documentation files (the // "Software"), to deal in the Software without restriction, including // without limitation the rights to use, copy, modify, merge, publish, // distribute, sublicense, and/or sell copies of the Software, and to permit // persons to whom the Software is furnished to do so, subject to the // following conditions: // // The above copyright notice and this permission notice shall be included // in all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS // OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF // MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN // NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, // DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR // OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE // USE OR OTHER DEALINGS IN THE SOFTWARE. var common = require('../common.js'); var assert = require('assert'); var http = require('http'); var net = require('net'); var tests = []; function test(fn) { if (!tests.length) process.nextTick(run); tests.push(fn); } function run() { var fn = tests.shift(); if (fn) { console.log('# %s', fn.name); fn(run); } else console.log('ok'); } test(function serverTimeout(cb) { var caughtTimeout = false; process.on('exit', function() { assert(caughtTimeout); }); var server = http.createServer(function(req, res) { // just do nothing, we should get a timeout event. }); server.listen(common.PORT); server.setTimeout(50, function(socket) { caughtTimeout = true; socket.destroy(); server.close(); cb(); }); http.get({ port: common.PORT }).on('error', function() {}); }); test(function serverRequestTimeout(cb) { var caughtTimeout = false; process.on('exit', function() { assert(caughtTimeout); }); var server = http.createServer(function(req, res) { // just do nothing, we should get a timeout event. req.setTimeout(50, function() { caughtTimeout = true; req.socket.destroy(); server.close(); cb(); }); }); server.listen(common.PORT); var req = http.request({ port: common.PORT, method: 'POST' }); req.on('error', function() {}); req.write('Hello'); // req is in progress }); test(function serverResponseTimeout(cb) { var caughtTimeout = false; process.on('exit', function() { assert(caughtTimeout); }); var server = http.createServer(function(req, res) { // just do nothing, we should get a timeout event. res.setTimeout(50, function() { caughtTimeout = true; res.socket.destroy(); server.close(); cb(); }); }); server.listen(common.PORT); http.get({ port: common.PORT }).on('error', function() {}); }); test(function serverRequestNotTimeoutAfterEnd(cb) { var caughtTimeoutOnRequest = false; var caughtTimeoutOnResponse = false; process.on('exit', function() { assert(!caughtTimeoutOnRequest); assert(caughtTimeoutOnResponse); }); var server = http.createServer(function(req, res) { // just do nothing, we should get a timeout event. req.setTimeout(50, function(socket) { caughtTimeoutOnRequest = true; }); res.on('timeout', function(socket) { caughtTimeoutOnResponse = true; }); }); server.on('timeout', function(socket) { socket.destroy(); server.close(); cb(); }); server.listen(common.PORT); http.get({ port: common.PORT }).on('error', function() {}); }); test(function serverResponseTimeoutWithPipeline(cb) { var caughtTimeout = ''; process.on('exit', function() { assert.equal(caughtTimeout, '/2'); }); var server = http.createServer(function(req, res) { res.setTimeout(50, function() { caughtTimeout += req.url; }); if (req.url === '/1') res.end(); }); server.on('timeout', function(socket) { socket.destroy(); server.close(); cb(); }); server.listen(common.PORT); var c = net.connect({ port: common.PORT, allowHalfOpen: true }, function() { c.write('GET /1 HTTP/1.1\r\nHost: localhost\r\n\r\n'); c.write('GET /2 HTTP/1.1\r\nHost: localhost\r\n\r\n'); c.write('GET /3 HTTP/1.1\r\nHost: localhost\r\n\r\n'); }); }); test(function idleTimeout(cb) { var caughtTimeoutOnRequest = false; var caughtTimeoutOnResponse = false; var caughtTimeoutOnServer = false; process.on('exit', function() { assert(!caughtTimeoutOnRequest); assert(!caughtTimeoutOnResponse); assert(caughtTimeoutOnServer); }); var server = http.createServer(function(req, res) { req.on('timeout', function(socket) { caughtTimeoutOnRequest = true; }); res.on('timeout', function(socket) { caughtTimeoutOnResponse = true; }); res.end(); }); server.setTimeout(50, function(socket) { caughtTimeoutOnServer = true; socket.destroy(); server.close(); cb(); }); server.listen(common.PORT); var c = net.connect({ port: common.PORT, allowHalfOpen: true }, function() { c.write('GET /1 HTTP/1.1\r\nHost: localhost\r\n\r\n'); // Keep-Alive }); }); node-v0.10.25~dfsg2/test/simple/test-timers-this.js0000644000000000000000000000431312270121457020651 0ustar rootroot// Copyright Joyent, Inc. and other Node contributors. // // Permission is hereby granted, free of charge, to any person obtaining a // copy of this software and associated documentation files (the // "Software"), to deal in the Software without restriction, including // without limitation the rights to use, copy, modify, merge, publish, // distribute, sublicense, and/or sell copies of the Software, and to permit // persons to whom the Software is furnished to do so, subject to the // following conditions: // // The above copyright notice and this permission notice shall be included // in all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS // OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF // MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN // NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, // DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR // OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE // USE OR OTHER DEALINGS IN THE SOFTWARE. var assert = require('assert'); var immediateThis, intervalThis, timeoutThis, immediateArgsThis, intervalArgsThis, timeoutArgsThis; var immediateHandler = setImmediate(function () { immediateThis = this; }); var immediateArgsHandler = setImmediate(function () { immediateArgsThis = this; }, "args ..."); var intervalHandler = setInterval(function () { clearInterval(intervalHandler); intervalThis = this; }); var intervalArgsHandler = setInterval(function () { clearInterval(intervalArgsHandler); intervalArgsThis = this; }, 0, "args ..."); var timeoutHandler = setTimeout(function () { timeoutThis = this; }); var timeoutArgsHandler = setTimeout(function () { timeoutArgsThis = this; }, 0, "args ..."); process.once('exit', function () { assert.strictEqual(immediateThis, immediateHandler); assert.strictEqual(immediateArgsThis, immediateArgsHandler); assert.strictEqual(intervalThis, intervalHandler); assert.strictEqual(intervalArgsThis, intervalArgsHandler); assert.strictEqual(timeoutThis, timeoutHandler); assert.strictEqual(timeoutArgsThis, timeoutArgsHandler); }); node-v0.10.25~dfsg2/test/simple/test-regress-GH-1697.js0000644000000000000000000000444312270121457020757 0ustar rootroot// Copyright Joyent, Inc. and other Node contributors. // // Permission is hereby granted, free of charge, to any person obtaining a // copy of this software and associated documentation files (the // "Software"), to deal in the Software without restriction, including // without limitation the rights to use, copy, modify, merge, publish, // distribute, sublicense, and/or sell copies of the Software, and to permit // persons to whom the Software is furnished to do so, subject to the // following conditions: // // The above copyright notice and this permission notice shall be included // in all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS // OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF // MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN // NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, // DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR // OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE // USE OR OTHER DEALINGS IN THE SOFTWARE. var common = require('../common'); var net = require('net'), cp = require('child_process'), util = require('util'); if (process.argv[2] === 'server') { // Server var server = net.createServer(function(conn) { conn.on('data', function(data) { console.log('server received ' + data.length + ' bytes'); }); conn.on('close', function() { server.close(); }); }); server.listen(common.PORT, '127.0.0.1', function() { console.log('Server running.'); }); } else { // Client var serverProcess = cp.spawn(process.execPath, [process.argv[1], 'server']); serverProcess.stdout.pipe(process.stdout); serverProcess.stderr.pipe(process.stdout); serverProcess.stdout.once('data', function() { var client = net.createConnection(common.PORT, '127.0.0.1'); client.on('connect', function() { var alot = new Buffer(1024), alittle = new Buffer(1); for (var i = 0; i < 100; i++) { client.write(alot); } // Block the event loop for 1 second var start = (new Date()).getTime(); while ((new Date).getTime() < start + 1000) {} client.write(alittle); client.destroySoon(); }); }); } node-v0.10.25~dfsg2/test/simple/test-child-process-cwd.js0000644000000000000000000000544512270121457021722 0ustar rootroot// Copyright Joyent, Inc. and other Node contributors. // // Permission is hereby granted, free of charge, to any person obtaining a // copy of this software and associated documentation files (the // "Software"), to deal in the Software without restriction, including // without limitation the rights to use, copy, modify, merge, publish, // distribute, sublicense, and/or sell copies of the Software, and to permit // persons to whom the Software is furnished to do so, subject to the // following conditions: // // The above copyright notice and this permission notice shall be included // in all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS // OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF // MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN // NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, // DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR // OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE // USE OR OTHER DEALINGS IN THE SOFTWARE. var common = require('../common'); var assert = require('assert'); var spawn = require('child_process').spawn; var path = require('path'); var returns = 0; /* Spawns 'pwd' with given options, then test - whether the exit code equals forCode, - optionally whether the stdout result matches forData (after removing traling whitespace) */ function testCwd(options, forCode, forData) { var data = ''; var child = common.spawnPwd(options); child.stdout.setEncoding('utf8'); child.stdout.on('data', function(chunk) { data += chunk; }); child.on('exit', function(code, signal) { assert.strictEqual(forCode, code); }); child.on('close', function () { forData && assert.strictEqual(forData, data.replace(/[\s\r\n]+$/, '')); returns--; }); returns++; return child; } // Assume these exist, and 'pwd' gives us the right directory back if (process.platform == 'win32') { testCwd({cwd: process.env.windir}, 0, process.env.windir); testCwd({cwd: 'c:\\'}, 0, 'c:\\'); } else { testCwd({cwd: '/dev'}, 0, '/dev'); testCwd({cwd: '/'}, 0, '/'); } // Assume does-not-exist doesn't exist, expect exitCode=-1 and errno=ENOENT (function() { var errors = 0; testCwd({cwd: 'does-not-exist'}, -1).on('error', function(e) { assert.equal(e.code, 'ENOENT'); errors++; }); process.on('exit', function() { assert.equal(errors, 1); }); })(); // Spawn() shouldn't try to chdir() so this should just work testCwd(undefined, 0); testCwd({}, 0); testCwd({cwd: ''}, 0); testCwd({cwd: undefined}, 0); testCwd({cwd: null}, 0); // Check whether all tests actually returned assert.notEqual(0, returns); process.on('exit', function() { assert.equal(0, returns); }); node-v0.10.25~dfsg2/test/simple/test-memory-usage-emfile.js0000644000000000000000000000261012270121457022250 0ustar rootroot// Copyright Joyent, Inc. and other Node contributors. // // Permission is hereby granted, free of charge, to any person obtaining a // copy of this software and associated documentation files (the // "Software"), to deal in the Software without restriction, including // without limitation the rights to use, copy, modify, merge, publish, // distribute, sublicense, and/or sell copies of the Software, and to permit // persons to whom the Software is furnished to do so, subject to the // following conditions: // // The above copyright notice and this permission notice shall be included // in all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS // OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF // MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN // NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, // DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR // OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE // USE OR OTHER DEALINGS IN THE SOFTWARE. var common = require('../common'); var assert = require('assert'); var fs = require('fs'); var files = []; while (files.length < 256) files.push(fs.openSync(__filename, 'r')); var r = process.memoryUsage(); console.log(common.inspect(r)); assert.equal(true, r['rss'] > 0); node-v0.10.25~dfsg2/test/simple/test-fs-mkdir.js0000644000000000000000000000445412270121457020123 0ustar rootroot// Copyright Joyent, Inc. and other Node contributors. // // Permission is hereby granted, free of charge, to any person obtaining a // copy of this software and associated documentation files (the // "Software"), to deal in the Software without restriction, including // without limitation the rights to use, copy, modify, merge, publish, // distribute, sublicense, and/or sell copies of the Software, and to permit // persons to whom the Software is furnished to do so, subject to the // following conditions: // // The above copyright notice and this permission notice shall be included // in all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS // OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF // MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN // NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, // DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR // OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE // USE OR OTHER DEALINGS IN THE SOFTWARE. var common = require('../common'); var assert = require('assert'); var fs = require('fs'); function unlink(pathname) { try { fs.rmdirSync(pathname); } catch (e) { } } (function() { var ncalls = 0; var pathname = common.tmpDir + '/test1'; unlink(pathname); fs.mkdir(pathname, function(err) { assert.equal(err, null); assert.equal(fs.existsSync(pathname), true); ncalls++; }); process.on('exit', function() { unlink(pathname); assert.equal(ncalls, 1); }); })(); (function() { var ncalls = 0; var pathname = common.tmpDir + '/test2'; unlink(pathname); fs.mkdir(pathname, 511 /*=0777*/, function(err) { assert.equal(err, null); assert.equal(fs.existsSync(pathname), true); ncalls++; }); process.on('exit', function() { unlink(pathname); assert.equal(ncalls, 1); }); })(); (function() { var pathname = common.tmpDir + '/test3'; unlink(pathname); fs.mkdirSync(pathname); var exists = fs.existsSync(pathname); unlink(pathname); assert.equal(exists, true); })(); // Keep the event loop alive so the async mkdir() requests // have a chance to run (since they don't ref the event loop). process.nextTick(function() {}); node-v0.10.25~dfsg2/test/simple/test-stream-pipe-after-end.js0000644000000000000000000000521112270121457022470 0ustar rootroot// Copyright Joyent, Inc. and other Node contributors. // // Permission is hereby granted, free of charge, to any person obtaining a // copy of this software and associated documentation files (the // "Software"), to deal in the Software without restriction, including // without limitation the rights to use, copy, modify, merge, publish, // distribute, sublicense, and/or sell copies of the Software, and to permit // persons to whom the Software is furnished to do so, subject to the // following conditions: // // The above copyright notice and this permission notice shall be included // in all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS // OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF // MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN // NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, // DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR // OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE // USE OR OTHER DEALINGS IN THE SOFTWARE. var common = require('../common'); var assert = require('assert'); var Readable = require('_stream_readable'); var Writable = require('_stream_writable'); var util = require('util'); util.inherits(TestReadable, Readable); function TestReadable(opt) { if (!(this instanceof TestReadable)) return new TestReadable(opt); Readable.call(this, opt); this._ended = false; } TestReadable.prototype._read = function(n) { if (this._ended) this.emit('error', new Error('_read called twice')); this._ended = true; this.push(null); }; util.inherits(TestWritable, Writable); function TestWritable(opt) { if (!(this instanceof TestWritable)) return new TestWritable(opt); Writable.call(this, opt); this._written = []; } TestWritable.prototype._write = function(chunk, encoding, cb) { this._written.push(chunk); cb(); }; // this one should not emit 'end' until we read() from it later. var ender = new TestReadable(); var enderEnded = false; // what happens when you pipe() a Readable that's already ended? var piper = new TestReadable(); // pushes EOF null, and length=0, so this will trigger 'end' piper.read(); setTimeout(function() { ender.on('end', function() { enderEnded = true; }); assert(!enderEnded); var c = ender.read(); assert.equal(c, null); var w = new TestWritable(); var writableFinished = false; w.on('finish', function() { writableFinished = true; }); piper.pipe(w); process.on('exit', function() { assert(enderEnded); assert(writableFinished); console.log('ok'); }); }); node-v0.10.25~dfsg2/test/simple/test-child-process-stdout-flush.js0000644000000000000000000000335312270121457023602 0ustar rootroot// Copyright Joyent, Inc. and other Node contributors. // // Permission is hereby granted, free of charge, to any person obtaining a // copy of this software and associated documentation files (the // "Software"), to deal in the Software without restriction, including // without limitation the rights to use, copy, modify, merge, publish, // distribute, sublicense, and/or sell copies of the Software, and to permit // persons to whom the Software is furnished to do so, subject to the // following conditions: // // The above copyright notice and this permission notice shall be included // in all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS // OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF // MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN // NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, // DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR // OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE // USE OR OTHER DEALINGS IN THE SOFTWARE. var common = require('../common'); var assert = require('assert'); var path = require('path'); var spawn = require('child_process').spawn; var sub = path.join(common.fixturesDir, 'print-chars.js'); var n = 500000; var child = spawn(process.argv[0], [sub, n]); var count = 0; child.stderr.setEncoding('utf8'); child.stderr.on('data', function(data) { console.log('parent stderr: ' + data); assert.ok(false); }); child.stdout.setEncoding('utf8'); child.stdout.on('data', function(data) { count += data.length; console.log(count); }); child.on('close', function(data) { assert.equal(n, count); console.log('okay'); }); node-v0.10.25~dfsg2/test/simple/test-http-response-readable.js0000644000000000000000000000321212270121457022746 0ustar rootroot// Copyright Joyent, Inc. and other Node contributors. // // Permission is hereby granted, free of charge, to any person obtaining a // copy of this software and associated documentation files (the // "Software"), to deal in the Software without restriction, including // without limitation the rights to use, copy, modify, merge, publish, // distribute, sublicense, and/or sell copies of the Software, and to permit // persons to whom the Software is furnished to do so, subject to the // following conditions: // // The above copyright notice and this permission notice shall be included // in all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS // OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF // MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN // NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, // DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR // OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE // USE OR OTHER DEALINGS IN THE SOFTWARE. var common = require('../common'); var assert = require('assert'); var http = require('http'); var testServer = new http.Server(function(req, res) { res.writeHead(200); res.end('Hello world'); }); testServer.listen(common.PORT, function() { http.get({ port: common.PORT }, function(res) { assert.equal(res.readable, true, 'res.readable initially true'); res.on('end', function() { assert.equal(res.readable, false, 'res.readable set to false after end'); testServer.close(); }); res.resume(); }); }); node-v0.10.25~dfsg2/test/simple/test-http-client-timeout-agent.js0000644000000000000000000000571312270121457023421 0ustar rootroot// Copyright Joyent, Inc. and other Node contributors. // // Permission is hereby granted, free of charge, to any person obtaining a // copy of this software and associated documentation files (the // "Software"), to deal in the Software without restriction, including // without limitation the rights to use, copy, modify, merge, publish, // distribute, sublicense, and/or sell copies of the Software, and to permit // persons to whom the Software is furnished to do so, subject to the // following conditions: // // The above copyright notice and this permission notice shall be included // in all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS // OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF // MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN // NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, // DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR // OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE // USE OR OTHER DEALINGS IN THE SOFTWARE. var common = require('../common'); var assert = require('assert'); var http = require('http'); var request_number = 0; var requests_sent = 0; var requests_done = 0; var options = { method: 'GET', port: common.PORT, host: '127.0.0.1', }; //http.globalAgent.maxSockets = 15; var server = http.createServer(function(req, res) { var m = /\/(.*)/.exec(req.url), reqid = parseInt(m[1], 10); if ( reqid % 2 ) { // do not reply the request } else { res.writeHead(200, {'Content-Type': 'text/plain'}); res.write(reqid.toString()); res.end(); } request_number+=1; }); server.listen(options.port, options.host, function() { var req; for (requests_sent = 0; requests_sent < 30; requests_sent+=1) { options.path = '/' + requests_sent; req = http.request(options); req.id = requests_sent; req.on('response', function(res) { res.on('data', function(data) { console.log('res#'+this.req.id+' data:'+data); }); res.on('end', function(data) { console.log('res#'+this.req.id+' end'); requests_done += 1; }); }); req.on('close', function() { console.log('req#'+this.id+' close'); }); req.on('error', function() { console.log('req#'+this.id+' error'); this.destroy(); }); req.setTimeout(50, function () { var req = this; console.log('req#'+this.id + ' timeout'); req.abort(); requests_done += 1; }); req.end(); } setTimeout(function maybeDone() { if (requests_done >= requests_sent) { setTimeout(function() { server.close(); }, 100); } else { setTimeout(maybeDone, 100); } }, 100); }); process.on('exit', function() { console.error('done=%j sent=%j', requests_done, requests_sent); assert.ok(requests_done == requests_sent, 'timeout on http request called too much'); }); node-v0.10.25~dfsg2/test/simple/test-repl-autolibs.js0000644000000000000000000000477112270121457021173 0ustar rootroot// Copyright Joyent, Inc. and other Node contributors. // // Permission is hereby granted, free of charge, to any person obtaining a // copy of this software and associated documentation files (the // "Software"), to deal in the Software without restriction, including // without limitation the rights to use, copy, modify, merge, publish, // distribute, sublicense, and/or sell copies of the Software, and to permit // persons to whom the Software is furnished to do so, subject to the // following conditions: // // The above copyright notice and this permission notice shall be included // in all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS // OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF // MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN // NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, // DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR // OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE // USE OR OTHER DEALINGS IN THE SOFTWARE. var assert = require('assert'); var util = require('util'); var repl = require('repl'); // A stream to push an array into a REPL function ArrayStream() { this.run = function (data) { var self = this; data.forEach(function (line) { self.emit('data', line + '\n'); }); } } util.inherits(ArrayStream, require('stream').Stream); ArrayStream.prototype.readable = true; ArrayStream.prototype.writable = true; ArrayStream.prototype.resume = function () {}; ArrayStream.prototype.write = function () {}; var putIn = new ArrayStream; var testMe = repl.start('', putIn, null, true); test1(); function test1(){ var gotWrite = false; putIn.write = function (data) { gotWrite = true; if (data.length) { // inspect output matches repl output assert.equal(data, util.inspect(require('fs'), null, 2, false) + '\n'); // globally added lib matches required lib assert.equal(global.fs, require('fs')); test2(); } }; assert(!gotWrite); putIn.run(['fs']); assert(gotWrite); } function test2(){ var gotWrite = false; putIn.write = function(data) { gotWrite = true; if (data.length) { // repl response error message assert.equal(data, '{}\n'); // original value wasn't overwritten assert.equal(val, global.url); } }; var val = {}; global.url = val; assert(!gotWrite); putIn.run(['url']); assert(gotWrite); } node-v0.10.25~dfsg2/test/simple/test-stdout-stderr-reading.js0000644000000000000000000000556012270121457022640 0ustar rootroot// Copyright Joyent, Inc. and other Node contributors. // // Permission is hereby granted, free of charge, to any person obtaining a // copy of this software and associated documentation files (the // "Software"), to deal in the Software without restriction, including // without limitation the rights to use, copy, modify, merge, publish, // distribute, sublicense, and/or sell copies of the Software, and to permit // persons to whom the Software is furnished to do so, subject to the // following conditions: // // The above copyright notice and this permission notice shall be included // in all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS // OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF // MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN // NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, // DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR // OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE // USE OR OTHER DEALINGS IN THE SOFTWARE. var common = require('../common'); var assert = require('assert'); // verify that stdout is never read from. var net = require('net'); var read = net.Socket.prototype.read; net.Socket.prototype.read = function() { if (this.fd === 1) throw new Error('reading from stdout!'); if (this.fd === 2) throw new Error('reading from stderr!'); return read.apply(this, arguments); }; if (process.argv[2] === 'child') child(); else parent(); function parent() { var spawn = require('child_process').spawn; var node = process.execPath; var closes = 0; var c1 = spawn(node, [__filename, 'child']); var c1out = ''; c1.stdout.setEncoding('utf8'); c1.stdout.on('data', function(chunk) { c1out += chunk; }); c1.stderr.setEncoding('utf8'); c1.stderr.on('data', function(chunk) { console.error('c1err: ' + chunk.split('\n').join('\nc1err: ')); }); c1.on('close', function(code, signal) { closes++; assert(!code); assert(!signal); assert.equal(c1out, 'ok\n'); console.log('ok'); }); var c2 = spawn(node, ['-e', 'console.log("ok")']); var c2out = ''; c2.stdout.setEncoding('utf8'); c2.stdout.on('data', function(chunk) { c2out += chunk; }); c1.stderr.setEncoding('utf8'); c1.stderr.on('data', function(chunk) { console.error('c1err: ' + chunk.split('\n').join('\nc1err: ')); }); c2.on('close', function(code, signal) { closes++; assert(!code); assert(!signal); assert.equal(c2out, 'ok\n'); console.log('ok'); }); process.on('exit', function() { assert.equal(closes, 2, 'saw both closes'); }); } function child() { // should not be reading *ever* in here. net.Socket.prototype.read = function() { throw new Error('no reading allowed in child'); }; console.log('ok'); } node-v0.10.25~dfsg2/test/simple/test-stdin-resume-pause.js0000644000000000000000000000223512270121457022134 0ustar rootroot// Copyright Joyent, Inc. and other Node contributors. // // Permission is hereby granted, free of charge, to any person obtaining a // copy of this software and associated documentation files (the // "Software"), to deal in the Software without restriction, including // without limitation the rights to use, copy, modify, merge, publish, // distribute, sublicense, and/or sell copies of the Software, and to permit // persons to whom the Software is furnished to do so, subject to the // following conditions: // // The above copyright notice and this permission notice shall be included // in all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS // OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF // MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN // NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, // DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR // OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE // USE OR OTHER DEALINGS IN THE SOFTWARE. process.stdin.resume(); process.stdin.pause(); node-v0.10.25~dfsg2/test/simple/test-fs-stat.js0000644000000000000000000000655512270121457017774 0ustar rootroot// Copyright Joyent, Inc. and other Node contributors. // // Permission is hereby granted, free of charge, to any person obtaining a // copy of this software and associated documentation files (the // "Software"), to deal in the Software without restriction, including // without limitation the rights to use, copy, modify, merge, publish, // distribute, sublicense, and/or sell copies of the Software, and to permit // persons to whom the Software is furnished to do so, subject to the // following conditions: // // The above copyright notice and this permission notice shall be included // in all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS // OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF // MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN // NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, // DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR // OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE // USE OR OTHER DEALINGS IN THE SOFTWARE. var common = require('../common'); var assert = require('assert'); var fs = require('fs'); var got_error = false; var success_count = 0; fs.stat('.', function(err, stats) { if (err) { got_error = true; } else { console.dir(stats); assert.ok(stats.mtime instanceof Date); success_count++; } assert(this === global); }); fs.lstat('.', function(err, stats) { if (err) { got_error = true; } else { console.dir(stats); assert.ok(stats.mtime instanceof Date); success_count++; } assert(this === global); }); // fstat fs.open('.', 'r', undefined, function(err, fd) { assert.ok(!err); assert.ok(fd); fs.fstat(fd, function(err, stats) { if (err) { got_error = true; } else { console.dir(stats); assert.ok(stats.mtime instanceof Date); success_count++; fs.close(fd); } assert(this === global); }); assert(this === global); }); // fstatSync fs.open('.', 'r', undefined, function(err, fd) { var stats; try { stats = fs.fstatSync(fd); } catch (err) { got_error = true; } if (stats) { console.dir(stats); assert.ok(stats.mtime instanceof Date); success_count++; } fs.close(fd); }); console.log('stating: ' + __filename); fs.stat(__filename, function(err, s) { if (err) { got_error = true; } else { console.dir(s); success_count++; console.log('isDirectory: ' + JSON.stringify(s.isDirectory())); assert.equal(false, s.isDirectory()); console.log('isFile: ' + JSON.stringify(s.isFile())); assert.equal(true, s.isFile()); console.log('isSocket: ' + JSON.stringify(s.isSocket())); assert.equal(false, s.isSocket()); console.log('isBlockDevice: ' + JSON.stringify(s.isBlockDevice())); assert.equal(false, s.isBlockDevice()); console.log('isCharacterDevice: ' + JSON.stringify(s.isCharacterDevice())); assert.equal(false, s.isCharacterDevice()); console.log('isFIFO: ' + JSON.stringify(s.isFIFO())); assert.equal(false, s.isFIFO()); console.log('isSymbolicLink: ' + JSON.stringify(s.isSymbolicLink())); assert.equal(false, s.isSymbolicLink()); assert.ok(s.mtime instanceof Date); } }); process.on('exit', function() { assert.equal(5, success_count); assert.equal(false, got_error); }); node-v0.10.25~dfsg2/test/simple/test-tls-junk-closes-server.js0000644000000000000000000000346212270121457022746 0ustar rootroot// Copyright Joyent, Inc. and other Node contributors. // // Permission is hereby granted, free of charge, to any person obtaining a // copy of this software and associated documentation files (the // "Software"), to deal in the Software without restriction, including // without limitation the rights to use, copy, modify, merge, publish, // distribute, sublicense, and/or sell copies of the Software, and to permit // persons to whom the Software is furnished to do so, subject to the // following conditions: // // The above copyright notice and this permission notice shall be included // in all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS // OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF // MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN // NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, // DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR // OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE // USE OR OTHER DEALINGS IN THE SOFTWARE. if (!process.versions.openssl) { console.error('Skipping because node compiled without OpenSSL.'); process.exit(0); } var common = require('../common'); var tls = require('tls'); var fs = require('fs'); var net = require('net'); var options = { key: fs.readFileSync(common.fixturesDir + '/keys/agent2-key.pem'), cert: fs.readFileSync(common.fixturesDir + '/keys/agent2-cert.pem') }; var server = tls.createServer(options, function(s) { s.write('welcome!\n'); s.pipe(s); }); server.listen(common.PORT, function() { var c = net.createConnection(common.PORT); c.on('connect', function() { c.write('blah\nblah\nblah\n'); }); c.on('end', function() { server.close(); }); }); node-v0.10.25~dfsg2/test/simple/test-debugger-repl.js0000644000000000000000000000373212270121457021131 0ustar rootroot// Copyright Joyent, Inc. and other Node contributors. // // Permission is hereby granted, free of charge, to any person obtaining a // copy of this software and associated documentation files (the // "Software"), to deal in the Software without restriction, including // without limitation the rights to use, copy, modify, merge, publish, // distribute, sublicense, and/or sell copies of the Software, and to permit // persons to whom the Software is furnished to do so, subject to the // following conditions: // // The above copyright notice and this permission notice shall be included // in all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS // OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF // MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN // NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, // DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR // OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE // USE OR OTHER DEALINGS IN THE SOFTWARE. var repl = require('./helper-debugger-repl.js'); repl.startDebugger('breakpoints.js'); var addTest = repl.addTest; // Next addTest('n', [ /break in .*:11/, /9/, /10/, /11/, /12/, /13/ ]); // Watch addTest('watch("\'x\'")'); // Continue addTest('c', [ /break in .*:5/, /Watchers/, /0:\s+'x' = "x"/, /()/, /3/, /4/, /5/, /6/, /7/ ]); // Show watchers addTest('watchers', [ /0:\s+'x' = "x"/ ]); // Unwatch addTest('unwatch("\'x\'")'); // Step out addTest('o', [ /break in .*:12/, /10/, /11/, /12/, /13/, /14/ ]); // Continue addTest('c', [ /break in .*:5/, /3/, /4/, /5/, /6/, /7/ ]); // Set breakpoint by function name addTest('sb("setInterval()", "!(setInterval.flag++)")', [ /1/, /2/, /3/, /4/, /5/, /6/, /7/, /8/, /9/, /10/ ]); // Continue addTest('c', [ /break in node.js:\d+/, /\d/, /\d/, /\d/, /\d/, /\d/ ]); addTest('quit', []); node-v0.10.25~dfsg2/test/simple/test-stream-unshift-read-race.js0000644000000000000000000000754212270121457023202 0ustar rootroot// Copyright Joyent, Inc. and other Node contributors. // // Permission is hereby granted, free of charge, to any person obtaining a // copy of this software and associated documentation files (the // "Software"), to deal in the Software without restriction, including // without limitation the rights to use, copy, modify, merge, publish, // distribute, sublicense, and/or sell copies of the Software, and to permit // persons to whom the Software is furnished to do so, subject to the // following conditions: // // The above copyright notice and this permission notice shall be included // in all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS // OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF // MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN // NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, // DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR // OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE // USE OR OTHER DEALINGS IN THE SOFTWARE. var common = require('../common'); var assert = require('assert'); // This test verifies that: // 1. unshift() does not cause colliding _read() calls. // 2. unshift() after the 'end' event is an error, but after the EOF // signalling null, it is ok, and just creates a new readable chunk. // 3. push() after the EOF signaling null is an error. // 4. _read() is not called after pushing the EOF null chunk. var stream = require('stream'); var hwm = 10; var r = stream.Readable({ highWaterMark: hwm }); var chunks = 10; var t = (chunks * 5); var data = new Buffer(chunks * hwm + Math.ceil(hwm / 2)); for (var i = 0; i < data.length; i++) { var c = 'asdf'.charCodeAt(i % 4); data[i] = c; } var pos = 0; var pushedNull = false; r._read = function(n) { assert(!pushedNull, '_read after null push'); // every third chunk is fast push(!(chunks % 3)); function push(fast) { assert(!pushedNull, 'push() after null push'); var c = pos >= data.length ? null : data.slice(pos, pos + n); pushedNull = c === null; if (fast) { pos += n; r.push(c); if (c === null) pushError(); } else { setTimeout(function() { pos += n; r.push(c); if (c === null) pushError(); }); } } }; function pushError() { assert.throws(function() { r.push(new Buffer(1)); }); } var w = stream.Writable(); var written = []; w._write = function(chunk, encoding, cb) { written.push(chunk.toString()); cb(); }; var ended = false; r.on('end', function() { assert(!ended, 'end emitted more than once'); assert.throws(function() { r.unshift(new Buffer(1)); }); ended = true; w.end(); }); r.on('readable', function() { var chunk; while (null !== (chunk = r.read(10))) { w.write(chunk); if (chunk.length > 4) r.unshift(new Buffer('1234')); } }); var finished = false; w.on('finish', function() { finished = true; // each chunk should start with 1234, and then be asfdasdfasdf... // The first got pulled out before the first unshift('1234'), so it's // lacking that piece. assert.equal(written[0], 'asdfasdfas'); var asdf = 'd'; console.error('0: %s', written[0]); for (var i = 1; i < written.length; i++) { console.error('%s: %s', i.toString(32), written[i]); assert.equal(written[i].slice(0, 4), '1234'); for (var j = 4; j < written[i].length; j++) { var c = written[i].charAt(j); assert.equal(c, asdf); switch (asdf) { case 'a': asdf = 's'; break; case 's': asdf = 'd'; break; case 'd': asdf = 'f'; break; case 'f': asdf = 'a'; break; } } } }); process.on('exit', function() { assert.equal(written.length, 18); assert(ended, 'stream ended'); assert(finished, 'stream finished'); console.log('ok'); }); node-v0.10.25~dfsg2/test/simple/test-tls-request-timeout.js0000644000000000000000000000343412270121457022360 0ustar rootroot// Copyright Joyent, Inc. and other Node contributors. // // Permission is hereby granted, free of charge, to any person obtaining a // copy of this software and associated documentation files (the // "Software"), to deal in the Software without restriction, including // without limitation the rights to use, copy, modify, merge, publish, // distribute, sublicense, and/or sell copies of the Software, and to permit // persons to whom the Software is furnished to do so, subject to the // following conditions: // // The above copyright notice and this permission notice shall be included // in all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS // OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF // MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN // NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, // DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR // OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE // USE OR OTHER DEALINGS IN THE SOFTWARE. var common = require('../common'); var assert = require('assert'); var tls = require('tls'); var fs = require('fs'); var hadTimeout = false; var options = { key: fs.readFileSync(common.fixturesDir + '/keys/agent1-key.pem'), cert: fs.readFileSync(common.fixturesDir + '/keys/agent1-cert.pem') }; var server = tls.Server(options, function(socket) { socket.setTimeout(100); socket.on('timeout', function(err) { hadTimeout = true; socket.end(); server.close(); }); }); server.listen(common.PORT, function() { var socket = tls.connect({ port: common.PORT, rejectUnauthorized: false }); }); process.on('exit', function() { assert.ok(hadTimeout); }); node-v0.10.25~dfsg2/test/simple/test-child-process-fork-exec-path.js0000755000000000000000000000415212270121457023757 0ustar rootroot// Copyright Joyent, Inc. and other Node contributors. // // Permission is hereby granted, free of charge, to any person obtaining a // copy of this software and associated documentation files (the // "Software"), to deal in the Software without restriction, including // without limitation the rights to use, copy, modify, merge, publish, // distribute, sublicense, and/or sell copies of the Software, and to permit // persons to whom the Software is furnished to do so, subject to the // following conditions: // // The above copyright notice and this permission notice shall be included // in all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS // OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF // MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN // NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, // DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR // OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE // USE OR OTHER DEALINGS IN THE SOFTWARE. var assert = require('assert'); var cp = require('child_process'); var fs = require('fs'); var path = require('path'); var common = require('../common'); var msg = {test: 'this'}; var nodePath = process.execPath; var copyPath = path.join(common.tmpDir, 'node-copy.exe'); if (process.env.FORK) { assert(process.send); assert.equal(process.argv[0], copyPath); process.send(msg); process.exit(); } else { try { fs.unlinkSync(copyPath); } catch (e) { if (e.code !== 'ENOENT') throw e; } fs.writeFileSync(copyPath, fs.readFileSync(nodePath)); fs.chmodSync(copyPath, '0755'); // slow but simple var envCopy = JSON.parse(JSON.stringify(process.env)); envCopy.FORK = 'true'; var child = require('child_process').fork(__filename, { execPath: copyPath, env: envCopy }); child.on('message', common.mustCall(function(recv) { assert.deepEqual(msg, recv); })); child.on('exit', common.mustCall(function(code) { fs.unlinkSync(copyPath); assert.equal(code, 0); })); } node-v0.10.25~dfsg2/test/simple/test-http-client-race.js0000644000000000000000000000441012270121457021542 0ustar rootroot// Copyright Joyent, Inc. and other Node contributors. // // Permission is hereby granted, free of charge, to any person obtaining a // copy of this software and associated documentation files (the // "Software"), to deal in the Software without restriction, including // without limitation the rights to use, copy, modify, merge, publish, // distribute, sublicense, and/or sell copies of the Software, and to permit // persons to whom the Software is furnished to do so, subject to the // following conditions: // // The above copyright notice and this permission notice shall be included // in all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS // OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF // MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN // NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, // DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR // OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE // USE OR OTHER DEALINGS IN THE SOFTWARE. var common = require('../common'); var assert = require('assert'); var http = require('http'); var url = require('url'); var body1_s = '1111111111111111'; var body2_s = '22222'; var server = http.createServer(function(req, res) { var body = url.parse(req.url).pathname === '/1' ? body1_s : body2_s; res.writeHead(200, {'Content-Type': 'text/plain', 'Content-Length': body.length}); res.end(body); }); server.listen(common.PORT); var body1 = ''; var body2 = ''; server.on('listening', function() { var req1 = http.request({ port: common.PORT, path: '/1' }); req1.end(); req1.on('response', function(res1) { res1.setEncoding('utf8'); res1.on('data', function(chunk) { body1 += chunk; }); res1.on('end', function() { var req2 = http.request({ port: common.PORT, path: '/2' }); req2.end(); req2.on('response', function(res2) { res2.setEncoding('utf8'); res2.on('data', function(chunk) { body2 += chunk; }); res2.on('end', function() { server.close(); }); }); }); }); }); process.on('exit', function() { assert.equal(body1_s, body1); assert.equal(body2_s, body2); }); node-v0.10.25~dfsg2/test/simple/test-crypto-padding.js0000644000000000000000000000772612270121457021340 0ustar rootroot// Copyright Joyent, Inc. and other Node contributors. // // Permission is hereby granted, free of charge, to any person obtaining a // copy of this software and associated documentation files (the // "Software"), to deal in the Software without restriction, including // without limitation the rights to use, copy, modify, merge, publish, // distribute, sublicense, and/or sell copies of the Software, and to permit // persons to whom the Software is furnished to do so, subject to the // following conditions: // // The above copyright notice and this permission notice shall be included // in all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS // OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF // MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN // NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, // DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR // OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE // USE OR OTHER DEALINGS IN THE SOFTWARE. var common = require('../common'); var assert = require('assert'); try { var crypto = require('crypto'); } catch (e) { console.log('Not compiled with OPENSSL support.'); process.exit(); } crypto.DEFAULT_ENCODING = 'buffer'; /* * Input data */ var ODD_LENGTH_PLAIN = 'Hello node world!', EVEN_LENGTH_PLAIN = 'Hello node world!AbC09876dDeFgHi'; var KEY_PLAIN = 'S3c.r.e.t.K.e.Y!', IV_PLAIN = 'blahFizz2011Buzz'; var CIPHER_NAME = 'aes-128-cbc'; /* * Expected result data */ // echo -n 'Hello node world!' | \ // openssl enc -aes-128-cbc -e -K 5333632e722e652e742e4b2e652e5921 \ // -iv 626c616846697a7a3230313142757a7a | xxd -p -c256 var ODD_LENGTH_ENCRYPTED = '7f57859550d4d2fdb9806da2a750461a9fe77253cd1cbd4b07beee4e070d561f'; // echo -n 'Hello node world!AbC09876dDeFgHi' | \ // openssl enc -aes-128-cbc -e -K 5333632e722e652e742e4b2e652e5921 \ // -iv 626c616846697a7a3230313142757a7a | xxd -p -c256 var EVEN_LENGTH_ENCRYPTED = '7f57859550d4d2fdb9806da2a750461ab46e71b3d78ebe2d9684dfc87f7575b988' + '6119866912cb8c7bcaf76c5ebc2378'; // echo -n 'Hello node world!AbC09876dDeFgHi' | \ // openssl enc -aes-128-cbc -e -K 5333632e722e652e742e4b2e652e5921 \ // -iv 626c616846697a7a3230313142757a7a -nopad | xxd -p -c256 var EVEN_LENGTH_ENCRYPTED_NOPAD = '7f57859550d4d2fdb9806da2a750461ab46e' + '71b3d78ebe2d9684dfc87f7575b9'; /* * Helper wrappers */ function enc(plain, pad) { var encrypt = crypto.createCipheriv(CIPHER_NAME, KEY_PLAIN, IV_PLAIN); encrypt.setAutoPadding(pad); var hex = encrypt.update(plain, 'ascii', 'hex'); hex += encrypt.final('hex'); return hex; } function dec(encd, pad) { var decrypt = crypto.createDecipheriv(CIPHER_NAME, KEY_PLAIN, IV_PLAIN); decrypt.setAutoPadding(pad); var plain = decrypt.update(encd, 'hex'); plain += decrypt.final('binary'); return plain; } /* * Test encryption */ assert.equal(enc(ODD_LENGTH_PLAIN, true), ODD_LENGTH_ENCRYPTED); assert.equal(enc(EVEN_LENGTH_PLAIN, true), EVEN_LENGTH_ENCRYPTED); assert.throws(function() { // input must have block length % enc(ODD_LENGTH_PLAIN, false); }); assert.doesNotThrow(function() { assert.equal(enc(EVEN_LENGTH_PLAIN, false), EVEN_LENGTH_ENCRYPTED_NOPAD); }); /* * Test decryption */ assert.equal(dec(ODD_LENGTH_ENCRYPTED, true), ODD_LENGTH_PLAIN); assert.equal(dec(EVEN_LENGTH_ENCRYPTED, true), EVEN_LENGTH_PLAIN); assert.doesNotThrow(function() { // returns including original padding assert.equal(dec(ODD_LENGTH_ENCRYPTED, false).length, 32); assert.equal(dec(EVEN_LENGTH_ENCRYPTED, false).length, 48); }); assert.throws(function() { // must have at least 1 byte of padding (PKCS): assert.equal(dec(EVEN_LENGTH_ENCRYPTED_NOPAD, true), EVEN_LENGTH_PLAIN); }); assert.doesNotThrow(function() { // no-pad encrypted string should return the same: assert.equal(dec(EVEN_LENGTH_ENCRYPTED_NOPAD, false), EVEN_LENGTH_PLAIN); }); node-v0.10.25~dfsg2/test/simple/test-timers-unref.js0000644000000000000000000000460412270121457021024 0ustar rootroot// Copyright Joyent, Inc. and other Node contributors. // // Permission is hereby granted, free of charge, to any person obtaining a // copy of this software and associated documentation files (the // "Software"), to deal in the Software without restriction, including // without limitation the rights to use, copy, modify, merge, publish, // distribute, sublicense, and/or sell copies of the Software, and to permit // persons to whom the Software is furnished to do so, subject to the // following conditions: // // The above copyright notice and this permission notice shall be included // in all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS // OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF // MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN // NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, // DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR // OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE // USE OR OTHER DEALINGS IN THE SOFTWARE. var common = require('../common'); var assert = require('assert'); var interval_fired = false, timeout_fired = false, unref_interval = false, unref_timer = false, interval, check_unref, checks = 0; var LONG_TIME = 10 * 1000; var SHORT_TIME = 100; setInterval(function() { interval_fired = true; }, LONG_TIME).unref(); setTimeout(function() { timeout_fired = true; }, LONG_TIME).unref(); interval = setInterval(function() { unref_interval = true; clearInterval(interval); }, SHORT_TIME).unref(); setTimeout(function() { unref_timer = true; }, SHORT_TIME).unref(); check_unref = setInterval(function() { if (checks > 5 || (unref_interval && unref_timer)) clearInterval(check_unref); checks += 1; }, 100); // Should not assert on args.Holder()->InternalFieldCount() > 0. See #4261. (function() { var t = setInterval(function() {}, 1); process.nextTick(t.unref.bind({})); process.nextTick(t.unref.bind(t)); })(); process.on('exit', function() { assert.strictEqual(interval_fired, false, 'Interval should not fire'); assert.strictEqual(timeout_fired, false, 'Timeout should not fire'); assert.strictEqual(unref_timer, true, 'An unrefd timeout should still fire'); assert.strictEqual(unref_interval, true, 'An unrefd interval should still fire'); }); node-v0.10.25~dfsg2/test/simple/test-listen-fd-detached.js0000644000000000000000000000771312270121457022034 0ustar rootroot// Copyright Joyent, Inc. and other Node contributors. // // Permission is hereby granted, free of charge, to any person obtaining a // copy of this software and associated documentation files (the // "Software"), to deal in the Software without restriction, including // without limitation the rights to use, copy, modify, merge, publish, // distribute, sublicense, and/or sell copies of the Software, and to permit // persons to whom the Software is furnished to do so, subject to the // following conditions: // // The above copyright notice and this permission notice shall be included // in all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS // OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF // MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN // NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, // DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR // OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE // USE OR OTHER DEALINGS IN THE SOFTWARE. var common = require('../common'); var assert = require('assert'); var http = require('http'); var net = require('net'); var PORT = common.PORT; var spawn = require('child_process').spawn; if (process.platform === 'win32') { console.error('This test is disabled on windows.'); return; } switch (process.argv[2]) { case 'child': return child(); case 'parent': return parent(); default: return test(); } // spawn the parent, and listen for it to tell us the pid of the child. // WARNING: This is an example of listening on some arbitrary FD number // that has already been bound elsewhere in advance. However, binding // server handles to stdio fd's is NOT a good or reliable way to do // concurrency in HTTP servers! Use the cluster module, or if you want // a more low-level approach, use child process IPC manually. function test() { var parent = spawn(process.execPath, [__filename, 'parent'], { stdio: [ 0, 'pipe', 2 ] }); var json = ''; parent.stdout.on('data', function(c) { json += c.toString(); if (json.indexOf('\n') !== -1) next(); }); function next() { console.error('output from parent = %s', json); var child = JSON.parse(json); // now make sure that we can request to the child, then kill it. http.get({ server: 'localhost', port: PORT, path: '/', }).on('response', function (res) { var s = ''; res.on('data', function(c) { s += c.toString(); }); res.on('end', function() { // kill the child before we start doing asserts. // it's really annoying when tests leave orphans! process.kill(child.pid, 'SIGKILL'); try { parent.kill(); } catch (e) {} assert.equal(s, 'hello from child\n'); assert.equal(res.statusCode, 200); }); }) } } function parent() { var server = net.createServer(function(conn) { console.error('connection on parent'); conn.end('hello from parent\n'); }).listen(PORT, function() { console.error('server listening on %d', PORT); var spawn = require('child_process').spawn; var child = spawn(process.execPath, [__filename, 'child'], { stdio: [ 'ignore', 'ignore', 'ignore', server._handle ], detached: true }); console.log('%j\n', { pid: child.pid }); // Now close the parent, so that the child is the only thing // referencing that handle. Note that connections will still // be accepted, because the child has the fd open, but the parent // will exit gracefully. server.close(); child.unref(); }); } function child() { // start a server on fd=3 http.createServer(function(req, res) { console.error('request on child'); console.error('%s %s', req.method, req.url, req.headers); res.end('hello from child\n'); }).listen({ fd: 3 }, function() { console.error('child listening on fd=3'); }); } node-v0.10.25~dfsg2/test/simple/test-http-client-response-domain.js0000644000000000000000000000402412270121457023734 0ustar rootroot// Copyright Joyent, Inc. and other Node contributors. // // Permission is hereby granted, free of charge, to any person obtaining a // copy of this software and associated documentation files (the // "Software"), to deal in the Software without restriction, including // without limitation the rights to use, copy, modify, merge, publish, // distribute, sublicense, and/or sell copies of the Software, and to permit // persons to whom the Software is furnished to do so, subject to the // following conditions: // // The above copyright notice and this permission notice shall be included // in all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS // OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF // MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN // NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, // DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR // OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE // USE OR OTHER DEALINGS IN THE SOFTWARE. var common = require('../common'), assert = require('assert'), http = require('http'), domain = require('domain'); var gotDomainError = false; var d; process.on('exit', function() { assert(gotDomainError); }); // first fire up a simple HTTP server var server = http.createServer(function(req, res) { res.writeHead(200); res.end(); server.close(); }); server.listen(common.PIPE, function() { // create a domain d = domain.create(); d.run(test); }); function test() { d.on('error', function(err) { gotDomainError = true; assert.equal('should be caught by domain', err.message); }); var req = http.get({ socketPath: common.PIPE, headers: {'Content-Length':'1'}, method: 'POST', path: '/' }); req.on('response', function(res) { res.on('end', function() { res.emit('error', new Error('should be caught by domain')); }); res.resume(); }); req.end(); } node-v0.10.25~dfsg2/test/simple/test-child-process-kill-throw.js0000644000000000000000000000342712270121457023237 0ustar rootroot// Copyright Joyent, Inc. and other Node contributors. // // Permission is hereby granted, free of charge, to any person obtaining a // copy of this software and associated documentation files (the // "Software"), to deal in the Software without restriction, including // without limitation the rights to use, copy, modify, merge, publish, // distribute, sublicense, and/or sell copies of the Software, and to permit // persons to whom the Software is furnished to do so, subject to the // following conditions: // // The above copyright notice and this permission notice shall be included // in all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS // OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF // MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN // NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, // DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR // OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE // USE OR OTHER DEALINGS IN THE SOFTWARE. var common = require('../common'); var assert = require('assert'); if (process.argv[2] === 'child') { process.exit(0); } else { var spawn = require('child_process').spawn; var child = spawn(process.execPath, [process.argv[1], 'child']); var error = {}; child.on('exit', function() { child._handle = { kill: function() { process._errno = 42; return -1; } }; child.once('error', function(err) { error = err; }); child.kill(); }); process.on('exit', function() { // we shouldn't reset errno since it accturlly isn't set // because of the fake .kill method assert.equal(error.syscall, 'kill'); }); } node-v0.10.25~dfsg2/test/simple/test-chdir.js0000644000000000000000000000316712270121457017500 0ustar rootroot// Copyright Joyent, Inc. and other Node contributors. // // Permission is hereby granted, free of charge, to any person obtaining a // copy of this software and associated documentation files (the // "Software"), to deal in the Software without restriction, including // without limitation the rights to use, copy, modify, merge, publish, // distribute, sublicense, and/or sell copies of the Software, and to permit // persons to whom the Software is furnished to do so, subject to the // following conditions: // // The above copyright notice and this permission notice shall be included // in all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS // OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF // MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN // NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, // DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR // OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE // USE OR OTHER DEALINGS IN THE SOFTWARE. var common = require('../common'); var assert = require('assert'); var fs = require('fs'); var path = require('path'); assert.equal(true, process.cwd() !== __dirname); process.chdir(__dirname); assert.equal(true, process.cwd() === __dirname); var dir = path.resolve(common.fixturesDir, 'weird \uc3a4\uc3ab\uc3af characters \u00e1\u00e2\u00e3'); fs.mkdirSync(dir); process.chdir(dir); assert(process.cwd() == dir); process.chdir('..'); assert(process.cwd() == path.resolve(common.fixturesDir)); fs.rmdirSync(dir); node-v0.10.25~dfsg2/test/simple/test-string-decoder.js0000644000000000000000000001360612270121457021317 0ustar rootroot// Copyright Joyent, Inc. and other Node contributors. // // Permission is hereby granted, free of charge, to any person obtaining a // copy of this software and associated documentation files (the // "Software"), to deal in the Software without restriction, including // without limitation the rights to use, copy, modify, merge, publish, // distribute, sublicense, and/or sell copies of the Software, and to permit // persons to whom the Software is furnished to do so, subject to the // following conditions: // // The above copyright notice and this permission notice shall be included // in all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS // OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF // MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN // NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, // DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR // OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE // USE OR OTHER DEALINGS IN THE SOFTWARE. var common = require('../common'); var assert = require('assert'); var StringDecoder = require('string_decoder').StringDecoder; var decoder = new StringDecoder('utf8'); var buffer = new Buffer('$'); assert.deepEqual('$', decoder.write(buffer)); buffer = new Buffer('¢'); assert.deepEqual('', decoder.write(buffer.slice(0, 1))); assert.deepEqual('¢', decoder.write(buffer.slice(1, 2))); buffer = new Buffer('€'); assert.deepEqual('', decoder.write(buffer.slice(0, 1))); assert.deepEqual('', decoder.write(buffer.slice(1, 2))); assert.deepEqual('€', decoder.write(buffer.slice(2, 3))); buffer = new Buffer([0xF0, 0xA4, 0xAD, 0xA2]); var s = ''; s += decoder.write(buffer.slice(0, 1)); s += decoder.write(buffer.slice(1, 2)); s += decoder.write(buffer.slice(2, 3)); s += decoder.write(buffer.slice(3, 4)); assert.ok(s.length > 0); // CESU-8 buffer = new Buffer('EDA0BDEDB18D', 'hex'); // THUMBS UP SIGN (in CESU-8) var s = ''; s += decoder.write(buffer.slice(0, 1)); s += decoder.write(buffer.slice(1, 2)); s += decoder.write(buffer.slice(2, 3)); // complete lead surrogate assert.equal(s, ''); s += decoder.write(buffer.slice(3, 4)); s += decoder.write(buffer.slice(4, 5)); s += decoder.write(buffer.slice(5, 6)); // complete trail surrogate assert.equal(s, '\uD83D\uDC4D'); // THUMBS UP SIGN (in UTF-16) var s = ''; s += decoder.write(buffer.slice(0, 2)); s += decoder.write(buffer.slice(2, 4)); // complete lead surrogate assert.equal(s, ''); s += decoder.write(buffer.slice(4, 6)); // complete trail surrogate assert.equal(s, '\uD83D\uDC4D'); // THUMBS UP SIGN (in UTF-16) var s = ''; s += decoder.write(buffer.slice(0, 3)); // complete lead surrogate assert.equal(s, ''); s += decoder.write(buffer.slice(3, 6)); // complete trail surrogate assert.equal(s, '\uD83D\uDC4D'); // THUMBS UP SIGN (in UTF-16) var s = ''; s += decoder.write(buffer.slice(0, 4)); // complete lead surrogate assert.equal(s, ''); s += decoder.write(buffer.slice(4, 5)); s += decoder.write(buffer.slice(5, 6)); // complete trail surrogate assert.equal(s, '\uD83D\uDC4D'); // THUMBS UP SIGN (in UTF-16) var s = ''; s += decoder.write(buffer.slice(0, 5)); // complete lead surrogate assert.equal(s, ''); s += decoder.write(buffer.slice(5, 6)); // complete trail surrogate assert.equal(s, '\uD83D\uDC4D'); // THUMBS UP SIGN (in UTF-16) var s = ''; s += decoder.write(buffer.slice(0, 6)); assert.equal(s, '\uD83D\uDC4D'); // THUMBS UP SIGN (in UTF-16) // UCS-2 decoder = new StringDecoder('ucs2'); buffer = new Buffer('ab', 'ucs2'); assert.equal(decoder.write(buffer), 'ab'); // 2 complete chars buffer = new Buffer('abc', 'ucs2'); assert.equal(decoder.write(buffer.slice(0, 3)), 'a'); // 'a' and first of 'b' assert.equal(decoder.write(buffer.slice(3, 6)), 'bc'); // second of 'b' and 'c' // UTF-16LE buffer = new Buffer('3DD84DDC', 'hex'); // THUMBS UP SIGN (in CESU-8) var s = ''; s += decoder.write(buffer.slice(0, 1)); s += decoder.write(buffer.slice(1, 2)); // complete lead surrogate assert.equal(s, ''); s += decoder.write(buffer.slice(2, 3)); s += decoder.write(buffer.slice(3, 4)); // complete trail surrogate assert.equal(s, '\uD83D\uDC4D'); // THUMBS UP SIGN (in UTF-16) var s = ''; s += decoder.write(buffer.slice(0, 2)); // complete lead surrogate assert.equal(s, ''); s += decoder.write(buffer.slice(2, 4)); // complete trail surrogate assert.equal(s, '\uD83D\uDC4D'); // THUMBS UP SIGN (in UTF-16) var s = ''; s += decoder.write(buffer.slice(0, 3)); // complete lead surrogate assert.equal(s, ''); s += decoder.write(buffer.slice(3, 4)); // complete trail surrogate assert.equal(s, '\uD83D\uDC4D'); // THUMBS UP SIGN (in UTF-16) var s = ''; s += decoder.write(buffer.slice(0, 4)); assert.equal(s, '\uD83D\uDC4D'); // THUMBS UP SIGN (in UTF-16) // A mixed ascii and non-ascii string // Test stolen from deps/v8/test/cctest/test-strings.cc // U+02E4 -> CB A4 // U+0064 -> 64 // U+12E4 -> E1 8B A4 // U+0030 -> 30 // U+3045 -> E3 81 85 var expected = '\u02e4\u0064\u12e4\u0030\u3045'; var buffer = new Buffer([0xCB, 0xA4, 0x64, 0xE1, 0x8B, 0xA4, 0x30, 0xE3, 0x81, 0x85]); var charLengths = [0, 0, 1, 2, 2, 2, 3, 4, 4, 4, 5, 5]; // Split the buffer into 3 segments // |----|------|-------| // 0 i j buffer.length // Scan through every possible 3 segment combination // and make sure that the string is always parsed. common.print('scanning '); for (var j = 2; j < buffer.length; j++) { for (var i = 1; i < j; i++) { var decoder = new StringDecoder('utf8'); var sum = decoder.write(buffer.slice(0, i)); // just check that we've received the right amount // after the first write assert.equal(charLengths[i], sum.length); sum += decoder.write(buffer.slice(i, j)); sum += decoder.write(buffer.slice(j, buffer.length)); assert.equal(expected, sum); common.print('.'); } } console.log(' crayon!'); node-v0.10.25~dfsg2/test/simple/test-cluster-bind-twice-v1.js0000644000000000000000000000462712270121457022441 0ustar rootroot// Copyright Joyent, Inc. and other Node contributors. // // Permission is hereby granted, free of charge, to any person obtaining a // copy of this software and associated documentation files (the // "Software"), to deal in the Software without restriction, including // without limitation the rights to use, copy, modify, merge, publish, // distribute, sublicense, and/or sell copies of the Software, and to permit // persons to whom the Software is furnished to do so, subject to the // following conditions: // // The above copyright notice and this permission notice shall be included // in all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS // OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF // MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN // NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, // DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR // OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE // USE OR OTHER DEALINGS IN THE SOFTWARE. // This test starts two clustered HTTP servers on the same port. It expects the // first cluster to succeed and the second cluster to fail with EADDRINUSE. var common = require('../common'); var assert = require('assert'); var cluster = require('cluster'); var fork = require('child_process').fork; var http = require('http'); var id = process.argv[2]; if (!id) { var a = fork(__filename, ['one']); var b = fork(__filename, ['two']); a.on('message', function(m) { assert.equal(m, 'READY'); b.send('START'); }); var ok = false; b.on('message', function(m) { assert.equal(m, 'EADDRINUSE'); a.kill(); b.kill(); ok = true; }); process.on('exit', function() { a.kill(); b.kill(); assert(ok); }); } else if (id === 'one') { if (cluster.isMaster) cluster.fork(); http.createServer(assert.fail).listen(common.PORT, function() { process.send('READY'); }); } else if (id === 'two') { if (cluster.isMaster) cluster.fork(); process.on('message', function(m) { assert.equal(m, 'START'); var server = http.createServer(assert.fail); server.listen(common.PORT, assert.fail); server.on('error', function(e) { assert.equal(e.code, 'EADDRINUSE'); process.send(e.code); }); }); } else { assert(0); // bad command line argument } node-v0.10.25~dfsg2/test/simple/test-net-connect-handle-econnrefused.js0000644000000000000000000000312612270121457024526 0ustar rootroot// Copyright Joyent, Inc. and other Node contributors. // // Permission is hereby granted, free of charge, to any person obtaining a // copy of this software and associated documentation files (the // "Software"), to deal in the Software without restriction, including // without limitation the rights to use, copy, modify, merge, publish, // distribute, sublicense, and/or sell copies of the Software, and to permit // persons to whom the Software is furnished to do so, subject to the // following conditions: // // The above copyright notice and this permission notice shall be included // in all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS // OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF // MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN // NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, // DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR // OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE // USE OR OTHER DEALINGS IN THE SOFTWARE. var common = require('../common'); var net = require('net'); var assert = require('assert'); // Hopefully nothing is running on common.PORT var c = net.createConnection(common.PORT); c.on('connect', function() { console.error('connected?!'); assert.ok(false); }); var gotError = false; c.on('error', function(e) { console.error('couldn\'t connect.'); gotError = true; assert.equal('ECONNREFUSED', e.code); }); process.on('exit', function() { assert.ok(gotError); }); node-v0.10.25~dfsg2/test/simple/test-https-timeout.js0000644000000000000000000000455112270121457021233 0ustar rootroot// Copyright Joyent, Inc. and other Node contributors. // // Permission is hereby granted, free of charge, to any person obtaining a // copy of this software and associated documentation files (the // "Software"), to deal in the Software without restriction, including // without limitation the rights to use, copy, modify, merge, publish, // distribute, sublicense, and/or sell copies of the Software, and to permit // persons to whom the Software is furnished to do so, subject to the // following conditions: // // The above copyright notice and this permission notice shall be included // in all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS // OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF // MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN // NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, // DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR // OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE // USE OR OTHER DEALINGS IN THE SOFTWARE. if (!process.versions.openssl) { console.error('Skipping because node compiled without OpenSSL.'); process.exit(0); } var common = require('../common'); var assert = require('assert'); var fs = require('fs'); var exec = require('child_process').exec; var https = require('https'); var options = { key: fs.readFileSync(common.fixturesDir + '/keys/agent1-key.pem'), cert: fs.readFileSync(common.fixturesDir + '/keys/agent1-cert.pem') }; // a server that never replies var server = https.createServer(options, function() { console.log('Got request. Doing nothing.'); }).listen(common.PORT, function() { var req = https.request({ host: 'localhost', port: common.PORT, path: '/', method: 'GET', rejectUnauthorized: false }); req.setTimeout(10); req.end(); req.on('response', function(res) { console.log('got response'); }); req.on('socket', function() { console.log('got a socket'); req.socket.on('connect', function() { console.log('socket connected'); }); setTimeout(function() { throw new Error('Did not get timeout event'); }, 200); }); req.on('timeout', function() { console.log('timeout occurred outside'); req.destroy(); server.close(); process.exit(0); }); }); node-v0.10.25~dfsg2/test/simple/test-fs-write-file.js0000644000000000000000000000737712270121457021073 0ustar rootroot// Copyright Joyent, Inc. and other Node contributors. // // Permission is hereby granted, free of charge, to any person obtaining a // copy of this software and associated documentation files (the // "Software"), to deal in the Software without restriction, including // without limitation the rights to use, copy, modify, merge, publish, // distribute, sublicense, and/or sell copies of the Software, and to permit // persons to whom the Software is furnished to do so, subject to the // following conditions: // // The above copyright notice and this permission notice shall be included // in all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS // OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF // MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN // NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, // DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR // OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE // USE OR OTHER DEALINGS IN THE SOFTWARE. var common = require('../common'); var assert = require('assert'); var fs = require('fs'); var join = require('path').join; var filename = join(common.tmpDir, 'test.txt'); common.error('writing to ' + filename); var n = 220; var s = '南越国是前203年至前111年存在于岭南地区的一个国家,国都位于番禺,疆域包括今天中国的广东、' + '广西两省区的大部份地区,福建省、湖南、贵州、云南的一小部份地区和越南的北部。' + '南越国是秦朝灭亡后,由南海郡尉赵佗于前203年起兵兼并桂林郡和象郡后建立。' + '前196年和前179年,南越国曾先后两次名义上臣属于西汉,成为西汉的“外臣”。前112年,' + '南越国末代君主赵建德与西汉发生战争,被汉武帝于前111年所灭。南越国共存在93年,' + '历经五代君主。南越国是岭南地区的第一个有记载的政权国家,采用封建制和郡县制并存的制度,' + '它的建立保证了秦末乱世岭南地区社会秩序的稳定,有效的改善了岭南地区落后的政治、##济现状。\n'; var ncallbacks = 0; fs.writeFile(filename, s, function(e) { if (e) throw e; ncallbacks++; common.error('file written'); fs.readFile(filename, function(e, buffer) { if (e) throw e; common.error('file read'); ncallbacks++; assert.equal(Buffer.byteLength(s), buffer.length); }); }); // test that writeFile accepts buffers var filename2 = join(common.tmpDir, 'test2.txt'); var buf = new Buffer(s, 'utf8'); common.error('writing to ' + filename2); fs.writeFile(filename2, buf, function(e) { if (e) throw e; ncallbacks++; common.error('file2 written'); fs.readFile(filename2, function(e, buffer) { if (e) throw e; common.error('file2 read'); ncallbacks++; assert.equal(buf.length, buffer.length); }); }); // test that writeFile accepts numbers. var filename3 = join(common.tmpDir, 'test3.txt'); common.error('writing to ' + filename3); var m = 0600; fs.writeFile(filename3, n, { mode: m }, function(e) { if (e) throw e; // windows permissions aren't unix if (process.platform !== 'win32') { var st = fs.statSync(filename3); assert.equal(st.mode & 0700, m); } ncallbacks++; common.error('file3 written'); fs.readFile(filename3, function(e, buffer) { if (e) throw e; common.error('file3 read'); ncallbacks++; assert.equal(Buffer.byteLength('' + n), buffer.length); }); }); process.on('exit', function() { common.error('done'); assert.equal(6, ncallbacks); fs.unlinkSync(filename); fs.unlinkSync(filename2); fs.unlinkSync(filename3); }); node-v0.10.25~dfsg2/test/simple/test-process-argv-0.js0000644000000000000000000000405712270121457021156 0ustar rootroot// Copyright Joyent, Inc. and other Node contributors. // // Permission is hereby granted, free of charge, to any person obtaining a // copy of this software and associated documentation files (the // "Software"), to deal in the Software without restriction, including // without limitation the rights to use, copy, modify, merge, publish, // distribute, sublicense, and/or sell copies of the Software, and to permit // persons to whom the Software is furnished to do so, subject to the // following conditions: // // The above copyright notice and this permission notice shall be included // in all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS // OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF // MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN // NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, // DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR // OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE // USE OR OTHER DEALINGS IN THE SOFTWARE. var util = require('util'); var path = require('path'); var assert = require('assert'); var spawn = require('child_process').spawn; var common = require('../common'); console.error('argv=%j', process.argv); console.error('exec=%j', process.execPath); if (process.argv[2] !== "child") { var child = spawn('./node', [__filename, "child"], { cwd: path.dirname(process.execPath) }); var childArgv0 = ''; var childErr = ''; child.stdout.on('data', function(chunk) { childArgv0 += chunk; }); child.stderr.on('data', function(chunk) { childErr += chunk; }); child.on('exit', function () { console.error('CHILD: %s', childErr.trim().split('\n').join('\nCHILD: ')); if (process.platform === 'win32') { // On Windows argv[0] is not expanded into full path assert.equal(childArgv0, './node'); } else { assert.equal(childArgv0, process.execPath); } }); } else { process.stdout.write(process.argv[0]); } node-v0.10.25~dfsg2/test/simple/test-delayed-require.js0000644000000000000000000000256612270121457021472 0ustar rootroot// Copyright Joyent, Inc. and other Node contributors. // // Permission is hereby granted, free of charge, to any person obtaining a // copy of this software and associated documentation files (the // "Software"), to deal in the Software without restriction, including // without limitation the rights to use, copy, modify, merge, publish, // distribute, sublicense, and/or sell copies of the Software, and to permit // persons to whom the Software is furnished to do so, subject to the // following conditions: // // The above copyright notice and this permission notice shall be included // in all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS // OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF // MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN // NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, // DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR // OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE // USE OR OTHER DEALINGS IN THE SOFTWARE. var common = require('../common'); var assert = require('assert'); var a; setTimeout(function() { a = require('../fixtures/a'); }, 50); process.on('exit', function() { assert.equal(true, 'A' in a); assert.equal('A', a.A()); assert.equal('D', a.D()); }); node-v0.10.25~dfsg2/test/simple/test-https-foafssl.js0000644000000000000000000000625512270121457021205 0ustar rootroot// Copyright Joyent, Inc. and other Node contributors. // // Permission is hereby granted, free of charge, to any person obtaining a // copy of this software and associated documentation files (the // "Software"), to deal in the Software without restriction, including // without limitation the rights to use, copy, modify, merge, publish, // distribute, sublicense, and/or sell copies of the Software, and to permit // persons to whom the Software is furnished to do so, subject to the // following conditions: // // The above copyright notice and this permission notice shall be included // in all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS // OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF // MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN // NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, // DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR // OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE // USE OR OTHER DEALINGS IN THE SOFTWARE. if (!process.versions.openssl) { console.error('Skipping because node compiled without OpenSSL.'); process.exit(0); } var common = require('../common'); var assert = require('assert'); var join = require('path').join; var fs = require('fs'); var exec = require('child_process').exec; var https = require('https'); var options = { key: fs.readFileSync(common.fixturesDir + '/agent.key'), cert: fs.readFileSync(common.fixturesDir + '/agent.crt'), requestCert: true }; var reqCount = 0; var body = 'hello world\n'; var cert; var subjectaltname; var modulus; var exponent; var server = https.createServer(options, function(req, res) { reqCount++; console.log('got request'); cert = req.connection.getPeerCertificate(); subjectaltname = cert.subjectaltname; modulus = cert.modulus; exponent = cert.exponent; res.writeHead(200, { 'content-type': 'text/plain' }); res.end(body); }); server.listen(common.PORT, function() { var cmd = 'curl --insecure https://127.0.0.1:' + common.PORT + '/'; cmd += ' --cert ' + join(common.fixturesDir, 'foafssl.crt'); cmd += ' --key ' + join(common.fixturesDir, 'foafssl.key'); console.error('executing %j', cmd); exec(cmd, function(err, stdout, stderr) { if (err) throw err; common.error(common.inspect(stdout)); assert.equal(body, stdout); server.close(); }); }); process.on('exit', function() { assert.equal(subjectaltname, 'URI:http://example.com/#me'); assert.equal(modulus, 'A6F44A9C25791431214F5C87AF9E040177A8BB89AC803F7E09' + 'BBC3A5519F349CD9B9C40BE436D0AA823A94147E26C89248ADA2BE3DD4D34E8C2896' + '4694B2047D217B4F1299371EA93A83C89AB9440724131E65F2B0161DE9560CDE9C13' + '455552B2F49CF0FB00D8D77532324913F6F80FF29D0A131D29DB06AFF8BE191B7920' + 'DC2DAE1C26EA82A47847A10391EF3BF6AABB3CC40FF82100B03A4F0FF1809278E4DD' + 'FDA7DE954ED56DC7AD9A47EEBC37D771A366FC60A5BCB72373BEC180649B3EFA0E90' + '92707210B41B90032BB18BC91F2046EBDAF1191F4A4E26D71879C4C7867B62FCD508' + 'E8CE66E82D128A71E915809FCF44E8DE774067F1DE5D70B9C03687'); assert.equal(exponent, '10001'); }); node-v0.10.25~dfsg2/test/simple/test-crypto-stream.js0000644000000000000000000000562512270121457021221 0ustar rootroot// Copyright Joyent, Inc. and other Node contributors. // // Permission is hereby granted, free of charge, to any person obtaining a // copy of this software and associated documentation files (the // "Software"), to deal in the Software without restriction, including // without limitation the rights to use, copy, modify, merge, publish, // distribute, sublicense, and/or sell copies of the Software, and to permit // persons to whom the Software is furnished to do so, subject to the // following conditions: // // The above copyright notice and this permission notice shall be included // in all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS // OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF // MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN // NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, // DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR // OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE // USE OR OTHER DEALINGS IN THE SOFTWARE. var common = require('../common'); var assert = require('assert'); var stream = require('stream'); var util = require('util'); try { var crypto = require('crypto'); } catch (e) { console.log('Not compiled with OPENSSL support.'); process.exit(); } // Small stream to buffer converter function Stream2buffer(callback) { stream.Writable.call(this); this._buffers = []; this.once('finish', function () { callback(null, Buffer.concat(this._buffers)); }); } util.inherits(Stream2buffer, stream.Writable); Stream2buffer.prototype._write = function (data, encodeing, done) { this._buffers.push(data); return done(null); }; // Create an md5 hash of "Hallo world" var hasher1 = crypto.createHash('md5'); hasher1.pipe(new Stream2buffer(common.mustCall(function end(err, hash) { assert.equal(err, null); assert.equal(hash.toString('hex'), '06460dadb35d3d503047ce750ceb2d07'); }))); hasher1.end('Hallo world'); // Simpler check for unpipe, setEncoding, pause and resume crypto.createHash('md5').unpipe({}); crypto.createHash('md5').setEncoding('utf8'); crypto.createHash('md5').pause(); crypto.createHash('md5').resume(); // Decipher._flush() should emit an error event, not an exception. var key = new Buffer('48fb56eb10ffeb13fc0ef551bbca3b1b', 'hex'), badkey = new Buffer('12341234123412341234123412341234', 'hex'), iv = new Buffer('6d358219d1f488f5f4eb12820a66d146', 'hex'), cipher = crypto.createCipheriv('aes-128-cbc', key, iv), decipher = crypto.createDecipheriv('aes-128-cbc', badkey, iv); cipher.pipe(decipher) .on('error', common.mustCall(function end(err) { // TypeError: error:06065064:digital envelope routines:EVP_DecryptFinal_ex:bad decrypt assert(/:06065064:/.test(err)); })); cipher.end('Papaya!'); // Should not cause an unhandled exception. node-v0.10.25~dfsg2/test/simple/test-listen-fd-cluster.js0000644000000000000000000001077612270121457021757 0ustar rootroot// Copyright Joyent, Inc. and other Node contributors. // // Permission is hereby granted, free of charge, to any person obtaining a // copy of this software and associated documentation files (the // "Software"), to deal in the Software without restriction, including // without limitation the rights to use, copy, modify, merge, publish, // distribute, sublicense, and/or sell copies of the Software, and to permit // persons to whom the Software is furnished to do so, subject to the // following conditions: // // The above copyright notice and this permission notice shall be included // in all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS // OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF // MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN // NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, // DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR // OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE // USE OR OTHER DEALINGS IN THE SOFTWARE. var common = require('../common'); var assert = require('assert'); var http = require('http'); var net = require('net'); var PORT = common.PORT; var spawn = require('child_process').spawn; var cluster = require('cluster'); console.error('Cluster listen fd test', process.argv.slice(2)); if (process.platform === 'win32') { console.error('This test is disabled on windows.'); return; } switch (process.argv[2]) { case 'master': return master(); case 'worker': return worker(); case 'parent': return parent(); default: return test(); } // spawn the parent, and listen for it to tell us the pid of the cluster. // WARNING: This is an example of listening on some arbitrary FD number // that has already been bound elsewhere in advance. However, binding // server handles to stdio fd's is NOT a good or reliable way to do // concurrency in HTTP servers! Use the cluster module, or if you want // a more low-level approach, use child process IPC manually. function test() { var parent = spawn(process.execPath, [__filename, 'parent'], { stdio: [ 0, 'pipe', 2 ] }); var json = ''; parent.stdout.on('data', function(c) { json += c.toString(); if (json.indexOf('\n') !== -1) next(); }); function next() { console.error('output from parent = %s', json); var cluster = JSON.parse(json); // now make sure that we can request to the worker, then kill it. http.get({ server: 'localhost', port: PORT, path: '/', }).on('response', function (res) { var s = ''; res.on('data', function(c) { s += c.toString(); }); res.on('end', function() { // kill the worker before we start doing asserts. // it's really annoying when tests leave orphans! parent.kill(); process.kill(cluster.master, 'SIGKILL'); assert.equal(s, 'hello from worker\n'); assert.equal(res.statusCode, 200); console.log('ok'); }); }) } } function parent() { console.error('about to listen in parent'); var server = net.createServer(function(conn) { console.error('connection on parent'); conn.end('hello from parent\n'); }).listen(PORT, function() { console.error('server listening on %d', PORT); var spawn = require('child_process').spawn; var master = spawn(process.execPath, [__filename, 'master'], { stdio: [ 0, 1, 2, server._handle ], detached: true }); // Now close the parent, so that the master is the only thing // referencing that handle. Note that connections will still // be accepted, because the master has the fd open. server.close(); master.on('exit', function(code) { console.error('master exited', code); }); master.on('close', function() { console.error('master closed'); }); console.error('master spawned'); }); } function master() { console.error('in master, spawning worker'); cluster.setupMaster({ args: [ 'worker' ] }); var worker = cluster.fork(); console.log('%j\n', { master: process.pid, worker: worker.pid }); } function worker() { console.error('worker, about to create server and listen on fd=3'); // start a server on fd=3 http.createServer(function(req, res) { console.error('request on worker'); console.error('%s %s', req.method, req.url, req.headers); res.end('hello from worker\n'); }).listen({ fd: 3 }, function() { console.error('worker listening on fd=3'); }); } node-v0.10.25~dfsg2/test/simple/test-tls-peer-certificate-multi-keys.js0000644000000000000000000000426512270121457024523 0ustar rootroot// Copyright Joyent, Inc. and other Node contributors. // // Permission is hereby granted, free of charge, to any person obtaining a // copy of this software and associated documentation files (the // "Software"), to deal in the Software without restriction, including // without limitation the rights to use, copy, modify, merge, publish, // distribute, sublicense, and/or sell copies of the Software, and to permit // persons to whom the Software is furnished to do so, subject to the // following conditions: // // The above copyright notice and this permission notice shall be included // in all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS // OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF // MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN // NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, // DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR // OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE // USE OR OTHER DEALINGS IN THE SOFTWARE. if (!process.versions.openssl) { console.error('Skipping because node compiled without OpenSSL.'); process.exit(0); } var common = require('../common'); var assert = require('assert'); var tls = require('tls'); var fs = require('fs'); var util = require('util'); var join = require('path').join; var spawn = require('child_process').spawn; var options = { key: fs.readFileSync(join(common.fixturesDir, 'agent.key')), cert: fs.readFileSync(join(common.fixturesDir, 'multi-alice.crt')) }; var verified = false; var server = tls.createServer(options, function(cleartext) { cleartext.end('World'); }); server.listen(common.PORT, function() { var socket = tls.connect({ port: common.PORT, rejectUnauthorized: false }, function() { var peerCert = socket.getPeerCertificate(); common.debug(util.inspect(peerCert)); assert.deepEqual(peerCert.subject.OU, ['Information Technology', 'Engineering', 'Marketing']); verified = true; server.close(); }); socket.end('Hello'); }); process.on('exit', function() { assert.ok(verified); }); node-v0.10.25~dfsg2/test/simple/test-next-tick-errors.js0000644000000000000000000000376612270121457021634 0ustar rootroot// Copyright Joyent, Inc. and other Node contributors. // // Permission is hereby granted, free of charge, to any person obtaining a // copy of this software and associated documentation files (the // "Software"), to deal in the Software without restriction, including // without limitation the rights to use, copy, modify, merge, publish, // distribute, sublicense, and/or sell copies of the Software, and to permit // persons to whom the Software is furnished to do so, subject to the // following conditions: // // The above copyright notice and this permission notice shall be included // in all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS // OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF // MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN // NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, // DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR // OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE // USE OR OTHER DEALINGS IN THE SOFTWARE. var common = require('../common'); var assert = require('assert'); var order = [], exceptionHandled = false; // This nextTick function will throw an error. It should only be called once. // When it throws an error, it should still get removed from the queue. process.nextTick(function() { order.push('A'); // cause an error what(); }); // This nextTick function should remain in the queue when the first one // is removed. It should be called if the error in the first one is // caught (which we do in this test). process.nextTick(function() { order.push('C'); }); process.on('uncaughtException', function() { if (!exceptionHandled) { exceptionHandled = true; order.push('B'); } else { // If we get here then the first process.nextTick got called twice order.push('OOPS!'); } }); process.on('exit', function() { assert.deepEqual(['A', 'B', 'C'], order); }); node-v0.10.25~dfsg2/test/simple/test-https-eof-for-eom.js0000644000000000000000000000633612270121457021663 0ustar rootroot// Copyright Joyent, Inc. and other Node contributors. // // Permission is hereby granted, free of charge, to any person obtaining a // copy of this software and associated documentation files (the // "Software"), to deal in the Software without restriction, including // without limitation the rights to use, copy, modify, merge, publish, // distribute, sublicense, and/or sell copies of the Software, and to permit // persons to whom the Software is furnished to do so, subject to the // following conditions: // // The above copyright notice and this permission notice shall be included // in all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS // OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF // MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN // NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, // DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR // OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE // USE OR OTHER DEALINGS IN THE SOFTWARE. // I hate HTTP. One way of terminating an HTTP response is to not send // a content-length header, not send a transfer-encoding: chunked header, // and simply terminate the TCP connection. That is identity // transfer-encoding. // // This test is to be sure that the https client is handling this case // correctly. if (!process.versions.openssl) { console.error('Skipping because node compiled without OpenSSL.'); process.exit(0); } var common = require('../common'); var assert = require('assert'); var tls = require('tls'); var https = require('https'); var fs = require('fs'); var options = { key: fs.readFileSync(common.fixturesDir + '/keys/agent1-key.pem'), cert: fs.readFileSync(common.fixturesDir + '/keys/agent1-cert.pem') }; var server = tls.Server(options, function(socket) { console.log('2) Server got request'); socket.write('HTTP/1.1 200 OK\r\n' + 'Date: Tue, 15 Feb 2011 22:14:54 GMT\r\n' + 'Expires: -1\r\n' + 'Cache-Control: private, max-age=0\r\n' + 'Set-Cookie: xyz\r\n' + 'Set-Cookie: abc\r\n' + 'Server: gws\r\n' + 'X-XSS-Protection: 1; mode=block\r\n' + 'Connection: close\r\n' + '\r\n'); socket.write('hello world\n'); setTimeout(function() { socket.end('hello world\n'); console.log('4) Server finished response'); }, 100); }); var gotHeaders = false; var gotEnd = false; var bodyBuffer = ''; server.listen(common.PORT, function() { console.log('1) Making Request'); var req = https.get({ port: common.PORT, rejectUnauthorized: false }, function(res) { server.close(); console.log('3) Client got response headers.'); assert.equal('gws', res.headers.server); gotHeaders = true; res.setEncoding('utf8'); res.on('data', function(s) { bodyBuffer += s; }); res.on('close', function() { console.log('5) Client got "end" event.'); gotEnd = true; }); }); }); process.on('exit', function() { assert.ok(gotHeaders); assert.ok(gotEnd); assert.equal('hello world\nhello world\n', bodyBuffer); }); node-v0.10.25~dfsg2/test/simple/test-cluster-fork-env.js0000644000000000000000000000420312270121457021605 0ustar rootroot// Copyright Joyent, Inc. and other Node contributors. // // Permission is hereby granted, free of charge, to any person obtaining a // copy of this software and associated documentation files (the // "Software"), to deal in the Software without restriction, including // without limitation the rights to use, copy, modify, merge, publish, // distribute, sublicense, and/or sell copies of the Software, and to permit // persons to whom the Software is furnished to do so, subject to the // following conditions: // // The above copyright notice and this permission notice shall be included // in all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS // OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF // MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN // NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, // DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR // OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE // USE OR OTHER DEALINGS IN THE SOFTWARE. var common = require('../common'); var assert = require('assert'); var cluster = require('cluster'); if (cluster.isWorker) { cluster.worker.send({ prop: process.env['cluster_test_prop'], overwrite: process.env['cluster_test_overwrite'] }); } else if (cluster.isMaster) { var checks = { using: false, overwrite: false }; // To check that the cluster extend on the process.env we will overwrite a // property process.env['cluster_test_overwrite'] = 'old'; // Fork worker var worker = cluster.fork({ 'cluster_test_prop': 'custom', 'cluster_test_overwrite': 'new' }); // Checks worker env worker.on('message', function(data) { checks.using = (data.prop === 'custom'); checks.overwrite = (data.overwrite === 'new'); process.exit(0); }); process.once('exit', function() { assert.ok(checks.using, 'The worker did not receive the correct env.'); assert.ok(checks.overwrite, 'The custom environment did not overwrite ' + 'the existing environment.'); }); } node-v0.10.25~dfsg2/test/simple/test-exec-max-buffer.js0000644000000000000000000000257612270121457021370 0ustar rootroot// Copyright Joyent, Inc. and other Node contributors. // // Permission is hereby granted, free of charge, to any person obtaining a // copy of this software and associated documentation files (the // "Software"), to deal in the Software without restriction, including // without limitation the rights to use, copy, modify, merge, publish, // distribute, sublicense, and/or sell copies of the Software, and to permit // persons to whom the Software is furnished to do so, subject to the // following conditions: // // The above copyright notice and this permission notice shall be included // in all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS // OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF // MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN // NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, // DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR // OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE // USE OR OTHER DEALINGS IN THE SOFTWARE. var common = require('../common'); var exec = require('child_process').exec; var assert = require('assert'); var cmd = 'echo "hello world"'; exec(cmd, { maxBuffer: 5 }, function(err, stdout, stderr) { assert.ok(err); assert.ok(/maxBuffer/.test(err.message)); }); node-v0.10.25~dfsg2/test/simple/test-http-head-request.js0000644000000000000000000000354112270121457021747 0ustar rootroot// Copyright Joyent, Inc. and other Node contributors. // // Permission is hereby granted, free of charge, to any person obtaining a // copy of this software and associated documentation files (the // "Software"), to deal in the Software without restriction, including // without limitation the rights to use, copy, modify, merge, publish, // distribute, sublicense, and/or sell copies of the Software, and to permit // persons to whom the Software is furnished to do so, subject to the // following conditions: // // The above copyright notice and this permission notice shall be included // in all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS // OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF // MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN // NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, // DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR // OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE // USE OR OTHER DEALINGS IN THE SOFTWARE. var common = require('../common'); var assert = require('assert'); var http = require('http'); var util = require('util'); var body = 'hello world\n'; var server = http.createServer(function(req, res) { common.error('req: ' + req.method); res.writeHead(200, {'Content-Length': body.length}); res.end(); server.close(); }); var gotEnd = false; server.listen(common.PORT, function() { var request = http.request({ port: common.PORT, method: 'HEAD', path: '/' }, function(response) { common.error('response start'); response.on('end', function() { common.error('response end'); gotEnd = true; }); response.resume(); }); request.end(); }); process.on('exit', function() { assert.ok(gotEnd); }); node-v0.10.25~dfsg2/test/simple/test-tcp-wrap.js0000644000000000000000000000306312270121457020137 0ustar rootroot// Copyright Joyent, Inc. and other Node contributors. // // Permission is hereby granted, free of charge, to any person obtaining a // copy of this software and associated documentation files (the // "Software"), to deal in the Software without restriction, including // without limitation the rights to use, copy, modify, merge, publish, // distribute, sublicense, and/or sell copies of the Software, and to permit // persons to whom the Software is furnished to do so, subject to the // following conditions: // // The above copyright notice and this permission notice shall be included // in all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS // OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF // MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN // NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, // DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR // OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE // USE OR OTHER DEALINGS IN THE SOFTWARE. var common = require('../common'); var assert = require('assert'); var TCP = process.binding('tcp_wrap').TCP; var handle = new TCP(); // Should be able to bind to the common.PORT var r = handle.bind('0.0.0.0', common.PORT); assert.equal(0, r); // Should not be able to bind to the same port again var r = handle.bind('0.0.0.0', common.PORT); assert.equal(-1, r); console.log(process._errno); assert.equal(process._errno, 'EINVAL'); handle.close(); node-v0.10.25~dfsg2/test/simple/test-http-url.parse-search.js0000644000000000000000000000340012270121457022530 0ustar rootroot// Copyright Joyent, Inc. and other Node contributors. // // Permission is hereby granted, free of charge, to any person obtaining a // copy of this software and associated documentation files (the // "Software"), to deal in the Software without restriction, including // without limitation the rights to use, copy, modify, merge, publish, // distribute, sublicense, and/or sell copies of the Software, and to permit // persons to whom the Software is furnished to do so, subject to the // following conditions: // // The above copyright notice and this permission notice shall be included // in all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS // OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF // MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN // NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, // DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR // OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE // USE OR OTHER DEALINGS IN THE SOFTWARE. var common = require('../common'); var assert = require('assert'); var http = require('http'); var https = require('https'); var url = require('url'); var testURL = url.parse('http://localhost:' + common.PORT + '/asdf?qwer=zxcv'); function check(request) { // a path should come over with params assert.strictEqual(request.url, '/asdf?qwer=zxcv'); } var server = http.createServer(function(request, response) { // run the check function check.call(this, request, response); response.writeHead(200, {}); response.end('ok'); server.close(); }); server.listen(common.PORT, function() { // make the request http.request(testURL).end(); }); node-v0.10.25~dfsg2/test/simple/test-path.js0000644000000000000000000003663712270121457017353 0ustar rootroot// Copyright Joyent, Inc. and other Node contributors. // // Permission is hereby granted, free of charge, to any person obtaining a // copy of this software and associated documentation files (the // "Software"), to deal in the Software without restriction, including // without limitation the rights to use, copy, modify, merge, publish, // distribute, sublicense, and/or sell copies of the Software, and to permit // persons to whom the Software is furnished to do so, subject to the // following conditions: // // The above copyright notice and this permission notice shall be included // in all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS // OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF // MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN // NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, // DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR // OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE // USE OR OTHER DEALINGS IN THE SOFTWARE. var common = require('../common'); var assert = require('assert'); var path = require('path'); var isWindows = process.platform === 'win32'; var f = __filename; assert.equal(path.basename(f), 'test-path.js'); assert.equal(path.basename(f, '.js'), 'test-path'); assert.equal(path.basename(''), ''); assert.equal(path.basename('/dir/basename.ext'), 'basename.ext'); assert.equal(path.basename('/basename.ext'), 'basename.ext'); assert.equal(path.basename('basename.ext'), 'basename.ext'); assert.equal(path.basename('basename.ext/'), 'basename.ext'); assert.equal(path.basename('basename.ext//'), 'basename.ext'); if (isWindows) { // On Windows a backslash acts as a path separator. assert.equal(path.basename('\\dir\\basename.ext'), 'basename.ext'); assert.equal(path.basename('\\basename.ext'), 'basename.ext'); assert.equal(path.basename('basename.ext'), 'basename.ext'); assert.equal(path.basename('basename.ext\\'), 'basename.ext'); assert.equal(path.basename('basename.ext\\\\'), 'basename.ext'); } else { // On unix a backslash is just treated as any other character. assert.equal(path.basename('\\dir\\basename.ext'), '\\dir\\basename.ext'); assert.equal(path.basename('\\basename.ext'), '\\basename.ext'); assert.equal(path.basename('basename.ext'), 'basename.ext'); assert.equal(path.basename('basename.ext\\'), 'basename.ext\\'); assert.equal(path.basename('basename.ext\\\\'), 'basename.ext\\\\'); } // POSIX filenames may include control characters // c.f. http://www.dwheeler.com/essays/fixing-unix-linux-filenames.html if (!isWindows) { var controlCharFilename = 'Icon' + String.fromCharCode(13); assert.equal(path.basename('/a/b/' + controlCharFilename), controlCharFilename); } assert.equal(path.extname(f), '.js'); assert.equal(path.dirname(f).substr(-11), isWindows ? 'test\\simple' : 'test/simple'); assert.equal(path.dirname('/a/b/'), '/a'); assert.equal(path.dirname('/a/b'), '/a'); assert.equal(path.dirname('/a'), '/'); assert.equal(path.dirname(''), '.'); assert.equal(path.dirname('/'), '/'); assert.equal(path.dirname('////'), '/'); if (isWindows) { assert.equal(path.dirname('c:\\'), 'c:\\'); assert.equal(path.dirname('c:\\foo'), 'c:\\'); assert.equal(path.dirname('c:\\foo\\'), 'c:\\'); assert.equal(path.dirname('c:\\foo\\bar'), 'c:\\foo'); assert.equal(path.dirname('c:\\foo\\bar\\'), 'c:\\foo'); assert.equal(path.dirname('c:\\foo\\bar\\baz'), 'c:\\foo\\bar'); assert.equal(path.dirname('\\'), '\\'); assert.equal(path.dirname('\\foo'), '\\'); assert.equal(path.dirname('\\foo\\'), '\\'); assert.equal(path.dirname('\\foo\\bar'), '\\foo'); assert.equal(path.dirname('\\foo\\bar\\'), '\\foo'); assert.equal(path.dirname('\\foo\\bar\\baz'), '\\foo\\bar'); assert.equal(path.dirname('c:'), 'c:'); assert.equal(path.dirname('c:foo'), 'c:'); assert.equal(path.dirname('c:foo\\'), 'c:'); assert.equal(path.dirname('c:foo\\bar'), 'c:foo'); assert.equal(path.dirname('c:foo\\bar\\'), 'c:foo'); assert.equal(path.dirname('c:foo\\bar\\baz'), 'c:foo\\bar'); assert.equal(path.dirname('\\\\unc\\share'), '\\\\unc\\share'); assert.equal(path.dirname('\\\\unc\\share\\foo'), '\\\\unc\\share\\'); assert.equal(path.dirname('\\\\unc\\share\\foo\\'), '\\\\unc\\share\\'); assert.equal(path.dirname('\\\\unc\\share\\foo\\bar'), '\\\\unc\\share\\foo'); assert.equal(path.dirname('\\\\unc\\share\\foo\\bar\\'), '\\\\unc\\share\\foo'); assert.equal(path.dirname('\\\\unc\\share\\foo\\bar\\baz'), '\\\\unc\\share\\foo\\bar'); } assert.equal(path.extname(''), ''); assert.equal(path.extname('/path/to/file'), ''); assert.equal(path.extname('/path/to/file.ext'), '.ext'); assert.equal(path.extname('/path.to/file.ext'), '.ext'); assert.equal(path.extname('/path.to/file'), ''); assert.equal(path.extname('/path.to/.file'), ''); assert.equal(path.extname('/path.to/.file.ext'), '.ext'); assert.equal(path.extname('/path/to/f.ext'), '.ext'); assert.equal(path.extname('/path/to/..ext'), '.ext'); assert.equal(path.extname('file'), ''); assert.equal(path.extname('file.ext'), '.ext'); assert.equal(path.extname('.file'), ''); assert.equal(path.extname('.file.ext'), '.ext'); assert.equal(path.extname('/file'), ''); assert.equal(path.extname('/file.ext'), '.ext'); assert.equal(path.extname('/.file'), ''); assert.equal(path.extname('/.file.ext'), '.ext'); assert.equal(path.extname('.path/file.ext'), '.ext'); assert.equal(path.extname('file.ext.ext'), '.ext'); assert.equal(path.extname('file.'), '.'); assert.equal(path.extname('.'), ''); assert.equal(path.extname('./'), ''); assert.equal(path.extname('.file.ext'), '.ext'); assert.equal(path.extname('.file'), ''); assert.equal(path.extname('.file.'), '.'); assert.equal(path.extname('.file..'), '.'); assert.equal(path.extname('..'), ''); assert.equal(path.extname('../'), ''); assert.equal(path.extname('..file.ext'), '.ext'); assert.equal(path.extname('..file'), '.file'); assert.equal(path.extname('..file.'), '.'); assert.equal(path.extname('..file..'), '.'); assert.equal(path.extname('...'), '.'); assert.equal(path.extname('...ext'), '.ext'); assert.equal(path.extname('....'), '.'); assert.equal(path.extname('file.ext/'), '.ext'); assert.equal(path.extname('file.ext//'), '.ext'); assert.equal(path.extname('file/'), ''); assert.equal(path.extname('file//'), ''); assert.equal(path.extname('file./'), '.'); assert.equal(path.extname('file.//'), '.'); if (isWindows) { // On windows, backspace is a path separator. assert.equal(path.extname('.\\'), ''); assert.equal(path.extname('..\\'), ''); assert.equal(path.extname('file.ext\\'), '.ext'); assert.equal(path.extname('file.ext\\\\'), '.ext'); assert.equal(path.extname('file\\'), ''); assert.equal(path.extname('file\\\\'), ''); assert.equal(path.extname('file.\\'), '.'); assert.equal(path.extname('file.\\\\'), '.'); } else { // On unix, backspace is a valid name component like any other character. assert.equal(path.extname('.\\'), ''); assert.equal(path.extname('..\\'), '.\\'); assert.equal(path.extname('file.ext\\'), '.ext\\'); assert.equal(path.extname('file.ext\\\\'), '.ext\\\\'); assert.equal(path.extname('file\\'), ''); assert.equal(path.extname('file\\\\'), ''); assert.equal(path.extname('file.\\'), '.\\'); assert.equal(path.extname('file.\\\\'), '.\\\\'); } // path.join tests var failures = []; var joinTests = // arguments result [[['.', 'x/b', '..', '/b/c.js'], 'x/b/c.js'], [['/.', 'x/b', '..', '/b/c.js'], '/x/b/c.js'], [['/foo', '../../../bar'], '/bar'], [['foo', '../../../bar'], '../../bar'], [['foo/', '../../../bar'], '../../bar'], [['foo/x', '../../../bar'], '../bar'], [['foo/x', './bar'], 'foo/x/bar'], [['foo/x/', './bar'], 'foo/x/bar'], [['foo/x/', '.', 'bar'], 'foo/x/bar'], [['./'], './'], [['.', './'], './'], [['.', '.', '.'], '.'], [['.', './', '.'], '.'], [['.', '/./', '.'], '.'], [['.', '/////./', '.'], '.'], [['.'], '.'], [['', '.'], '.'], [['', 'foo'], 'foo'], [['foo', '/bar'], 'foo/bar'], [['', '/foo'], '/foo'], [['', '', '/foo'], '/foo'], [['', '', 'foo'], 'foo'], [['foo', ''], 'foo'], [['foo/', ''], 'foo/'], [['foo', '', '/bar'], 'foo/bar'], [['./', '..', '/foo'], '../foo'], [['./', '..', '..', '/foo'], '../../foo'], [['.', '..', '..', '/foo'], '../../foo'], [['', '..', '..', '/foo'], '../../foo'], [['/'], '/'], [['/', '.'], '/'], [['/', '..'], '/'], [['/', '..', '..'], '/'], [[''], '.'], [['', ''], '.'], [[' /foo'], ' /foo'], [[' ', 'foo'], ' /foo'], [[' ', '.'], ' '], [[' ', '/'], ' /'], [[' ', ''], ' '], [['/', 'foo'], '/foo'], [['/', '/foo'], '/foo'], [['/', '//foo'], '/foo'], [['/', '', '/foo'], '/foo'], [['', '/', 'foo'], '/foo'], [['', '/', '/foo'], '/foo'] ]; // Windows-specific join tests if (isWindows) { joinTests = joinTests.concat( [// UNC path expected [['//foo/bar'], '//foo/bar/'], [['\\/foo/bar'], '//foo/bar/'], [['\\\\foo/bar'], '//foo/bar/'], // UNC path expected - server and share separate [['//foo', 'bar'], '//foo/bar/'], [['//foo/', 'bar'], '//foo/bar/'], [['//foo', '/bar'], '//foo/bar/'], // UNC path expected - questionable [['//foo', '', 'bar'], '//foo/bar/'], [['//foo/', '', 'bar'], '//foo/bar/'], [['//foo/', '', '/bar'], '//foo/bar/'], // UNC path expected - even more questionable [['', '//foo', 'bar'], '//foo/bar/'], [['', '//foo/', 'bar'], '//foo/bar/'], [['', '//foo/', '/bar'], '//foo/bar/'], // No UNC path expected (no double slash in first component) [['\\', 'foo/bar'], '/foo/bar'], [['\\', '/foo/bar'], '/foo/bar'], [['', '/', '/foo/bar'], '/foo/bar'], // No UNC path expected (no non-slashes in first component - questionable) [['//', 'foo/bar'], '/foo/bar'], [['//', '/foo/bar'], '/foo/bar'], [['\\\\', '/', '/foo/bar'], '/foo/bar'], [['//'], '/'], // No UNC path expected (share name missing - questionable). [['//foo'], '/foo'], [['//foo/'], '/foo/'], [['//foo', '/'], '/foo/'], [['//foo', '', '/'], '/foo/'], // No UNC path expected (too many leading slashes - questionable) [['///foo/bar'], '/foo/bar'], [['////foo', 'bar'], '/foo/bar'], [['\\\\\\/foo/bar'], '/foo/bar'], // Drive-relative vs drive-absolute paths. This merely describes the // status quo, rather than being obviously right [['c:'], 'c:.'], [['c:.'], 'c:.'], [['c:', ''], 'c:.'], [['', 'c:'], 'c:.'], [['c:.', '/'], 'c:./'], [['c:.', 'file'], 'c:file'], [['c:', '/'], 'c:/'], [['c:', 'file'], 'c:/file'] ]); } // Run the join tests. joinTests.forEach(function(test) { var actual = path.join.apply(path, test[0]); var expected = isWindows ? test[1].replace(/\//g, '\\') : test[1]; var message = 'path.join(' + test[0].map(JSON.stringify).join(',') + ')' + '\n expect=' + JSON.stringify(expected) + '\n actual=' + JSON.stringify(actual); if (actual !== expected) failures.push('\n' + message); // assert.equal(actual, expected, message); }); assert.equal(failures.length, 0, failures.join('')); var joinThrowTests = [true, false, 7, null, {}, undefined, [], NaN]; joinThrowTests.forEach(function(test) { assert.throws(function() { path.join(test); }, TypeError); assert.throws(function() { path.resolve(test); }, TypeError); }); // path normalize tests if (isWindows) { assert.equal(path.normalize('./fixtures///b/../b/c.js'), 'fixtures\\b\\c.js'); assert.equal(path.normalize('/foo/../../../bar'), '\\bar'); assert.equal(path.normalize('a//b//../b'), 'a\\b'); assert.equal(path.normalize('a//b//./c'), 'a\\b\\c'); assert.equal(path.normalize('a//b//.'), 'a\\b'); assert.equal(path.normalize('//server/share/dir/file.ext'), '\\\\server\\share\\dir\\file.ext'); } else { assert.equal(path.normalize('./fixtures///b/../b/c.js'), 'fixtures/b/c.js'); assert.equal(path.normalize('/foo/../../../bar'), '/bar'); assert.equal(path.normalize('a//b//../b'), 'a/b'); assert.equal(path.normalize('a//b//./c'), 'a/b/c'); assert.equal(path.normalize('a//b//.'), 'a/b'); } // path.resolve tests if (isWindows) { // windows var resolveTests = // arguments result [[['c:/blah\\blah', 'd:/games', 'c:../a'], 'c:\\blah\\a'], [['c:/ignore', 'd:\\a/b\\c/d', '\\e.exe'], 'd:\\e.exe'], [['c:/ignore', 'c:/some/file'], 'c:\\some\\file'], [['d:/ignore', 'd:some/dir//'], 'd:\\ignore\\some\\dir'], [['.'], process.cwd()], [['//server/share', '..', 'relative\\'], '\\\\server\\share\\relative'], [['c:/', '//'], 'c:\\'], [['c:/', '//dir'], 'c:\\dir'], [['c:/', '//server/share'], '\\\\server\\share\\'], [['c:/', '//server//share'], '\\\\server\\share\\'], [['c:/', '///some//dir'], 'c:\\some\\dir'] ]; } else { // Posix var resolveTests = // arguments result [[['/var/lib', '../', 'file/'], '/var/file'], [['/var/lib', '/../', 'file/'], '/file'], [['a/b/c/', '../../..'], process.cwd()], [['.'], process.cwd()], [['/some/dir', '.', '/absolute/'], '/absolute']]; } var failures = []; resolveTests.forEach(function(test) { var actual = path.resolve.apply(path, test[0]); var expected = test[1]; var message = 'path.resolve(' + test[0].map(JSON.stringify).join(',') + ')' + '\n expect=' + JSON.stringify(expected) + '\n actual=' + JSON.stringify(actual); if (actual !== expected) failures.push('\n' + message); // assert.equal(actual, expected, message); }); assert.equal(failures.length, 0, failures.join('')); // path.relative tests if (isWindows) { // windows var relativeTests = // arguments result [['c:/blah\\blah', 'd:/games', 'd:\\games'], ['c:/aaaa/bbbb', 'c:/aaaa', '..'], ['c:/aaaa/bbbb', 'c:/cccc', '..\\..\\cccc'], ['c:/aaaa/bbbb', 'c:/aaaa/bbbb', ''], ['c:/aaaa/bbbb', 'c:/aaaa/cccc', '..\\cccc'], ['c:/aaaa/', 'c:/aaaa/cccc', 'cccc'], ['c:/', 'c:\\aaaa\\bbbb', 'aaaa\\bbbb'], ['c:/aaaa/bbbb', 'd:\\', 'd:\\']]; } else { // posix var relativeTests = // arguments result [['/var/lib', '/var', '..'], ['/var/lib', '/bin', '../../bin'], ['/var/lib', '/var/lib', ''], ['/var/lib', '/var/apache', '../apache'], ['/var/', '/var/lib', 'lib'], ['/', '/var/lib', 'var/lib']]; } var failures = []; relativeTests.forEach(function(test) { var actual = path.relative(test[0], test[1]); var expected = test[2]; var message = 'path.relative(' + test.slice(0, 2).map(JSON.stringify).join(',') + ')' + '\n expect=' + JSON.stringify(expected) + '\n actual=' + JSON.stringify(actual); if (actual !== expected) failures.push('\n' + message); }); assert.equal(failures.length, 0, failures.join('')); // path.sep tests if (isWindows) { // windows assert.equal(path.sep, '\\'); } else { // posix assert.equal(path.sep, '/'); } // path.delimiter tests if (isWindows) { // windows assert.equal(path.delimiter, ';'); } else { // posix assert.equal(path.delimiter, ':'); } node-v0.10.25~dfsg2/test/simple/test-http-client-upload-buf.js0000644000000000000000000000444712270121457022700 0ustar rootroot// Copyright Joyent, Inc. and other Node contributors. // // Permission is hereby granted, free of charge, to any person obtaining a // copy of this software and associated documentation files (the // "Software"), to deal in the Software without restriction, including // without limitation the rights to use, copy, modify, merge, publish, // distribute, sublicense, and/or sell copies of the Software, and to permit // persons to whom the Software is furnished to do so, subject to the // following conditions: // // The above copyright notice and this permission notice shall be included // in all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS // OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF // MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN // NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, // DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR // OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE // USE OR OTHER DEALINGS IN THE SOFTWARE. var common = require('../common'); var assert = require('assert'); var http = require('http'); var N = 1024; var bytesReceived = 0; var server_req_complete = false; var client_res_complete = false; var server = http.createServer(function(req, res) { assert.equal('POST', req.method); req.on('data', function(chunk) { bytesReceived += chunk.length; }); req.on('end', function() { server_req_complete = true; console.log('request complete from server'); res.writeHead(200, {'Content-Type': 'text/plain'}); res.write('hello\n'); res.end(); }); }); server.listen(common.PORT); server.on('listening', function() { var req = http.request({ port: common.PORT, method: 'POST', path: '/' }, function(res) { res.setEncoding('utf8'); res.on('data', function(chunk) { console.log(chunk); }); res.on('end', function() { client_res_complete = true; server.close(); }); }); req.write(new Buffer(N)); req.end(); common.error('client finished sending request'); }); process.on('exit', function() { assert.equal(N, bytesReceived); assert.equal(true, server_req_complete); assert.equal(true, client_res_complete); }); node-v0.10.25~dfsg2/test/simple/test-exception-handler.js0000644000000000000000000000330612270121457022013 0ustar rootroot// Copyright Joyent, Inc. and other Node contributors. // // Permission is hereby granted, free of charge, to any person obtaining a // copy of this software and associated documentation files (the // "Software"), to deal in the Software without restriction, including // without limitation the rights to use, copy, modify, merge, publish, // distribute, sublicense, and/or sell copies of the Software, and to permit // persons to whom the Software is furnished to do so, subject to the // following conditions: // // The above copyright notice and this permission notice shall be included // in all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS // OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF // MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN // NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, // DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR // OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE // USE OR OTHER DEALINGS IN THE SOFTWARE. var common = require('../common'); var assert = require('assert'); var MESSAGE = 'catch me if you can'; var caughtException = false; process.on('uncaughtException', function(e) { console.log('uncaught exception! 1'); assert.equal(MESSAGE, e.message); caughtException = true; }); process.on('uncaughtException', function(e) { console.log('uncaught exception! 2'); assert.equal(MESSAGE, e.message); caughtException = true; }); setTimeout(function() { throw new Error(MESSAGE); }, 10); process.on('exit', function() { console.log('exit'); assert.equal(true, caughtException); }); node-v0.10.25~dfsg2/test/simple/test-dgram-listen-after-bind.js0000644000000000000000000000303312270121457022776 0ustar rootroot// Copyright Joyent, Inc. and other Node contributors. // // Permission is hereby granted, free of charge, to any person obtaining a // copy of this software and associated documentation files (the // "Software"), to deal in the Software without restriction, including // without limitation the rights to use, copy, modify, merge, publish, // distribute, sublicense, and/or sell copies of the Software, and to permit // persons to whom the Software is furnished to do so, subject to the // following conditions: // // The above copyright notice and this permission notice shall be included // in all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS // OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF // MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN // NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, // DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR // OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE // USE OR OTHER DEALINGS IN THE SOFTWARE. var common = require('../common'); var assert = require('assert'); var dgram = require('dgram'); var socket = dgram.createSocket('udp4'); socket.bind(); var fired = false; var timer = setTimeout(function () { socket.close(); }, 100); socket.on('listening', function () { clearTimeout(timer); fired = true; socket.close(); }); socket.on('close', function () { assert(fired, 'listening should fire after bind'); }); node-v0.10.25~dfsg2/test/simple/test-child-process-exec-cwd.js0000644000000000000000000000361512270121457022641 0ustar rootroot// Copyright Joyent, Inc. and other Node contributors. // // Permission is hereby granted, free of charge, to any person obtaining a // copy of this software and associated documentation files (the // "Software"), to deal in the Software without restriction, including // without limitation the rights to use, copy, modify, merge, publish, // distribute, sublicense, and/or sell copies of the Software, and to permit // persons to whom the Software is furnished to do so, subject to the // following conditions: // // The above copyright notice and this permission notice shall be included // in all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS // OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF // MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN // NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, // DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR // OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE // USE OR OTHER DEALINGS IN THE SOFTWARE. require('../common'); var assert = require('assert'); var exec = require('child_process').exec; var success_count = 0; var error_count = 0; var pwdcommand, dir; if (process.platform == 'win32') { pwdcommand = 'echo %cd%'; dir = 'c:\\windows'; } else { pwdcommand = 'pwd'; dir = '/dev'; } var child = exec(pwdcommand, {cwd: dir}, function(err, stdout, stderr) { if (err) { error_count++; console.log('error!: ' + err.code); console.log('stdout: ' + JSON.stringify(stdout)); console.log('stderr: ' + JSON.stringify(stderr)); assert.equal(false, err.killed); } else { success_count++; console.log(stdout); assert.ok(stdout.indexOf(dir) == 0); } }); process.on('exit', function() { assert.equal(1, success_count); assert.equal(0, error_count); }); node-v0.10.25~dfsg2/test/simple/test-stdin-pause-resume-sync.js0000644000000000000000000000262412270121457023110 0ustar rootroot// Copyright Joyent, Inc. and other Node contributors. // // Permission is hereby granted, free of charge, to any person obtaining a // copy of this software and associated documentation files (the // "Software"), to deal in the Software without restriction, including // without limitation the rights to use, copy, modify, merge, publish, // distribute, sublicense, and/or sell copies of the Software, and to permit // persons to whom the Software is furnished to do so, subject to the // following conditions: // // The above copyright notice and this permission notice shall be included // in all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS // OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF // MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN // NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, // DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR // OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE // USE OR OTHER DEALINGS IN THE SOFTWARE. console.error('before opening stdin'); process.stdin.resume(); console.error('stdin opened'); console.error('pausing stdin'); process.stdin.pause(); console.error('opening again'); process.stdin.resume(); console.error('pausing again'); process.stdin.pause(); console.error('should exit now'); node-v0.10.25~dfsg2/test/simple/test-http-contentLength0.js0000644000000000000000000000327312270121457022256 0ustar rootroot// Copyright Joyent, Inc. and other Node contributors. // // Permission is hereby granted, free of charge, to any person obtaining a // copy of this software and associated documentation files (the // "Software"), to deal in the Software without restriction, including // without limitation the rights to use, copy, modify, merge, publish, // distribute, sublicense, and/or sell copies of the Software, and to permit // persons to whom the Software is furnished to do so, subject to the // following conditions: // // The above copyright notice and this permission notice shall be included // in all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS // OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF // MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN // NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, // DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR // OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE // USE OR OTHER DEALINGS IN THE SOFTWARE. var common = require('../common'); var http = require('http'); // Simple test of Node's HTTP Client choking on a response // with a 'Content-Length: 0 ' response header. // I.E. a space character after the 'Content-Length' throws an `error` event. var s = http.createServer(function(req, res) { res.writeHead(200, {'Content-Length': '0 '}); res.end(); }); s.listen(common.PORT, function() { var request = http.request({ port: common.PORT }, function(response) { console.log('STATUS: ' + response.statusCode); s.close(); response.resume(); }); request.end(); }); node-v0.10.25~dfsg2/test/simple/test-stream2-pipe-error-handling.js0000644000000000000000000000556612270121457023635 0ustar rootroot// Copyright Joyent, Inc. and other Node contributors. // // Permission is hereby granted, free of charge, to any person obtaining a // copy of this software and associated documentation files (the // "Software"), to deal in the Software without restriction, including // without limitation the rights to use, copy, modify, merge, publish, // distribute, sublicense, and/or sell copies of the Software, and to permit // persons to whom the Software is furnished to do so, subject to the // following conditions: // // The above copyright notice and this permission notice shall be included // in all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS // OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF // MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN // NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, // DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR // OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE // USE OR OTHER DEALINGS IN THE SOFTWARE. var common = require('../common'); var assert = require('assert'); var stream = require('stream'); (function testErrorListenerCatches() { var count = 1000; var source = new stream.Readable(); source._read = function(n) { n = Math.min(count, n); count -= n; source.push(new Buffer(n)); }; var unpipedDest; source.unpipe = function(dest) { unpipedDest = dest; stream.Readable.prototype.unpipe.call(this, dest); }; var dest = new stream.Writable(); dest._write = function(chunk, encoding, cb) { cb(); }; source.pipe(dest); var gotErr = null; dest.on('error', function(err) { gotErr = err; }); var unpipedSource; dest.on('unpipe', function(src) { unpipedSource = src; }); var err = new Error('This stream turned into bacon.'); dest.emit('error', err); assert.strictEqual(gotErr, err); assert.strictEqual(unpipedSource, source); assert.strictEqual(unpipedDest, dest); })(); (function testErrorWithoutListenerThrows() { var count = 1000; var source = new stream.Readable(); source._read = function(n) { n = Math.min(count, n); count -= n; source.push(new Buffer(n)); }; var unpipedDest; source.unpipe = function(dest) { unpipedDest = dest; stream.Readable.prototype.unpipe.call(this, dest); }; var dest = new stream.Writable(); dest._write = function(chunk, encoding, cb) { cb(); }; source.pipe(dest); var unpipedSource; dest.on('unpipe', function(src) { unpipedSource = src; }); var err = new Error('This stream turned into bacon.'); var gotErr = null; try { dest.emit('error', err); } catch (e) { gotErr = e; } assert.strictEqual(gotErr, err); assert.strictEqual(unpipedSource, source); assert.strictEqual(unpipedDest, dest); })(); node-v0.10.25~dfsg2/test/simple/test-http-chunked.js0000644000000000000000000000566012270121457021005 0ustar rootroot// Copyright Joyent, Inc. and other Node contributors. // // Permission is hereby granted, free of charge, to any person obtaining a // copy of this software and associated documentation files (the // "Software"), to deal in the Software without restriction, including // without limitation the rights to use, copy, modify, merge, publish, // distribute, sublicense, and/or sell copies of the Software, and to permit // persons to whom the Software is furnished to do so, subject to the // following conditions: // // The above copyright notice and this permission notice shall be included // in all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS // OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF // MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN // NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, // DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR // OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE // USE OR OTHER DEALINGS IN THE SOFTWARE. var common = require('../common'); var assert = require('assert'); var http = require('http'); var UTF8_STRING = '南越国是前203年至前111年存在于岭南地区的一个国家,' + '国都位于番禺,疆域包括今天中国的广东、广西两省区的大部份地区,福建省、湖南、' + '贵州、云南的一小部份地区和越南的北部。南越国是秦朝灭亡后,' + '由南海郡尉赵佗于前203年起兵兼并桂林郡和象郡后建立。前196年和前179年,' + '南越国曾先后两次名义上臣属于西汉,成为西汉的“外臣”。前112年,' + '南越国末代君主赵建德与西汉发生战争,被汉武帝于前111年所灭。' + '南越国共存在93年,历经五代君主。南越国是岭南地区的第一个有记载的政权国家,' + '采用封建制和郡县制并存的制度,它的建立保证了秦末乱世岭南地区社会秩序的稳定,' + '有效的改善了岭南地区落后的政治、经济现状。'; var server = http.createServer(function(req, res) { res.writeHead(200, {'Content-Type': 'text/plain; charset=utf8'}); res.end(UTF8_STRING, 'utf8'); }); server.listen(common.PORT, function() { var data = ''; var get = http.get({ path: '/', host: 'localhost', port: common.PORT }, function(x) { x.setEncoding('utf8'); x.on('data', function(c) {data += c}); x.on('error', function(e) { throw e; }); x.on('end', function() { assert.equal('string', typeof data); console.log('here is the response:'); assert.equal(UTF8_STRING, data); console.log(data); server.close(); }); }); get.on('error', function(e) {throw e}); get.end(); }); node-v0.10.25~dfsg2/test/simple/test-http-url.parse-basic.js0000644000000000000000000000424712270121457022356 0ustar rootroot// Copyright Joyent, Inc. and other Node contributors. // // Permission is hereby granted, free of charge, to any person obtaining a // copy of this software and associated documentation files (the // "Software"), to deal in the Software without restriction, including // without limitation the rights to use, copy, modify, merge, publish, // distribute, sublicense, and/or sell copies of the Software, and to permit // persons to whom the Software is furnished to do so, subject to the // following conditions: // // The above copyright notice and this permission notice shall be included // in all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS // OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF // MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN // NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, // DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR // OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE // USE OR OTHER DEALINGS IN THE SOFTWARE. var common = require('../common'); var assert = require('assert'); var http = require('http'); var url = require('url'); var testURL = url.parse('http://localhost:' + common.PORT); // make sure the basics work function check(request) { // default method should still be get assert.strictEqual(request.method, 'GET'); // there are no URL params, so you should not see any assert.strictEqual(request.url, '/'); // the host header should use the url.parse.hostname assert.strictEqual(request.headers.host, testURL.hostname + ':' + testURL.port); } var server = http.createServer(function(request, response) { // run the check function check.call(this, request, response); response.writeHead(200, {}); response.end('ok'); server.close(); }); server.listen(common.PORT, function() { // make the request var clientRequest = http.request(testURL); // since there is a little magic with the agent // make sure that an http request uses the http.Agent assert.ok(clientRequest.agent instanceof http.Agent); clientRequest.end(); }); node-v0.10.25~dfsg2/test/simple/test-global.js0000644000000000000000000000317212270121457017643 0ustar rootroot// Copyright Joyent, Inc. and other Node contributors. // // Permission is hereby granted, free of charge, to any person obtaining a // copy of this software and associated documentation files (the // "Software"), to deal in the Software without restriction, including // without limitation the rights to use, copy, modify, merge, publish, // distribute, sublicense, and/or sell copies of the Software, and to permit // persons to whom the Software is furnished to do so, subject to the // following conditions: // // The above copyright notice and this permission notice shall be included // in all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS // OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF // MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN // NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, // DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR // OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE // USE OR OTHER DEALINGS IN THE SOFTWARE. var common = require('../common'); var assert = require('assert'); common.globalCheck = false; baseFoo = 'foo'; global.baseBar = 'bar'; assert.equal('foo', global.baseFoo, 'x -> global.x in base level not working'); assert.equal('bar', baseBar, 'global.x -> x in base level not working'); var module = require('../fixtures/global/plain'), fooBar = module.fooBar; assert.equal('foo', fooBar.foo, 'x -> global.x in sub level not working'); assert.equal('bar', fooBar.bar, 'global.x -> x in sub level not working'); node-v0.10.25~dfsg2/test/simple/test-http-upgrade-server.js0000644000000000000000000001162212270121457022312 0ustar rootroot// Copyright Joyent, Inc. and other Node contributors. // // Permission is hereby granted, free of charge, to any person obtaining a // copy of this software and associated documentation files (the // "Software"), to deal in the Software without restriction, including // without limitation the rights to use, copy, modify, merge, publish, // distribute, sublicense, and/or sell copies of the Software, and to permit // persons to whom the Software is furnished to do so, subject to the // following conditions: // // The above copyright notice and this permission notice shall be included // in all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS // OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF // MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN // NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, // DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR // OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE // USE OR OTHER DEALINGS IN THE SOFTWARE. var common = require('../common'); var assert = require('assert'); var util = require('util'); var net = require('net'); var http = require('http'); var requests_recv = 0; var requests_sent = 0; var request_upgradeHead = null; function createTestServer() { return new testServer(); } function testServer() { var server = this; http.Server.call(server, function() {}); server.on('connection', function() { requests_recv++; }); server.on('request', function(req, res) { res.writeHead(200, {'Content-Type': 'text/plain'}); res.write('okay'); res.end(); }); server.on('upgrade', function(req, socket, upgradeHead) { socket.write('HTTP/1.1 101 Web Socket Protocol Handshake\r\n' + 'Upgrade: WebSocket\r\n' + 'Connection: Upgrade\r\n' + '\r\n\r\n'); request_upgradeHead = upgradeHead; socket.ondata = function(d, start, end) { var data = d.toString('utf8', start, end); if (data == 'kill') { socket.end(); } else { socket.write(data, 'utf8'); } }; }); } util.inherits(testServer, http.Server); function writeReq(socket, data, encoding) { requests_sent++; socket.write(data); } /*----------------------------------------------- connection: Upgrade with listener -----------------------------------------------*/ function test_upgrade_with_listener(_server) { var conn = net.createConnection(common.PORT); conn.setEncoding('utf8'); var state = 0; conn.on('connect', function() { writeReq(conn, 'GET / HTTP/1.1\r\n' + 'Upgrade: WebSocket\r\n' + 'Connection: Upgrade\r\n' + '\r\n' + 'WjN}|M(6'); }); conn.on('data', function(data) { state++; assert.equal('string', typeof data); if (state == 1) { assert.equal('HTTP/1.1 101', data.substr(0, 12)); assert.equal('WjN}|M(6', request_upgradeHead.toString('utf8')); conn.write('test', 'utf8'); } else if (state == 2) { assert.equal('test', data); conn.write('kill', 'utf8'); } }); conn.on('end', function() { assert.equal(2, state); conn.end(); _server.removeAllListeners('upgrade'); test_upgrade_no_listener(); }); } /*----------------------------------------------- connection: Upgrade, no listener -----------------------------------------------*/ var test_upgrade_no_listener_ended = false; function test_upgrade_no_listener() { var conn = net.createConnection(common.PORT); conn.setEncoding('utf8'); conn.on('connect', function() { writeReq(conn, 'GET / HTTP/1.1\r\n' + 'Upgrade: WebSocket\r\n' + 'Connection: Upgrade\r\n' + '\r\n'); }); conn.on('end', function() { test_upgrade_no_listener_ended = true; conn.end(); }); conn.on('close', function() { test_standard_http(); }); } /*----------------------------------------------- connection: normal -----------------------------------------------*/ function test_standard_http() { var conn = net.createConnection(common.PORT); conn.setEncoding('utf8'); conn.on('connect', function() { writeReq(conn, 'GET / HTTP/1.1\r\n\r\n'); }); conn.on('data', function(data) { assert.equal('string', typeof data); assert.equal('HTTP/1.1 200', data.substr(0, 12)); conn.end(); }); conn.on('close', function() { server.close(); }); } var server = createTestServer(); server.listen(common.PORT, function() { // All tests get chained after this: test_upgrade_with_listener(server); }); /*----------------------------------------------- Fin. -----------------------------------------------*/ process.on('exit', function() { assert.equal(3, requests_recv); assert.equal(3, requests_sent); assert.ok(test_upgrade_no_listener_ended); }); node-v0.10.25~dfsg2/test/simple/test-http-keep-alive.js0000644000000000000000000000470212270121457021402 0ustar rootroot// Copyright Joyent, Inc. and other Node contributors. // // Permission is hereby granted, free of charge, to any person obtaining a // copy of this software and associated documentation files (the // "Software"), to deal in the Software without restriction, including // without limitation the rights to use, copy, modify, merge, publish, // distribute, sublicense, and/or sell copies of the Software, and to permit // persons to whom the Software is furnished to do so, subject to the // following conditions: // // The above copyright notice and this permission notice shall be included // in all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS // OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF // MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN // NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, // DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR // OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE // USE OR OTHER DEALINGS IN THE SOFTWARE. var common = require('../common'); var assert = require('assert'); var http = require('http'); var body = 'hello world\n'; var server = http.createServer(function(req, res) { res.writeHead(200, {'Content-Length': body.length}); res.write(body); res.end(); }); var connectCount = 0; var name = 'localhost:' + common.PORT; var agent = new http.Agent({maxSockets: 1}); var headers = {'connection': 'keep-alive'}; server.listen(common.PORT, function() { http.get({ path: '/', headers: headers, port: common.PORT, agent: agent }, function(response) { assert.equal(agent.sockets[name].length, 1); assert.equal(agent.requests[name].length, 2); response.resume(); }); http.get({ path: '/', headers: headers, port: common.PORT, agent: agent }, function(response) { assert.equal(agent.sockets[name].length, 1); assert.equal(agent.requests[name].length, 1); response.resume(); }); http.get({ path: '/', headers: headers, port: common.PORT, agent: agent }, function(response) { response.on('end', function() { assert.equal(agent.sockets[name].length, 1); assert(!agent.requests.hasOwnProperty(name)); server.close(); }); response.resume(); }); }); process.on('exit', function() { assert(!agent.sockets.hasOwnProperty(name)); assert(!agent.requests.hasOwnProperty(name)); }); node-v0.10.25~dfsg2/test/simple/test-net-pingpong.js0000644000000000000000000001030112270121457021000 0ustar rootroot// Copyright Joyent, Inc. and other Node contributors. // // Permission is hereby granted, free of charge, to any person obtaining a // copy of this software and associated documentation files (the // "Software"), to deal in the Software without restriction, including // without limitation the rights to use, copy, modify, merge, publish, // distribute, sublicense, and/or sell copies of the Software, and to permit // persons to whom the Software is furnished to do so, subject to the // following conditions: // // The above copyright notice and this permission notice shall be included // in all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS // OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF // MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN // NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, // DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR // OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE // USE OR OTHER DEALINGS IN THE SOFTWARE. var common = require('../common'); var assert = require('assert'); var net = require('net'); var tests_run = 0; function pingPongTest(port, host) { var N = 1000; var count = 0; var sentPongs = 0; var sent_final_ping = false; var server = net.createServer({ allowHalfOpen: true }, function(socket) { console.log('connection: ' + socket.remoteAddress); assert.equal(server, socket.server); assert.equal(1, server.connections); socket.setNoDelay(); socket.timeout = 0; socket.setEncoding('utf8'); socket.on('data', function(data) { // Since we never queue data (we're always waiting for the PING // before sending a pong) the writeQueueSize should always be less // than one message. assert.ok(0 <= socket.bufferSize && socket.bufferSize <= 4); console.log('server got: ' + data); assert.equal(true, socket.writable); assert.equal(true, socket.readable); assert.equal(true, count <= N); if (/PING/.exec(data)) { socket.write('PONG', function() { sentPongs++; console.error('sent PONG'); }); } }); socket.on('end', function() { console.error(socket); assert.equal(true, socket.allowHalfOpen); assert.equal(true, socket.writable); // because allowHalfOpen assert.equal(false, socket.readable); socket.end(); }); socket.on('error', function(e) { throw e; }); socket.on('close', function() { console.log('server socket.endd'); assert.equal(false, socket.writable); assert.equal(false, socket.readable); socket.server.close(); }); }); server.listen(port, host, function() { console.log('server listening on ' + port + ' ' + host); var client = net.createConnection(port, host); client.setEncoding('ascii'); client.on('connect', function() { assert.equal(true, client.readable); assert.equal(true, client.writable); client.write('PING'); }); client.on('data', function(data) { console.log('client got: ' + data); assert.equal('PONG', data); count += 1; if (sent_final_ping) { assert.equal(false, client.writable); assert.equal(true, client.readable); return; } else { assert.equal(true, client.writable); assert.equal(true, client.readable); } if (count < N) { client.write('PING'); } else { sent_final_ping = true; client.write('PING'); client.end(); } }); client.on('close', function() { console.log('client.end'); assert.equal(N + 1, count); assert.equal(N + 1, sentPongs); assert.equal(true, sent_final_ping); tests_run += 1; }); client.on('error', function(e) { throw e; }); }); } /* All are run at once, so run on different ports */ console.log(common.PIPE); pingPongTest(common.PIPE); pingPongTest(common.PORT); pingPongTest(common.PORT + 1, 'localhost'); pingPongTest(common.PORT + 2, '::1'); process.on('exit', function() { assert.equal(4, tests_run); console.log('done'); }); node-v0.10.25~dfsg2/test/simple/test-net-socket-destroy-twice.js0000644000000000000000000000275412270121457023264 0ustar rootroot// Copyright Joyent, Inc. and other Node contributors. // // Permission is hereby granted, free of charge, to any person obtaining a // copy of this software and associated documentation files (the // "Software"), to deal in the Software without restriction, including // without limitation the rights to use, copy, modify, merge, publish, // distribute, sublicense, and/or sell copies of the Software, and to permit // persons to whom the Software is furnished to do so, subject to the // following conditions: // // The above copyright notice and this permission notice shall be included // in all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS // OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF // MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN // NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, // DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR // OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE // USE OR OTHER DEALINGS IN THE SOFTWARE. var common = require('../common'); var assert = require('assert'); var net = require('net'); var nerrors = 0; var ncloses = 0; process.on('exit', function() { assert.equal(nerrors, 1); assert.equal(ncloses, 1); }); var conn = net.createConnection(common.PORT); conn.on('error', function() { nerrors++; conn.destroy(); }); conn.on('close', function() { ncloses++; }); node-v0.10.25~dfsg2/test/simple/test-memory-usage.js0000644000000000000000000000242612270121457021016 0ustar rootroot// Copyright Joyent, Inc. and other Node contributors. // // Permission is hereby granted, free of charge, to any person obtaining a // copy of this software and associated documentation files (the // "Software"), to deal in the Software without restriction, including // without limitation the rights to use, copy, modify, merge, publish, // distribute, sublicense, and/or sell copies of the Software, and to permit // persons to whom the Software is furnished to do so, subject to the // following conditions: // // The above copyright notice and this permission notice shall be included // in all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS // OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF // MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN // NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, // DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR // OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE // USE OR OTHER DEALINGS IN THE SOFTWARE. var common = require('../common'); var assert = require('assert'); var r = process.memoryUsage(); console.log(common.inspect(r)); assert.equal(true, r['rss'] > 0); node-v0.10.25~dfsg2/test/simple/test-pipe.js0000644000000000000000000000634312270121457017343 0ustar rootroot// Copyright Joyent, Inc. and other Node contributors. // // Permission is hereby granted, free of charge, to any person obtaining a // copy of this software and associated documentation files (the // "Software"), to deal in the Software without restriction, including // without limitation the rights to use, copy, modify, merge, publish, // distribute, sublicense, and/or sell copies of the Software, and to permit // persons to whom the Software is furnished to do so, subject to the // following conditions: // // The above copyright notice and this permission notice shall be included // in all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS // OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF // MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN // NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, // DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR // OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE // USE OR OTHER DEALINGS IN THE SOFTWARE. var common = require('../common'); var assert = require('assert'); var http = require('http'); var net = require('net'); var webPort = common.PORT; var tcpPort = webPort + 1; var listenCount = 0; var gotThanks = false; var tcpLengthSeen = 0; var bufferSize = 5 * 1024 * 1024; /* * 5MB of random buffer. */ var buffer = Buffer(bufferSize); for (var i = 0; i < buffer.length; i++) { buffer[i] = parseInt(Math.random() * 10000) % 256; } var web = http.Server(function(req, res) { web.close(); console.log(req.headers); var socket = net.Stream(); socket.connect(tcpPort); socket.on('connect', function() { console.log('socket connected'); }); req.pipe(socket); req.on('end', function() { res.writeHead(200); res.write('thanks'); res.end(); console.log('response with \'thanks\''); }); req.connection.on('error', function(e) { console.log('http server-side error: ' + e.message); process.exit(1); }); }); web.listen(webPort, startClient); var tcp = net.Server(function(s) { tcp.close(); console.log('tcp server connection'); var i = 0; s.on('data', function(d) { process.stdout.write('.'); tcpLengthSeen += d.length; for (var j = 0; j < d.length; j++) { assert.equal(buffer[i], d[j]); i++; } }); s.on('end', function() { console.log('tcp socket disconnect'); s.end(); }); s.on('error', function(e) { console.log('tcp server-side error: ' + e.message); process.exit(1); }); }); tcp.listen(tcpPort, startClient); function startClient() { listenCount++; if (listenCount < 2) return; console.log('Making request'); var req = http.request({ port: common.PORT, method: 'GET', path: '/', headers: { 'content-length': buffer.length } }, function(res) { console.log('Got response'); res.setEncoding('utf8'); res.on('data', function(string) { assert.equal('thanks', string); gotThanks = true; }); }); req.write(buffer); req.end(); console.error('ended request', req); } process.on('exit', function() { assert.ok(gotThanks); assert.equal(bufferSize, tcpLengthSeen); }); node-v0.10.25~dfsg2/test/addons/0000755000000000000000000000000012270121457015044 5ustar rootrootnode-v0.10.25~dfsg2/test/addons/hello-world/0000755000000000000000000000000012270121457017274 5ustar rootrootnode-v0.10.25~dfsg2/test/addons/hello-world/test.js0000644000000000000000000000025512270121457020613 0ustar rootrootvar assert = require('assert'); var binding = require('./build/Release/binding'); assert.equal('world', binding.hello()); console.log('binding.hello() =', binding.hello()); node-v0.10.25~dfsg2/test/addons/hello-world/binding.gyp0000644000000000000000000000014512270121457021427 0ustar rootroot{ 'targets': [ { 'target_name': 'binding', 'sources': [ 'binding.cc' ] } ] } node-v0.10.25~dfsg2/test/addons/hello-world/binding.cc0000644000000000000000000000043012270121457021212 0ustar rootroot#include #include using namespace v8; Handle Method(const Arguments& args) { HandleScope scope; return scope.Close(String::New("world")); } void init(Handle target) { NODE_SET_METHOD(target, "hello", Method); } NODE_MODULE(binding, init); node-v0.10.25~dfsg2/test/addons/hello-world-function-export/0000755000000000000000000000000012270121457022436 5ustar rootrootnode-v0.10.25~dfsg2/test/addons/hello-world-function-export/test.js0000644000000000000000000000024112270121457023750 0ustar rootrootvar assert = require('assert'); var binding = require('./build/Release/binding'); assert.equal('world', binding()); console.log('binding.hello() =', binding()); node-v0.10.25~dfsg2/test/addons/hello-world-function-export/binding.gyp0000644000000000000000000000014512270121457024571 0ustar rootroot{ 'targets': [ { 'target_name': 'binding', 'sources': [ 'binding.cc' ] } ] } node-v0.10.25~dfsg2/test/addons/hello-world-function-export/binding.cc0000644000000000000000000000046212270121457024361 0ustar rootroot#include #include using namespace v8; Handle Method(const Arguments& args) { HandleScope scope; return scope.Close(String::New("world")); } void init(Handle exports, Handle module) { NODE_SET_METHOD(module, "exports", Method); } NODE_MODULE(binding, init); node-v0.10.25~dfsg2/test/addons/.gitignore0000644000000000000000000000005712270121457017036 0ustar rootrootMakefile *.Makefile *.mk gyp-mac-tool /*/build node-v0.10.25~dfsg2/test/addons/at-exit/0000755000000000000000000000000012270121457016417 5ustar rootrootnode-v0.10.25~dfsg2/test/addons/at-exit/test.js0000644000000000000000000000006212270121457017732 0ustar rootrootvar binding = require('./build/Release/binding'); node-v0.10.25~dfsg2/test/addons/at-exit/binding.gyp0000644000000000000000000000014512270121457020552 0ustar rootroot{ 'targets': [ { 'target_name': 'binding', 'sources': [ 'binding.cc' ] } ] } node-v0.10.25~dfsg2/test/addons/at-exit/binding.cc0000644000000000000000000000161012270121457020336 0ustar rootroot#undef NDEBUG #include #include #include #include using node::AtExit; using v8::Handle; using v8::HandleScope; using v8::Local; using v8::Object; static char cookie[] = "yum yum"; static int at_exit_cb1_called = 0; static int at_exit_cb2_called = 0; static void at_exit_cb1(void* arg) { HandleScope scope; assert(arg == 0); Local obj = Object::New(); assert(!obj.IsEmpty()); // assert VM is still alive assert(obj->IsObject()); at_exit_cb1_called++; } static void at_exit_cb2(void* arg) { assert(arg == static_cast(cookie)); at_exit_cb2_called++; } static void sanity_check(void) { assert(at_exit_cb1_called == 1); assert(at_exit_cb2_called == 2); } void init(Handle target) { AtExit(at_exit_cb1); AtExit(at_exit_cb2, cookie); AtExit(at_exit_cb2, cookie); atexit(sanity_check); } NODE_MODULE(binding, init); node-v0.10.25~dfsg2/test/addons/async-hello-world/0000755000000000000000000000000012270121457020407 5ustar rootrootnode-v0.10.25~dfsg2/test/addons/async-hello-world/test.js0000644000000000000000000000046212270121457021726 0ustar rootrootvar assert = require('assert'); var binding = require('./build/Release/binding'); var called = false; process.on('exit', function () { assert(called); }); binding(5, function (err, val) { assert.equal(null, err); assert.equal(10, val); process.nextTick(function () { called = true; }); }); node-v0.10.25~dfsg2/test/addons/async-hello-world/binding.gyp0000644000000000000000000000014512270121457022542 0ustar rootroot{ 'targets': [ { 'target_name': 'binding', 'sources': [ 'binding.cc' ] } ] } node-v0.10.25~dfsg2/test/addons/async-hello-world/binding.cc0000644000000000000000000000254312270121457022334 0ustar rootroot#include #include #include #include using namespace v8; using namespace node; struct async_req { uv_work_t req; int input; int output; Persistent callback; }; void DoAsync (uv_work_t *r) { async_req *req = reinterpret_cast(r->data); sleep(1); // simulate CPU intensive process... req->output = req->input * 2; } void AfterAsync (uv_work_t *r) { HandleScope scope; async_req *req = reinterpret_cast(r->data); Handle argv[2] = { Null(), Integer::New(req->output) }; TryCatch try_catch; req->callback->Call(Context::GetCurrent()->Global(), 2, argv); // cleanup req->callback.Dispose(); delete req; if (try_catch.HasCaught()) { FatalException(try_catch); } } Handle Method(const Arguments& args) { HandleScope scope; async_req *req = new async_req; req->req.data = req; req->input = args[0]->IntegerValue(); req->output = 0; Local callback = Local::Cast(args[1]); req->callback = Persistent::New(callback); uv_queue_work(uv_default_loop(), &req->req, DoAsync, (uv_after_work_cb)AfterAsync); return Undefined(); } void init(Handle exports, Handle module) { NODE_SET_METHOD(module, "exports", Method); } NODE_MODULE(binding, init); node-v0.10.25~dfsg2/test/pummel/0000755000000000000000000000000012270121457015073 5ustar rootrootnode-v0.10.25~dfsg2/test/pummel/test-watch-file.js0000644000000000000000000000340312270121457020431 0ustar rootroot// Copyright Joyent, Inc. and other Node contributors. // // Permission is hereby granted, free of charge, to any person obtaining a // copy of this software and associated documentation files (the // "Software"), to deal in the Software without restriction, including // without limitation the rights to use, copy, modify, merge, publish, // distribute, sublicense, and/or sell copies of the Software, and to permit // persons to whom the Software is furnished to do so, subject to the // following conditions: // // The above copyright notice and this permission notice shall be included // in all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS // OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF // MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN // NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, // DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR // OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE // USE OR OTHER DEALINGS IN THE SOFTWARE. var common = require('../common'); var assert = require('assert'); var fs = require('fs'); var path = require('path'); var f = path.join(common.fixturesDir, 'x.txt'); var f2 = path.join(common.fixturesDir, 'x2.txt'); console.log('watching for changes of ' + f); var changes = 0; function watchFile() { fs.watchFile(f, function(curr, prev) { console.log(f + ' change'); changes++; assert.ok(curr.mtime != prev.mtime); fs.unwatchFile(f); watchFile(); fs.unwatchFile(f); }); } watchFile(); var fd = fs.openSync(f, 'w+'); fs.writeSync(fd, 'xyz\n'); fs.closeSync(fd); process.on('exit', function() { assert.ok(changes > 0); }); node-v0.10.25~dfsg2/test/pummel/test-net-connect-econnrefused.js0000644000000000000000000000412112270121457023277 0ustar rootroot// Copyright Joyent, Inc. and other Node contributors. // // Permission is hereby granted, free of charge, to any person obtaining a // copy of this software and associated documentation files (the // "Software"), to deal in the Software without restriction, including // without limitation the rights to use, copy, modify, merge, publish, // distribute, sublicense, and/or sell copies of the Software, and to permit // persons to whom the Software is furnished to do so, subject to the // following conditions: // // The above copyright notice and this permission notice shall be included // in all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS // OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF // MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN // NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, // DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR // OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE // USE OR OTHER DEALINGS IN THE SOFTWARE. // verify that connect reqs are properly cleaned up var common = require('../common'); var assert = require('assert'); var net = require('net'); var ROUNDS = 5; var ATTEMPTS_PER_ROUND = 200; var rounds = 1; var reqs = 0; pummel(); function pummel() { console.log('Round', rounds, '/', ROUNDS); for (var pending = 0; pending < ATTEMPTS_PER_ROUND; pending++) { net.createConnection(common.PORT).on('error', function(err) { assert.equal(err.code, 'ECONNREFUSED'); if (--pending > 0) return; if (rounds == ROUNDS) return check(); rounds++; pummel(); }); reqs++; } } function check() { setTimeout(function() { assert.equal(process._getActiveRequests().length, 0); assert.equal(process._getActiveHandles().length, 1); // the timer check_called = true; }, 0); } var check_called = false; process.on('exit', function() { assert.equal(rounds, ROUNDS); assert.equal(reqs, ROUNDS * ATTEMPTS_PER_ROUND); assert(check_called); }); node-v0.10.25~dfsg2/test/pummel/test-process-hrtime.js0000644000000000000000000000311412270121457021351 0ustar rootroot// Copyright Joyent, Inc. and other Node contributors. // // Permission is hereby granted, free of charge, to any person obtaining a // copy of this software and associated documentation files (the // "Software"), to deal in the Software without restriction, including // without limitation the rights to use, copy, modify, merge, publish, // distribute, sublicense, and/or sell copies of the Software, and to permit // persons to whom the Software is furnished to do so, subject to the // following conditions: // // The above copyright notice and this permission notice shall be included // in all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS // OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF // MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN // NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, // DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR // OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE // USE OR OTHER DEALINGS IN THE SOFTWARE. var common = require('../common'); var assert = require('assert'); var start = process.hrtime(); // process.hrtime() should return an Array assert(Array.isArray(start)); // busy-loop for 2 seconds var now = Date.now(); while (Date.now() - now < 2000); // get a diff reading var diff = process.hrtime(start); // should be at least 1 second, at most 2 seconds later // (the while loop will usually exit a few nanoseconds before 2) assert(diff[0] >= 1); assert(diff[0] <= 2); node-v0.10.25~dfsg2/test/pummel/test-keep-alive.js0000644000000000000000000000561012270121457020432 0ustar rootroot// Copyright Joyent, Inc. and other Node contributors. // // Permission is hereby granted, free of charge, to any person obtaining a // copy of this software and associated documentation files (the // "Software"), to deal in the Software without restriction, including // without limitation the rights to use, copy, modify, merge, publish, // distribute, sublicense, and/or sell copies of the Software, and to permit // persons to whom the Software is furnished to do so, subject to the // following conditions: // // The above copyright notice and this permission notice shall be included // in all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS // OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF // MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN // NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, // DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR // OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE // USE OR OTHER DEALINGS IN THE SOFTWARE. // This test requires the program 'ab' var common = require('../common'); var assert = require('assert'); var http = require('http'); var exec = require('child_process').exec; var body = 'hello world\n'; var server = http.createServer(function(req, res) { res.writeHead(200, { 'Content-Length': body.length, 'Content-Type': 'text/plain' }); res.write(body); res.end(); }); var keepAliveReqSec = 0; var normalReqSec = 0; function runAb(opts, callback) { var command = 'ab ' + opts + ' http://127.0.0.1:' + common.PORT + '/'; exec(command, function(err, stdout, stderr) { if (err) { if (stderr.indexOf('ab') >= 0) { console.log('ab not installed? skipping test.\n' + stderr); process.reallyExit(0); } return; } if (err) throw err; var matches = /Requests per second:\s*(\d+)\./mi.exec(stdout); var reqSec = parseInt(matches[1]); matches = /Keep-Alive requests:\s*(\d+)/mi.exec(stdout); var keepAliveRequests; if (matches) { keepAliveRequests = parseInt(matches[1]); } else { keepAliveRequests = 0; } callback(reqSec, keepAliveRequests); }); } server.listen(common.PORT, function() { runAb('-k -c 100 -t 2', function(reqSec, keepAliveRequests) { keepAliveReqSec = reqSec; assert.equal(true, keepAliveRequests > 0); console.log('keep-alive: ' + keepAliveReqSec + ' req/sec'); runAb('-c 100 -t 2', function(reqSec, keepAliveRequests) { normalReqSec = reqSec; assert.equal(0, keepAliveRequests); console.log('normal: ' + normalReqSec + ' req/sec'); server.close(); }); }); }); process.on('exit', function() { assert.equal(true, normalReqSec > 50); assert.equal(true, keepAliveReqSec > 50); assert.equal(true, normalReqSec < keepAliveReqSec); }); node-v0.10.25~dfsg2/test/pummel/test-postmortem-jsstack.js0000644000000000000000000001205112270121457022256 0ustar rootroot// Copyright Joyent, Inc. and other Node contributors. // // Permission is hereby granted, free of charge, to any person obtaining a // copy of this software and associated documentation files (the // "Software"), to deal in the Software without restriction, including // without limitation the rights to use, copy, modify, merge, publish, // distribute, sublicense, and/or sell copies of the Software, and to permit // persons to whom the Software is furnished to do so, subject to the // following conditions: // // The above copyright notice and this permission notice shall be included // in all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS // OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF // MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN // NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, // DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR // OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE // USE OR OTHER DEALINGS IN THE SOFTWARE. var common = require('../common'); var assert = require('assert'); var os = require('os'); var util = require('util'); if (os.type() != 'SunOS') { console.error('Skipping because postmortem debugging not available.'); process.exit(0); } /* * Some functions to create a recognizable stack. */ var frames = [ 'stalloogle', 'bagnoogle', 'doogle' ]; var expected; var stalloogle = function (str) { expected = str; os.loadavg(); }; var bagnoogle = function (arg0, arg1) { stalloogle(arg0 + ' is ' + arg1 + ' except that it is read-only'); }; var done = false; var doogle = function () { if (!done) setTimeout(doogle, 10); bagnoogle('The bfs command', '(almost) like ed(1)'); }; var spawn = require('child_process').spawn; var prefix = '/var/tmp/node'; var corefile = prefix + '.' + process.pid; var args = [ corefile ]; if (process.env.MDB_LIBRARY_PATH && process.env.MDB_LIBRARY_PATH != '') args = args.concat([ '-L', process.env.MDB_LIBRARY_PATH ]); /* * We're going to use DTrace to stop us, gcore us, and set us running again * when we call getloadavg() -- with the implicit assumption that our * deepest function is the only caller of os.loadavg(). */ var dtrace = spawn('dtrace', [ '-qwn', 'syscall::getloadavg:entry/pid == ' + process.pid + '/{stop(); system("gcore -o ' + prefix + ' %d", pid); system("prun %d", pid); exit(0); }' ]); var output = ''; var unlinkSync = require('fs').unlinkSync; dtrace.stderr.on('data', function (data) { console.log('dtrace: ' + data); }); dtrace.on('exit', function (code) { if (code != 0) { console.error('dtrace exited with code ' + code); process.exit(code); } done = true; /* * We have our core file. Now we need to fire up mdb to analyze it... */ var mdb = spawn('mdb', args, { stdio: 'pipe' }); mdb.on('exit', function (code) { var retained = '; core retained as ' + corefile; if (code != 0) { console.error('mdb exited with code ' + code + retained); process.exit(code); } var sentinel = ' (as '; var arg1 = ' arg1: '; var lines = output.split('\n'); var matched = 0; var straddr = undefined; for (var i = 0; i < lines.length; i++) { var line = lines[i]; if (matched == 1 && line.indexOf(arg1) === 0) { straddr = line.substr(arg1.length).split(' ')[0]; } if (line.indexOf(sentinel) == -1 || frames.length === 0) continue; var frame = line.substr(line.indexOf(sentinel) + sentinel.length); var top = frames.shift(); assert.equal(frame.indexOf(top), 0, 'unexpected frame where ' + top + ' was expected' + retained); matched++; } assert.equal(frames.length, 0, 'did not find expected frame ' + frames[0] + retained); assert.notEqual(straddr, undefined, 'did not find arg1 for top frame' + retained); /* * Now we're going to take one more swing at the core file to print out * the argument string that we found. */ output = ''; mdb = spawn('mdb', args, { stdio: 'pipe' }); mdb.on('exit', function (code) { if (code != 0) { console.error('mdb (second) exited with code ' + code + retained); process.exit(code); } assert.notEqual(output.indexOf(expected), -1, 'did not find arg1 (' + straddr + ') to contain expected string' + retained); unlinkSync(corefile); process.exit(0); }); mdb.stdout.on('data', function (data) { output += data; }); mdb.stderr.on('data', function (data) { console.log('mdb (second) stderr: ' + data); }); mdb.stdin.write('::load v8.so\n'); mdb.stdin.write(straddr + '::v8str\n'); mdb.stdin.end(); }); mdb.stdout.on('data', function (data) { output += data; }); mdb.stderr.on('data', function (data) { console.log('mdb stderr: ' + data); }); mdb.stdin.write('::load v8.so\n'); mdb.stdin.write('::jsstack -v\n'); mdb.stdin.end(); }); setTimeout(doogle, 10); node-v0.10.25~dfsg2/test/pummel/test-dtrace-jsstack.js0000644000000000000000000000611112270121457021307 0ustar rootroot// Copyright Joyent, Inc. and other Node contributors. // // Permission is hereby granted, free of charge, to any person obtaining a // copy of this software and associated documentation files (the // "Software"), to deal in the Software without restriction, including // without limitation the rights to use, copy, modify, merge, publish, // distribute, sublicense, and/or sell copies of the Software, and to permit // persons to whom the Software is furnished to do so, subject to the // following conditions: // // The above copyright notice and this permission notice shall be included // in all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS // OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF // MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN // NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, // DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR // OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE // USE OR OTHER DEALINGS IN THE SOFTWARE. var common = require('../common'); var assert = require('assert'); var os = require('os'); var util = require('util'); if (os.type() != 'SunOS') { console.error('Skipping because DTrace not available.'); process.exit(0); } /* * Some functions to create a recognizable stack. */ var frames = [ 'stalloogle', 'bagnoogle', 'doogle' ]; var expected; var stalloogle = function (str) { expected = str; os.loadavg(); }; var bagnoogle = function (arg0, arg1) { stalloogle(arg0 + ' is ' + arg1 + ' except that it is read-only'); }; var done = false; var doogle = function () { if (!done) setTimeout(doogle, 10); bagnoogle('The bfs command', '(almost) like ed(1)'); }; var spawn = require('child_process').spawn; var prefix = '/var/tmp/node'; var corefile = prefix + '.' + process.pid; /* * We're going to use DTrace to stop us, gcore us, and set us running again * when we call getloadavg() -- with the implicit assumption that our * deepest function is the only caller of os.loadavg(). */ var dtrace = spawn('dtrace', [ '-qwn', 'syscall::getloadavg:entry/pid == ' + process.pid + '/{ustack(100, 8192); exit(0); }' ]); var output = ''; dtrace.stderr.on('data', function (data) { console.log('dtrace: ' + data); }); dtrace.stdout.on('data', function (data) { output += data; }); dtrace.on('exit', function (code) { if (code != 0) { console.error('dtrace exited with code ' + code); process.exit(code); } done = true; var sentinel = '(anon) as '; var lines = output.split('\n'); for (var i = 0; i < lines.length; i++) { var line = lines[i]; if (line.indexOf(sentinel) == -1 || frames.length === 0) continue; var frame = line.substr(line.indexOf(sentinel) + sentinel.length); var top = frames.shift(); assert.equal(frame.indexOf(top), 0, 'unexpected frame where ' + top + ' was expected'); } assert.equal(frames.length, 0, 'did not find expected frame ' + frames[0]); process.exit(0); }); setTimeout(doogle, 10); node-v0.10.25~dfsg2/test/pummel/test-regress-GH-892.js0000644000000000000000000000734112270121457020701 0ustar rootroot// Copyright Joyent, Inc. and other Node contributors. // // Permission is hereby granted, free of charge, to any person obtaining a // copy of this software and associated documentation files (the // "Software"), to deal in the Software without restriction, including // without limitation the rights to use, copy, modify, merge, publish, // distribute, sublicense, and/or sell copies of the Software, and to permit // persons to whom the Software is furnished to do so, subject to the // following conditions: // // The above copyright notice and this permission notice shall be included // in all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS // OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF // MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN // NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, // DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR // OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE // USE OR OTHER DEALINGS IN THE SOFTWARE. // Uploading a big file via HTTPS causes node to drop out of the event loop. // https://github.com/joyent/node/issues/892 // In this test we set up an HTTPS in this process and launch a subprocess // to POST a 32mb file to us. A bug in the pause/resume functionality of the // TLS server causes the child process to exit cleanly before having sent // the entire buffer. var common = require('../common'); var assert = require('assert'); var spawn = require('child_process').spawn; var https = require('https'); var fs = require('fs'); var PORT = 8000; var bytesExpected = 1024 * 1024 * 32; var gotResponse = false; var started = false; var childScript = require('path').join(common.fixturesDir, 'GH-892-request.js'); function makeRequest() { if (started) return; started = true; var stderrBuffer = ''; // Pass along --trace-deprecation/--throw-deprecation in // process.execArgv to track down nextTick recursion errors // more easily. Also, this is handy when using this test to // view V8 opt/deopt behavior. var args = process.execArgv.concat([ childScript, common.PORT, bytesExpected ]); var child = spawn(process.execPath, args); child.on('exit', function(code) { assert.ok(/DONE/.test(stderrBuffer)); assert.equal(0, code); }); // The following two lines forward the stdio from the child // to parent process for debugging. child.stderr.pipe(process.stderr); child.stdout.pipe(process.stdout); // Buffer the stderr so that we can check that it got 'DONE' child.stderr.setEncoding('ascii'); child.stderr.on('data', function(d) { stderrBuffer += d; }); } var serverOptions = { key: fs.readFileSync(common.fixturesDir + '/keys/agent1-key.pem'), cert: fs.readFileSync(common.fixturesDir + '/keys/agent1-cert.pem') }; var uploadCount = 0; var server = https.Server(serverOptions, function(req, res) { // Close the server immediately. This test is only doing a single upload. // We need to make sure the server isn't keeping the event loop alive // while the upload is in progress. server.close(); req.on('data', function(d) { process.stderr.write('.'); uploadCount += d.length; }); req.on('end', function() { assert.equal(bytesExpected, uploadCount); res.writeHead(200, {'content-type': 'text/plain'}); res.end('successful upload\n'); }); }); server.listen(common.PORT, function() { console.log('expecting %d bytes', bytesExpected); makeRequest(); }); process.on('exit', function() { console.error('got %d bytes', uploadCount); assert.equal(uploadCount, bytesExpected); }); node-v0.10.25~dfsg2/test/pummel/test-net-pingpong-delay.js0000644000000000000000000000653412270121457022117 0ustar rootroot// Copyright Joyent, Inc. and other Node contributors. // // Permission is hereby granted, free of charge, to any person obtaining a // copy of this software and associated documentation files (the // "Software"), to deal in the Software without restriction, including // without limitation the rights to use, copy, modify, merge, publish, // distribute, sublicense, and/or sell copies of the Software, and to permit // persons to whom the Software is furnished to do so, subject to the // following conditions: // // The above copyright notice and this permission notice shall be included // in all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS // OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF // MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN // NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, // DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR // OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE // USE OR OTHER DEALINGS IN THE SOFTWARE. var common = require('../common'); var assert = require('assert'); var net = require('net'); var tests_run = 0; function pingPongTest(port, host, on_complete) { var N = 100; var DELAY = 1; var count = 0; var client_ended = false; var server = net.createServer({ allowHalfOpen: true }, function(socket) { socket.setEncoding('utf8'); socket.on('data', function(data) { console.log(data); assert.equal('PING', data); assert.equal('open', socket.readyState); assert.equal(true, count <= N); setTimeout(function() { assert.equal('open', socket.readyState); socket.write('PONG'); }, DELAY); }); socket.on('timeout', function() { common.debug('server-side timeout!!'); assert.equal(false, true); }); socket.on('end', function() { console.log('server-side socket EOF'); assert.equal('writeOnly', socket.readyState); socket.end(); }); socket.on('close', function(had_error) { console.log('server-side socket.end'); assert.equal(false, had_error); assert.equal('closed', socket.readyState); socket.server.close(); }); }); server.listen(port, host, function() { var client = net.createConnection(port, host); client.setEncoding('utf8'); client.on('connect', function() { assert.equal('open', client.readyState); client.write('PING'); }); client.on('data', function(data) { console.log(data); assert.equal('PONG', data); assert.equal('open', client.readyState); setTimeout(function() { assert.equal('open', client.readyState); if (count++ < N) { client.write('PING'); } else { console.log('closing client'); client.end(); client_ended = true; } }, DELAY); }); client.on('timeout', function() { common.debug('client-side timeout!!'); assert.equal(false, true); }); client.on('close', function() { console.log('client.end'); assert.equal(N + 1, count); assert.ok(client_ended); if (on_complete) on_complete(); tests_run += 1; }); }); } pingPongTest(common.PORT); process.on('exit', function() { assert.equal(1, tests_run); }); node-v0.10.25~dfsg2/test/pummel/test-net-timeout.js0000644000000000000000000000620012270121457020656 0ustar rootroot// Copyright Joyent, Inc. and other Node contributors. // // Permission is hereby granted, free of charge, to any person obtaining a // copy of this software and associated documentation files (the // "Software"), to deal in the Software without restriction, including // without limitation the rights to use, copy, modify, merge, publish, // distribute, sublicense, and/or sell copies of the Software, and to permit // persons to whom the Software is furnished to do so, subject to the // following conditions: // // The above copyright notice and this permission notice shall be included // in all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS // OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF // MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN // NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, // DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR // OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE // USE OR OTHER DEALINGS IN THE SOFTWARE. var common = require('../common'); var assert = require('assert'); var net = require('net'); var exchanges = 0; var starttime = null; var timeouttime = null; var timeout = 1000; var echo_server = net.createServer(function(socket) { socket.setTimeout(timeout); socket.on('timeout', function() { console.log('server timeout'); timeouttime = new Date; console.dir(timeouttime); socket.destroy(); }); socket.on('error', function(e) { throw new Error('Server side socket should not get error. ' + 'We disconnect willingly.'); }); socket.on('data', function(d) { console.log(d); socket.write(d); }); socket.on('end', function() { socket.end(); }); }); echo_server.listen(common.PORT, function() { console.log('server listening at ' + common.PORT); var client = net.createConnection(common.PORT); client.setEncoding('UTF8'); client.setTimeout(0); // disable the timeout for client client.on('connect', function() { console.log('client connected.'); client.write('hello\r\n'); }); client.on('data', function(chunk) { assert.equal('hello\r\n', chunk); if (exchanges++ < 5) { setTimeout(function() { console.log('client write "hello"'); client.write('hello\r\n'); }, 500); if (exchanges == 5) { console.log('wait for timeout - should come in ' + timeout + ' ms'); starttime = new Date; console.dir(starttime); } } }); client.on('timeout', function() { throw new Error("client timeout - this shouldn't happen"); }); client.on('end', function() { console.log('client end'); client.end(); }); client.on('close', function() { console.log('client disconnect'); echo_server.close(); }); }); process.on('exit', function() { assert.ok(starttime != null); assert.ok(timeouttime != null); diff = timeouttime - starttime; console.log('diff = ' + diff); assert.ok(timeout < diff); // Allow for 800 milliseconds more assert.ok(diff < timeout + 800); }); node-v0.10.25~dfsg2/test/pummel/test-crypto-dh.js0000644000000000000000000000504512270121457020323 0ustar rootroot// Copyright Joyent, Inc. and other Node contributors. // // Permission is hereby granted, free of charge, to any person obtaining a // copy of this software and associated documentation files (the // "Software"), to deal in the Software without restriction, including // without limitation the rights to use, copy, modify, merge, publish, // distribute, sublicense, and/or sell copies of the Software, and to permit // persons to whom the Software is furnished to do so, subject to the // following conditions: // // The above copyright notice and this permission notice shall be included // in all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS // OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF // MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN // NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, // DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR // OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE // USE OR OTHER DEALINGS IN THE SOFTWARE. var common = require('../common'); var assert = require('assert'); try { var crypto = require('crypto'); } catch (e) { console.log('Not compiled with OPENSSL support.'); process.exit(); } assert.throws(function() { crypto.getDiffieHellman('unknown-group'); }); assert.throws(function() { crypto.getDiffieHellman('modp1').setPrivateKey(''); }); assert.throws(function() { crypto.getDiffieHellman('modp1').setPublicKey(''); }); var hashes = { modp1 : "b4b330a6ffeacfbd861e7fe2135b4431", modp2 : "7c3c5cad8b9f378d88f1dd64a4b6413a", modp5 : "b1d2acc22c542e08669a5c5ae812694d", modp14 : "8d041538cecc1a7d915ba4b718f8ad20", modp15 : "dc3b93def24e078c4fbf92d5e14ba69b", modp16 : "a273487f46f699461f613b3878d9dfd9", modp17 : "dc76e09935310348c492de9bd82014d0", modp18 : "db08973bfd2371758a69db180871c993" } for (var name in hashes) { var group = crypto.getDiffieHellman(name); var private_key = group.getPrime('hex'); var hash1 = hashes[name]; var hash2 = crypto.createHash('md5').update(private_key.toUpperCase()).digest('hex'); assert.equal(hash1, hash2); assert.equal(group.getGenerator('hex'), '02'); } for (var name in hashes) { var group1 = crypto.getDiffieHellman(name); var group2 = crypto.getDiffieHellman(name); group1.generateKeys(); group2.generateKeys(); var key1 = group1.computeSecret(group2.getPublicKey()); var key2 = group2.computeSecret(group1.getPublicKey()); assert.deepEqual(key1, key2); } node-v0.10.25~dfsg2/test/pummel/test-net-throttle.js0000644000000000000000000000502112270121457021035 0ustar rootroot// Copyright Joyent, Inc. and other Node contributors. // // Permission is hereby granted, free of charge, to any person obtaining a // copy of this software and associated documentation files (the // "Software"), to deal in the Software without restriction, including // without limitation the rights to use, copy, modify, merge, publish, // distribute, sublicense, and/or sell copies of the Software, and to permit // persons to whom the Software is furnished to do so, subject to the // following conditions: // // The above copyright notice and this permission notice shall be included // in all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS // OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF // MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN // NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, // DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR // OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE // USE OR OTHER DEALINGS IN THE SOFTWARE. var common = require('../common'); var assert = require('assert'); var net = require('net'); var N = 1024 * 1024; var part_N = N / 3; var chars_recved = 0; var npauses = 0; console.log('build big string'); var body = ''; for (var i = 0; i < N; i++) { body += 'C'; } console.log('start server on port ' + common.PORT); var server = net.createServer(function(connection) { connection.write(body.slice(0, part_N)); connection.write(body.slice(part_N, 2 * part_N)); assert.equal(false, connection.write(body.slice(2 * part_N, N))); console.log('bufferSize: ' + connection.bufferSize); assert.ok(0 <= connection.bufferSize && connection.bufferSize <= N); connection.end(); }); server.listen(common.PORT, function() { var paused = false; var client = net.createConnection(common.PORT); client.setEncoding('ascii'); client.on('data', function(d) { chars_recved += d.length; console.log('got ' + chars_recved); if (!paused) { client.pause(); npauses += 1; paused = true; console.log('pause'); var x = chars_recved; setTimeout(function() { assert.equal(chars_recved, x); client.resume(); console.log('resume'); paused = false; }, 100); } }); client.on('end', function() { server.close(); client.end(); }); }); process.on('exit', function() { assert.equal(N, chars_recved); assert.equal(true, npauses > 2); }); node-v0.10.25~dfsg2/test/pummel/test-buffer-big.js0000644000000000000000000000303212270121457020414 0ustar rootroot// Copyright Joyent, Inc. and other Node contributors. // // Permission is hereby granted, free of charge, to any person obtaining a // copy of this software and associated documentation files (the // "Software"), to deal in the Software without restriction, including // without limitation the rights to use, copy, modify, merge, publish, // distribute, sublicense, and/or sell copies of the Software, and to permit // persons to whom the Software is furnished to do so, subject to the // following conditions: // // The above copyright notice and this permission notice shall be included // in all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS // OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF // MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN // NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, // DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR // OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE // USE OR OTHER DEALINGS IN THE SOFTWARE. var common = require('../common'); var assert = require('assert'); // The tests below should throw an error, not abort the process... assert.throws(function() { new Buffer(0x3fffffff + 1) }, RangeError); assert.throws(function() { new Int8Array(0x3fffffff + 1) }, RangeError); assert.throws(function() { new ArrayBuffer(0x3fffffff + 1) }, RangeError); assert.throws(function() { new Float64Array(0x7ffffff + 1) }, RangeError); node-v0.10.25~dfsg2/test/pummel/test-net-write-callbacks.js0000644000000000000000000000421112270121457022237 0ustar rootroot// Copyright Joyent, Inc. and other Node contributors. // // Permission is hereby granted, free of charge, to any person obtaining a // copy of this software and associated documentation files (the // "Software"), to deal in the Software without restriction, including // without limitation the rights to use, copy, modify, merge, publish, // distribute, sublicense, and/or sell copies of the Software, and to permit // persons to whom the Software is furnished to do so, subject to the // following conditions: // // The above copyright notice and this permission notice shall be included // in all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS // OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF // MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN // NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, // DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR // OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE // USE OR OTHER DEALINGS IN THE SOFTWARE. var common = require('../common'); var net = require('net'); var assert = require('assert'); var cbcount = 0; var N = 500000; var server = net.Server(function(socket) { socket.on('data', function(d) { console.error('got %d bytes', d.length); }); socket.on('end', function() { console.error('end'); socket.destroy(); server.close(); }); }); var lastCalled = -1; function makeCallback(c) { var called = false; return function() { if (called) throw new Error('called callback #' + c + ' more than once'); called = true; if (c < lastCalled) throw new Error('callbacks out of order. last=' + lastCalled + ' current=' + c); lastCalled = c; cbcount++; }; } server.listen(common.PORT, function() { var client = net.createConnection(common.PORT); client.on('connect', function() { for (var i = 0; i < N; i++) { client.write('hello world', makeCallback(i)); } client.end(); }); }); process.on('exit', function() { assert.equal(N, cbcount); }); node-v0.10.25~dfsg2/test/pummel/test-next-tick-loops-quick.js0000644000000000000000000000323212270121457022560 0ustar rootroot// Copyright Joyent, Inc. and other Node contributors. // // Permission is hereby granted, free of charge, to any person obtaining a // copy of this software and associated documentation files (the // "Software"), to deal in the Software without restriction, including // without limitation the rights to use, copy, modify, merge, publish, // distribute, sublicense, and/or sell copies of the Software, and to permit // persons to whom the Software is furnished to do so, subject to the // following conditions: // // The above copyright notice and this permission notice shall be included // in all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS // OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF // MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN // NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, // DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR // OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE // USE OR OTHER DEALINGS IN THE SOFTWARE. var common = require('../common'); var assert = require('assert'); // Regression test GH-511: https://github.com/joyent/node/issues/issue/511 // Make sure nextTick loops quickly setTimeout(function() { t = Date.now() - t; STOP = 1; console.log(['ctr: ', ctr, ', t:', t, 'ms -> ', (ctr / t).toFixed(2), 'KHz'] .join('')); assert.ok(ctr > 1000); }, 2000); var ctr = 0; var STOP = 0; var t = Date.now() + 2; while (t > Date.now()); //get in sync with clock (function foo() { if (STOP) return; process.nextTick(foo); ctr++; })(); node-v0.10.25~dfsg2/test/pummel/test-tls-throttle.js0000644000000000000000000000502512270121457021055 0ustar rootroot// Copyright Joyent, Inc. and other Node contributors. // // Permission is hereby granted, free of charge, to any person obtaining a // copy of this software and associated documentation files (the // "Software"), to deal in the Software without restriction, including // without limitation the rights to use, copy, modify, merge, publish, // distribute, sublicense, and/or sell copies of the Software, and to permit // persons to whom the Software is furnished to do so, subject to the // following conditions: // // The above copyright notice and this permission notice shall be included // in all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS // OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF // MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN // NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, // DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR // OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE // USE OR OTHER DEALINGS IN THE SOFTWARE. // Server sends a large string. Client counts bytes and pauses every few // seconds. Makes sure that pause and resume work properly. var common = require('../common'); var assert = require('assert'); var tls = require('tls'); var fs = require('fs'); var body = ''; process.stdout.write('build body...'); for (var i = 0; i < 1024 * 1024; i++) { body += 'hello world\n'; } process.stdout.write('done\n'); var options = { key: fs.readFileSync(common.fixturesDir + '/keys/agent2-key.pem'), cert: fs.readFileSync(common.fixturesDir + '/keys/agent2-cert.pem') }; var connections = 0; var server = tls.Server(options, function(socket) { socket.end(body); connections++; }); var recvCount = 0; server.listen(common.PORT, function() { var client = tls.connect({ port: common.PORT, rejectUnauthorized: false }); client.on('data', function(d) { process.stdout.write('.'); recvCount += d.length; client.pause(); process.nextTick(function() { client.resume(); }); }); client.on('close', function() { console.error('close'); server.close(); clearTimeout(timeout); }); }); function displayCounts() { console.log('body.length: %d', body.length); console.log(' recvCount: %d', recvCount); } var timeout = setTimeout(displayCounts, 10 * 1000); process.on('exit', function() { displayCounts(); assert.equal(1, connections); assert.equal(body.length, recvCount); }); node-v0.10.25~dfsg2/test/pummel/test-dh-regr.js0000644000000000000000000000305512270121457017741 0ustar rootroot// Copyright Joyent, Inc. and other Node contributors. // // Permission is hereby granted, free of charge, to any person obtaining a // copy of this software and associated documentation files (the // "Software"), to deal in the Software without restriction, including // without limitation the rights to use, copy, modify, merge, publish, // distribute, sublicense, and/or sell copies of the Software, and to permit // persons to whom the Software is furnished to do so, subject to the // following conditions: // // The above copyright notice and this permission notice shall be included // in all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS // OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF // MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN // NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, // DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR // OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE // USE OR OTHER DEALINGS IN THE SOFTWARE. var common = require('../common'); var assert = require('assert'); var crypto = require('crypto'); var p = crypto.createDiffieHellman(256).getPrime(); for (var i = 0; i < 2000; i++) { var a = crypto.createDiffieHellman(p), b = crypto.createDiffieHellman(p); a.generateKeys(); b.generateKeys(); assert.deepEqual( a.computeSecret(b.getPublicKey()), b.computeSecret(a.getPublicKey()), 'secrets should be equal!' ); } node-v0.10.25~dfsg2/test/pummel/test-net-timeout2.js0000644000000000000000000000376712270121457020757 0ustar rootroot// Copyright Joyent, Inc. and other Node contributors. // // Permission is hereby granted, free of charge, to any person obtaining a // copy of this software and associated documentation files (the // "Software"), to deal in the Software without restriction, including // without limitation the rights to use, copy, modify, merge, publish, // distribute, sublicense, and/or sell copies of the Software, and to permit // persons to whom the Software is furnished to do so, subject to the // following conditions: // // The above copyright notice and this permission notice shall be included // in all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS // OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF // MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN // NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, // DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR // OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE // USE OR OTHER DEALINGS IN THE SOFTWARE. // socket.write was not resetting the timeout timer. See // https://github.com/joyent/node/issues/2002 var common = require('../common'); var assert = require('assert'); var net = require('net'); var seconds = 5; var gotTimeout = false; var counter = 0; var server = net.createServer(function(socket) { socket.setTimeout((seconds / 2) * 1000, function() { gotTimeout = true; console.log('timeout!!'); socket.destroy(); process.exit(1); }); var interval = setInterval(function() { counter++; if (counter == seconds) { clearInterval(interval); server.close(); socket.destroy(); } if (socket.writable) { socket.write(Date.now() + '\n'); } }, 1000); }); server.listen(common.PORT, function() { var s = net.connect(common.PORT); s.pipe(process.stdout); }); process.on('exit', function() { assert.equal(false, gotTimeout); }); node-v0.10.25~dfsg2/test/pummel/test-http-upload-timeout.js0000644000000000000000000000452312270121457022337 0ustar rootroot// Copyright Joyent, Inc. and other Node contributors. // // Permission is hereby granted, free of charge, to any person obtaining a // copy of this software and associated documentation files (the // "Software"), to deal in the Software without restriction, including // without limitation the rights to use, copy, modify, merge, publish, // distribute, sublicense, and/or sell copies of the Software, and to permit // persons to whom the Software is furnished to do so, subject to the // following conditions: // // The above copyright notice and this permission notice shall be included // in all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS // OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF // MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN // NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, // DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR // OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE // USE OR OTHER DEALINGS IN THE SOFTWARE. // This tests setTimeout() by having multiple clients connecting and sending // data in random intervals. Clients are also randomly disconnecting until there // are no more clients left. If no false timeout occurs, this test has passed. var common = require('../common'), assert = require('assert'), http = require('http'), server = http.createServer(), connections = 0; server.on('request', function(req, res) { req.socket.setTimeout(1000); req.socket.on('timeout', function() { throw new Error('Unexpected timeout'); }); req.on('end', function() { connections--; res.writeHead(200); res.end('done\n'); if (connections == 0) { server.close(); } }); req.resume(); }); server.listen(common.PORT, '127.0.0.1', function() { for (var i = 0; i < 10; i++) { connections++; setTimeout(function() { var request = http.request({ port: common.PORT, method: 'POST', path: '/' }); function ping() { var nextPing = (Math.random() * 900).toFixed(); if (nextPing > 600) { request.end(); return; } request.write('ping'); setTimeout(ping, nextPing); } ping(); }, i * 50); } }); node-v0.10.25~dfsg2/test/pummel/test-tls-connect-memleak.js0000644000000000000000000000410612270121457022251 0ustar rootroot// Copyright Joyent, Inc. and other Node contributors. // // Permission is hereby granted, free of charge, to any person obtaining a // copy of this software and associated documentation files (the // "Software"), to deal in the Software without restriction, including // without limitation the rights to use, copy, modify, merge, publish, // distribute, sublicense, and/or sell copies of the Software, and to permit // persons to whom the Software is furnished to do so, subject to the // following conditions: // // The above copyright notice and this permission notice shall be included // in all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS // OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF // MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN // NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, // DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR // OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE // USE OR OTHER DEALINGS IN THE SOFTWARE. // Flags: --expose-gc var common = require('../common'); var assert = require('assert'); var tls = require('tls'); var fs = require('fs'); assert(typeof gc === 'function', 'Run this test with --expose-gc'); tls.createServer({ cert: fs.readFileSync(common.fixturesDir + '/test_cert.pem'), key: fs.readFileSync(common.fixturesDir + '/test_key.pem') }).listen(common.PORT); (function() { // 2**26 == 64M entries for (var i = 0, junk = [0]; i < 26; ++i) junk = junk.concat(junk); var options = { rejectUnauthorized: false }; tls.connect(common.PORT, '127.0.0.1', options, function() { assert(junk.length != 0); // keep reference alive setTimeout(done, 10); gc(); }); })(); function done() { var before = process.memoryUsage().rss; gc(); var after = process.memoryUsage().rss; var reclaimed = (before - after) / 1024; console.log('%d kB reclaimed', reclaimed); assert(reclaimed > 256 * 1024); // it's more like 512M on x64 process.exit(); } node-v0.10.25~dfsg2/test/pummel/test-timer-wrap2.js0000644000000000000000000000251212270121457020557 0ustar rootroot// Copyright Joyent, Inc. and other Node contributors. // // Permission is hereby granted, free of charge, to any person obtaining a // copy of this software and associated documentation files (the // "Software"), to deal in the Software without restriction, including // without limitation the rights to use, copy, modify, merge, publish, // distribute, sublicense, and/or sell copies of the Software, and to permit // persons to whom the Software is furnished to do so, subject to the // following conditions: // // The above copyright notice and this permission notice shall be included // in all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS // OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF // MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN // NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, // DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR // OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE // USE OR OTHER DEALINGS IN THE SOFTWARE. var common = require('../common'); var assert = require('assert'); // Test that allocating a timer does not increase the loop's reference // count. var Timer = process.binding('timer_wrap').Timer; var t = new Timer(); node-v0.10.25~dfsg2/test/pummel/test-fs-largefile.js0000644000000000000000000000407612270121457020755 0ustar rootroot// Copyright Joyent, Inc. and other Node contributors. // // Permission is hereby granted, free of charge, to any person obtaining a // copy of this software and associated documentation files (the // "Software"), to deal in the Software without restriction, including // without limitation the rights to use, copy, modify, merge, publish, // distribute, sublicense, and/or sell copies of the Software, and to permit // persons to whom the Software is furnished to do so, subject to the // following conditions: // // The above copyright notice and this permission notice shall be included // in all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS // OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF // MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN // NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, // DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR // OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE // USE OR OTHER DEALINGS IN THE SOFTWARE. var common = require('../common'); var assert = require('assert'); var path = require('path'), fs = require('fs'), filepath = path.join(common.tmpDir, 'large.txt'), fd = fs.openSync(filepath, 'w+'), offset = 5 * 1024 * 1024 * 1024, // 5GB message = 'Large File'; fs.truncateSync(fd, offset); assert.equal(fs.statSync(filepath).size, offset); var writeBuf = new Buffer(message); fs.writeSync(fd, writeBuf, 0, writeBuf.length, offset); var readBuf = new Buffer(writeBuf.length); fs.readSync(fd, readBuf, 0, readBuf.length, offset); assert.equal(readBuf.toString(), message); fs.readSync(fd, readBuf, 0, 1, 0); assert.equal(readBuf[0], 0); var exceptionRaised = false; try { fs.writeSync(fd, writeBuf, 0, writeBuf.length, 42.000001); } catch (err) { console.log(err); exceptionRaised = true; assert.equal(err.message, 'Not an integer'); } assert.ok(exceptionRaised); fs.close(fd); process.on('exit', function() { fs.unlinkSync(filepath); }); node-v0.10.25~dfsg2/test/pummel/test-timers.js0000644000000000000000000000677312270121457017726 0ustar rootroot// Copyright Joyent, Inc. and other Node contributors. // // Permission is hereby granted, free of charge, to any person obtaining a // copy of this software and associated documentation files (the // "Software"), to deal in the Software without restriction, including // without limitation the rights to use, copy, modify, merge, publish, // distribute, sublicense, and/or sell copies of the Software, and to permit // persons to whom the Software is furnished to do so, subject to the // following conditions: // // The above copyright notice and this permission notice shall be included // in all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS // OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF // MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN // NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, // DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR // OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE // USE OR OTHER DEALINGS IN THE SOFTWARE. var common = require('../common'); var assert = require('assert'); var WINDOW = 200; // why is does this need to be so big? var interval_count = 0; var setTimeout_called = false; // check that these don't blow up. clearTimeout(null); clearInterval(null); assert.equal(true, setTimeout instanceof Function); var starttime = new Date; setTimeout(function() { var endtime = new Date; var diff = endtime - starttime; assert.ok(diff > 0); console.error('diff: ' + diff); assert.equal(true, 1000 - WINDOW < diff && diff < 1000 + WINDOW); setTimeout_called = true; }, 1000); // this timer shouldn't execute var id = setTimeout(function() { assert.equal(true, false); }, 500); clearTimeout(id); setInterval(function() { interval_count += 1; var endtime = new Date; var diff = endtime - starttime; assert.ok(diff > 0); console.error('diff: ' + diff); var t = interval_count * 1000; assert.equal(true, t - WINDOW < diff && diff < t + WINDOW); assert.equal(true, interval_count <= 3); if (interval_count == 3) clearInterval(this); }, 1000); // Single param: setTimeout(function(param) { assert.equal('test param', param); }, 1000, 'test param'); var interval_count2 = 0; setInterval(function(param) { ++interval_count2; assert.equal('test param', param); if (interval_count2 == 3) clearInterval(this); }, 1000, 'test param'); // Multiple param setTimeout(function(param1, param2) { assert.equal('param1', param1); assert.equal('param2', param2); }, 1000, 'param1', 'param2'); var interval_count3 = 0; setInterval(function(param1, param2) { ++interval_count3; assert.equal('param1', param1); assert.equal('param2', param2); if (interval_count3 == 3) clearInterval(this); }, 1000, 'param1', 'param2'); // setInterval(cb, 0) should be called multiple times. var count4 = 0; var interval4 = setInterval(function() { if (++count4 > 10) clearInterval(interval4); }, 0); // we should be able to clearTimeout multiple times without breakage. var expectedTimeouts = 3; function t() { expectedTimeouts--; } var w = setTimeout(t, 200); var x = setTimeout(t, 200); var y = setTimeout(t, 200); clearTimeout(y); var z = setTimeout(t, 200); clearTimeout(y); process.on('exit', function() { assert.equal(true, setTimeout_called); assert.equal(3, interval_count); assert.equal(11, count4); assert.equal(0, expectedTimeouts, 'clearTimeout cleared too many timeouts'); }); node-v0.10.25~dfsg2/test/pummel/test-net-connect-memleak.js0000644000000000000000000000363712270121457022245 0ustar rootroot// Copyright Joyent, Inc. and other Node contributors. // // Permission is hereby granted, free of charge, to any person obtaining a // copy of this software and associated documentation files (the // "Software"), to deal in the Software without restriction, including // without limitation the rights to use, copy, modify, merge, publish, // distribute, sublicense, and/or sell copies of the Software, and to permit // persons to whom the Software is furnished to do so, subject to the // following conditions: // // The above copyright notice and this permission notice shall be included // in all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS // OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF // MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN // NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, // DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR // OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE // USE OR OTHER DEALINGS IN THE SOFTWARE. // Flags: --expose-gc var common = require('../common'); var assert = require('assert'); var net = require('net'); assert(typeof gc === 'function', 'Run this test with --expose-gc'); net.createServer(function() {}).listen(common.PORT); var before = 0; (function() { // 2**26 == 64M entries gc(); for (var i = 0, junk = [0]; i < 26; ++i) junk = junk.concat(junk); before = process.memoryUsage().rss; net.createConnection(common.PORT, '127.0.0.1', function() { assert(junk.length != 0); // keep reference alive setTimeout(done, 10); gc(); }); })(); function done() { gc(); var after = process.memoryUsage().rss; var reclaimed = (before - after) / 1024; console.log('%d kB reclaimed', reclaimed); assert(reclaimed > 128 * 1024); // It's around 256 MB on x64. process.exit(); } node-v0.10.25~dfsg2/test/pummel/test-exec.js0000644000000000000000000000754712270121457017347 0ustar rootroot// Copyright Joyent, Inc. and other Node contributors. // // Permission is hereby granted, free of charge, to any person obtaining a // copy of this software and associated documentation files (the // "Software"), to deal in the Software without restriction, including // without limitation the rights to use, copy, modify, merge, publish, // distribute, sublicense, and/or sell copies of the Software, and to permit // persons to whom the Software is furnished to do so, subject to the // following conditions: // // The above copyright notice and this permission notice shall be included // in all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS // OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF // MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN // NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, // DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR // OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE // USE OR OTHER DEALINGS IN THE SOFTWARE. var common = require('../common'); var assert = require('assert'); var exec = require('child_process').exec; if (process.platform !== 'win32') { // Unix. var SLEEP3_COMMAND = "sleep 3"; } else { // Windows: `choice` is a command built into cmd.exe. Use another cmd process // to create a process tree, so we can catch bugs related to it. var SLEEP3_COMMAND = "cmd /c choice /t 3 /c X /d X"; } var success_count = 0; var error_count = 0; exec(process.execPath + ' -p -e process.versions', function(err, stdout, stderr) { if (err) { error_count++; console.log('error!: ' + err.code); console.log('stdout: ' + JSON.stringify(stdout)); console.log('stderr: ' + JSON.stringify(stderr)); assert.equal(false, err.killed); } else { success_count++; console.dir(stdout); } }); exec('thisisnotavalidcommand', function(err, stdout, stderr) { if (err) { error_count++; assert.equal('', stdout); assert.equal(true, err.code != 0); assert.equal(false, err.killed); assert.strictEqual(null, err.signal); console.log('error code: ' + err.code); console.log('stdout: ' + JSON.stringify(stdout)); console.log('stderr: ' + JSON.stringify(stderr)); } else { success_count++; console.dir(stdout); assert.equal(true, stdout != ''); } }); var sleeperStart = new Date(); exec(SLEEP3_COMMAND, { timeout: 50 }, function(err, stdout, stderr) { var diff = (new Date()) - sleeperStart; console.log('\'sleep 3\' with timeout 50 took %d ms', diff); assert.ok(diff < 500); assert.ok(err); assert.ok(err.killed); assert.equal(err.signal, 'SIGTERM'); }); var startSleep3 = new Date(); var killMeTwice = exec(SLEEP3_COMMAND, {timeout: 1000}, killMeTwiceCallback); process.nextTick(function() { console.log('kill pid %d', killMeTwice.pid); // make sure there is no race condition in starting the process // the PID SHOULD exist directly following the exec() call. assert.equal('number', typeof killMeTwice._handle.pid); // Kill the process killMeTwice.kill(); }); function killMeTwiceCallback(err, stdout, stderr) { var diff = (new Date()) - startSleep3; // We should have already killed this process. Assert that the timeout still // works and that we are getting the proper callback parameters. assert.ok(err); assert.ok(err.killed); assert.equal(err.signal, 'SIGTERM'); // the timeout should still be in effect console.log('\'sleep 3\' was already killed. Took %d ms', diff); assert.ok(diff < 1500); } exec('python -c "print 200000*\'C\'"', {maxBuffer: 1000}, function(err, stdout, stderr) { assert.ok(err); assert.ok(/maxBuffer/.test(err.message)); }); process.on('exit', function() { assert.equal(1, success_count); assert.equal(1, error_count); }); node-v0.10.25~dfsg2/test/pummel/pummel.status0000644000000000000000000000001612270121457017634 0ustar rootrootprefix pummel node-v0.10.25~dfsg2/test/pummel/test-process-uptime.js0000644000000000000000000000300512270121457021363 0ustar rootroot// Copyright Joyent, Inc. and other Node contributors. // // Permission is hereby granted, free of charge, to any person obtaining a // copy of this software and associated documentation files (the // "Software"), to deal in the Software without restriction, including // without limitation the rights to use, copy, modify, merge, publish, // distribute, sublicense, and/or sell copies of the Software, and to permit // persons to whom the Software is furnished to do so, subject to the // following conditions: // // The above copyright notice and this permission notice shall be included // in all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS // OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF // MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN // NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, // DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR // OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE // USE OR OTHER DEALINGS IN THE SOFTWARE. var common = require('../common'); var assert = require('assert'); console.error(process.uptime()); assert.ok(process.uptime() <= 2); var original = process.uptime(); setTimeout(function() { var uptime = process.uptime(); // some wiggle room to account for timer // granularity, processor speed, and scheduling assert.ok(uptime >= original + 2); assert.ok(uptime <= original + 3); }, 2000); node-v0.10.25~dfsg2/test/pummel/test-tls-ci-reneg-attack.js0000644000000000000000000000633412270121457022152 0ustar rootroot// Copyright Joyent, Inc. and other Node contributors. // // Permission is hereby granted, free of charge, to any person obtaining a // copy of this software and associated documentation files (the // "Software"), to deal in the Software without restriction, including // without limitation the rights to use, copy, modify, merge, publish, // distribute, sublicense, and/or sell copies of the Software, and to permit // persons to whom the Software is furnished to do so, subject to the // following conditions: // // The above copyright notice and this permission notice shall be included // in all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS // OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF // MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN // NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, // DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR // OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE // USE OR OTHER DEALINGS IN THE SOFTWARE. var common = require('../common'); var assert = require('assert'); var spawn = require('child_process').spawn; var tls = require('tls'); var fs = require('fs'); // renegotiation limits to test var LIMITS = [0, 1, 2, 3, 5, 10, 16]; if (process.platform === 'win32') { console.log('Skipping test, you probably don\'t have openssl installed.'); process.exit(); } (function() { var n = 0; function next() { if (n >= LIMITS.length) return; tls.CLIENT_RENEG_LIMIT = LIMITS[n++]; test(next); } next(); })(); function test(next) { var options = { cert: fs.readFileSync(common.fixturesDir + '/test_cert.pem'), key: fs.readFileSync(common.fixturesDir + '/test_key.pem') }; var seenError = false; var server = tls.createServer(options, function(conn) { conn.on('error', function(err) { console.error('Caught exception: ' + err); assert(/TLS session renegotiation attack/.test(err)); conn.destroy(); seenError = true; }); conn.pipe(conn); }); server.listen(common.PORT, function() { var args = ('s_client -connect 127.0.0.1:' + common.PORT).split(' '); var child = spawn('openssl', args); child.stdout.pipe(process.stdout); child.stderr.pipe(process.stderr); // count handshakes, start the attack after the initial handshake is done var handshakes = 0; var renegs = 0; child.stderr.on('data', function(data) { if (seenError) return; handshakes += (('' + data).match(/verify return:1/g) || []).length; if (handshakes === 2) spam(); renegs += (('' + data).match(/RENEGOTIATING/g) || []).length; }); child.on('exit', function() { assert.equal(renegs, tls.CLIENT_RENEG_LIMIT + 1); server.close(); process.nextTick(next); }); var closed = false; child.stdin.on('error', function(err) { assert.equal(err.code, 'ECONNRESET'); closed = true; }); child.stdin.on('close', function() { closed = true; }); // simulate renegotiation attack function spam() { if (closed) return; child.stdin.write('R\n'); setTimeout(spam, 50); } }); } node-v0.10.25~dfsg2/test/pummel/test-net-many-clients.js0000644000000000000000000000532012270121457021575 0ustar rootroot// Copyright Joyent, Inc. and other Node contributors. // // Permission is hereby granted, free of charge, to any person obtaining a // copy of this software and associated documentation files (the // "Software"), to deal in the Software without restriction, including // without limitation the rights to use, copy, modify, merge, publish, // distribute, sublicense, and/or sell copies of the Software, and to permit // persons to whom the Software is furnished to do so, subject to the // following conditions: // // The above copyright notice and this permission notice shall be included // in all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS // OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF // MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN // NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, // DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR // OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE // USE OR OTHER DEALINGS IN THE SOFTWARE. var common = require('../common'); var assert = require('assert'); var net = require('net'); // settings var bytes = 1024 * 40; var concurrency = 100; var connections_per_client = 5; // measured var total_connections = 0; var body = ''; for (var i = 0; i < bytes; i++) { body += 'C'; } var server = net.createServer(function(c) { console.log('connected'); total_connections++; common.print('#'); c.write(body); c.end(); }); function runClient(callback) { var client = net.createConnection(common.PORT); client.connections = 0; client.setEncoding('utf8'); client.on('connect', function() { common.print('c'); client.recved = ''; client.connections += 1; }); client.on('data', function(chunk) { this.recved += chunk; }); client.on('end', function() { client.end(); }); client.on('error', function(e) { console.log('\n\nERROOOOOr'); throw e; }); client.on('close', function(had_error) { common.print('.'); assert.equal(false, had_error); assert.equal(bytes, client.recved.length); if (client.fd) { console.log(client.fd); } assert.ok(!client.fd); if (this.connections < connections_per_client) { this.connect(common.PORT); } else { callback(); } }); } server.listen(common.PORT, function() { var finished_clients = 0; for (var i = 0; i < concurrency; i++) { runClient(function() { if (++finished_clients == concurrency) server.close(); }); } }); process.on('exit', function() { assert.equal(connections_per_client * concurrency, total_connections); console.log('\nokay!'); }); node-v0.10.25~dfsg2/test/pummel/test-regress-GH-814_2.js0000644000000000000000000000553612270121457021120 0ustar rootroot// Copyright Joyent, Inc. and other Node contributors. // // Permission is hereby granted, free of charge, to any person obtaining a // copy of this software and associated documentation files (the // "Software"), to deal in the Software without restriction, including // without limitation the rights to use, copy, modify, merge, publish, // distribute, sublicense, and/or sell copies of the Software, and to permit // persons to whom the Software is furnished to do so, subject to the // following conditions: // // The above copyright notice and this permission notice shall be included // in all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS // OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF // MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN // NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, // DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR // OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE // USE OR OTHER DEALINGS IN THE SOFTWARE. // Flags: --expose_gc var common = require('../common'); var fs = require('fs'); var testFileName = require('path').join(common.tmpDir, 'GH-814_test.txt'); var testFD = fs.openSync(testFileName, 'w'); console.error(testFileName + '\n'); var tailProc = require('child_process').spawn('tail', ['-f', testFileName]); tailProc.stdout.on('data', tailCB); function tailCB(data) { PASS = data.toString().indexOf('.') < 0; if (PASS) { //console.error('i'); } else { console.error('[FAIL]\n DATA -> '); console.error(data); console.error('\n'); throw Error('Buffers GC test -> FAIL'); } } var PASS = true; var bufPool = []; var kBufSize = 16 * 1024 * 1024; var neverWrittenBuffer = newBuffer(kBufSize, 0x2e); //0x2e === '.' var timeToQuit = Date.now() + 5e3; //Test should last no more than this. writer(); function writer() { if (PASS) { if (Date.now() > timeToQuit) { setTimeout(function() { process.kill(tailProc.pid); console.error('\nBuffers GC test -> PASS (OK)\n'); }, 555); } else { fs.write(testFD, newBuffer(kBufSize, 0x61), 0, kBufSize, -1, writerCB); gc(); gc(); gc(); gc(); gc(); gc(); var nuBuf = new Buffer(kBufSize); neverWrittenBuffer.copy(nuBuf); if (bufPool.push(nuBuf) > 100) { bufPool.length = 0; } process.nextTick(writer); //console.error('o'); } } } function writerCB(err, written) { //console.error('cb.'); if (err) { throw err; } } // ******************* UTILITIES function newBuffer(size, value) { var buffer = new Buffer(size); while (size--) { buffer[size] = value; } buffer[buffer.length - 1] = 0x0d; buffer[buffer.length - 1] = 0x0a; return buffer; } node-v0.10.25~dfsg2/test/pummel/test-postmortem-findjsobjects.js0000644000000000000000000000625412270121457023453 0ustar rootroot// Copyright Joyent, Inc. and other Node contributors. // // Permission is hereby granted, free of charge, to any person obtaining a // copy of this software and associated documentation files (the // "Software"), to deal in the Software without restriction, including // without limitation the rights to use, copy, modify, merge, publish, // distribute, sublicense, and/or sell copies of the Software, and to permit // persons to whom the Software is furnished to do so, subject to the // following conditions: // // The above copyright notice and this permission notice shall be included // in all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS // OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF // MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN // NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, // DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR // OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE // USE OR OTHER DEALINGS IN THE SOFTWARE. var common = require('../common'); var assert = require('assert'); var os = require('os'); var util = require('util'); if (os.type() != 'SunOS') { console.error('Skipping because postmortem debugging not available.'); process.exit(0); } /* * Now we're going to fork ourselves to gcore */ var spawn = require('child_process').spawn; var prefix = '/var/tmp/node'; var corefile = prefix + '.' + process.pid; var gcore = spawn('gcore', [ '-o', prefix, process.pid + '' ]); var output = ''; var unlinkSync = require('fs').unlinkSync; var args = [ corefile ]; if (process.env.MDB_LIBRARY_PATH && process.env.MDB_LIBRARY_PATH != '') args = args.concat([ '-L', process.env.MDB_LIBRARY_PATH ]); function LanguageH(chapter) { this.OBEY = 'CHAPTER ' + parseInt(chapter, 10); } var obj = new LanguageH(1); gcore.stderr.on('data', function (data) { console.log('gcore: ' + data); }); gcore.on('exit', function (code) { if (code != 0) { console.error('gcore exited with code ' + code); process.exit(code); } var mdb = spawn('mdb', args, { stdio: 'pipe' }); mdb.on('exit', function (code) { var retained = '; core retained as ' + corefile; if (code != 0) { console.error('mdb exited with code ' + util.inspect(code) + retained); process.exit(code); } var lines = output.split('\n'); var found = 0, i, expected = 'OBEY: "' + obj.OBEY + '"', nexpected = 2; for (var i = 0; i < lines.length; i++) { if (lines[i].indexOf(expected) != -1) found++; } assert.equal(found, nexpected, 'expected ' + nexpected + ' objects, found ' + found + retained); unlinkSync(corefile); process.exit(0); }); mdb.stdout.on('data', function (data) { output += data; }); mdb.stderr.on('data', function (data) { console.log('mdb stderr: ' + data); }); mdb.stdin.write('::load v8.so\n'); mdb.stdin.write('::findjsobjects -c LanguageH | '); mdb.stdin.write('::findjsobjects | ::jsprint\n'); mdb.stdin.write('::findjsobjects -p OBEY | '); mdb.stdin.write('::findjsobjects | ::jsprint\n'); mdb.stdin.end(); }); node-v0.10.25~dfsg2/test/pummel/test-fs-watch-file.js0000644000000000000000000000653412270121457021047 0ustar rootroot// Copyright Joyent, Inc. and other Node contributors. // // Permission is hereby granted, free of charge, to any person obtaining a // copy of this software and associated documentation files (the // "Software"), to deal in the Software without restriction, including // without limitation the rights to use, copy, modify, merge, publish, // distribute, sublicense, and/or sell copies of the Software, and to permit // persons to whom the Software is furnished to do so, subject to the // following conditions: // // The above copyright notice and this permission notice shall be included // in all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS // OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF // MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN // NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, // DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR // OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE // USE OR OTHER DEALINGS IN THE SOFTWARE. var common = require('../common'); var assert = require('assert'); var path = require('path'); var fs = require('fs'); var watchSeenOne = 0; var watchSeenTwo = 0; var watchSeenThree = 0; var startDir = process.cwd(); var testDir = common.tmpDir; var filenameOne = 'watch.txt'; var filepathOne = path.join(testDir, filenameOne); var filenameTwo = 'hasOwnProperty'; var filepathTwo = filenameTwo; var filepathTwoAbs = path.join(testDir, filenameTwo); var filenameThree = 'charm'; // because the third time is process.on('exit', function() { fs.unlinkSync(filepathOne); fs.unlinkSync(filepathTwoAbs); fs.unlinkSync(filenameThree); assert.equal(1, watchSeenOne); assert.equal(2, watchSeenTwo); assert.equal(1, watchSeenThree); }); fs.writeFileSync(filepathOne, 'hello'); assert.throws( function() { fs.watchFile(filepathOne); }, function(e) { return e.message === 'watchFile requires a listener function'; } ); assert.doesNotThrow( function() { fs.watchFile(filepathOne, function(curr, prev) { fs.unwatchFile(filepathOne); ++watchSeenOne; }); } ); setTimeout(function() { fs.writeFileSync(filepathOne, 'world'); }, 1000); process.chdir(testDir); fs.writeFileSync(filepathTwoAbs, 'howdy'); assert.throws( function() { fs.watchFile(filepathTwo); }, function(e) { return e.message === 'watchFile requires a listener function'; } ); assert.doesNotThrow( function() { function a(curr, prev) { fs.unwatchFile(filepathTwo, a); ++watchSeenTwo; } function b(curr, prev) { fs.unwatchFile(filepathTwo, b); ++watchSeenTwo; } fs.watchFile(filepathTwo, a); fs.watchFile(filepathTwo, b); } ); setTimeout(function() { fs.writeFileSync(filepathTwoAbs, 'pardner'); }, 1000); assert.doesNotThrow( function() { function a(curr, prev) { assert.ok(0); // should not run } function b(curr, prev) { fs.unwatchFile(filenameThree, b); ++watchSeenThree; } fs.watchFile(filenameThree, a); fs.watchFile(filenameThree, b); fs.unwatchFile(filenameThree, a); } ); setTimeout(function() { fs.writeFileSync(filenameThree, 'pardner'); }, 1000); node-v0.10.25~dfsg2/test/pummel/test-net-pause.js0000644000000000000000000000504412270121457020312 0ustar rootroot// Copyright Joyent, Inc. and other Node contributors. // // Permission is hereby granted, free of charge, to any person obtaining a // copy of this software and associated documentation files (the // "Software"), to deal in the Software without restriction, including // without limitation the rights to use, copy, modify, merge, publish, // distribute, sublicense, and/or sell copies of the Software, and to permit // persons to whom the Software is furnished to do so, subject to the // following conditions: // // The above copyright notice and this permission notice shall be included // in all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS // OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF // MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN // NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, // DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR // OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE // USE OR OTHER DEALINGS IN THE SOFTWARE. var common = require('../common'); var assert = require('assert'); var net = require('net'); var N = 200; var recv = '', chars_recved = 0; var server = net.createServer(function(connection) { function write(j) { if (j >= N) { connection.end(); return; } setTimeout(function() { connection.write('C'); write(j + 1); }, 10); } write(0); }); server.on('listening', function() { var client = net.createConnection(common.PORT); client.setEncoding('ascii'); client.on('data', function(d) { common.print(d); recv += d; }); setTimeout(function() { chars_recved = recv.length; console.log('pause at: ' + chars_recved); assert.equal(true, chars_recved > 1); client.pause(); setTimeout(function() { console.log('resume at: ' + chars_recved); assert.equal(chars_recved, recv.length); client.resume(); setTimeout(function() { chars_recved = recv.length; console.log('pause at: ' + chars_recved); client.pause(); setTimeout(function() { console.log('resume at: ' + chars_recved); assert.equal(chars_recved, recv.length); client.resume(); }, 500); }, 500); }, 500); }, 500); client.on('end', function() { server.close(); client.end(); }); }); server.listen(common.PORT); process.on('exit', function() { assert.equal(N, recv.length); common.debug('Exit'); }); node-v0.10.25~dfsg2/test/pummel/test-vm-memleak.js0000644000000000000000000000326712270121457020451 0ustar rootroot// Copyright Joyent, Inc. and other Node contributors. // // Permission is hereby granted, free of charge, to any person obtaining a // copy of this software and associated documentation files (the // "Software"), to deal in the Software without restriction, including // without limitation the rights to use, copy, modify, merge, publish, // distribute, sublicense, and/or sell copies of the Software, and to permit // persons to whom the Software is furnished to do so, subject to the // following conditions: // // The above copyright notice and this permission notice shall be included // in all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS // OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF // MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN // NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, // DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR // OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE // USE OR OTHER DEALINGS IN THE SOFTWARE. var assert = require('assert'); var common = require('../common'); var start = Date.now(); var maxMem = 0; var interval = setInterval(function() { try { require('vm').runInNewContext('throw 1;'); } catch (e) { } var rss = process.memoryUsage().rss; maxMem = Math.max(rss, maxMem); if (Date.now() - start > 5 * 1000) { // wait 10 seconds. clearInterval(interval); } }, 1); process.on('exit', function() { console.error('max mem: %dmb', Math.round(maxMem / (1024 * 1024))); // make sure we stay below 100mb assert.ok(maxMem < 50 * 1024 * 1024); }); node-v0.10.25~dfsg2/test/pummel/test-child-process-spawn-loop.js0000644000000000000000000000365112270121457023247 0ustar rootroot// Copyright Joyent, Inc. and other Node contributors. // // Permission is hereby granted, free of charge, to any person obtaining a // copy of this software and associated documentation files (the // "Software"), to deal in the Software without restriction, including // without limitation the rights to use, copy, modify, merge, publish, // distribute, sublicense, and/or sell copies of the Software, and to permit // persons to whom the Software is furnished to do so, subject to the // following conditions: // // The above copyright notice and this permission notice shall be included // in all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS // OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF // MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN // NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, // DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR // OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE // USE OR OTHER DEALINGS IN THE SOFTWARE. var common = require('../common'); var assert = require('assert'); var spawn = require('child_process').spawn; var is_windows = process.platform === 'win32'; var SIZE = 1000 * 1024; var N = 40; var finished = false; function doSpawn(i) { var child = spawn('python', ['-c', 'print ' + SIZE + ' * "C"']); var count = 0; child.stdout.setEncoding('ascii'); child.stdout.on('data', function(chunk) { count += chunk.length; }); child.stderr.on('data', function(chunk) { console.log('stderr: ' + chunk); }); child.on('close', function() { // + 1 for \n or + 2 for \r\n on Windows assert.equal(SIZE + (is_windows ? 2 : 1), count); if (i < N) { doSpawn(i + 1); } else { finished = true; } }); } doSpawn(0); process.on('exit', function() { assert.ok(finished); }); node-v0.10.25~dfsg2/test/pummel/test-regress-GH-814.js0000644000000000000000000000472012270121457020671 0ustar rootroot// Copyright Joyent, Inc. and other Node contributors. // // Permission is hereby granted, free of charge, to any person obtaining a // copy of this software and associated documentation files (the // "Software"), to deal in the Software without restriction, including // without limitation the rights to use, copy, modify, merge, publish, // distribute, sublicense, and/or sell copies of the Software, and to permit // persons to whom the Software is furnished to do so, subject to the // following conditions: // // The above copyright notice and this permission notice shall be included // in all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS // OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF // MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN // NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, // DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR // OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE // USE OR OTHER DEALINGS IN THE SOFTWARE. // Flags: --expose_gc function newBuffer(size, value) { var buffer = new Buffer(size); while (size--) { buffer[size] = value; } //buffer[buffer.length-2]= 0x0d; buffer[buffer.length - 1] = 0x0a; return buffer; } var common = require('../common'); var fs = require('fs'); var testFileName = require('path').join(common.tmpDir, 'GH-814_testFile.txt'); var testFileFD = fs.openSync(testFileName, 'w'); console.log(testFileName); var kBufSize = 128 * 1024; var PASS = true; var neverWrittenBuffer = newBuffer(kBufSize, 0x2e); //0x2e === '.' var bufPool = []; var tail = require('child_process').spawn('tail', ['-f', testFileName]); tail.stdout.on('data', tailCB); function tailCB(data) { PASS = data.toString().indexOf('.') < 0; } var timeToQuit = Date.now() + 8e3; //Test during no more than this seconds. (function main() { if (PASS) { fs.write(testFileFD, newBuffer(kBufSize, 0x61), 0, kBufSize, -1, cb); gc(); var nuBuf = new Buffer(kBufSize); neverWrittenBuffer.copy(nuBuf); if (bufPool.push(nuBuf) > 100) { bufPool.length = 0; } } else { throw Error("Buffer GC'ed test -> FAIL"); } if (Date.now() < timeToQuit) { process.nextTick(main); } else { tail.kill(); console.log("Buffer GC'ed test -> PASS (OK)"); } })(); function cb(err, written) { if (err) { throw err; } } node-v0.10.25~dfsg2/test/pummel/test-https-large-response.js0000644000000000000000000000471012270121457022476 0ustar rootroot// Copyright Joyent, Inc. and other Node contributors. // // Permission is hereby granted, free of charge, to any person obtaining a // copy of this software and associated documentation files (the // "Software"), to deal in the Software without restriction, including // without limitation the rights to use, copy, modify, merge, publish, // distribute, sublicense, and/or sell copies of the Software, and to permit // persons to whom the Software is furnished to do so, subject to the // following conditions: // // The above copyright notice and this permission notice shall be included // in all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS // OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF // MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN // NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, // DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR // OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE // USE OR OTHER DEALINGS IN THE SOFTWARE. var common = require('../common'); var assert = require('assert'); var fs = require('fs'); var https = require('https'); var options = { key: fs.readFileSync(common.fixturesDir + '/keys/agent1-key.pem'), cert: fs.readFileSync(common.fixturesDir + '/keys/agent1-cert.pem') }; var reqCount = 0; var body = ''; process.stdout.write('build body...'); for (var i = 0; i < 1024 * 1024; i++) { body += 'hello world\n'; } process.stdout.write('done\n'); var server = https.createServer(options, function(req, res) { reqCount++; console.log('got request'); res.writeHead(200, { 'content-type': 'text/plain' }); res.end(body); }); var count = 0; var gotResEnd = false; server.listen(common.PORT, function() { https.get({ port: common.PORT, rejectUnauthorized: false }, function(res) { console.log('response!'); res.on('data', function(d) { process.stdout.write('.'); count += d.length; res.pause(); process.nextTick(function() { res.resume(); }); }); res.on('end', function(d) { process.stdout.write('\n'); console.log('expected: ', body.length); console.log(' got: ', count); server.close(); gotResEnd = true; }); }); }); process.on('exit', function() { assert.equal(1, reqCount); assert.equal(body.length, count); assert.ok(gotResEnd); }); node-v0.10.25~dfsg2/test/pummel/test-fs-watch-file-slow.js0000644000000000000000000000406312270121457022024 0ustar rootroot// Copyright Joyent, Inc. and other Node contributors. // // Permission is hereby granted, free of charge, to any person obtaining a // copy of this software and associated documentation files (the // "Software"), to deal in the Software without restriction, including // without limitation the rights to use, copy, modify, merge, publish, // distribute, sublicense, and/or sell copies of the Software, and to permit // persons to whom the Software is furnished to do so, subject to the // following conditions: // // The above copyright notice and this permission notice shall be included // in all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS // OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF // MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN // NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, // DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR // OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE // USE OR OTHER DEALINGS IN THE SOFTWARE. var common = require('../common'); var assert = require('assert'); var path = require('path'); var fs = require('fs'); var FILENAME = path.join(common.tmpDir, 'watch-me'); var TIMEOUT = 1300; var nevents = 0; try { fs.unlinkSync(FILENAME); } catch (e) { // swallow } fs.watchFile(FILENAME, {interval:TIMEOUT - 250}, function(curr, prev) { console.log([curr, prev]); switch (++nevents) { case 1: case 2: assert.equal(fs.existsSync(FILENAME), true); break; case 3: assert.equal(fs.existsSync(FILENAME), false); fs.unwatchFile(FILENAME); break; default: assert(0); } }); process.on('exit', function() { assert.equal(nevents, 3); }); setTimeout(createFile, TIMEOUT); function createFile() { fs.writeFileSync(FILENAME, "test"); setTimeout(touchFile, TIMEOUT); } function touchFile() { fs.writeFileSync(FILENAME, "test"); setTimeout(removeFile, TIMEOUT); } function removeFile() { fs.unlinkSync(FILENAME); } node-v0.10.25~dfsg2/test/pummel/testcfg.py0000644000000000000000000001025112270121457017103 0ustar rootroot# Copyright 2008 the V8 project authors. All rights reserved. # Redistribution and use in source and binary forms, with or without # modification, are permitted provided that the following conditions are # met: # # * Redistributions of source code must retain the above copyright # notice, this list of conditions and the following disclaimer. # * Redistributions in binary form must reproduce the above # copyright notice, this list of conditions and the following # disclaimer in the documentation and/or other materials provided # with the distribution. # * Neither the name of Google Inc. nor the names of its # contributors may be used to endorse or promote products derived # from this software without specific prior written permission. # # THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS # "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT # LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR # A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT # OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, # SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT # LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, # DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY # THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT # (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE # OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. import test import os import shutil from shutil import rmtree from os import mkdir from glob import glob from os.path import join, dirname, exists import re FLAGS_PATTERN = re.compile(r"//\s+Flags:(.*)") FILES_PATTERN = re.compile(r"//\s+Files:(.*)") class PummelTestCase(test.TestCase): def __init__(self, path, file, mode, context, config): super(PummelTestCase, self).__init__(context, path, mode) self.file = file self.config = config self.mode = mode self.tmpdir = join(dirname(self.config.root), 'tmp') def AfterRun(self, result): # delete the whole tmp dir try: rmtree(self.tmpdir) except: pass # make it again. try: mkdir(self.tmpdir) except: pass def BeforeRun(self): # delete the whole tmp dir try: rmtree(self.tmpdir) except: pass # make it again. try: mkdir(self.tmpdir) except: pass def GetLabel(self): return "%s %s" % (self.mode, self.GetName()) def GetName(self): return self.path[-1] def GetCommand(self): result = [self.config.context.GetVm(self.mode)] source = open(self.file).read() flags_match = FLAGS_PATTERN.search(source) if flags_match: result += flags_match.group(1).strip().split() files_match = FILES_PATTERN.search(source); additional_files = [] if files_match: additional_files += files_match.group(1).strip().split() for a_file in additional_files: result.append(join(dirname(self.config.root), '..', a_file)) result += [self.file] return result def GetSource(self): return open(self.file).read() class PummelTestConfiguration(test.TestConfiguration): def __init__(self, context, root): super(PummelTestConfiguration, self).__init__(context, root) def Ls(self, path): def SelectTest(name): return name.startswith('test-') and name.endswith('.js') return [f[:-3] for f in os.listdir(path) if SelectTest(f)] def ListTests(self, current_path, path, mode): all_tests = [current_path + [t] for t in self.Ls(join(self.root))] result = [] for test in all_tests: if self.Contains(path, test): file_path = join(self.root, reduce(join, test[1:], "") + ".js") result.append(PummelTestCase(test, file_path, mode, self.context, self)) return result def GetBuildRequirements(self): return ['sample', 'sample=shell'] def GetTestStatus(self, sections, defs): status_file = join(self.root, 'simple.status') if exists(status_file): test.ReadConfigurationInto(status_file, sections, defs) def GetConfiguration(context, root): return PummelTestConfiguration(context, root) node-v0.10.25~dfsg2/test/pummel/test-timer-wrap.js0000644000000000000000000000266412270121457020505 0ustar rootroot// Copyright Joyent, Inc. and other Node contributors. // // Permission is hereby granted, free of charge, to any person obtaining a // copy of this software and associated documentation files (the // "Software"), to deal in the Software without restriction, including // without limitation the rights to use, copy, modify, merge, publish, // distribute, sublicense, and/or sell copies of the Software, and to permit // persons to whom the Software is furnished to do so, subject to the // following conditions: // // The above copyright notice and this permission notice shall be included // in all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS // OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF // MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN // NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, // DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR // OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE // USE OR OTHER DEALINGS IN THE SOFTWARE. var common = require('../common'); var assert = require('assert'); var timeouts = 0; var Timer = process.binding('timer_wrap').Timer; var t = new Timer(); t.start(1000, 0); t.ontimeout = function() { timeouts++; console.log('timeout'); t.close(); }; process.on('exit', function() { assert.equal(1, timeouts); }); node-v0.10.25~dfsg2/test/pummel/test-https-ci-reneg-attack.js0000644000000000000000000000643512270121457022514 0ustar rootroot// Copyright Joyent, Inc. and other Node contributors. // // Permission is hereby granted, free of charge, to any person obtaining a // copy of this software and associated documentation files (the // "Software"), to deal in the Software without restriction, including // without limitation the rights to use, copy, modify, merge, publish, // distribute, sublicense, and/or sell copies of the Software, and to permit // persons to whom the Software is furnished to do so, subject to the // following conditions: // // The above copyright notice and this permission notice shall be included // in all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS // OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF // MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN // NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, // DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR // OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE // USE OR OTHER DEALINGS IN THE SOFTWARE. var common = require('../common'); var assert = require('assert'); var spawn = require('child_process').spawn; var tls = require('tls'); var https = require('https'); var fs = require('fs'); // renegotiation limits to test var LIMITS = [0, 1, 2, 3, 5, 10, 16]; if (process.platform === 'win32') { console.log('Skipping test, you probably don\'t have openssl installed.'); process.exit(); } (function() { var n = 0; function next() { if (n >= LIMITS.length) return; tls.CLIENT_RENEG_LIMIT = LIMITS[n++]; test(next); } next(); })(); function test(next) { var options = { cert: fs.readFileSync(common.fixturesDir + '/test_cert.pem'), key: fs.readFileSync(common.fixturesDir + '/test_key.pem') }; var seenError = false; var server = https.createServer(options, function(req, res) { var conn = req.connection; conn.on('error', function(err) { console.error('Caught exception: ' + err); assert(/TLS session renegotiation attack/.test(err)); conn.destroy(); seenError = true; }); res.end('ok'); }); server.listen(common.PORT, function() { var args = ('s_client -connect 127.0.0.1:' + common.PORT).split(' '); var child = spawn('openssl', args); child.stdout.pipe(process.stdout); child.stderr.pipe(process.stderr); // count handshakes, start the attack after the initial handshake is done var handshakes = 0; var renegs = 0; child.stderr.on('data', function(data) { if (seenError) return; handshakes += (('' + data).match(/verify return:1/g) || []).length; if (handshakes === 2) spam(); renegs += (('' + data).match(/RENEGOTIATING/g) || []).length; }); child.on('exit', function() { assert.equal(renegs, tls.CLIENT_RENEG_LIMIT + 1); server.close(); process.nextTick(next); }); var closed = false; child.stdin.on('error', function(err) { assert.equal(err.code, 'ECONNRESET'); closed = true; }); child.stdin.on('close', function() { closed = true; }); // simulate renegotiation attack function spam() { if (closed) return; child.stdin.write('R\n'); setTimeout(spam, 50); } }); } node-v0.10.25~dfsg2/test/pummel/test-http-client-reconnect-bug.js0000644000000000000000000000416312270121457023376 0ustar rootroot// Copyright Joyent, Inc. and other Node contributors. // // Permission is hereby granted, free of charge, to any person obtaining a // copy of this software and associated documentation files (the // "Software"), to deal in the Software without restriction, including // without limitation the rights to use, copy, modify, merge, publish, // distribute, sublicense, and/or sell copies of the Software, and to permit // persons to whom the Software is furnished to do so, subject to the // following conditions: // // The above copyright notice and this permission notice shall be included // in all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS // OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF // MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN // NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, // DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR // OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE // USE OR OTHER DEALINGS IN THE SOFTWARE. var common = require('../common'); var assert = require('assert'); var net = require('net'), util = require('util'), http = require('http'); var errorCount = 0; var eofCount = 0; var server = net.createServer(function(socket) { socket.end(); }); server.on('listening', function() { var client = http.createClient(common.PORT); client.on('error', function(err) { // We should receive one error console.log('ERROR! ' + err.message); errorCount++; }); client.on('end', function() { // When we remove the old Client interface this will most likely have to be // changed. console.log('EOF!'); eofCount++; }); var request = client.request('GET', '/', {'host': 'localhost'}); request.end(); request.on('response', function(response) { console.log('STATUS: ' + response.statusCode); }); }); server.listen(common.PORT); setTimeout(function() { server.close(); }, 500); process.on('exit', function() { assert.equal(1, errorCount); assert.equal(1, eofCount); }); node-v0.10.25~dfsg2/test/pummel/test-debugger-debug-brk.js0000644000000000000000000000331112270121457022030 0ustar rootroot// Copyright Joyent, Inc. and other Node contributors. // // Permission is hereby granted, free of charge, to any person obtaining a // copy of this software and associated documentation files (the // "Software"), to deal in the Software without restriction, including // without limitation the rights to use, copy, modify, merge, publish, // distribute, sublicense, and/or sell copies of the Software, and to permit // persons to whom the Software is furnished to do so, subject to the // following conditions: // // The above copyright notice and this permission notice shall be included // in all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS // OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF // MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN // NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, // DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR // OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE // USE OR OTHER DEALINGS IN THE SOFTWARE. var common = require('../common'); var assert = require('assert'); var spawn = require('child_process').spawn; var script = common.fixturesDir + '/empty.js'; function fail() { assert(0); // `node --debug-brk script.js` should not quit } function test(arg) { var child = spawn(process.execPath, [arg, script]); child.on('exit', fail); // give node time to start up the debugger setTimeout(function() { child.removeListener('exit', fail); child.kill(); }, 2000); process.on('exit', function() { assert(child.killed); }); } test('--debug-brk'); test('--debug-brk=5959'); node-v0.10.25~dfsg2/test/pummel/test-net-pingpong.js0000644000000000000000000000723512270121457021022 0ustar rootroot// Copyright Joyent, Inc. and other Node contributors. // // Permission is hereby granted, free of charge, to any person obtaining a // copy of this software and associated documentation files (the // "Software"), to deal in the Software without restriction, including // without limitation the rights to use, copy, modify, merge, publish, // distribute, sublicense, and/or sell copies of the Software, and to permit // persons to whom the Software is furnished to do so, subject to the // following conditions: // // The above copyright notice and this permission notice shall be included // in all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS // OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF // MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN // NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, // DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR // OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE // USE OR OTHER DEALINGS IN THE SOFTWARE. var common = require('../common'); var assert = require('assert'); var net = require('net'); var tests_run = 0; function pingPongTest(port, host, on_complete) { var N = 1000; var count = 0; var sent_final_ping = false; var server = net.createServer({ allowHalfOpen: true }, function(socket) { assert.equal(true, socket.remoteAddress !== null); assert.equal(true, socket.remoteAddress !== undefined); if (host === '127.0.0.1' || host === 'localhost' || !host) { assert.equal(socket.remoteAddress, '127.0.0.1'); } else { console.log('host = ' + host + ', remoteAddress = ' + socket.remoteAddress); assert.equal(socket.remoteAddress, '::1'); } socket.setEncoding('utf8'); socket.setNoDelay(); socket.timeout = 0; socket.on('data', function(data) { console.log('server got: ' + JSON.stringify(data)); assert.equal('open', socket.readyState); assert.equal(true, count <= N); if (/PING/.exec(data)) { socket.write('PONG'); } }); socket.on('end', function() { assert.equal('writeOnly', socket.readyState); socket.end(); }); socket.on('close', function(had_error) { assert.equal(false, had_error); assert.equal('closed', socket.readyState); socket.server.close(); }); }); server.listen(port, host, function() { var client = net.createConnection(port, host); client.setEncoding('utf8'); client.on('connect', function() { assert.equal('open', client.readyState); client.write('PING'); }); client.on('data', function(data) { console.log('client got: ' + data); assert.equal('PONG', data); count += 1; if (sent_final_ping) { assert.equal('readOnly', client.readyState); return; } else { assert.equal('open', client.readyState); } if (count < N) { client.write('PING'); } else { sent_final_ping = true; client.write('PING'); client.end(); } }); client.on('close', function() { assert.equal(N + 1, count); assert.equal(true, sent_final_ping); if (on_complete) on_complete(); tests_run += 1; }); }); } /* All are run at once, so run on different ports */ pingPongTest(common.PORT, 'localhost'); pingPongTest(common.PORT + 1, null); // This IPv6 isn't working on Solaris var solaris = /sunos/i.test(process.platform); if (!solaris) pingPongTest(common.PORT + 2, '::1'); process.on('exit', function() { assert.equal(solaris ? 2 : 3, tests_run); }); node-v0.10.25~dfsg2/test/gc/0000755000000000000000000000000012271410374014165 5ustar rootrootnode-v0.10.25~dfsg2/test/gc/test-http-client.js0000644000000000000000000000243312270121457017735 0ustar rootroot// just a simple http server and client. function serverHandler(req, res) { res.writeHead(200, {'Content-Type': 'text/plain'}); res.end('Hello World\n'); } var http = require('http'), weak = require('weak'), done = 0, count = 0, countGC = 0, todo = 500, common = require('../common.js'), assert = require('assert'), PORT = common.PORT; console.log('We should do '+ todo +' requests'); var http = require('http'); var server = http.createServer(serverHandler); server.listen(PORT, getall); function getall() { for (var i = 0; i < todo; i++) { (function(){ function cb(res) { console.error('in cb') done+=1; res.on('end', statusLater); } var req = http.get({ hostname: 'localhost', pathname: '/', port: PORT }, cb) count++; weak(req, afterGC); })() } } function afterGC(){ countGC ++; } var timer; function statusLater() { gc(); if (timer) clearTimeout(timer); timer = setTimeout(status, 1); } function status() { gc(); console.log('Done: %d/%d', done, todo); console.log('Collected: %d/%d', countGC, count); if (done === todo) { console.log('All should be collected now.'); assert(count === countGC); process.exit(0); } } node-v0.10.25~dfsg2/test/gc/test-net-timeout.js0000644000000000000000000000267012270121457017757 0ustar rootroot// just like test/gc/http-client-timeout.js, // but using a net server/client instead function serverHandler(sock) { sock.setTimeout(120000); setTimeout(function () { sock.end('hello\n'); }, 100); } var net = require('net'), weak = require('weak'), done = 0, count = 0, countGC = 0, todo = 500, common = require('../common.js'), assert = require('assert'), PORT = common.PORT; console.log('We should do '+ todo +' requests'); var server = net.createServer(serverHandler); server.listen(PORT, getall); function getall() { for (var i = 0; i < todo; i++) { (function(){ var req = net.connect(PORT, '127.0.0.1'); req.setTimeout(10, function() { console.log('timeout (expected)') req.destroy(); done++; statusLater(); }); count++; weak(req, afterGC); })(); } } function afterGC(){ countGC ++; } var timer; function statusLater() { gc(); if (timer) clearTimeout(timer); timer = setTimeout(status, 1); } function status() { gc(); console.log('Done: %d/%d', done, todo); console.log('Collected: %d/%d', countGC, count); if (done === todo) { /* Give libuv some time to make close callbacks. */ setTimeout(function() { gc(); console.log('All should be collected now.'); console.log('Collected: %d/%d', countGC, count); assert(count === countGC); process.exit(0); }, 200); } } node-v0.10.25~dfsg2/test/gc/test-http-client-timeout.js0000644000000000000000000000257112270121457021424 0ustar rootroot// just like test/gc/http-client.js, // but with a timeout set function serverHandler(req, res) { setTimeout(function () { res.writeHead(200) res.end('hello\n'); }, 100); } var http = require('http'), weak = require('weak'), done = 0, count = 0, countGC = 0, todo = 550, common = require('../common.js'), assert = require('assert'), PORT = common.PORT; console.log('We should do '+ todo +' requests'); var http = require('http'); var server = http.createServer(serverHandler); server.listen(PORT, getall); function getall() { for (var i = 0; i < todo; i++) { (function(){ function cb() { done+=1; statusLater(); } var req = http.get({ hostname: 'localhost', pathname: '/', port: PORT }, cb); req.on('error', cb); req.setTimeout(10, function(){ console.log('timeout (expected)') }); count++; weak(req, afterGC); })() } } function afterGC(){ countGC ++; } var timer; function statusLater() { gc(); if (timer) clearTimeout(timer); timer = setTimeout(status, 1); } function status() { gc(); console.log('Done: %d/%d', done, todo); console.log('Collected: %d/%d', countGC, count); if (done === todo) { console.log('All should be collected now.'); assert(count === countGC); process.exit(0); } } node-v0.10.25~dfsg2/test/gc/test-http-client-onerror.js0000644000000000000000000000255512270121457021426 0ustar rootroot// just like test/gc/http-client.js, // but with an on('error') handler that does nothing. function serverHandler(req, res) { res.writeHead(200, {'Content-Type': 'text/plain'}); res.end('Hello World\n'); } var http = require('http'), weak = require('weak'), done = 0, count = 0, countGC = 0, todo = 500, common = require('../common.js'), assert = require('assert'), PORT = common.PORT; console.log('We should do '+ todo +' requests'); var http = require('http'); var server = http.createServer(serverHandler); server.listen(PORT, getall); function getall() { for (var i = 0; i < todo; i++) { (function(){ function cb(res) { done+=1; statusLater(); } function onerror(er) { throw er; } var req = http.get({ hostname: 'localhost', pathname: '/', port: PORT }, cb).on('error', onerror); count++; weak(req, afterGC); })() } } function afterGC(){ countGC ++; } var timer; function statusLater() { gc(); if (timer) clearTimeout(timer); timer = setTimeout(status, 1); } function status() { gc(); console.log('Done: %d/%d', done, todo); console.log('Collected: %d/%d', countGC, count); if (done === todo) { console.log('All should be collected now.'); assert(count === countGC); process.exit(0); } } node-v0.10.25~dfsg2/test/gc/test-http-client-connaborted.js0000644000000000000000000000236412270121457022234 0ustar rootroot// just like test/gc/http-client.js, // but aborting every connection that comes in. function serverHandler(req, res) { res.connection.destroy(); } var http = require('http'), weak = require('weak'), done = 0, count = 0, countGC = 0, todo = 500, common = require('../common.js'), assert = require('assert'), PORT = common.PORT; console.log('We should do '+ todo +' requests'); var http = require('http'); var server = http.createServer(serverHandler); server.listen(PORT, getall); function getall() { for (var i = 0; i < todo; i++) { (function(){ function cb(res) { done+=1; statusLater(); } var req = http.get({ hostname: 'localhost', pathname: '/', port: PORT }, cb).on('error', cb); count++; weak(req, afterGC); })() } } function afterGC(){ countGC ++; } var timer; function statusLater() { gc(); if (timer) clearTimeout(timer); timer = setTimeout(status, 1); } function status() { gc(); console.log('Done: %d/%d', done, todo); console.log('Collected: %d/%d', countGC, count); if (done === todo) { console.log('All should be collected now.'); assert(count === countGC); process.exit(0); } } node-v0.10.25~dfsg2/test/gc/testcfg.py0000644000000000000000000001042412270121457016177 0ustar rootroot# Copyright 2008 the V8 project authors. All rights reserved. # Redistribution and use in source and binary forms, with or without # modification, are permitted provided that the following conditions are # met: # # * Redistributions of source code must retain the above copyright # notice, this list of conditions and the following disclaimer. # * Redistributions in binary form must reproduce the above # copyright notice, this list of conditions and the following # disclaimer in the documentation and/or other materials provided # with the distribution. # * Neither the name of Google Inc. nor the names of its # contributors may be used to endorse or promote products derived # from this software without specific prior written permission. # # THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS # "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT # LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR # A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT # OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, # SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT # LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, # DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY # THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT # (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE # OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. import test import os import shutil from shutil import rmtree from os import mkdir from glob import glob from os.path import join, dirname, exists import re FLAGS_PATTERN = re.compile(r"//\s+Flags:(.*)") FILES_PATTERN = re.compile(r"//\s+Files:(.*)") class GCTestCase(test.TestCase): def __init__(self, path, file, mode, context, config): super(GCTestCase, self).__init__(context, path, mode) self.file = file self.config = config self.mode = mode self.tmpdir = join(dirname(self.config.root), 'tmp') def AfterRun(self, result): # delete the whole tmp dir try: rmtree(self.tmpdir) except: pass # make it again. try: mkdir(self.tmpdir) except: pass def BeforeRun(self): # delete the whole tmp dir try: rmtree(self.tmpdir) except: pass # make it again. # intermittently fails on win32, so keep trying while not os.path.exists(self.tmpdir): try: mkdir(self.tmpdir) except: pass def GetLabel(self): return "%s %s" % (self.mode, self.GetName()) def GetName(self): return self.path[-1] def GetCommand(self): result = [self.config.context.GetVm(self.mode)] source = open(self.file).read() flags_match = FLAGS_PATTERN.search(source) if flags_match: result += flags_match.group(1).strip().split() files_match = FILES_PATTERN.search(source); additional_files = [] if files_match: additional_files += files_match.group(1).strip().split() for a_file in additional_files: result.append(join(dirname(self.config.root), '..', a_file)) result += ["--expose-gc"] result += [self.file] return result def GetSource(self): return open(self.file).read() class GCTestConfiguration(test.TestConfiguration): def __init__(self, context, root): super(GCTestConfiguration, self).__init__(context, root) def Ls(self, path): def SelectTest(name): return name.startswith('test-') and name.endswith('.js') return [f[:-3] for f in os.listdir(path) if SelectTest(f)] def ListTests(self, current_path, path, mode): all_tests = [current_path + [t] for t in self.Ls(join(self.root))] result = [] for test in all_tests: if self.Contains(path, test): file_path = join(self.root, reduce(join, test[1:], "") + ".js") result.append(GCTestCase(test, file_path, mode, self.context, self)) return result def GetBuildRequirements(self): return ['sample', 'sample=shell'] def GetTestStatus(self, sections, defs): status_file = join(self.root, 'gc.status') if exists(status_file): test.ReadConfigurationInto(status_file, sections, defs) def GetConfiguration(context, root): return GCTestConfiguration(context, root) node-v0.10.25~dfsg2/test/fixtures/0000755000000000000000000000000012270121457015445 5ustar rootrootnode-v0.10.25~dfsg2/test/fixtures/exit.js0000644000000000000000000000222212270121457016752 0ustar rootroot// Copyright Joyent, Inc. and other Node contributors. // // Permission is hereby granted, free of charge, to any person obtaining a // copy of this software and associated documentation files (the // "Software"), to deal in the Software without restriction, including // without limitation the rights to use, copy, modify, merge, publish, // distribute, sublicense, and/or sell copies of the Software, and to permit // persons to whom the Software is furnished to do so, subject to the // following conditions: // // The above copyright notice and this permission notice shall be included // in all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS // OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF // MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN // NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, // DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR // OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE // USE OR OTHER DEALINGS IN THE SOFTWARE. process.exit(process.argv[2] || 1); node-v0.10.25~dfsg2/test/fixtures/a.js0000644000000000000000000000267312270121457016233 0ustar rootroot// Copyright Joyent, Inc. and other Node contributors. // // Permission is hereby granted, free of charge, to any person obtaining a // copy of this software and associated documentation files (the // "Software"), to deal in the Software without restriction, including // without limitation the rights to use, copy, modify, merge, publish, // distribute, sublicense, and/or sell copies of the Software, and to permit // persons to whom the Software is furnished to do so, subject to the // following conditions: // // The above copyright notice and this permission notice shall be included // in all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS // OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF // MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN // NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, // DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR // OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE // USE OR OTHER DEALINGS IN THE SOFTWARE. var c = require('./b/c'); console.error('load fixtures/a.js'); var string = 'A'; exports.SomeClass = c.SomeClass; exports.A = function() { return string; }; exports.C = function() { return c.C(); }; exports.D = function() { return c.D(); }; exports.number = 42; process.on('exit', function() { string = 'A done'; }); node-v0.10.25~dfsg2/test/fixtures/throws_error2.js0000644000000000000000000000220712270121457020625 0ustar rootroot// Copyright Joyent, Inc. and other Node contributors. // // Permission is hereby granted, free of charge, to any person obtaining a // copy of this software and associated documentation files (the // "Software"), to deal in the Software without restriction, including // without limitation the rights to use, copy, modify, merge, publish, // distribute, sublicense, and/or sell copies of the Software, and to permit // persons to whom the Software is furnished to do so, subject to the // following conditions: // // The above copyright notice and this permission notice shall be included // in all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS // OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF // MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN // NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, // DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR // OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE // USE OR OTHER DEALINGS IN THE SOFTWARE. JSON.parse(undefined); node-v0.10.25~dfsg2/test/fixtures/empty/0000755000000000000000000000000012270121457016603 5ustar rootrootnode-v0.10.25~dfsg2/test/fixtures/empty/.gitkeep0000644000000000000000000000000012270121457020222 0ustar rootrootnode-v0.10.25~dfsg2/test/fixtures/break-in-module/0000755000000000000000000000000012270121457020420 5ustar rootrootnode-v0.10.25~dfsg2/test/fixtures/break-in-module/mod.js0000644000000000000000000000225412270121457021540 0ustar rootroot// Copyright Joyent, Inc. and other Node contributors. // // Permission is hereby granted, free of charge, to any person obtaining a // copy of this software and associated documentation files (the // "Software"), to deal in the Software without restriction, including // without limitation the rights to use, copy, modify, merge, publish, // distribute, sublicense, and/or sell copies of the Software, and to permit // persons to whom the Software is furnished to do so, subject to the // following conditions: // // The above copyright notice and this permission notice shall be included // in all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS // OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF // MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN // NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, // DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR // OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE // USE OR OTHER DEALINGS IN THE SOFTWARE. exports.hello = function() { return 'hello from module'; }; node-v0.10.25~dfsg2/test/fixtures/break-in-module/main.js0000644000000000000000000000010312270121457021674 0ustar rootrootvar mod = require('./mod.js'); mod.hello(); mod.hello(); debugger; node-v0.10.25~dfsg2/test/fixtures/foo0000644000000000000000000000002412270121457016147 0ustar rootroot exports.foo = "ok" node-v0.10.25~dfsg2/test/fixtures/child-process-spawn-node.js0000644000000000000000000000035212270121457022613 0ustar rootrootvar assert = require('assert'); function onmessage(m) { console.log('CHILD got message:', m); assert.ok(m.hello); process.removeListener('message', onmessage); } process.on('message', onmessage); process.send({ foo: 'bar' }); node-v0.10.25~dfsg2/test/fixtures/fixture.ini0000644000000000000000000000045012270121457017633 0ustar rootroot; a comment root=something url = http://example.com/?foo=bar [ the section with whitespace ] this has whitespace = yep ; and a comment; and then another just a flag, no value. [section] one=two Foo=Bar this=Your Mother! blank= [Section Two] something else=blah remove = whitespacenode-v0.10.25~dfsg2/test/fixtures/cycles/0000755000000000000000000000000012270121457016727 5ustar rootrootnode-v0.10.25~dfsg2/test/fixtures/cycles/root.js0000644000000000000000000000246312270121457020255 0ustar rootroot// Copyright Joyent, Inc. and other Node contributors. // // Permission is hereby granted, free of charge, to any person obtaining a // copy of this software and associated documentation files (the // "Software"), to deal in the Software without restriction, including // without limitation the rights to use, copy, modify, merge, publish, // distribute, sublicense, and/or sell copies of the Software, and to permit // persons to whom the Software is furnished to do so, subject to the // following conditions: // // The above copyright notice and this permission notice shall be included // in all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS // OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF // MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN // NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, // DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR // OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE // USE OR OTHER DEALINGS IN THE SOFTWARE. var foo = exports.foo = require('./folder/foo'); exports.hello = 'hello'; exports.sayHello = function() { return foo.hello(); }; exports.calledFromFoo = function() { return exports.hello; }; node-v0.10.25~dfsg2/test/fixtures/cycles/folder/0000755000000000000000000000000012270121457020202 5ustar rootrootnode-v0.10.25~dfsg2/test/fixtures/cycles/folder/foo.js0000644000000000000000000000232012270121457021320 0ustar rootroot// Copyright Joyent, Inc. and other Node contributors. // // Permission is hereby granted, free of charge, to any person obtaining a // copy of this software and associated documentation files (the // "Software"), to deal in the Software without restriction, including // without limitation the rights to use, copy, modify, merge, publish, // distribute, sublicense, and/or sell copies of the Software, and to permit // persons to whom the Software is furnished to do so, subject to the // following conditions: // // The above copyright notice and this permission notice shall be included // in all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS // OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF // MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN // NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, // DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR // OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE // USE OR OTHER DEALINGS IN THE SOFTWARE. var root = require('./../root'); exports.hello = function() { return root.calledFromFoo(); }; node-v0.10.25~dfsg2/test/fixtures/test_dsa_privkey.pem0000644000000000000000000000225412270121457021532 0ustar rootroot-----BEGIN DSA PRIVATE KEY----- MIIDPwIBAAKCAQEAiJCR40HCtA6pk864XhKceke8N4chlrpwcphAXpHwSQGHlv1J JFyjaPqugWtzwZH55g7qpIiT3fmg6V6PfzNfx4sQGlSjckZaN02WRUAacn0va6Ub wyYV7LZzuHlHzayHLl/btGeTF+zL+9eMLKfll+r+5bJXDMWh3xUD1Nldf+fsIsbV ZI9QNzf3L1/07XVTLedQYaE77OqVuu+cfoBtb+K5MsQdHMMN20BGjKIvGkJICuC4 48GkDx1wpxz2vSJEi6FqXruM6c9yrPvhJKSfbVFYK2n82MMXMNNu9Dwqwsv6Ig6d IVywdKDrSw1Nz9j9TWA5BolNta3yMPHrEjCuIQIVAKq0ZZ0/36sZE1cqt6j0hZTi sWUVAoIBAFbI9MKn9DBJ7lo7+LRblgNKg9lk4D/6NBBRgOeCN4WnOxHQrqpSTUBG +VcABDKEfoHfEPI9KZKpEgpzGTpr7mGxDPLHfGL+vvf1EYbmcTDrUWlf9B/3+L3u wIddv3NYLepyEZ8L8g6eRGSQ4Svg1oSR/GAUTeGJczPg6qW0b/LTpf4eeDNWYGF6 aogJUphnPcZ0Xqw+yvq/i1uzAVirUxp9Crb7km0dfA0G/HBiSdcEt6l8LdQd6qmc L0nxcm9x6L+tSol5hXNynV0wcxdCQz4Xj5na+NoRGb9jPYxgLkoq07hwAkqkQDyF 61txfWgGc7zmh/x6JMGe/Xhg1TvgxLsCggEBAIXcOokkhVjC+i/I/grM9qTh6fCV jzSbOsIVi9Hfj7GCTRYA/QFnNbiWbOWzP7t2cEQFLfZoJmTK71+htZql9/GRMzV+ dnyhwuRh9YWkuCOlFHD7hDFBC+e1VqhV7ltaokqkZU18BsmgZG/fxeqOAfElEKLE 796rOAXmtx8F14Mn+IQteEAmifF1140C0bFzH67RSZU13pRCB7TKbruTevnhdQct LOzhgpMuoEWAjSWni5+WklOg/LxrMZ7MFz+Kqph1PxSX7kg/S8yCjNFtaviY7HrJ E7wUqi3Z/VPV4HKGeHzX1k1Z9RE/oJTsR2yT2rtJvSGO9lDk6Fj5tIv1fC8CFQCd 3V7C07NVeTiUU1WTP2nFNgMqEQ== -----END DSA PRIVATE KEY----- node-v0.10.25~dfsg2/test/fixtures/catch-stdout-error.js0000644000000000000000000000263612270121457021543 0ustar rootroot// Copyright Joyent, Inc. and other Node contributors. // // Permission is hereby granted, free of charge, to any person obtaining a // copy of this software and associated documentation files (the // "Software"), to deal in the Software without restriction, including // without limitation the rights to use, copy, modify, merge, publish, // distribute, sublicense, and/or sell copies of the Software, and to permit // persons to whom the Software is furnished to do so, subject to the // following conditions: // // The above copyright notice and this permission notice shall be included // in all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS // OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF // MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN // NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, // DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR // OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE // USE OR OTHER DEALINGS IN THE SOFTWARE. function write() { try { process.stdout.write('Hello, world\n'); } catch (ex) { throw new Error('this should never happen'); } setImmediate(function() { write(); }); } process.stdout.on('error', function(er) { console.error(JSON.stringify(er)); process.exit(42); }); write(); node-v0.10.25~dfsg2/test/fixtures/foafssl.key0000644000000000000000000000354012270121457017616 0ustar rootrootBag Attributes friendlyName: Me's Not a Certification Authority ID localKeyID: 98 CC 02 91 83 8D 14 4A 60 40 B7 11 E8 EF A9 01 4B D7 16 8A Key Attributes: -----BEGIN PRIVATE KEY----- MIIEvwIBADANBgkqhkiG9w0BAQEFAASCBKkwggSlAgEAAoIBAQCm9EqcJXkUMSFP XIevngQBd6i7iayAP34Ju8OlUZ80nNm5xAvkNtCqgjqUFH4myJJIraK+PdTTTowo lkaUsgR9IXtPEpk3Hqk6g8iauUQHJBMeZfKwFh3pVgzenBNFVVKy9Jzw+wDY13Uy MkkT9vgP8p0KEx0p2wav+L4ZG3kg3C2uHCbqgqR4R6EDke879qq7PMQP+CEAsDpP D/GAknjk3f2n3pVO1W3HrZpH7rw313GjZvxgpby3I3O+wYBkmz76DpCScHIQtBuQ Ayuxi8kfIEbr2vEZH0pOJtcYecTHhnti/NUI6M5m6C0SinHpFYCfz0To3ndAZ/He XXC5wDaHAgMBAAECggEAEhwrv7Zc5PDTYS1zVnx4iMQ3HGi5uouom1uvxE4PTAC7 qWf3tkCv798Cha+XY5OcMqALKEHCxU0e7QQoEdchn4UzQAePcSg1STCkYQw5seCa 5lA+vBUaF4aLDNa3TG0N9HWOVKGVnO/6OYC05qKClBBIMqCSKEkm942u6UBOql6q 71Sj1Nd/4eP9AcvgO5cgyUszM2I25LzXIZW7JLgdqXiJRj8CuY3X5FVURvadENgk ctw5EjdT7LNdc67Ot9Bs6qcVr2ld/U+4ZSC2+cqtPyn7mnA4hrYXlpA1Ilv3oRwZ aUJfG5HVV4jjNVHxDqddBh3UhOxJYZ1DNEMndTBx8QKBgQDcsrLfkE6utaj8w/of Hk/aq1JRNLgSvhoP2wVmK7USvYFj7DIvL4CqyghY5TLgNk272v8mT0Q7R6AtsOUk Gf50uZFAtIoPvTsvBu6cbRsPTeGJ0i1+LLme/AJu3MexXLF6mlzoGmlx8V7CoFqI 9hvqBA5rZ6ecoSjmU2q2xWKXKQKBgQDBqNqicSp2jnHiTXYbG/tsnxhFwALdEjvb EgZprmoBzo1eQFOY/DNBdDiEZBstu9mJBX3XWTU1F4c6tYRocNCMDwLBZAB6NnVM JjoddJApa5Qg3uoXmk53saZhcVkOzh+P/Dxg9c9O3q4DDUegnkM95ZSbCPtIBq6K bPA3OS+GLwKBgQCY0022LjGuHbFlRzg+sDjPzW71OLJ2mBln/VyhwYZj8cJVtUuT DSvmGHzrQduXE0OE4ENq/dzbx9+NhD9IXo+ruIxy6BHqkDkZeY1l2M+yK1YQn/BM vR/UjeIJbu0BTpS/t4C6YP+/nUrnLy9CRFpUFHb/vQl+FsNBq2XsJob88QKBgQCD 6B5bbNduf2HEsdxTZMDhYJAo2jtZFxVcBzAFBb7A0k7qNsh6OLY0zBO+4Wy9vujR 8sKfTuz157u9WmwAs27pJ0RKM3I7zCIjJxqIe5/CBruTlCJAx2LRFljsoEb31aAb 88Owi12ULAq8m2wBVCsa2uhYnUqC6cIzGTaZdsMPEwKBgQDJXI+J2d36IWzFrByH yskssFldbLxm/7EexzAYuoSpHuQIxGJYHTHn6CZhqrX8UbxVnS909ES+17kdLZVP egvaxn1mtfZInnH64PiQDQrsNnbP4Zg8yvLvIcEVIPqnSQ5QrhdR29tjYuDwUIKM 4BMR2yfkFp6URRX7ZD1UQsduww== -----END PRIVATE KEY----- node-v0.10.25~dfsg2/test/fixtures/net-fd-passing-receiver.js0000644000000000000000000000354712270121457022435 0ustar rootroot// Copyright Joyent, Inc. and other Node contributors. // // Permission is hereby granted, free of charge, to any person obtaining a // copy of this software and associated documentation files (the // "Software"), to deal in the Software without restriction, including // without limitation the rights to use, copy, modify, merge, publish, // distribute, sublicense, and/or sell copies of the Software, and to permit // persons to whom the Software is furnished to do so, subject to the // following conditions: // // The above copyright notice and this permission notice shall be included // in all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS // OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF // MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN // NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, // DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR // OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE // USE OR OTHER DEALINGS IN THE SOFTWARE. process.mixin(require('../common')); net = require('net'); path = process.ARGV[2]; greeting = process.ARGV[3]; receiver = net.createServer(function(socket) { socket.on('fd', function(fd) { var peerInfo = process.getpeername(fd); peerInfo.fd = fd; var passedSocket = new net.Socket(peerInfo); passedSocket.on('eof', function() { passedSocket.close(); }); passedSocket.on('data', function(data) { passedSocket.send('[echo] ' + data); }); passedSocket.on('close', function() { receiver.close(); }); passedSocket.send('[greeting] ' + greeting); }); }); /* To signal the test runne we're up and listening */ receiver.on('listening', function() { common.print('ready'); }); receiver.listen(path); node-v0.10.25~dfsg2/test/fixtures/registerExt.test0000644000000000000000000000002612270121457020651 0ustar rootrootthis is custom source node-v0.10.25~dfsg2/test/fixtures/test_dsa_params.pem0000644000000000000000000000144412270121457021324 0ustar rootroot-----BEGIN DSA PARAMETERS----- MIICIAKCAQEAiJCR40HCtA6pk864XhKceke8N4chlrpwcphAXpHwSQGHlv1JJFyj aPqugWtzwZH55g7qpIiT3fmg6V6PfzNfx4sQGlSjckZaN02WRUAacn0va6UbwyYV 7LZzuHlHzayHLl/btGeTF+zL+9eMLKfll+r+5bJXDMWh3xUD1Nldf+fsIsbVZI9Q Nzf3L1/07XVTLedQYaE77OqVuu+cfoBtb+K5MsQdHMMN20BGjKIvGkJICuC448Gk Dx1wpxz2vSJEi6FqXruM6c9yrPvhJKSfbVFYK2n82MMXMNNu9Dwqwsv6Ig6dIVyw dKDrSw1Nz9j9TWA5BolNta3yMPHrEjCuIQIVAKq0ZZ0/36sZE1cqt6j0hZTisWUV AoIBAFbI9MKn9DBJ7lo7+LRblgNKg9lk4D/6NBBRgOeCN4WnOxHQrqpSTUBG+VcA BDKEfoHfEPI9KZKpEgpzGTpr7mGxDPLHfGL+vvf1EYbmcTDrUWlf9B/3+L3uwIdd v3NYLepyEZ8L8g6eRGSQ4Svg1oSR/GAUTeGJczPg6qW0b/LTpf4eeDNWYGF6aogJ UphnPcZ0Xqw+yvq/i1uzAVirUxp9Crb7km0dfA0G/HBiSdcEt6l8LdQd6qmcL0nx cm9x6L+tSol5hXNynV0wcxdCQz4Xj5na+NoRGb9jPYxgLkoq07hwAkqkQDyF61tx fWgGc7zmh/x6JMGe/Xhg1TvgxLs= -----END DSA PARAMETERS----- node-v0.10.25~dfsg2/test/fixtures/test-init-index/0000755000000000000000000000000012270121457020472 5ustar rootrootnode-v0.10.25~dfsg2/test/fixtures/test-init-index/index.js0000644000000000000000000000226412270121457022143 0ustar rootroot// Copyright Joyent, Inc. and other Node contributors. // // Permission is hereby granted, free of charge, to any person obtaining a // copy of this software and associated documentation files (the // "Software"), to deal in the Software without restriction, including // without limitation the rights to use, copy, modify, merge, publish, // distribute, sublicense, and/or sell copies of the Software, and to permit // persons to whom the Software is furnished to do so, subject to the // following conditions: // // The above copyright notice and this permission notice shall be included // in all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS // OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF // MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN // NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, // DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR // OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE // USE OR OTHER DEALINGS IN THE SOFTWARE. (function() { require('util').print('Loaded successfully!'); })(); node-v0.10.25~dfsg2/test/fixtures/test_dsa_pubkey.pem0000644000000000000000000000223212270121457021334 0ustar rootroot-----BEGIN PUBLIC KEY----- MIIDOzCCAi0GByqGSM44BAEwggIgAoIBAQCIkJHjQcK0DqmTzrheEpx6R7w3hyGW unBymEBekfBJAYeW/UkkXKNo+q6Ba3PBkfnmDuqkiJPd+aDpXo9/M1/HixAaVKNy Rlo3TZZFQBpyfS9rpRvDJhXstnO4eUfNrIcuX9u0Z5MX7Mv714wsp+WX6v7lslcM xaHfFQPU2V1/5+wixtVkj1A3N/cvX/TtdVMt51BhoTvs6pW675x+gG1v4rkyxB0c ww3bQEaMoi8aQkgK4LjjwaQPHXCnHPa9IkSLoWpeu4zpz3Ks++EkpJ9tUVgrafzY wxcw0270PCrCy/oiDp0hXLB0oOtLDU3P2P1NYDkGiU21rfIw8esSMK4hAhUAqrRl nT/fqxkTVyq3qPSFlOKxZRUCggEAVsj0wqf0MEnuWjv4tFuWA0qD2WTgP/o0EFGA 54I3hac7EdCuqlJNQEb5VwAEMoR+gd8Q8j0pkqkSCnMZOmvuYbEM8sd8Yv6+9/UR huZxMOtRaV/0H/f4ve7Ah12/c1gt6nIRnwvyDp5EZJDhK+DWhJH8YBRN4YlzM+Dq pbRv8tOl/h54M1ZgYXpqiAlSmGc9xnRerD7K+r+LW7MBWKtTGn0KtvuSbR18DQb8 cGJJ1wS3qXwt1B3qqZwvSfFyb3Hov61KiXmFc3KdXTBzF0JDPhePmdr42hEZv2M9 jGAuSirTuHACSqRAPIXrW3F9aAZzvOaH/HokwZ79eGDVO+DEuwOCAQYAAoIBAQCF 3DqJJIVYwvovyP4KzPak4enwlY80mzrCFYvR34+xgk0WAP0BZzW4lmzlsz+7dnBE BS32aCZkyu9fobWapffxkTM1fnZ8ocLkYfWFpLgjpRRw+4QxQQvntVaoVe5bWqJK pGVNfAbJoGRv38XqjgHxJRCixO/eqzgF5rcfBdeDJ/iELXhAJonxddeNAtGxcx+u 0UmVNd6UQge0ym67k3r54XUHLSzs4YKTLqBFgI0lp4uflpJToPy8azGezBc/iqqY dT8Ul+5IP0vMgozRbWr4mOx6yRO8FKot2f1T1eByhnh819ZNWfURP6CU7Edsk9q7 Sb0hjvZQ5OhY+bSL9Xwv -----END PUBLIC KEY----- node-v0.10.25~dfsg2/test/fixtures/alice.crt0000644000000000000000000000262412270121457017240 0ustar rootroot-----BEGIN CERTIFICATE----- MIID8DCCAtigAwIBAgIJALmw0zKhqlY1MA0GCSqGSIb3DQEBBQUAMFgxDjAMBgNV BAMTBWFsaWNlMUYwRAYDVR0RFD11bmlmb3JtUmVzb3VyY2VJZGVudGlmaWVyOmh0 dHA6Ly9sb2NhbGhvc3Q6ODAwMC9hbGljZS5mb2FmI21lMB4XDTExMDgyNDA1NTUx NFoXDTExMDkyMzA1NTUxNFowWDEOMAwGA1UEAxMFYWxpY2UxRjBEBgNVHREUPXVu aWZvcm1SZXNvdXJjZUlkZW50aWZpZXI6aHR0cDovL2xvY2FsaG9zdDo4MDAwL2Fs aWNlLmZvYWYjbWUwggEiMA0GCSqGSIb3DQEBAQUAA4IBDwAwggEKAoIBAQDP4tdk 6NxAImrf5kpQVpuPvWij97H9ewFwWq0FOGONPD0JURXB89BCnhfC0+IHbTi+dhfB DX9HY11NCoJm7juXv0uywv+7Zrlj37Q0RTedADmp237UUATRzmh7E+KZc6tHcZZ8 rPs+ZnY7TXXsh4JRRc8blTy6aEN7/iYMXhk0mIpzjTha2Gq5OqBLustBkeFnoPQS cac6TOWbEkxg80dI5jX/qK901RRwLztrA0QDeWB+HLbkjIErdAlz5pgo1Nu3vQt6 vLdu7bBYsUa2Y2IaVBNLgmzEiZGwQJMjvbs5tLv8VYBCypb4I4vRJrkG4wWsUimM +sR7SKHu9FFt2ZdHAgMBAAGjgbwwgbkwHQYDVR0OBBYEFA51eHepg7Tp5bi6Ao5F B01/5+GoMIGJBgNVHSMEgYEwf4AUDnV4d6mDtOnluLoCjkUHTX/n4aihXKRaMFgx DjAMBgNVBAMTBWFsaWNlMUYwRAYDVR0RFD11bmlmb3JtUmVzb3VyY2VJZGVudGlm aWVyOmh0dHA6Ly9sb2NhbGhvc3Q6ODAwMC9hbGljZS5mb2FmI21lggkAubDTMqGq VjUwDAYDVR0TBAUwAwEB/zANBgkqhkiG9w0BAQUFAAOCAQEAreudH4Y7R9Vl2GJo 2xRUEwZiMj/ogomZ7B+IZtcuMIR8X2mzQ30xmPKaCy/fjbueqBroIDdxFeQ4eWZf MD3AK/q5lJXwSInDjnn7jE9gNgLdQeCnajV0/QH+eDxIe/Alvx+RuvrDiNOudEs4 vhqv5zEaL6VEXoWVb4/cghDbynQucSpyOMmGGPYYw2zmg0nNXdQauYWDUZIaDwQ6 tM/pi2ewYubHPZdwJv5jvxTN3Z7RuuGHM+aLAZSAqSgAi0ml8PYYd2eRzXMaEI0c eajcEvVa405aYT6dxuF1qqRDYx14As/R7O5RKCpz7wsxD6ICD/Ynv3GCUGxANQim bcCjpg== -----END CERTIFICATE----- node-v0.10.25~dfsg2/test/fixtures/test_cert.pem0000644000000000000000000000231012270121457020140 0ustar rootroot-----BEGIN CERTIFICATE----- MIIDXDCCAsWgAwIBAgIJAKL0UG+mRkSPMA0GCSqGSIb3DQEBBQUAMH0xCzAJBgNV BAYTAlVLMRQwEgYDVQQIEwtBY2tuYWNrIEx0ZDETMBEGA1UEBxMKUmh5cyBKb25l czEQMA4GA1UEChMHbm9kZS5qczEdMBsGA1UECxMUVGVzdCBUTFMgQ2VydGlmaWNh dGUxEjAQBgNVBAMTCWxvY2FsaG9zdDAeFw0wOTExMTEwOTUyMjJaFw0yOTExMDYw OTUyMjJaMH0xCzAJBgNVBAYTAlVLMRQwEgYDVQQIEwtBY2tuYWNrIEx0ZDETMBEG A1UEBxMKUmh5cyBKb25lczEQMA4GA1UEChMHbm9kZS5qczEdMBsGA1UECxMUVGVz dCBUTFMgQ2VydGlmaWNhdGUxEjAQBgNVBAMTCWxvY2FsaG9zdDCBnzANBgkqhkiG 9w0BAQEFAAOBjQAwgYkCgYEA8d8Hc6atq78Jt1HLp9agA/wpQfsFvkYUdZ1YsdvO kL2janjwHQgMMCy/Njal3FUEW0OLPebKZUJ8L44JBXSlVxU4zyiiSOWld8EkTetR AVT3WKQq3ud+cnxv7g8rGRQp1UHZwmdbZ1wEfAYq8QjYx6m1ciMgRo7DaDQhD29k d+UCAwEAAaOB4zCB4DAdBgNVHQ4EFgQUL9miTJn+HKNuTmx/oMWlZP9cd4QwgbAG A1UdIwSBqDCBpYAUL9miTJn+HKNuTmx/oMWlZP9cd4ShgYGkfzB9MQswCQYDVQQG EwJVSzEUMBIGA1UECBMLQWNrbmFjayBMdGQxEzARBgNVBAcTClJoeXMgSm9uZXMx EDAOBgNVBAoTB25vZGUuanMxHTAbBgNVBAsTFFRlc3QgVExTIENlcnRpZmljYXRl MRIwEAYDVQQDEwlsb2NhbGhvc3SCCQCi9FBvpkZEjzAMBgNVHRMEBTADAQH/MA0G CSqGSIb3DQEBBQUAA4GBADRXXA2xSUK5W1i3oLYWW6NEDVWkTQ9RveplyeS9MOkP e7yPcpz0+O0ZDDrxR9chAiZ7fmdBBX1Tr+pIuCrG/Ud49SBqeS5aMJGVwiSd7o1n dhU2Sz3Q60DwJEL1VenQHiVYlWWtqXBThe9ggqRPnCfsCRTP8qifKkjk45zWPcpN -----END CERTIFICATE----- node-v0.10.25~dfsg2/test/fixtures/GH-1899-output.js0000644000000000000000000000221512270121457020247 0ustar rootroot// Copyright Joyent, Inc. and other Node contributors. // // Permission is hereby granted, free of charge, to any person obtaining a // copy of this software and associated documentation files (the // "Software"), to deal in the Software without restriction, including // without limitation the rights to use, copy, modify, merge, publish, // distribute, sublicense, and/or sell copies of the Software, and to permit // persons to whom the Software is furnished to do so, subject to the // following conditions: // // The above copyright notice and this permission notice shall be included // in all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS // OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF // MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN // NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, // DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR // OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE // USE OR OTHER DEALINGS IN THE SOFTWARE. console.log('hello, world!'); node-v0.10.25~dfsg2/test/fixtures/foafssl.crt0000644000000000000000000000277712270121457017631 0ustar rootrootBag Attributes friendlyName: Me's Not a Certification Authority ID localKeyID: 98 CC 02 91 83 8D 14 4A 60 40 B7 11 E8 EF A9 01 4B D7 16 8A subject=/O=FOAF+SSL/OU=The Community Of Self Signers/UID=http://example.com/#me/CN=Me issuer=/O=FOAF+SSL/OU=The Community of Self Signers/CN=Not a Certification Authority -----BEGIN CERTIFICATE----- MIIDVDCCAr2gAwIBAgIQRLIhwZ2N3ciEdpWb6kPmPzANBgkqhkiG9w0BAQUFADBj MREwDwYDVQQKDAhGT0FGK1NTTDEmMCQGA1UECwwdVGhlIENvbW11bml0eSBvZiBT ZWxmIFNpZ25lcnMxJjAkBgNVBAMMHU5vdCBhIENlcnRpZmljYXRpb24gQXV0aG9y aXR5MB4XDTExMDgzMDE3MzIwNFoXDTEyMDgyMDE5MzIwNFowcDERMA8GA1UECgwI Rk9BRitTU0wxJjAkBgNVBAsMHVRoZSBDb21tdW5pdHkgT2YgU2VsZiBTaWduZXJz MSYwJAYKCZImiZPyLGQBAQwWaHR0cDovL2V4YW1wbGUuY29tLyNtZTELMAkGA1UE AwwCTWUwggEiMA0GCSqGSIb3DQEBAQUAA4IBDwAwggEKAoIBAQCm9EqcJXkUMSFP XIevngQBd6i7iayAP34Ju8OlUZ80nNm5xAvkNtCqgjqUFH4myJJIraK+PdTTTowo lkaUsgR9IXtPEpk3Hqk6g8iauUQHJBMeZfKwFh3pVgzenBNFVVKy9Jzw+wDY13Uy MkkT9vgP8p0KEx0p2wav+L4ZG3kg3C2uHCbqgqR4R6EDke879qq7PMQP+CEAsDpP D/GAknjk3f2n3pVO1W3HrZpH7rw313GjZvxgpby3I3O+wYBkmz76DpCScHIQtBuQ Ayuxi8kfIEbr2vEZH0pOJtcYecTHhnti/NUI6M5m6C0SinHpFYCfz0To3ndAZ/He XXC5wDaHAgMBAAGjeDB2MAwGA1UdEwEB/wQCMAAwDgYDVR0PAQH/BAQDAgLsMBEG CWCGSAGG+EIBAQQEAwIFoDAdBgNVHQ4EFgQU3gJIUFpe8rKklsjEdsxlaT6rZhow JAYDVR0RAQH/BBowGIYWaHR0cDovL2V4YW1wbGUuY29tLyNtZTANBgkqhkiG9w0B AQUFAAOBgQBLhwWbYMdeSkVZ4biVUle+XHP4Gv8V9WSfldvgn1PntS1lpVR46Exl AkLO1SrnN5WHeAjv6VNb3KmTF+QhLt/4a1l9CEEeZSg5ml5aeXE+veobgypDoam+ NKYAeIW9Wx+HcgBL4leIX3WiCKu/eal+a5ro18LQ8hkZqryHeVESIw== -----END CERTIFICATE----- node-v0.10.25~dfsg2/test/fixtures/multi-alice.crt0000644000000000000000000000244212270121457020366 0ustar rootroot-----BEGIN CERTIFICATE----- MIIDnjCCAoYCCQCXooHS0l6bHDANBgkqhkiG9w0BAQUFADCBkDELMAkGA1UEBhMC QVUxEzARBgNVBAgMClNvbWUtU3RhdGUxITAfBgNVBAoMGEludGVybmV0IFdpZGdp dHMgUHR5IEx0ZDEfMB0GA1UECwwWSW5mb3JtYXRpb24gVGVjaG5vbG9neTEUMBIG A1UECwwLRW5naW5lZXJpbmcxEjAQBgNVBAsMCU1hcmtldGluZzAeFw0xMjAzMDQx NDA4MDVaFw0xMjA0MDMxNDA4MDVaMIGQMQswCQYDVQQGEwJBVTETMBEGA1UECAwK U29tZS1TdGF0ZTEhMB8GA1UECgwYSW50ZXJuZXQgV2lkZ2l0cyBQdHkgTHRkMR8w HQYDVQQLDBZJbmZvcm1hdGlvbiBUZWNobm9sb2d5MRQwEgYDVQQLDAtFbmdpbmVl cmluZzESMBAGA1UECwwJTWFya2V0aW5nMIIBIjANBgkqhkiG9w0BAQEFAAOCAQ8A MIIBCgKCAQEAz+LXZOjcQCJq3+ZKUFabj71oo/ex/XsBcFqtBThjjTw9CVEVwfPQ Qp4XwtPiB204vnYXwQ1/R2NdTQqCZu47l79LssL/u2a5Y9+0NEU3nQA5qdt+1FAE 0c5oexPimXOrR3GWfKz7PmZ2O0117IeCUUXPG5U8umhDe/4mDF4ZNJiKc404Wthq uTqgS7rLQZHhZ6D0EnGnOkzlmxJMYPNHSOY1/6ivdNUUcC87awNEA3lgfhy25IyB K3QJc+aYKNTbt70Lery3bu2wWLFGtmNiGlQTS4JsxImRsECTI727ObS7/FWAQsqW +COL0Sa5BuMFrFIpjPrEe0ih7vRRbdmXRwIDAQABMA0GCSqGSIb3DQEBBQUAA4IB AQC7kyzjGXy7SnT1tvefdvtdAtErDuD375/sB2l1V72+BNXlIlddmEC8IkAVSKg2 5Y7MuQ4yMsHlhrdUxj/XOOVMHY/49xsZiN5hF2jb2mdq7KdvlVMYqyf126bW2mOx cLVSiuucdp88zoJopWBUnNyVOYhh18St9bNosGgPzppGBCpL+MJvoSn3wrnFn8ER wwN1m3ga590wHa4fny+qlD/hJNww16wbwgdF9NqsuR/e+sj9ZsoIYRCF8iKBajzt 3o7cZIRlvGtJfJRM87YCAn4BR3JgQPXfbhx31KwtMXtAJNzOHk26bblW3jTC8c7+ Cu1gNEM083vUq6/UxJUM8lOM -----END CERTIFICATE----- node-v0.10.25~dfsg2/test/fixtures/registerExt.hello.world0000644000000000000000000000003012270121457022116 0ustar rootrootexports.test = 'passed' node-v0.10.25~dfsg2/test/fixtures/should_exit.js0000644000000000000000000000241512270121457020334 0ustar rootroot// Copyright Joyent, Inc. and other Node contributors. // // Permission is hereby granted, free of charge, to any person obtaining a // copy of this software and associated documentation files (the // "Software"), to deal in the Software without restriction, including // without limitation the rights to use, copy, modify, merge, publish, // distribute, sublicense, and/or sell copies of the Software, and to permit // persons to whom the Software is furnished to do so, subject to the // following conditions: // // The above copyright notice and this permission notice shall be included // in all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS // OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF // MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN // NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, // DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR // OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE // USE OR OTHER DEALINGS IN THE SOFTWARE. function tmp() {} process.on('SIGINT', tmp); process.removeListener('SIGINT', tmp); setInterval(function() { process.stdout.write('keep alive\n'); }, 1000); node-v0.10.25~dfsg2/test/fixtures/pass-cert.pem0000644000000000000000000000127412270121457020055 0ustar rootroot-----BEGIN CERTIFICATE----- MIIB2TCCAUICCQDQv9q5AAtoEzANBgkqhkiG9w0BAQUFADAxMQswCQYDVQQGEwJK UDEOMAwGA1UECBMFVG9reW8xEjAQBgNVBAoUCW5vZGVqc19qcDAeFw0xMTExMjYx NzA0MDhaFw0yMTExMjMxNzA0MDhaMDExCzAJBgNVBAYTAkpQMQ4wDAYDVQQIEwVU b2t5bzESMBAGA1UEChQJbm9kZWpzX2pwMIGfMA0GCSqGSIb3DQEBAQUAA4GNADCB iQKBgQChmQeFwsaomtQbw9Nm55Dn6KSR9bkY8PDroQUeTNa90BlIbhGsKYm4l7bE RaasFgOrkcQpk45fdDVYPjKxraZiGXXKjSIDYeDAIC/+CkwQKrejgCPmJs4gV4g+ npvwi1gVr2NAg7fkJOyEW2TDp4dsAD8qtG8Aml0C1hJXwFYmBwIDAQABMA0GCSqG SIb3DQEBBQUAA4GBAGJYkr3VgHUZSyGrdUWeGKiKS4EY3D4ki8Luv9Jf/IpxJLbZ NGaKUbXSVYSW3US0yR1+lsNvWchmc0wLsbNEHbIiS4BQPkqX7F8FCthM1gwRLQPa Sofz3dRNFKDmivG9mdbQDPD/duft7Kn6E3JS5myYUJ0dRKeYfOXLXCY2pZpG -----END CERTIFICATE----- node-v0.10.25~dfsg2/test/fixtures/module-load-order/0000755000000000000000000000000012270121457020760 5ustar rootrootnode-v0.10.25~dfsg2/test/fixtures/module-load-order/file6/0000755000000000000000000000000012270121457021765 5ustar rootrootnode-v0.10.25~dfsg2/test/fixtures/module-load-order/file6/index.reg20000644000000000000000000000004412270121457023653 0ustar rootrootexports.file6 = 'file6/index.reg2'; node-v0.10.25~dfsg2/test/fixtures/module-load-order/file6/index.node0000644000000000000000000000004412270121457023741 0ustar rootrootexports.file6 = 'file6/index.node'; node-v0.10.25~dfsg2/test/fixtures/module-load-order/file6/index.reg0000644000000000000000000000004312270121457023570 0ustar rootrootexports.file6 = 'file6/index.reg'; node-v0.10.25~dfsg2/test/fixtures/module-load-order/file6/index.js0000644000000000000000000000222012270121457023426 0ustar rootroot// Copyright Joyent, Inc. and other Node contributors. // // Permission is hereby granted, free of charge, to any person obtaining a // copy of this software and associated documentation files (the // "Software"), to deal in the Software without restriction, including // without limitation the rights to use, copy, modify, merge, publish, // distribute, sublicense, and/or sell copies of the Software, and to permit // persons to whom the Software is furnished to do so, subject to the // following conditions: // // The above copyright notice and this permission notice shall be included // in all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS // OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF // MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN // NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, // DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR // OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE // USE OR OTHER DEALINGS IN THE SOFTWARE. exports.file6 = 'file6/index.js'; node-v0.10.25~dfsg2/test/fixtures/module-load-order/file4.reg20000644000000000000000000000003612270121457022543 0ustar rootrootexports.file4 = 'file4.reg2'; node-v0.10.25~dfsg2/test/fixtures/module-load-order/file1.node0000644000000000000000000000003612270121457022626 0ustar rootrootexports.file1 = 'file1.node'; node-v0.10.25~dfsg2/test/fixtures/module-load-order/file5.reg20000644000000000000000000000003612270121457022544 0ustar rootrootexports.file5 = 'file5.reg2'; node-v0.10.25~dfsg2/test/fixtures/module-load-order/file3/0000755000000000000000000000000012270121457021762 5ustar rootrootnode-v0.10.25~dfsg2/test/fixtures/module-load-order/file3/index.reg20000644000000000000000000000004412270121457023650 0ustar rootrootexports.file3 = 'file3/index.reg2'; node-v0.10.25~dfsg2/test/fixtures/module-load-order/file3/index.node0000644000000000000000000000004412270121457023736 0ustar rootrootexports.file3 = 'file3/index.node'; node-v0.10.25~dfsg2/test/fixtures/module-load-order/file3/index.reg0000644000000000000000000000004312270121457023565 0ustar rootrootexports.file3 = 'file3/index.reg'; node-v0.10.25~dfsg2/test/fixtures/module-load-order/file3/index.js0000644000000000000000000000222012270121457023423 0ustar rootroot// Copyright Joyent, Inc. and other Node contributors. // // Permission is hereby granted, free of charge, to any person obtaining a // copy of this software and associated documentation files (the // "Software"), to deal in the Software without restriction, including // without limitation the rights to use, copy, modify, merge, publish, // distribute, sublicense, and/or sell copies of the Software, and to permit // persons to whom the Software is furnished to do so, subject to the // following conditions: // // The above copyright notice and this permission notice shall be included // in all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS // OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF // MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN // NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, // DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR // OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE // USE OR OTHER DEALINGS IN THE SOFTWARE. exports.file3 = 'file3/index.js'; node-v0.10.25~dfsg2/test/fixtures/module-load-order/file4.reg0000644000000000000000000000003512270121457022460 0ustar rootrootexports.file4 = 'file4.reg'; node-v0.10.25~dfsg2/test/fixtures/module-load-order/file1.js0000644000000000000000000000221212270121457022313 0ustar rootroot// Copyright Joyent, Inc. and other Node contributors. // // Permission is hereby granted, free of charge, to any person obtaining a // copy of this software and associated documentation files (the // "Software"), to deal in the Software without restriction, including // without limitation the rights to use, copy, modify, merge, publish, // distribute, sublicense, and/or sell copies of the Software, and to permit // persons to whom the Software is furnished to do so, subject to the // following conditions: // // The above copyright notice and this permission notice shall be included // in all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS // OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF // MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN // NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, // DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR // OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE // USE OR OTHER DEALINGS IN THE SOFTWARE. exports.file1 = 'file1.js'; node-v0.10.25~dfsg2/test/fixtures/module-load-order/file2/0000755000000000000000000000000012270121457021761 5ustar rootrootnode-v0.10.25~dfsg2/test/fixtures/module-load-order/file2/index.reg20000644000000000000000000000004412270121457023647 0ustar rootrootexports.file2 = 'file2/index.reg2'; node-v0.10.25~dfsg2/test/fixtures/module-load-order/file2/index.node0000644000000000000000000000004412270121457023735 0ustar rootrootexports.file2 = 'file2/index.node'; node-v0.10.25~dfsg2/test/fixtures/module-load-order/file2/index.reg0000644000000000000000000000004312270121457023564 0ustar rootrootexports.file2 = 'file2/index.reg'; node-v0.10.25~dfsg2/test/fixtures/module-load-order/file2/index.js0000644000000000000000000000222012270121457023422 0ustar rootroot// Copyright Joyent, Inc. and other Node contributors. // // Permission is hereby granted, free of charge, to any person obtaining a // copy of this software and associated documentation files (the // "Software"), to deal in the Software without restriction, including // without limitation the rights to use, copy, modify, merge, publish, // distribute, sublicense, and/or sell copies of the Software, and to permit // persons to whom the Software is furnished to do so, subject to the // following conditions: // // The above copyright notice and this permission notice shall be included // in all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS // OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF // MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN // NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, // DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR // OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE // USE OR OTHER DEALINGS IN THE SOFTWARE. exports.file2 = 'file2/index.js'; node-v0.10.25~dfsg2/test/fixtures/module-load-order/file2.js0000644000000000000000000000221212270121457022314 0ustar rootroot// Copyright Joyent, Inc. and other Node contributors. // // Permission is hereby granted, free of charge, to any person obtaining a // copy of this software and associated documentation files (the // "Software"), to deal in the Software without restriction, including // without limitation the rights to use, copy, modify, merge, publish, // distribute, sublicense, and/or sell copies of the Software, and to permit // persons to whom the Software is furnished to do so, subject to the // following conditions: // // The above copyright notice and this permission notice shall be included // in all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS // OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF // MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN // NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, // DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR // OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE // USE OR OTHER DEALINGS IN THE SOFTWARE. exports.file2 = 'file2.js'; node-v0.10.25~dfsg2/test/fixtures/module-load-order/file2.node0000644000000000000000000000003612270121457022627 0ustar rootrootexports.file2 = 'file2.node'; node-v0.10.25~dfsg2/test/fixtures/module-load-order/file1.reg20000644000000000000000000000003612270121457022540 0ustar rootrootexports.file1 = 'file1.reg2'; node-v0.10.25~dfsg2/test/fixtures/module-load-order/file9/0000755000000000000000000000000012270121457021770 5ustar rootrootnode-v0.10.25~dfsg2/test/fixtures/module-load-order/file9/index.reg20000644000000000000000000000004412270121457023656 0ustar rootrootexports.file9 = 'file9/index.reg2'; node-v0.10.25~dfsg2/test/fixtures/module-load-order/file3.reg20000644000000000000000000000003612270121457022542 0ustar rootrootexports.file3 = 'file3.reg2'; node-v0.10.25~dfsg2/test/fixtures/module-load-order/file2.reg0000644000000000000000000000003512270121457022456 0ustar rootrootexports.file2 = 'file2.reg'; node-v0.10.25~dfsg2/test/fixtures/module-load-order/file1.reg0000644000000000000000000000003512270121457022455 0ustar rootrootexports.file1 = 'file1.reg'; node-v0.10.25~dfsg2/test/fixtures/module-load-order/file2.reg20000644000000000000000000000003612270121457022541 0ustar rootrootexports.file2 = 'file2.reg2'; node-v0.10.25~dfsg2/test/fixtures/module-load-order/file5/0000755000000000000000000000000012270121457021764 5ustar rootrootnode-v0.10.25~dfsg2/test/fixtures/module-load-order/file5/index.reg20000644000000000000000000000004412270121457023652 0ustar rootrootexports.file5 = 'file5/index.reg2'; node-v0.10.25~dfsg2/test/fixtures/module-load-order/file5/index.node0000644000000000000000000000004412270121457023740 0ustar rootrootexports.file5 = 'file5/index.node'; node-v0.10.25~dfsg2/test/fixtures/module-load-order/file5/index.reg0000644000000000000000000000004312270121457023567 0ustar rootrootexports.file5 = 'file5/index.reg'; node-v0.10.25~dfsg2/test/fixtures/module-load-order/file5/index.js0000644000000000000000000000222012270121457023425 0ustar rootroot// Copyright Joyent, Inc. and other Node contributors. // // Permission is hereby granted, free of charge, to any person obtaining a // copy of this software and associated documentation files (the // "Software"), to deal in the Software without restriction, including // without limitation the rights to use, copy, modify, merge, publish, // distribute, sublicense, and/or sell copies of the Software, and to permit // persons to whom the Software is furnished to do so, subject to the // following conditions: // // The above copyright notice and this permission notice shall be included // in all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS // OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF // MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN // NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, // DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR // OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE // USE OR OTHER DEALINGS IN THE SOFTWARE. exports.file5 = 'file5/index.js'; node-v0.10.25~dfsg2/test/fixtures/module-load-order/file10000644000000000000000000000003112270121457021675 0ustar rootrootexports.file1 = 'file1'; node-v0.10.25~dfsg2/test/fixtures/module-load-order/file8/0000755000000000000000000000000012270121457021767 5ustar rootrootnode-v0.10.25~dfsg2/test/fixtures/module-load-order/file8/index.reg20000644000000000000000000000004412270121457023655 0ustar rootrootexports.file8 = 'file8/index.reg2'; node-v0.10.25~dfsg2/test/fixtures/module-load-order/file8/index.reg0000644000000000000000000000004312270121457023572 0ustar rootrootexports.file8 = 'file8/index.reg'; node-v0.10.25~dfsg2/test/fixtures/module-load-order/file7/0000755000000000000000000000000012270121457021766 5ustar rootrootnode-v0.10.25~dfsg2/test/fixtures/module-load-order/file7/index.reg20000644000000000000000000000004412270121457023654 0ustar rootrootexports.file7 = 'file7/index.reg2'; node-v0.10.25~dfsg2/test/fixtures/module-load-order/file7/index.node0000644000000000000000000000004412270121457023742 0ustar rootrootexports.file7 = 'file7/index.node'; node-v0.10.25~dfsg2/test/fixtures/module-load-order/file7/index.reg0000644000000000000000000000004312270121457023571 0ustar rootrootexports.file7 = 'file7/index.reg'; node-v0.10.25~dfsg2/test/fixtures/module-load-order/file3.node0000644000000000000000000000003612270121457022630 0ustar rootrootexports.file3 = 'file3.node'; node-v0.10.25~dfsg2/test/fixtures/module-load-order/file4/0000755000000000000000000000000012270121457021763 5ustar rootrootnode-v0.10.25~dfsg2/test/fixtures/module-load-order/file4/index.reg20000644000000000000000000000004412270121457023651 0ustar rootrootexports.file4 = 'file4/index.reg2'; node-v0.10.25~dfsg2/test/fixtures/module-load-order/file4/index.node0000644000000000000000000000004412270121457023737 0ustar rootrootexports.file4 = 'file4/index.node'; node-v0.10.25~dfsg2/test/fixtures/module-load-order/file4/index.reg0000644000000000000000000000004312270121457023566 0ustar rootrootexports.file4 = 'file4/index.reg'; node-v0.10.25~dfsg2/test/fixtures/module-load-order/file4/index.js0000644000000000000000000000222012270121457023424 0ustar rootroot// Copyright Joyent, Inc. and other Node contributors. // // Permission is hereby granted, free of charge, to any person obtaining a // copy of this software and associated documentation files (the // "Software"), to deal in the Software without restriction, including // without limitation the rights to use, copy, modify, merge, publish, // distribute, sublicense, and/or sell copies of the Software, and to permit // persons to whom the Software is furnished to do so, subject to the // following conditions: // // The above copyright notice and this permission notice shall be included // in all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS // OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF // MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN // NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, // DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR // OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE // USE OR OTHER DEALINGS IN THE SOFTWARE. exports.file4 = 'file4/index.js'; node-v0.10.25~dfsg2/test/fixtures/module-load-order/file3.reg0000644000000000000000000000003512270121457022457 0ustar rootrootexports.file3 = 'file3.reg'; node-v0.10.25~dfsg2/test/fixtures/breakpoints.js0000644000000000000000000000034712270121457020330 0ustar rootrootdebugger; function a(x) { var i = 10; while (--i != 0); debugger; return i; } function b() { return ['hello', 'world'].join(' '); } a(); a(1); b(); b(); setInterval(function() { }, 5000); now = new Date(); debugger; node-v0.10.25~dfsg2/test/fixtures/stdio-filter.js0000644000000000000000000000261112270121457020410 0ustar rootroot// Copyright Joyent, Inc. and other Node contributors. // // Permission is hereby granted, free of charge, to any person obtaining a // copy of this software and associated documentation files (the // "Software"), to deal in the Software without restriction, including // without limitation the rights to use, copy, modify, merge, publish, // distribute, sublicense, and/or sell copies of the Software, and to permit // persons to whom the Software is furnished to do so, subject to the // following conditions: // // The above copyright notice and this permission notice shall be included // in all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS // OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF // MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN // NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, // DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR // OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE // USE OR OTHER DEALINGS IN THE SOFTWARE. var util = require('util'); var regexIn = process.argv[2]; var replacement = process.argv[3]; var re = new RegExp(regexIn, 'g'); var stdin = process.openStdin(); stdin.on('data', function(data) { data = data.toString(); process.stdout.write(data.replace(re, replacement)); }); node-v0.10.25~dfsg2/test/fixtures/throws_error1.js0000644000000000000000000000220712270121457020624 0ustar rootroot// Copyright Joyent, Inc. and other Node contributors. // // Permission is hereby granted, free of charge, to any person obtaining a // copy of this software and associated documentation files (the // "Software"), to deal in the Software without restriction, including // without limitation the rights to use, copy, modify, merge, publish, // distribute, sublicense, and/or sell copies of the Software, and to permit // persons to whom the Software is furnished to do so, subject to the // following conditions: // // The above copyright notice and this permission notice shall be included // in all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS // OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF // MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN // NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, // DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR // OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE // USE OR OTHER DEALINGS IN THE SOFTWARE. throw new Error('blah'); node-v0.10.25~dfsg2/test/fixtures/module-require/0000755000000000000000000000000012270121457020404 5ustar rootrootnode-v0.10.25~dfsg2/test/fixtures/module-require/child/0000755000000000000000000000000012270121457021467 5ustar rootrootnode-v0.10.25~dfsg2/test/fixtures/module-require/child/node_modules/0000755000000000000000000000000012270121457024144 5ustar rootrootnode-v0.10.25~dfsg2/test/fixtures/module-require/child/node_modules/target.js0000644000000000000000000000003712270121457025770 0ustar rootrootexports.loaded = 'from child'; node-v0.10.25~dfsg2/test/fixtures/module-require/child/index.js0000644000000000000000000000007512270121457023136 0ustar rootrootexports.loaded = require('target'); exports.module = module; node-v0.10.25~dfsg2/test/fixtures/module-require/parent/0000755000000000000000000000000012270121457021675 5ustar rootrootnode-v0.10.25~dfsg2/test/fixtures/module-require/parent/node_modules/0000755000000000000000000000000012270121457024352 5ustar rootrootnode-v0.10.25~dfsg2/test/fixtures/module-require/parent/node_modules/target.js0000644000000000000000000000004012270121457026170 0ustar rootrootexports.loaded = 'from parent'; node-v0.10.25~dfsg2/test/fixtures/module-require/parent/index.js0000644000000000000000000000031512270121457023341 0ustar rootrootvar child = require('../child'); //console.log(child.module.require, child.module); console.log(child.module.require('target')); console.log(child.loaded); exports.loaded = child.module.require('target'); node-v0.10.25~dfsg2/test/fixtures/readdir/0000755000000000000000000000000012270121457017057 5ustar rootrootnode-v0.10.25~dfsg2/test/fixtures/readdir/empty0000644000000000000000000000000012270121457020126 0ustar rootrootnode-v0.10.25~dfsg2/test/fixtures/readdir/for0000644000000000000000000000000012270121457017556 0ustar rootrootnode-v0.10.25~dfsg2/test/fixtures/readdir/testing.js0000644000000000000000000000215612270121457021076 0ustar rootroot// Copyright Joyent, Inc. and other Node contributors. // // Permission is hereby granted, free of charge, to any person obtaining a // copy of this software and associated documentation files (the // "Software"), to deal in the Software without restriction, including // without limitation the rights to use, copy, modify, merge, publish, // distribute, sublicense, and/or sell copies of the Software, and to permit // persons to whom the Software is furnished to do so, subject to the // following conditions: // // The above copyright notice and this permission notice shall be included // in all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS // OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF // MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN // NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, // DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR // OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE // USE OR OTHER DEALINGS IN THE SOFTWARE. node-v0.10.25~dfsg2/test/fixtures/readdir/just0000644000000000000000000000000012270121457017755 0ustar rootrootnode-v0.10.25~dfsg2/test/fixtures/readdir/files0000644000000000000000000000000012270121457020072 0ustar rootrootnode-v0.10.25~dfsg2/test/fixtures/readdir/are0000644000000000000000000000000012270121457017537 0ustar rootrootnode-v0.10.25~dfsg2/test/fixtures/readdir/dir/0000755000000000000000000000000012270121457017635 5ustar rootrootnode-v0.10.25~dfsg2/test/fixtures/readdir/dir/empty0000644000000000000000000000000012270121457020704 0ustar rootrootnode-v0.10.25~dfsg2/test/fixtures/readdir/these0000644000000000000000000000000012270121457020100 0ustar rootrootnode-v0.10.25~dfsg2/test/fixtures/not-main-module.js0000644000000000000000000000250312270121457021010 0ustar rootroot// Copyright Joyent, Inc. and other Node contributors. // // Permission is hereby granted, free of charge, to any person obtaining a // copy of this software and associated documentation files (the // "Software"), to deal in the Software without restriction, including // without limitation the rights to use, copy, modify, merge, publish, // distribute, sublicense, and/or sell copies of the Software, and to permit // persons to whom the Software is furnished to do so, subject to the // following conditions: // // The above copyright notice and this permission notice shall be included // in all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS // OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF // MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN // NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, // DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR // OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE // USE OR OTHER DEALINGS IN THE SOFTWARE. var assert = require('assert'); assert.notEqual(module, require.main, 'require.main should not == module'); assert.notEqual(module, process.mainModule, 'process.mainModule should not === module'); node-v0.10.25~dfsg2/test/fixtures/pass-key.pem0000644000000000000000000000170312270121457017705 0ustar rootroot-----BEGIN RSA PRIVATE KEY----- Proc-Type: 4,ENCRYPTED DEK-Info: DES-EDE3-CBC,CE30CF10CDD3C074 A9Vjoxw1Z6pfyxMHXxDi88JVcLN0uWJAjo97nsdzV1cYmEk4bQUe6XVu8UGCzbYX 1RVeglOwyKfp631l5j5KHNfzA4lEU46uqAkRZbkzaHg6sVK7nuSBamiDqkO+BSEU kDCDqImcx+wUXjlFsYc2UO3DJen8QVEVYQthpxqS7UGh6SCGKyb8FzHu+nzOtRrZ y2Y9r8vyllH5+qxyGymkJJgPGYd9a/q3uTjxjBsb252SC6JEMt/njXdtlt3zUCQl 8aEok8xXIyDFsrhkQ1chXYt/neWdgVh+R9HulVvSLKkACSfX19F2ooIIWhoml4C1 VE9iX7wytbD7LxLK4kWQL0sRi0MQPwBEag6m9K6skcsN8qIRJwJZeevc3xw+08uI IqUL4Ouy+eNMYQIxxgKBcgVWV51X1HWCcwjBkDp9x/qU+URKBmGcpTKEiOrKGG/I 8JN3IreJU5EhtGqE15J4ep/hS4CwJ9+CFysRs0vFCw24GS+O2CXWT9rgza4VX1we dUVnGGodJcXgAf0sNECm8zYk2fjy1SICm+fknsN466d2pmCO43/WpBhZyjbLEHsJ a5pUVQroZdU2W70eGh2yIGVrMmgVbYPitTBafruW8w03oarG4XWA4caEmJMEVC68 WZxuQ1Wg1J+fNl+Klq3b+4yImmoFrelh2gBANwYKnE9Z+JLtfv01et9DNOXR2DQM 6pPzrL0JUHetqko4mJTVNvW8h/Jv+0UVwmxmwm6mR4IBcKwQyY5V5VqeFfnXlvM1 xpg33AEKNquAPC8G4pIHwG4aBo9fLp+I3cxPuY6dnR6i2tyQ5ONvvw== -----END RSA PRIVATE KEY----- node-v0.10.25~dfsg2/test/fixtures/create-file.js0000644000000000000000000000237312270121457020170 0ustar rootroot// Copyright Joyent, Inc. and other Node contributors. // // Permission is hereby granted, free of charge, to any person obtaining a // copy of this software and associated documentation files (the // "Software"), to deal in the Software without restriction, including // without limitation the rights to use, copy, modify, merge, publish, // distribute, sublicense, and/or sell copies of the Software, and to permit // persons to whom the Software is furnished to do so, subject to the // following conditions: // // The above copyright notice and this permission notice shall be included // in all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS // OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF // MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN // NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, // DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR // OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE // USE OR OTHER DEALINGS IN THE SOFTWARE. var fs = require('fs'); var file_name = process.argv[2]; var file_size = parseInt(process.argv[3]); fs.truncateSync(file_name, file_size); node-v0.10.25~dfsg2/test/fixtures/packages/0000755000000000000000000000000012270121457017223 5ustar rootrootnode-v0.10.25~dfsg2/test/fixtures/packages/main/0000755000000000000000000000000012270121457020147 5ustar rootrootnode-v0.10.25~dfsg2/test/fixtures/packages/main/package-main-module.js0000644000000000000000000000220112270121457024300 0ustar rootroot// Copyright Joyent, Inc. and other Node contributors. // // Permission is hereby granted, free of charge, to any person obtaining a // copy of this software and associated documentation files (the // "Software"), to deal in the Software without restriction, including // without limitation the rights to use, copy, modify, merge, publish, // distribute, sublicense, and/or sell copies of the Software, and to permit // persons to whom the Software is furnished to do so, subject to the // following conditions: // // The above copyright notice and this permission notice shall be included // in all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS // OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF // MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN // NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, // DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR // OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE // USE OR OTHER DEALINGS IN THE SOFTWARE. exports.ok = 'ok'; node-v0.10.25~dfsg2/test/fixtures/packages/main/package.json0000644000000000000000000000011112270121457022426 0ustar rootroot{"name":"package-name" ,"version":"1.2.3" ,"main":"package-main-module"} node-v0.10.25~dfsg2/test/fixtures/packages/main-index/0000755000000000000000000000000012270121457021254 5ustar rootrootnode-v0.10.25~dfsg2/test/fixtures/packages/main-index/package-main-module/0000755000000000000000000000000012270121457025054 5ustar rootrootnode-v0.10.25~dfsg2/test/fixtures/packages/main-index/package-main-module/index.js0000644000000000000000000000220112270121457026514 0ustar rootroot// Copyright Joyent, Inc. and other Node contributors. // // Permission is hereby granted, free of charge, to any person obtaining a // copy of this software and associated documentation files (the // "Software"), to deal in the Software without restriction, including // without limitation the rights to use, copy, modify, merge, publish, // distribute, sublicense, and/or sell copies of the Software, and to permit // persons to whom the Software is furnished to do so, subject to the // following conditions: // // The above copyright notice and this permission notice shall be included // in all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS // OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF // MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN // NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, // DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR // OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE // USE OR OTHER DEALINGS IN THE SOFTWARE. exports.ok = 'ok'; node-v0.10.25~dfsg2/test/fixtures/packages/main-index/package.json0000644000000000000000000000011112270121457023533 0ustar rootroot{"name":"package-name" ,"version":"1.2.3" ,"main":"package-main-module"} node-v0.10.25~dfsg2/test/fixtures/registerExt2.test0000644000000000000000000000004312270121457020732 0ustar rootrootThis is for the object return test node-v0.10.25~dfsg2/test/fixtures/person.jpg.gz0000644000000000000000000014201312270121457020075 0ustar rootroottlMperson.jpgeT]6.݂,`n-@pww Ip Cp'8ds}w?Xf?]5y */-' ȾrZ4b 34A<<@KSw;7ҟv3wstw!uu252݉nz0-.@/^rz 7)// i @@ 1/ؿ"6!<+W; uMRsw߰0xb`)<@ {  )L@P4Z]O~`0 XS5%!aၑQ1 I)遽ss {  VVV lllll\ \\ <<<, BBB" "bbb  RRR 22rr JJ **jjZZ5t4ttGIM+<!S7p jn)mXXXvXiX}X`TJSppTpp*pppqppppph4B6A}|j @twe/Dܐb*z! c 3#![  g! O!P4¡RJfΣ^a٣EU }GAFB@E/BAĀ0(ƄƤô|Y K + =665vv'g .(.7 wO /o_ ?@ `P5a(1 QQ!16( q2= aI2I7>)i:i/)!,;Y{rr-`: x ^ Kd$JUTpTTTiTT?iuPR񡩢YEu-㥳ˡ碷Ϣggf10L2B11:023!21y0U13c3+232P$ 9VTTTVUWWUVOHִ2a׽}xnU\BF&fVֵ6v̝͝e]d]Y}ۧOV6?|^Uҧ7/3 6=(45?>;:=25<5K8xDǤ)OӒ3r3#ʳsZs_ ׾Z|`px [*ju M̓-׭]݊߻& ÏЎiNDOFOuO\Ξϣ/..9/?_^}uwS~{;ps{Hl|$jjD S8N`AJ/imj3I›;: ~t6B!̝XM]l5v9:$a#~Vj>.R=}> Y8%@(  W  "4u?B W^-^+C#!T@@BAQ`0/_`h(2t615h Sr LzqOf.gT 殟$iq4-z6`CqBh7/zg.a)%}Wᩥ-s;<2:VoZwZ{E ~~C'̨hZػ׷ʬ^ܿ{>PP/cO^4vJ`/?4N!nrA)AUhukC2G3 R4nZjb+_{Ssn3MuƿB(a6JsP6e-])z Όa8MݕdžQ7)WU8ZeȠ3ˑ~ X+e80i9W$qF[~,!y\>Z. ټ]!kp(TV(08'ؓyuhoV[1wu֣t4;`v6 r BZgmd-2ߑt;j"+A85]s[%dW6.Jl<-eQB5'|BGr9VWj`ke˸JyF%hLEEu!?'kޗ43wvJ4ss2C7%-hcNXyHݑH7&ݚ,E[곐 "$ D( f 2<RTNJw ױ=uG*roYDGԟ$@ki337Y|)T:(z玻ofVm>E֓.SB[vN (!_-L6FUgg~vGz5NX%JYW/Z6nr]`5bfhVqyšHK]I.*ȝ)gjQck5,i{$Ҕ:T $tgMF 3IRPN{]qIyռkiTu-#3l?eb|NGA&D/1t*Y,&M t=ޙzȻ"mZJ#PXoBL~Ry;xoieaH2dkl4s!A2d2ʫh9S̝AZ_TycG.2i?("*}GO;H#6x* c*N _i&eUD[QZ/˦^kNDsDZnH?V*}INBUݩ^6?RQdH$>Q:309 R;ñ'DFpcy-9`9Qbk>gW?-ݲ0߃geeAkT)Uv4Saڥg%15|Śd<HF%~cpa )̆Dl.5|&'I"BFsL r[8Y"K#Q7OJĝ;z5\\atu!ݒ%w'P}z r!!y=_2fIMZ,E4iɼ!~q#j'mr޺ѐh9X͖ޤ$ ٺ;E!H[{s>rX)u {b!E ve "-Hdƶgy2MDç-ϦHB+\g:1e龜e=/V]?^H37  &xGM $% mqhHLȊep1EN="9 ,KklrT4g/'i B0B5&LEh̝~GC5*mNMH<1:q r^@=Gk>`9''Hr,fh,u;4OLoo۶9C$F8ts]^h53dPkgm  [ΥUJ^ x2[p/nDA.X¯#l GTJȖ >@Q% d2/\I)7E"ra0I s~mE4E mͫHҎ08)`h($,b]rZE썴PI"L >HhY]#Bx#Høս{</Ki&bz(]ݪhq+m"VGzhC$^/.ȶԽ؊VA! " U/ibM `ct ? 5Ð}VإӇ _a+Y%bE׶]\cG )T4.2d#_Dw0~; (|;`[>FQ)Qь;?͢$̀j|+j8 Z`A0\l~2?2Z]oj V<D~C$"VٺT?BՀMz|2)C ih|2,# )f>^H{&𼙶L,B.'Iݟ~իS]'}bq0^;֛ x'q ѯF+U%ך @oeI[qNdtMK=]ݪxԊy/):ݻ0H @>d٣zӏ2,/x=.ߞcWL+{2_z7WR&ASեr m1n3.}O`Mg!qF ɑvk9 `Z.A<GB8#GhgӉɗC3:6$vaaJJErу|j-4'ZQdF wb%{{&d^'0Fn2d~81/ٷu^ ` 6~|Xcʒ`Tϵ,ʀXΕ2]rEW<.J8N̬x-|pvXWe`<*bm%U\ +( " "o; ^Izآf[:qܸb?glW3KNqgީQJ1 V%7dPVK^rM5y2_6Q6O&XkjjuBJ@켉w6M̲(Ԇ?ImDF4[nwXl312{29[[S??]X@`\d^ڎ9/[ےϒêhy >oy]@t?\o .aYzTFr/<$z5rEYI|٤+ CFnf3@zE b2v1^U<R1t1MIZ>v!#4MJE^;WɵE]ݴFsy>jY9K5Xm|j{m`R~A*n~O@Go1O#xOw2"g u,Iwπܗͷ!vIF))GufH)a .Qag@v\ӑݱFY[,L["i+j>-8 92?Pv!`\}W\_׈iqWiH\a*x x>BvlY1 %2~AP~a3v3~&Ol>Ydt$ز|Ujr77l0"k  gղ&LIx|33yEPL1S5E(V[@6խ)K!]q_ҧL?x(cϖ(dݤ'DImȥY%Wxͨa0!)hn XLr[4Eܨw>V45w˒T}\J.('/V?}-Arպs.uؖ-I&EJ,&eÙ+ 9U6@)Ú|0pim5U̒[N&q|/çN3_g@$!3G%sySXTXFHLL7ĔjYXq*?1NJ'McV6<,NӜY`y~k~X/b=7 < 0a{+XqX TWEW%?w;ZRaŬ@*D.nGϹ%6lP0Fz;#2gD:pG-UUжQ>z ]EO!EINRFl :.[v8O, *T C֣aFwf[)SfEZ'Ft97*?:4mKct2\|Lu]_wCNJוrϥ2p:oءtxXL7EP&*N[u XEt}Īd~k.:kbn~XY(`I hp~q]vdYMU6߯sl~Mn6-f=xd:cokajÚcIn)c4,0̄J Мר>Vb?X e#RKY&PP N"k1:k;&NF4j↞k!| "n\X8ڑbVJ$Kb$HϷ7 y_W8:mP'/񷂣ST@$2y<_Mo2Y OsX2 Ԉs<%Yo=pIDQ_ؗ͹iEll7V݆rp+p8 b7 $W\)(p罽wӌE[# nlY)b`}39Pˀ sE;$,C$Xs5dgZg55.h3iFYU؈Ѯb|Y,N2`k&8Nv uT9S5$evnD0tFbѶo|eP269oGBF\ŗ#d]vۛJUef]Ѥ+imfڮm&7Bf޹#=7i ͊?yCu#l1<ػ~_KDy~0w9Ltu],CdcJ3ӄ_$M' Xxd @}3ԴNC@ƧȄ~h:B&om☫Lg|ѨCeSY;37<1֕ԛv|xPN[v%'}f:ʨk쇻=)80Sƿ/QZ(I't "@-n՟SdP,eC, ҂8<AӊiZ .X .:Lb/s6N`:*E F|_$'11aY2{iq(Z((G"4TfZGF€dL!˚9BrSx5&aiGDnR짾*7 nQb=kezqYAU$ :TG1xB`?ZxiWeULoA CBP=S[Q `31 ogQֺWTv  >b8_៺K0B TT}zO DO.7,Puo0jJRȥTfT4|9ppj_$z8vxnǐkg=ϋ R|R\>ݦq΋w'g/ ecEd_XB#b(ڠpKksy5jajՓ*JEi !3.:SH$o&DDid9N-qcr;@U~N3D7ݷ} V;͔l,$ZxuCNQON`Euwգ%ō-0~R|큆}Y2b %h AcVt?#d4/̈́ g'LِToVJ@ѯ-ZՁfF1m>y:t6'[y>Kʯ6ٽv^`pl͒F}8%lLk7c ~^=W8Uvu'+oJ ,C-ɪ|;&U)DZ]L%|TF|k AdPy Oh lC_r ;9 rߌlO e-3iE]fO>Ի|P0j <h :3ڦmJ2#SK-֏ }(-?&1eNٗD3=svl)_bNFWDPr5Òx:OdE ;$t5ؽF|}D=͕(F5P~ttǃ,ߛ[3v v$<.#'5|-LzNLlYa3eC[ 63]rC3\+yzN`Y?B35rr s;wdmaRW$-+E#O0n8#T&eBR!Ig>=[fvD!%˔b{@0s >0צYB΄GxPVeocF^̇pQF{"8 ?~ڷ; '-6K㢒S~w]Zu[ۦMYX7Gk':;"Od2gpcd.2F&= VJQ_ob):":P?Q&qS^f)~77*m-)fhwgߢ"G_~zS<ipQs$LU˶'7JR6vSJ,,t>|ʨŒ6$wLUC|Jb*I@M$@,lxt #X1d :R?75t&V ie$ʜ4D3$=.ߚ:yg/.rMi>m?_] 3Sfv'}0Iľ Qکק4'}-B&@ |+nnaMW*R6ر[_#V{h>A]Xa]Kdt3~5NS|lw/A S ]'Rxv{Ɨ)u U*bZy7rņ}23V汅Ib̺#4&yrkvbQ2jPf[!t(dR9yc?X!a V }h 33"zo`#2EXs,93HNJ]+{ %2t-Sz-W -`RAʪSk9="̬FBEtfk5n-rIe^[*`q^)UY*3<5k糖 Sh慸4Vm%RO4T Ө@ MB}tӏTߍSq(R64/ C%ȇ?kЂ^ͼCdwj=VO-'%ڲgrhd\@7{.xj{);gLW%sJ x^O84F|?FE}#U(UyC&$#GU5{ ؿlgѲBз< >pM'$4fRz5N4UuS&,Hӛ. 0 l*J>2 2V.vWͳ/ fKroxy%"d,o%:rؗ|nEU:cFA4cN0JO?FLH7:; k& )btQ⸍MKSyKK咒E7|4.Zs.W@S`T7}#o qIF# w'-3'٪kƯE^q8BJ<G?u}ivp?@hewc==aIËd,}kC䃠D{/EKV5v2" yw)e)u_yK3wmcy{y}-nvS$J.EO$$+ԉp44Dnʌn}<Ǚ$ LnM=aJ_Fb;~if]P)ȕ bӎ sU3ak~Ox4ByƢ-~{G~.mgW{kO+$]{*7jԡs+bY!(!l@nbl:JoVv26$m\d~hhtBJ.%I_h|5kiwzb`f*hJs {͸rߠK KIv/< $W_|ϰOk{葮:Te2@亥ͱ'x;uR?$s|yȭSCɝkXBIdF_K^EmN| -.//u1LCDSڙ2 \@w(T]iSGL-1- yaH Nh:7q>ㅂ%B/e,S,gL;l3G߻C`OQj+8Y.d#qv`۪!d ^TUhn bE0yBγ}nQPHY 3 yA}`lʊ-+oV.PHyhI K SCUC-=W)Q5LSZaNeU1N"d҈z'b*:Vg.BWBr"/=m: #"IG+w?H+} ^b?t!V^Z017,c DvxÒ\>l6X2C+A9*!]MʭpflkTOΔ+PT޴^ӅJ)ndV\-=4^AqtG+msۡE kw=VM_7wt]^mQݣ5(]m)޸Qxo460}anr2(Mlw%|@j06APxP6=} Iڗ]㸅rl8Uu5H#R3A"g:$-(be2IGHrޫ) \Ux9q]=-WmJh@ Qx|U&'M`" Z>yMgJ@ɩPg[(}ƛ$nU+Jұ1T+mH7u"RйqsC+*wV\{ ᚡKx)fQWD}Knr^IW6 5G{#,}'uW,1 黼VWq̙m0CqSރLl=MK(&6 t}B%{ɵPJpKLHCEE1'LT:Hk4ԦԣSs1HEyPw, Q.T wO鈈m>,K^lzDojFZq`"c\9|iÞ));a"ɛC۝ySs`4H*Ңn6|c? tn#8fyk>F^x,J1 v%zE瑉$Yb=ڊ+5K\ +=É ?9i|~QpCʐ^\d$ @?0HinXzA) Z?uͦay7Cḅ&(5ΰ5kI=Wwtd9jPXzk>9qF\侚pjF5KL87<9v\#w)ܧmq`TFvW: ˙;*_,Jly(ˆee?n.SYmsV@9HZ*ܡu+RW "͖1GDaKQxm$)[KzeVrq4B0yTy:Ul)y#j9nVnTaȝD1"YfY$<qirA:&*2b iΐ&AE~PGy؂f2EؓY-DB4;Ӝayӂٙc긂VNPl&̽޿(@Z0j;߀@R-^P;ѭ1okF41&WZ}y|m$NK"v]x7YSiN^V }vʫ=Ҝp17Y8ha8jcEřYl=1~q(* 2$NoCߨ5]’12TY,ը/IÃ>VCm[(SQFc_Tߝx( KrL˓awj .*ћ0~6NQOІ'[nWƤ MNnZwmwn Ct b-<3㜶:-y֠\V6`{H|Ċ >[5;Ӟo2/Fg9$FF3}Ag>NJZ]"[TBFGŚf(^&Uä!6AԄ1^/e w:MF6IB?,&jӮH;;s {tq(_(V?f l#yf0w)*5jI$ >TT`\Ԍ{At"r}h傔h=q1t1ݙ\^+97眏}95|rH3k*p;'QRP˯JR #N*Q1hdk.`PP%6V"]8#_NNKlcl9Қ|_iA2ИJoC9^kG%#(wBz)B3JjU ,crYu :IrpU-w#jK1sWw˥YԡT=2ԞpbD Ot?$<V"*Xq-FB;6p .8" 6wK1!*)K`b0_?13_MARvԉMD`K}:*9O,^N,l̬,A/'Ss[ D~MN "RbUrZd}\>ʚ>|"^^N@7SR/{;W~/!_?YI :]E R G )'3;9+;+)3;'+/#;TDFCJ{!'tW]˕O`vtbacaegaggz`rvp3brpo}H]]@NNymj&DNSo,/v2ܟف^3nʟMݽ/]p829 htps}i~s`njt1er1dr\C=|]O +%LThTRNFNSLTNWKTNN9{S+Zo"'HWh@,l`zH(쿠zjg ) '@ kw77hmj+not"]_bN@oLXˌ6i#V>&Vn&v.M66~6n~..Vv?W#ɗ6n V8wUXY8L);/ ǟL|1ċkB\ݿ$//Ɉ@ן n֎- ;KRF^`t9oZ бML hN?WM_ęx΋vl,?6@՗qD_='/SoUyt%_noig_S%F K''dgbpp]܎.vZ98]Q./V_U\? bՃ_$+˯22s0ёσ_8L/biӁ%n{s1s>#J2r."&EOg_~Rg54_B9tK_.]\% Kes;GeGYG kG9b/7\ϸ6e;* zQB 7_u.ꟙ_/X\R~ɾ0dT;z]b;S_$?_pYؼĹGLE¿l_Q1gw ۹w.NvVy ?;??O\abM'?q=u?Li`#m,7?<2~'ۿ',DUM]^2t7??@ISKj?5|Y׹C%Awt;Z ^ݿc/M_HYXL]mB:I8:e| /6q1v}I^,.mj 7JxMf T]-A?J@_DϵX[LKLJGZBW\W\CBhhNL\~J.%/`gd t-e+$xxn1qqqs9B&Vf^>N>ٿ激T?gF)fZx9xo̗ [NUS_֕ga`dTgk{FFZ2Y=Q9F?[Hy cM s~Ww3ۯߞWZvۥHY~+_7'~A;{_#d2d ge$e/_f#?WG,!7?=-P,~ ? Bܓ\Dy y)/(X((HH(xhXDxDDx$dtT$d4dTlT4 L,,,D\lL\tL,̟A|&]jS@ӟޥ  !5 $4,84pHHa`?ߣ!c T3bwJ/V7D!0~Gs\/P`~.ޠa^@.4O9PR׫  <(ᔽ$&:%_0)XfL<YÙ0I㸐D2Q @ǻȧ5*#V݁;zt9oEQ<_ZbYR8ZIgS(e(FQ!$zT:_˟ Ki(ٝmhm& "Up8i%ϻk""π\o ?S|}Uj_o(*J8?^gr9ǧM ,[Qo?ҫmӃ1b^)U0M#J 3yi$0c1j]be_a Sh@eAd+.8Y 'Mj1A86ТF9 4r>n,qӊcY)GB'\z8lK>5b[oZZVY{aTSGpGT|Im.^EZRL:& <"$}I[1ˀ/H_ ^8X  #+!1f'EG6cbȾK3.$ RDiu/hEwg?Ԯb&%iǟ!R;!3 ?>TYKU^iokdAe~n[{e=oBbn]sEY̛űk#)܄ fĩ+=٥޳a'rwgUr5K9K-B8o(xZקaZeI\Ok6:%ߕ|klѷT0SpWtQosrB)v~v3Fty|ڂ ~Io'm{JX ĝIle bc!thC&,-GV+UZ 7@hC`}?*G6\(#q(w iᯔiqn%Znɠ`}4n)9@]`L]\H2q1=yWl eQFHcH@̥HU7y{ڝJK"8:<0e/IxkQ33>Jjpl=ͷ(Wݲv.Y##L =䋒U27F N-p9*%z|GtڹywI/?Ƒ_fw,F0k΂i 5>%7׊RU/%`͍߫\SqvuDWE'z W,0e;|N؂\;PǷE3 Hqz A8*4yU!)p٠lD]ŘW0 ~G@ѾeaPϕS #nly>Xl4XPb$qyۣva2}3iZfN5ߤiM:D%zԛBٖ{H;$GlZ*3mrJ 픉lL<"d2 =l3xxjOʔ -"rV-kʴ($ Ud1 X?L8 %A<n'C^J"W.GWPwp8>Qt{AN,Ҧ DE UҾg: ֧KI,/1Daqs`Wj 8~Ч60s/c:]? \MXA#7/3I mQ"/1hZZ5sA2R%Q]R}ˍ`u2WJT p*W9zI';VСͬG?qξtP*> .~C;i+6{T4+Ixs*[P%=Y8u%Z6i)`QgHIN̑aEd:#\` -3-';M1K-}S˦Az}٪ks2K+bh5Z H|x9UjJ\9;L}&&& :&΂}ZāHkJ)7,Ϭ++ŽR¾luLV"ytl<}5]>ݾ+PM Môfv;;6$,/=*>J3c&7JeCn[|@Xcu-UOQۮ#o}5.+yav־dWTHBrf,mk[oyRXἁM/ޖRn)`dԸPD2ڸ40L3Bg^L6ky-b9$y%sl1Zv!S+0Ak>g*}J ] /|H8IlOl /VBJՑ.Qm`ri jǾt'%V)E|4eG>C[62 o)GTs/D>FS0bt|#W4}ce S3BAx_E0X.&܈:bޘx  0*0"r1zܿbb= 38bχnZ rCZp⇲Ur2a̍a&郿wUѯ~WA6 0UĒ#V,>3.];2KݱÃXxib|W¾Rgܝ,]_w+>b/W o(/q׸I^Fc >,H_3!m[^NZ]ۀmiɹN9ûOVf+ܱo\fi[징+2Mk.|ƫ,#:opDE`@Zw"*Lr9Fg \%,]fJ<󭪚!Tl`K?M Cep{yl[3؉twg=Ѵ2KKQ j_/]£@J=:0_(ʠ1Ԣ6u+rjK5a; M:waik'W;k Anl9Z[&%Hoe z),~EpM8q@^ ·g ۷TP{d4$quJv[15m@SȄ.1ucY*b ~z۱)Ex k:=!- Fʁ(d'+r*M 9DYӘgrQ\QX1O^lmgc'CYv|5)L1gՖfڦWhm'*0ấewC}ÍG^~Xz訔%TRq4Ugm_CBC"%v0sn;uevfπ疄OGeW=沺X6jb"$xogM.qRr%+fBspqdO'.C$e\J<1urYXj#M1F_a\Rq,u6%9ɮ#T@ ZjVFOY9^Us6Œ8x'#t[ih{VraUVY`IW4dc:6b$WeM/ZiH?zԖN$9{ljiL7/9X=;I #b)gY$TH]We- [l *#!!Մ ɴmHwrvmO@p_A7n GiØ *ll/GK%CeNsskcZr}L'gnoX✵3ZGPL3x42<9 IA󐱜]JJO1FըgEE'b :-#IFf)^-3}"d ^@h@"ty6UQ N1!wxDpiNO$qK-v3wvMv䝁p\73C[B6fHT(U\H=mB pk۷ VҺ5܆3\?BCh!B~ S͠LJ0 RMN4KHGj;Z{OY4=嶤)w~z Y]d$tRAΦ25H#=[#˨( ĵe+^0x辵,02hV+:UC0ҷs ~G܎JFRw}yW ZC鰎Z|2xڥ2F4Fv8|>I7D[-N V4kX/?l0K(@E@w]O)8( \#Dޤ @˥%m RG 5]òz[!ҿ5`[.}˘kY&{l] YG+L򔊁p/ 52幵CU7hh7~#7 'vbΪ +庣`u%2T +v<3q*jM^J]D&I!V tjW#CqxX;rouQWx";rئ͸ƯVJ^xk15ÿѼ e3 mrȦ bUh )Ӝ'7Gmce4%hOXՂKYC!Ex稽Q{<Gd:γxƌ/$ĻNe02 p +|!}7_xˬ|[Qڂi-a 9ՠ:gg}E4tC`X_LPr"L{@NLJ.Š#͡0jbOX<m`%J1Ujc3!…6dg$0>gd9}a[3ibb5D7Gєn2è tgG r V\ZavB 7"iS D̶ Qt%S7٦\"]7; A-voiywwvC2FlRqAJ^OYny*\u4rA;ITJ2z\N^Y88qc{$jk["ɧ]yJ|FܝA[AIh# vOdwqgqtDhi L>JkJ0]x bшYڗ9SckmN,By\Z3п*{oGmhR%ƛ+BH=鑭)yLtI/P|'Ch%ÈxuG&rD>L\M\w`raY%9TSz؉x'7EƢa5k$^y4(*Q ha(,h-ScQ)OB˻ _Ot߻'ShlT{%Th_}CppZz2V0Ǥ^0y +)xT9({0Q?P|"t't`8".z%!rndK DjǵgދN$MЙg;ǯ|q*!jA ;/HPڤq{k╗~zޮu/c/;=X)&G+ګޭn&|y#ϹúK@7vo%Sh4-}:jw6gS .>E4-V8x)mHl|`B= < 3rO5٢s , qZ7,¨y`%E1 s b7o zlVk],b+{dM tR/t:]Ʋp0P;/ѦR' 'jU/@x1jh㹃 d _3#KxRf@?Xa)5%P5/"' ZzOYRF10 SmTrJ͕4 S<O}6XI0W0zpf[GTPdf.&IZA99Шx6_g:JO/of֍N)Wʴ. qC{ejj*}ܝ[L ,rtfb+Ag F7fŏ1:?qT`"iÝ\ܧ5ve8#عg5$d%nUjZp˙>3i*p<_l+H3Jlw+ӯ/uYF%AfRlwyRw ty7Sjhhӈv̾豫ֹ|iYfy~?On"9$0Τ .m%uac:BCDu0zp]ձ k[=]FEKVp4U Y hZJO=?̴Fu/~8E2u7d)u+v֎\W?xfsokSH-USq7tƹS0-W^(Ԑv<\B1#^."K.TplD=(oi?d:]P]݂;udG%0Ug)7'w|a)𻵌D M[|JSkyӔA9 A5cVK 㤛&T(0վvQbyM3#jZ֍ˠ7QdLD(Ħ+H݉|b 8Dj;xۦ|l_";Zk3 79ljtyYƒ#?>Ey/K/ׄ usw͸:{4hN,*'r;pvHOyxN5,kY^kbqL4X|d"iH_y4]ZL@9/g3TR)_zQ8S_# Å\N|t>,A"+e/{Zn+ay{ 5.#ғ)wQ4}>,߈Zn!#?> [ ש+M33sIN'Oz=ijHBQwf#٪bŇ,o&fӽP:x[^Yai)4.J303`- (ͺn>]}wQr_w+ж7gb@i ӯE``pKtK2!p v!tJD1g@uI,?}\t&6N >d ]L6KE^!/xqc5ǼbjτY8YB' ƞ5|02p N%Li"ڠ`h+)h]W0jSwBNu'>h/ѯUVW ;871fE'LnJ2舤M̚k;p1b^V)R\S/ڔyh-})<fjjMLXdԭcp؂6jiX;mMrT;lUṾW{m2#OP$ 0_ct2-B<~RnEaoZ+-|%*ؑ}dϵMhpjZ%e_A,oA5yZ8m!:xTu"8W t{" "EMVӓiwQ <b|WY}Piim4*(I9iT"LZ7{*gT Ͱ45E=UVr8ј)DR9-RN+O%fyFE`AGFk@ݍM("Vmx T}F>x4ZMUeP&.y\J`#pF?q>5}Rm,;[;lscMz5R=2Qex>M2))>wπEQp׷ˆnoln 8+l{k VNAY?tZG\12Z#L`MxIo ǔ7֭//^B:|2;q?t Az Bh]驷P&ܒ1=zSUh%Eč i&jy* y# ÿ#ꕿR^n ` .{ \dLj^X۠hҞb iGNzmx9Znqd(vK&?f+hr:y8RQ~|rmSQVSm5HED=՛ @kQLSsRMh)1bnyq$ٽ؎M>洚/ }yWOqWADpvt'zqB .gqF`[@`z|)h6=53uD,Yujq&ex/uddo7?9],]7$X*ב'hlf@OUUei"ƻP. ٵ͂E,0GR03߆ e =w_+Rꥦ TZPF@ `0~\<((IzDǃj]-?+Gn7X' ʂ3qqV4ә|SkZ~+t ,w)O> ?m2sPsT|Ls:7Y-SP0Ri!ЁtУP=,k(oOjY @w!w1'=1@W@WL `_cĘuOSdՕ`U(/jnZ[mvLu;$#%WӀU^:!%-j>`KYQ3K0=I2c8>A'FpAX8?N v($nH*o$HI#pXD#]0+O/<$3I`+=%:ij(,Xꙙoʅ0>gs+8c=F鶋ط&k5 +-~\yĒNs;Wq2<p3Ϧ6e"& UCݫTMXu)#wc=U)yO;Y=-0xL[~jg]QYF2KGbQ7A%ܣ|@^ofjA-!$I/9\x[*7.zbYK-] [c֎YRD/U\! pAeBwoSc'Rv\*sۊ% 38d/V{ʱ%ULp4r{tToeZ ]$QR1TO8PԥǥT6xLMC. 8I$1!fDŽH} MtvDFgX!R(3='pf5%r &]mHZfP4ɾ}x/ҔPZỉG.Ioޗ;@ʻ j̃4`9F@ g5|g](֢Z6R\E  (^=+'JFSy $œԁM~`ײ|d%<4{G+Hf|E}bseydb/bڂ1k2ClS=SOh1%)$"ϙ`^ͣ1#>rKh cA\O㍓zW66B3eU?xءbWk2%M2xTW.뎇 ?=/!5wjMr3ARʪ',N0gQ:ϯE~ 3T6O[Tj}7ISWwi%E?62QC:T:=@@:yIA؎rqб"hX| aNI?hJ[SC3+JezR[#ڸQD:I"I'ĹFnǿo^q!Fɖ)~ߚ-B79a#`q5];Fxz;>S ^jX)3'Q%cFex6AʺZq5T(p%HS*{m==Qf3s~qї?dw-Ux-ZJDЧBF·шf>n{Ng&מegoA%Kb.uQGS=4P]^eYwbG`UTy1o?i1g뿽zw;C{Er[u)djS!p,0YdLx2C+xm5ͨƳ VIIYU_}]KnAyDtH`g<ӚI=nPڒ}Ca{}\ @O=HT?̀'܌80 4M)REY#ݯsIAmI]*=$z6Z&5t~OU]5Ay#KZ|5T$u7;0gŮes:5M4"f ==C^Z 5.5Oz_{bAU^BeZ:w`q0]N"G$Ѱ"HT3=>UB+bW>a^[uKhRKVފWF DH 2PGvt8Ym[1=6~f݅ڲBՄ5L4H7IQKˁJV PZA9uMC]+wϹm TڒiBD'wϠe'ĠnvM,#@[o'1@3*CbU<7%]rTfˬ=(LqSUld}yl@l'4nګCPK}G+.BUJW^/!^562b.us2GƂ\鎧IymPԺ"فߪ0.Jqʟ&I, ;Ӏ!]+;kR& ZM2zp;x@!e/|j9GFӷc~930+ g<\S :\#,rFfS:)MkI "ʁH?Җ|Κ#?WjHڎJF' =4dp8#}F~@mxkZe]t II"f52,EX w1=-l*  3Si{#ERzi$(*ۛx1yX.-s60O 5%KQ{hz[o+m+jYQ>84ޠ@Vs՚xZPI:[K'rkg恾!Fk+MnxQj8*Bk6 q Ǯ~\n,, j  uj=ޕ%0'H g$?xrC#U5óO*G]*$H$PxVuHep0>dܹFU#;KX,z"^OO!4S" AP6^]6yqG-d%4UvcbIwS:u e:~\lz#1gVú_݃êeGYWSIZ=\[PT(9JmHEoT52i C 0Eţ]_ET !T>BʭWM9[ R$$Ol l e]iWt/ۧ p)O^?NV^s<5),q2$/bhT -b7NaM«@;=[tW̽KFfiG,&!P(rw1t?/uDC@cY^5F }U}!g M榤İb r^01IfTjԫw8mZgSw!5r eOoWg%|O@Y!cEY iRG\@'izcpuh[U٨aO42pۊ",FӨzS#zt|uQ14*'!`i`hjC1r$=cpJDBC{п~frj씺j(2[-/Ne_1} a|Ą{TɆIj6Sd+ a8sOwdlsƋYTh*qOjRVGs"68VaV!f$"@7Y6ɒ#MSK~X+zzO|v}thDhxځ&}@.>f*oh3KxL<eOy{eAd+ 4qUNze3ܔM)WdǢ&:ZcGh-S[[iȑ;cK?ez*k#Mw[4-WN/_R-һƕajES1" b )xN`5#qV82mRGuHK/ C968`x 㒠`i2yL#y7_鬷1R-:e]ȧ9=~|i׮\Ȧ5|$tO|*MuxX*oUr:6*C$` :5MTlt>vK?hfc\@r{OPq/?ҔGE A!Ocj LePrN$#) p!8|U&GISE_SK=™Q0Fذ=ؒERkUFGjs5>}I' Vd/T{Vo.ЧJ[^nU $*Kgsۮz uq7*8~;t 4e铜u cd -/wҷrB.Tbxi")vg$}@2Xʦf 8ҦIS4PLLvǿ&+tt h>ds@ 2qB =uΓ7Bs*5 WbY8Rb8eĞ\D?~=Cxn{ OpU47:$vj(Hz8'O a3U|( ZV Gl:n!YVzj+kR8 eKpQX֓r߇ nBګ>;KX:U0V1dWs@ıe \>_XѴOկBi/uKtj jVS.ߧAb~|sUyv t6\<7QA[6`1է4MݰD=Lj_X8c;hU*g ZF$=3_dx"7-4-$v]fU馾=kҜ#ţ Q805Qmf0zoV}qʻ 9* 7x*i˓ː{}3]X|lS*pQTf{fH^cs1p8a/2vSm'94[4tO +*TJ&x1ŽA#Ł`ǩki4B檺S$tݓAVS,nQqJ*=XJHN2Ӧ H:yvL,Ufh/SޖXT}'rgv8%:X4WzL#GTf6Qa Qcӆګ%ěu0TjVIC>.F>`c'x y)W8<*W:|:JI˘USD.< `|}DY 'aK J1\LYk]O Lp%BH P} &`]O铗5VdGXᩖ4p <+)q*g3I@~Ȯ?O7t2H' `ؒsӿs:, DUPE ҆452CQղ2) {1v;W ;nwQu"ϛzDor,׮^R]Zy(+MV"%ǟ4@H*W=sƃ\2g90>sϯP.$)R7*ؐ=j 5M&]!X0*(*N2k,>>E-0>/_M;L@!v @3?N2+Tv00{o0·}曹_F4rNx[fz{|De:ZR^m"DT[s!")՗ go)IgzFXb1d1/ iժlȅ{cZJ6(,bucjhh皎a@< #FW=u/p{łi\稫xH Hz֫YN5hB7vgΆCNTNeɎmJ#߼TMM?NI& &0 V# ˜g>2ݬKg R]P7HO auL5+)fcxrB #iQTbNtYGI7 #+ ǘaH q!Teu &fm~i[n[Qf,ȦQ0y`;>*4H{wsmD eIh==I- sd~ p8ibS$elgV\D  Pg |0"[YnyȰZ "$42a~08 9OWgZ7|\ Xj4E\0+,~s ,q U`3+w,kk3o%^2TzsUTWNU7Y`qWz9yZhfFL;Nb;@ q䜟P|V MϒңB2۝-]4B9vYHU@l\١ttp8_DΟr|уlՑJrT}i7 . iecSo% .x^IW\ޥY%z];75椊nt}sy*7yd5N5[+_OqrAOK'`mˌP:n#j`EXFpxܲtSK-=+İC2OSf0r^oDiyzvI;Lf\w9j$AqD;??g5qq J`>|q 9Q 'R55G3,7"ij_ee vP dq!X֐e$5ݙi.=ښ$};0D@U~_v50U]'/8p諦ujâ YY7jwZb_)[ D6zzx5ټzV̏Dt? 4CD\S}GA'-{ OSr_(ae%'<_$`!6U*R P7L)ځp@^!dhTTUt@ >cU*J [> ,3ԅiCHIO'ߒ<pV(WTUT2Q4J}ΟJE)xc]:l_sN;Gf x?긮S-#nW m5Vzv",Sj'?BI㎸$0f I"OA4c|Ǹ{q㟜WEhcHUvk9taׯ ZItu\[eG=sitH{צIc@$<')5薚T*6ئeK5 I YI}[TaFuvQl>ls-+6뤔UD:HAj>ˉMnby,A+W2v}8 ) yrSLl7e'dl p%ADUkf6P"55—YA7c N{8iqnZjQ 'ywpcWiX5:z0p1ψPphm3jN4Mʋ'I}ᑆHn%2t`\}SFYikf?uDU dqWvjYGPM2ǩ8RHtW hyͺ=]jI LџKqt `+b8 "z 4% %գaWtpǶB}f+jwLq}v ̺&t:iJN*ˤ4v3uU R j#l"BX'1o@<[.~sOS{ y=zc j#dp$cw]zӌ耎]Cæyy9tE[^1|(TyV/OGIJ^/3V3m쯅Ui̔J[,$cԎ8n.h'=XCYP #8o>IS$Ų۰$-dV!9=b&# ݔQOB_4{tuJM}{mA-`=?'w u\.RD5C{Q^=JaHt5:" l,R/2ùBYV[WTuu|! ӝO[QSBcU $]L3g,NT-;:[?>ω(Fg55m%]ƞEaҿ*lS ucI59u/0i3[q8}%Hб~V6%kLֈ+igPDUQ: 2dHr!ۢ{ʁV ÎӚKTP\ʶ2P~!*]bUXoWv5MMبt Tv :G%3gCrsWVNNO`zE> 'S\5ؗԌKztD/ ~Ԗ9m!<.69*/zL tEWJrTR eY,F3ԀJsFǨ$I{zUyu4ݧ-TMU'$^ !`Ͼ1HH+%>U|$ә*ʢa_JkKs5$t9q&BPJ;C;STFRH%QW?1 kd* ZI] 0Cd)#GiiTHKcc?."fJ0\O<2poPdžNApzJ2 y98ඵD1; Nz#)DLW]Ut+\t4%Gp2FYv6>ڨϗP]>ң<ܼ6?AHP eY.[#ݬ c3ߨ Z7Jc7y2 /ᑃ32OЫct[ ]5mUV[^2"9I,׷+E 0Op5j IJ_u'0qAqMs\Bjhfa5+(p@2 U[@a]D::M ~i.+m0 Kʆ8ݔ+V0ΤυL,4 qQHUyFO,=JFcrFHzK_`%TU 52v:IG[QU#8 H?~& Dl-TqT/`/$߯ˉ9@ET '}擞s8$ON})Jw,qaۅ %P}?,pӧ o(@v)#@I=Q!IU* ?DJmeg$aUSݪ%z6OG,]7m@8$ + UfTl2< gՃqSX/ z6R`v}%%%Dc1 xx Kgz0vf}ϙk˯$ͻu5ɦiuQGI\@#KXI+D"w&15;hs8, Pz3O~h LrXimq驚_.Vv&xSF9NCJ 5V%n>PۥsIaVݖDG}N;9䆦ٴvkMTBJ5@;7/GtE#=qqrUnY5kMUV[SSq(08 O]92e\(\RI}®U4S=4er8''rPI[ HEJ5I+#Ez=;gA>E!8QkУpSVUC>ݪv${6;"J&\g'1Im|Z Vpk2_ny,U*jB*+mZIl lwH6z3uۓ->nRDw#OP[-u%*l3Mx5o-K$bFFr )`Ct42@ls Ys%Y9oR]蠦-5EM-27HIO~q-AHd*ys"5,M䎋cq}{?z.uuFҦ1h%r.z\\j3M+;sqKt=ޅ $2٨|e_ӄmhUնԃӆNG%H-JI:oK!=IJYA 4S6|Րl4<5U1GIOLf'䞘~\"l5uf4m$^KRіkӋ ( iqO+yVJAQ„Cq# &͡Bw#ߧ %ֺUE*YUrz `?=7.$TA2;|, &tXJ X Ok 'LL`,}F2>_N"Z 52Z[VZ}t+AA$:w7: CWǑ<Rzڻ5@ZˎTH`bdS*Jݞ)hvkc*uS.x<ߪ6sOGrޣ{|v4 M`S+T*>OWvƁk]m;=nC54WjIBr RO(Gn((ZnPK$#j`N\ |L<骉Ȣ%dRS:"*:qӘ tTQ ҫeK(['㎤evWeEx NIu-95 *ervc#)q\en<.iҷaIӄM;ЇIq0at?ˇBVYjie J͟[(J%e$LI$?Ϸ9Y Vw v~G(exG{◰8AN ^'PieҢѬCi|[?χas.אIEӔLJ<=(d.2n Xwj[Ϊ+'bzp># fӷ=]+gjIj(.&*Tܻ F[}/BY t?E.-mBK sW:b[7 %S~fȏe+>q8)| E *;I}Ԥ/H#$o x8ڭ+0=ILGO pTSl2w~(/;D$Wc_ㄔt)]*^;rX O\ dg *dRkk'S4s$K!3<(NRcxM+jJ̐* #`xh JU+<~ᠧSq,c$[#>Ӆ) r#y[\jj1 Gj2 B\dОR4wGa+Cn'dڨ^,i>eZy]Ng :$ P\/Z枢KQMwHwfxàOmz/*tp*oY|zY@XpI?OӍ_ٓCHnode-v0.10.25~dfsg2/test/fixtures/test-init-native/0000755000000000000000000000000012270121457020651 5ustar rootrootnode-v0.10.25~dfsg2/test/fixtures/test-init-native/fs.js0000644000000000000000000000235312270121457021622 0ustar rootroot// Copyright Joyent, Inc. and other Node contributors. // // Permission is hereby granted, free of charge, to any person obtaining a // copy of this software and associated documentation files (the // "Software"), to deal in the Software without restriction, including // without limitation the rights to use, copy, modify, merge, publish, // distribute, sublicense, and/or sell copies of the Software, and to permit // persons to whom the Software is furnished to do so, subject to the // following conditions: // // The above copyright notice and this permission notice shall be included // in all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS // OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF // MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN // NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, // DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR // OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE // USE OR OTHER DEALINGS IN THE SOFTWARE. (function() { var fs = require('fs'); if (fs.readFile) { require('util').print('fs loaded successfully'); } })(); node-v0.10.25~dfsg2/test/fixtures/module-loading-error.node0000644000000000000000000000000712270121457022340 0ustar rootrootfoobar node-v0.10.25~dfsg2/test/fixtures/utf8-bom.json0000644000000000000000000000000612270121457017775 0ustar rootroot42 node-v0.10.25~dfsg2/test/fixtures/empty.js0000644000000000000000000000000012270121457017127 0ustar rootrootnode-v0.10.25~dfsg2/test/fixtures/b/0000755000000000000000000000000012270121457015666 5ustar rootrootnode-v0.10.25~dfsg2/test/fixtures/b/c.js0000644000000000000000000000300712270121457016446 0ustar rootroot// Copyright Joyent, Inc. and other Node contributors. // // Permission is hereby granted, free of charge, to any person obtaining a // copy of this software and associated documentation files (the // "Software"), to deal in the Software without restriction, including // without limitation the rights to use, copy, modify, merge, publish, // distribute, sublicense, and/or sell copies of the Software, and to permit // persons to whom the Software is furnished to do so, subject to the // following conditions: // // The above copyright notice and this permission notice shall be included // in all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS // OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF // MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN // NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, // DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR // OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE // USE OR OTHER DEALINGS IN THE SOFTWARE. var d = require('./d'); var assert = require('assert'); var package = require('./package'); assert.equal('world', package.hello); console.error('load fixtures/b/c.js'); var string = 'C'; exports.SomeClass = function() { }; exports.C = function() { return string; }; exports.D = function() { return d.D(); }; process.on('exit', function() { string = 'C done'; console.log('b/c.js exit'); }); node-v0.10.25~dfsg2/test/fixtures/b/package/0000755000000000000000000000000012270121457017261 5ustar rootrootnode-v0.10.25~dfsg2/test/fixtures/b/package/index.js0000644000000000000000000000225712270121457020734 0ustar rootroot// Copyright Joyent, Inc. and other Node contributors. // // Permission is hereby granted, free of charge, to any person obtaining a // copy of this software and associated documentation files (the // "Software"), to deal in the Software without restriction, including // without limitation the rights to use, copy, modify, merge, publish, // distribute, sublicense, and/or sell copies of the Software, and to permit // persons to whom the Software is furnished to do so, subject to the // following conditions: // // The above copyright notice and this permission notice shall be included // in all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS // OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF // MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN // NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, // DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR // OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE // USE OR OTHER DEALINGS IN THE SOFTWARE. exports.hello = 'world'; console.error('load package/index.js'); node-v0.10.25~dfsg2/test/fixtures/b/d.js0000644000000000000000000000242112270121457016446 0ustar rootroot// Copyright Joyent, Inc. and other Node contributors. // // Permission is hereby granted, free of charge, to any person obtaining a // copy of this software and associated documentation files (the // "Software"), to deal in the Software without restriction, including // without limitation the rights to use, copy, modify, merge, publish, // distribute, sublicense, and/or sell copies of the Software, and to permit // persons to whom the Software is furnished to do so, subject to the // following conditions: // // The above copyright notice and this permission notice shall be included // in all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS // OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF // MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN // NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, // DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR // OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE // USE OR OTHER DEALINGS IN THE SOFTWARE. console.error('load fixtures/b/d.js'); var string = 'D'; exports.D = function() { return string; }; process.on('exit', function() { string = 'D done'; }); node-v0.10.25~dfsg2/test/fixtures/node_modules/0000755000000000000000000000000012270121457020122 5ustar rootrootnode-v0.10.25~dfsg2/test/fixtures/node_modules/bar.js0000644000000000000000000000227012270121457021225 0ustar rootroot// Copyright Joyent, Inc. and other Node contributors. // // Permission is hereby granted, free of charge, to any person obtaining a // copy of this software and associated documentation files (the // "Software"), to deal in the Software without restriction, including // without limitation the rights to use, copy, modify, merge, publish, // distribute, sublicense, and/or sell copies of the Software, and to permit // persons to whom the Software is furnished to do so, subject to the // following conditions: // // The above copyright notice and this permission notice shall be included // in all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS // OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF // MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN // NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, // DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR // OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE // USE OR OTHER DEALINGS IN THE SOFTWARE. console.error(__filename); console.error(module.paths.join('\n') + '\n'); node-v0.10.25~dfsg2/test/fixtures/node_modules/foo.js0000644000000000000000000000242112270121457021242 0ustar rootroot// Copyright Joyent, Inc. and other Node contributors. // // Permission is hereby granted, free of charge, to any person obtaining a // copy of this software and associated documentation files (the // "Software"), to deal in the Software without restriction, including // without limitation the rights to use, copy, modify, merge, publish, // distribute, sublicense, and/or sell copies of the Software, and to permit // persons to whom the Software is furnished to do so, subject to the // following conditions: // // The above copyright notice and this permission notice shall be included // in all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS // OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF // MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN // NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, // DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR // OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE // USE OR OTHER DEALINGS IN THE SOFTWARE. console.error(__filename); console.error(module.paths.join('\n') + '\n'); var assert = require('assert'); assert.equal(require('baz'), require('./baz/index.js')); node-v0.10.25~dfsg2/test/fixtures/node_modules/asdf.js0000644000000000000000000000234612270121457021402 0ustar rootroot// Copyright Joyent, Inc. and other Node contributors. // // Permission is hereby granted, free of charge, to any person obtaining a // copy of this software and associated documentation files (the // "Software"), to deal in the Software without restriction, including // without limitation the rights to use, copy, modify, merge, publish, // distribute, sublicense, and/or sell copies of the Software, and to permit // persons to whom the Software is furnished to do so, subject to the // following conditions: // // The above copyright notice and this permission notice shall be included // in all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS // OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF // MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN // NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, // DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR // OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE // USE OR OTHER DEALINGS IN THE SOFTWARE. console.error(__filename); console.error(module.paths.join('\n') + '\n'); throw new Error('Should not ever get here.'); node-v0.10.25~dfsg2/test/fixtures/node_modules/node_modules/0000755000000000000000000000000012270121457022577 5ustar rootrootnode-v0.10.25~dfsg2/test/fixtures/node_modules/node_modules/bar.js0000644000000000000000000000234612270121457023706 0ustar rootroot// Copyright Joyent, Inc. and other Node contributors. // // Permission is hereby granted, free of charge, to any person obtaining a // copy of this software and associated documentation files (the // "Software"), to deal in the Software without restriction, including // without limitation the rights to use, copy, modify, merge, publish, // distribute, sublicense, and/or sell copies of the Software, and to permit // persons to whom the Software is furnished to do so, subject to the // following conditions: // // The above copyright notice and this permission notice shall be included // in all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS // OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF // MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN // NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, // DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR // OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE // USE OR OTHER DEALINGS IN THE SOFTWARE. console.error(__filename); console.error(module.paths.join('\n') + '\n'); throw new Error('Should not ever get here.'); node-v0.10.25~dfsg2/test/fixtures/node_modules/baz/0000755000000000000000000000000012270121457020676 5ustar rootrootnode-v0.10.25~dfsg2/test/fixtures/node_modules/baz/node_modules/0000755000000000000000000000000012270121457023353 5ustar rootrootnode-v0.10.25~dfsg2/test/fixtures/node_modules/baz/node_modules/asdf.js0000644000000000000000000000227012270121457024627 0ustar rootroot// Copyright Joyent, Inc. and other Node contributors. // // Permission is hereby granted, free of charge, to any person obtaining a // copy of this software and associated documentation files (the // "Software"), to deal in the Software without restriction, including // without limitation the rights to use, copy, modify, merge, publish, // distribute, sublicense, and/or sell copies of the Software, and to permit // persons to whom the Software is furnished to do so, subject to the // following conditions: // // The above copyright notice and this permission notice shall be included // in all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS // OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF // MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN // NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, // DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR // OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE // USE OR OTHER DEALINGS IN THE SOFTWARE. console.error(__filename); console.error(module.paths.join('\n') + '\n'); node-v0.10.25~dfsg2/test/fixtures/node_modules/baz/index.js0000644000000000000000000000270612270121457022350 0ustar rootroot// Copyright Joyent, Inc. and other Node contributors. // // Permission is hereby granted, free of charge, to any person obtaining a // copy of this software and associated documentation files (the // "Software"), to deal in the Software without restriction, including // without limitation the rights to use, copy, modify, merge, publish, // distribute, sublicense, and/or sell copies of the Software, and to permit // persons to whom the Software is furnished to do so, subject to the // following conditions: // // The above copyright notice and this permission notice shall be included // in all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS // OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF // MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN // NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, // DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR // OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE // USE OR OTHER DEALINGS IN THE SOFTWARE. console.error(__filename); console.error(module.paths.join('\n') + '\n'); // this should work, and get the one that doesn't throw var assert = require('assert'); assert.equal(require('bar'), require('../bar.js')); // this should work, and get the one in ./node_modules/asdf.js assert.equal(require('asdf'), require('./node_modules/asdf.js')); node-v0.10.25~dfsg2/test/fixtures/global/0000755000000000000000000000000012270121457016705 5ustar rootrootnode-v0.10.25~dfsg2/test/fixtures/global/plain.js0000644000000000000000000000227612270121457020355 0ustar rootroot// Copyright Joyent, Inc. and other Node contributors. // // Permission is hereby granted, free of charge, to any person obtaining a // copy of this software and associated documentation files (the // "Software"), to deal in the Software without restriction, including // without limitation the rights to use, copy, modify, merge, publish, // distribute, sublicense, and/or sell copies of the Software, and to permit // persons to whom the Software is furnished to do so, subject to the // following conditions: // // The above copyright notice and this permission notice shall be included // in all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS // OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF // MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN // NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, // DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR // OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE // USE OR OTHER DEALINGS IN THE SOFTWARE. foo = 'foo'; global.bar = 'bar'; exports.fooBar = {foo: global.foo, bar: bar}; node-v0.10.25~dfsg2/test/fixtures/breakpoints_utf8.js0000644000000000000000000000035412270121457021274 0ustar rootrootdebugger; function a(x) { var i = 10; while (--i != 0); debugger; return i; } function b() { return ['こんにち', 'わ'].join(' '); } a(); a(1); b(); b(); setInterval(function() { }, 5000); now = new Date(); debugger; node-v0.10.25~dfsg2/test/fixtures/test_ca.pem0000644000000000000000000000231012270121457017566 0ustar rootroot-----BEGIN CERTIFICATE----- MIIDXDCCAsWgAwIBAgIJAKL0UG+mRkSPMA0GCSqGSIb3DQEBBQUAMH0xCzAJBgNV BAYTAlVLMRQwEgYDVQQIEwtBY2tuYWNrIEx0ZDETMBEGA1UEBxMKUmh5cyBKb25l czEQMA4GA1UEChMHbm9kZS5qczEdMBsGA1UECxMUVGVzdCBUTFMgQ2VydGlmaWNh dGUxEjAQBgNVBAMTCWxvY2FsaG9zdDAeFw0wOTExMTEwOTUyMjJaFw0yOTExMDYw OTUyMjJaMH0xCzAJBgNVBAYTAlVLMRQwEgYDVQQIEwtBY2tuYWNrIEx0ZDETMBEG A1UEBxMKUmh5cyBKb25lczEQMA4GA1UEChMHbm9kZS5qczEdMBsGA1UECxMUVGVz dCBUTFMgQ2VydGlmaWNhdGUxEjAQBgNVBAMTCWxvY2FsaG9zdDCBnzANBgkqhkiG 9w0BAQEFAAOBjQAwgYkCgYEA8d8Hc6atq78Jt1HLp9agA/wpQfsFvkYUdZ1YsdvO kL2janjwHQgMMCy/Njal3FUEW0OLPebKZUJ8L44JBXSlVxU4zyiiSOWld8EkTetR AVT3WKQq3ud+cnxv7g8rGRQp1UHZwmdbZ1wEfAYq8QjYx6m1ciMgRo7DaDQhD29k d+UCAwEAAaOB4zCB4DAdBgNVHQ4EFgQUL9miTJn+HKNuTmx/oMWlZP9cd4QwgbAG A1UdIwSBqDCBpYAUL9miTJn+HKNuTmx/oMWlZP9cd4ShgYGkfzB9MQswCQYDVQQG EwJVSzEUMBIGA1UECBMLQWNrbmFjayBMdGQxEzARBgNVBAcTClJoeXMgSm9uZXMx EDAOBgNVBAoTB25vZGUuanMxHTAbBgNVBAsTFFRlc3QgVExTIENlcnRpZmljYXRl MRIwEAYDVQQDEwlsb2NhbGhvc3SCCQCi9FBvpkZEjzAMBgNVHRMEBTADAQH/MA0G CSqGSIb3DQEBBQUAA4GBADRXXA2xSUK5W1i3oLYWW6NEDVWkTQ9RveplyeS9MOkP e7yPcpz0+O0ZDDrxR9chAiZ7fmdBBX1Tr+pIuCrG/Ud49SBqeS5aMJGVwiSd7o1n dhU2Sz3Q60DwJEL1VenQHiVYlWWtqXBThe9ggqRPnCfsCRTP8qifKkjk45zWPcpN -----END CERTIFICATE----- node-v0.10.25~dfsg2/test/fixtures/test_rsa_privkey_2.pem0000644000000000000000000000156312270121457021773 0ustar rootroot-----BEGIN RSA PRIVATE KEY----- MIICWQIBAAKBgQCsMgRdxxEeeXscPvqFzp/6/IIdoeKSlBn7361FWZwMQUG0qCbr XYtdXPyqp2B4GThviIqiaJZITCTY87CiV7bFvH2lmUMJLsCc3BaQ4XFQbEU5D5jN FfP7g78MEKbCb9rEfYMI2EGwbfKRUZUrYeBadzIMHEMEHDyiBXrCohTXMQIBIwKB gHEoLsFITRQGr/yeah1qhmMa9ms+fvKb1o+S/NXNLAgNoDTjh0o2KGHspgm+cpgQ kszzU8nPszbS86SC4cnEnKy/g3uw3Lf55a2P8vgh1P386/PzI+Im8s6E/EpDwn/P R2E5gqTfePl8m7r9oeIARZXysmHHgBtEm5pTUav6QvOLAkEA2arx2R/3Yb6yZ5oO 3ldZEzCBNmB6mCoczrH6jjBosb4Gj7TK+asNlbinw1gj8sgdkzAw6jGnJ2IUfftm QMykwQJBAMqFDclCf2b9cwi82+Xg+mjlT8BEf+l5xdRrweOyjB6DmUhgeqDISJUK JgxGr4TxIQ6DGeEWxChGzzU6utlRnnECQDf4wdi/E7oMdwSylhvqkz9y32XBCZTX oQHzQG20rTUE+l93oeht0EsSOcSEYQPqUL9yyr/g4dbtVbn+0SabBcsCQEs4u/pL 5i2RVpzYbu77yrk/OuEDf/eiQipT6O4sX+4Tn1VlqePynp3B8N/8/11DnpBclJVu 2yTnGcNQVAeTWBsCQFMekiY/KbwAgTopqpCUg5CLNph91FVW5PIntLmd5gSj8ZJS uNuro8CURrOe8iiI3pG9m4KkbDdOBSOMADXJojE= -----END RSA PRIVATE KEY----- node-v0.10.25~dfsg2/test/fixtures/test-regress-GH-4015.js0000644000000000000000000000012312270121457021311 0ustar rootrootvar fs = require('fs'); function load() { fs.statSync('.'); load(); } load(); node-v0.10.25~dfsg2/test/fixtures/x1024.txt0000644000000000000000000000200012270121457016754 0ustar rootrootxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxnode-v0.10.25~dfsg2/test/fixtures/test-fs-readfile-error.js0000644000000000000000000000223512270121457022272 0ustar rootroot// Copyright Joyent, Inc. and other Node contributors. // // Permission is hereby granted, free of charge, to any person obtaining a // copy of this software and associated documentation files (the // "Software"), to deal in the Software without restriction, including // without limitation the rights to use, copy, modify, merge, publish, // distribute, sublicense, and/or sell copies of the Software, and to permit // persons to whom the Software is furnished to do so, subject to the // following conditions: // // The above copyright notice and this permission notice shall be included // in all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS // OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF // MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN // NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, // DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR // OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE // USE OR OTHER DEALINGS IN THE SOFTWARE. require('fs').readFile('/'); // throws EISDIR node-v0.10.25~dfsg2/test/fixtures/test_cert.pfx0000644000000000000000000000366212270121457020167 0ustar rootroot00t *H ea0]0/ *H  00 *H 0 *H  0`XG"XcVS]/7+zH3;Zpl\ OKav@2QO$y(xfKI}z>g9 fvM ۪hSӇ`h. *ɻ_ 'ji.ҺoGq~#F@ yl!#m*s34#l;\҄ewJ`m}c^Dvf3{^ᎆ}AͣTa:0hYIͽlpWN;׽6cy8fZ@;dL  ś#0 5 ~FjvKP~-܃+#qj{.1m:1- ;)瞄G>Y47:B~fڼU,CFrHA"BsnFJIzh\3~2 Z4`ye**g$.?;ˊ޹U9lENoɲdZFq̑iV9`SON{lT(>wQ23ҸF\Zbc[ Ǧ֨?6ˮ5G2F Wc'D|5r&ꐑ9LºFon0FB :O [H<оB6] "[G]s#b?vێ"ty'f/~4!G2R|ґ]fy ]s/В`؄\ɇ+)4<u<ԡTX0qSa8٢I  ãzhI% NHD<Ϋ9\y//.1J#ZotIr-3u}$Q?[dzafqyۿ}:»Vb \$iO=!a8b9gJ}z񍧷o :F)X֯i18QΑwFNRӷr旎0& *H 00  *H  00 *H  0~(4s\5M ;GNy`^ G1{^LVA4wSpؿ**64di!~ue -ޤJ9&B7dޅs>ґg¶LyQ<E؀~ٚx.%'} C چr?jF"3ZF;똗;qQZP9w5f&gĚ"`RyF珯wX}(,K.4Гt:5er)g7o*] 0 ͇<# {'µ_RERP^[7tk@mF{vL(d(;b 4 8m凞Iiy#śu?;] kͤ0ݠϾ6~)pկ\H$wC:նr(WI#:Meje{n Bh֢1)Pg~78TyV[<-ǧZyf5D{5ҩITKHio[fT6Ð7uPόuDڼ 6ɤ͡C#J߱_[Ard0cq/HmDayRJ%f@M>4zbrOʑc0ѥ:O"p(1R0# *H  1*zSr5zZq8R0+ *H  1MY Certificate010!0 +k#>wLɱBhcnode-v0.10.25~dfsg2/test/fixtures/agent.key0000644000000000000000000000321312270121457017254 0ustar rootroot-----BEGIN RSA PRIVATE KEY----- MIIEowIBAAKCAQEAz+LXZOjcQCJq3+ZKUFabj71oo/ex/XsBcFqtBThjjTw9CVEV wfPQQp4XwtPiB204vnYXwQ1/R2NdTQqCZu47l79LssL/u2a5Y9+0NEU3nQA5qdt+ 1FAE0c5oexPimXOrR3GWfKz7PmZ2O0117IeCUUXPG5U8umhDe/4mDF4ZNJiKc404 WthquTqgS7rLQZHhZ6D0EnGnOkzlmxJMYPNHSOY1/6ivdNUUcC87awNEA3lgfhy2 5IyBK3QJc+aYKNTbt70Lery3bu2wWLFGtmNiGlQTS4JsxImRsECTI727ObS7/FWA QsqW+COL0Sa5BuMFrFIpjPrEe0ih7vRRbdmXRwIDAQABAoIBAGe4+9VqZfJN+dsq 8Osyuz01uQ8OmC0sAWTIqUlQgENIyf9rCJsUBlYmwR5BT6Z69XP6QhHdpSK+TiAR XUz0EqG9HYzcxHIBaACP7j6iRoQ8R4kbbiWKo0z3WqQGIOqFjvD/mKEuQdE5mEYw eOUCG6BnX1WY2Yr8WKd2AA/tp0/Y4d8z04u9eodMpSTbHTzYMJb5SbBN1vo6FY7q 8zSuO0BMzXlAxUsCwHsk1GQHFr8Oh3zIR7bQGtMBouI+6Lhh7sjFYsfxJboqMTBV IKaA216M6ggHG7MU1/jeKcMGDmEfqQLQoyWp29rMK6TklUgipME2L3UD7vTyAVzz xbVOpZkCgYEA8CXW4sZBBrSSrLR5SB+Ubu9qNTggLowOsC/kVKB2WJ4+xooc5HQo mFhq1v/WxPQoWIxdYsfg2odlL+JclK5Qcy6vXmRSdAQ5lK9gBDKxZSYc3NwAw2HA zyHCTK+I0n8PBYQ+yGcrxu0WqTGnlLW+Otk4CejO34WlgHwbH9bbY5UCgYEA3ZvT C4+OoMHXlmICSt29zUrYiL33IWsR3/MaONxTEDuvgkOSXXQOl/8Ebd6Nu+3WbsSN bjiPC/JyL1YCVmijdvFpl4gjtgvfJifs4G+QHvO6YfsYoVANk4u6g6rUuBIOwNK4 RwYxwDc0oysp+g7tPxoSgDHReEVKJNzGBe9NGGsCgYEA4O4QP4gCEA3B9BF2J5+s n9uPVxmiyvZUK6Iv8zP4pThTBBMIzNIf09G9AHPQ7djikU2nioY8jXKTzC3xGTHM GJZ5m6fLsu7iH+nDvSreDSeNkTBfZqGAvoGYQ8uGE+L+ZuRfCcXYsxIOT5s6o4c3 Dle2rVFpsuKzCY00urW796ECgYBn3go75+xEwrYGQSer6WR1nTgCV29GVYXKPooy zmmMOT1Yw80NSkEw0pFD4cTyqVYREsTrPU0mn1sPfrOXxnGfZSVFpcR/Je9QVfQ7 eW7GYxwfom335aqHVj10SxRqteP+UoWWnHujCPz94VRKZMakBddYCIGSan+G6YdS 7sdmwwKBgBc2qj0wvGXDF2kCLwSGfWoMf8CS1+5fIiUIdT1e/+7MfDdbmLMIFVjF QKS3zVViXCbrG5SY6wS9hxoc57f6E2A8vcaX6zy2xkZlGHQCpWRtEM5R01OWJQaH HsHMmQZGUQVoDm1oRkDhrTFK4K3ukc3rAxzeTZ96utOQN8/KJsTv -----END RSA PRIVATE KEY----- node-v0.10.25~dfsg2/test/fixtures/elipses.txt0000644000000000000000000007246012270121457017663 0ustar rootroot…………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………node-v0.10.25~dfsg2/test/fixtures/parent-process-nonpersistent.js0000644000000000000000000000042512270121457023662 0ustar rootroot var spawn = require('child_process').spawn, path = require('path'), childPath = path.join(__dirname, 'child-process-persistent.js'); var child = spawn(process.execPath, [ childPath ], { detached: true, stdio: 'ignore' }); console.log(child.pid); child.unref(); node-v0.10.25~dfsg2/test/fixtures/test_key.pem0000644000000000000000000000156712270121457020010 0ustar rootroot-----BEGIN RSA PRIVATE KEY----- MIICXQIBAAKBgQDx3wdzpq2rvwm3Ucun1qAD/ClB+wW+RhR1nVix286QvaNqePAd CAwwLL82NqXcVQRbQ4s95splQnwvjgkFdKVXFTjPKKJI5aV3wSRN61EBVPdYpCre 535yfG/uDysZFCnVQdnCZ1tnXAR8BirxCNjHqbVyIyBGjsNoNCEPb2R35QIDAQAB AoGBAJNem9C4ftrFNGtQ2DB0Udz7uDuucepkErUy4MbFsc947GfENjDKJXr42Kx0 kYx09ImS1vUpeKpH3xiuhwqe7tm4FsCBg4TYqQle14oxxm7TNeBwwGC3OB7hiokb aAjbPZ1hAuNs6ms3Ybvvj6Lmxzx42m8O5DXCG2/f+KMvaNUhAkEA/ekrOsWkNoW9 2n3m+msdVuxeek4B87EoTOtzCXb1dybIZUVv4J48VAiM43hhZHWZck2boD/hhwjC M5NWd4oY6QJBAPPcgBVNdNZSZ8hR4ogI4nzwWrQhl9MRbqqtfOn2TK/tjMv10ALg lPmn3SaPSNRPKD2hoLbFuHFERlcS79pbCZ0CQQChX3PuIna/gDitiJ8oQLOg7xEM wk9TRiDK4kl2lnhjhe6PDpaQN4E4F0cTuwqLAoLHtrNWIcOAQvzKMrYdu1MhAkBm Et3qDMnjDAs05lGT72QeN90/mPAcASf5eTTYGahv21cb6IBxM+AnwAPpqAAsHhYR 9h13Y7uYbaOjvuF23LRhAkBoI9eaSMn+l81WXOVUHnzh3ZwB4GuTyxMXXNOhuiFd 0z4LKAMh99Z4xQmqSoEkXsfM4KPpfhYjF/bwIcP5gOei -----END RSA PRIVATE KEY----- node-v0.10.25~dfsg2/test/fixtures/child-process-message-and-exit.js0000644000000000000000000000005112270121457023667 0ustar rootroot process.send('hello'); process.exit(0); node-v0.10.25~dfsg2/test/fixtures/test_rsa_pubkey.pem0000644000000000000000000000042012270121457021347 0ustar rootroot-----BEGIN PUBLIC KEY----- MIGfMA0GCSqGSIb3DQEBAQUAA4GNADCBiQKBgQDCFENGw33yGihy92pDjZQhl0C3 6rPJj+CvfSC8+q28hxA161QFNUd13wuCTUcq0Qd2qsBe/2hFyc2DCJJg0h1L78+6 Z4UMR7EOcpfdUE9Hf3m/hs+FUR45uBJeDK1HSFHD8bHKD6kv8FPGfJTotc+2xjJw oYi+1hqp1fIekaxsyQIDAQAB -----END PUBLIC KEY----- node-v0.10.25~dfsg2/test/fixtures/throws_error3.js0000644000000000000000000000225112270121457020625 0ustar rootroot// Copyright Joyent, Inc. and other Node contributors. // // Permission is hereby granted, free of charge, to any person obtaining a // copy of this software and associated documentation files (the // "Software"), to deal in the Software without restriction, including // without limitation the rights to use, copy, modify, merge, publish, // distribute, sublicense, and/or sell copies of the Software, and to permit // persons to whom the Software is furnished to do so, subject to the // following conditions: // // The above copyright notice and this permission notice shall be included // in all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS // OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF // MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN // NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, // DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR // OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE // USE OR OTHER DEALINGS IN THE SOFTWARE. process.nextTick(function() { JSON.parse(undefined); }); node-v0.10.25~dfsg2/test/fixtures/keys/0000755000000000000000000000000012270121457016420 5ustar rootrootnode-v0.10.25~dfsg2/test/fixtures/keys/agent1-csr.pem0000644000000000000000000000104612270121457021070 0ustar rootroot-----BEGIN CERTIFICATE REQUEST----- MIIBXTCCAQcCAQAwfTELMAkGA1UEBhMCVVMxCzAJBgNVBAgTAkNBMQswCQYDVQQH EwJTRjEPMA0GA1UEChMGSm95ZW50MRAwDgYDVQQLEwdOb2RlLmpzMQ8wDQYDVQQD EwZhZ2VudDExIDAeBgkqhkiG9w0BCQEWEXJ5QHRpbnljbG91ZHMub3JnMFwwDQYJ KoZIhvcNAQEBBQADSwAwSAJBAJ86QKnKF2cVic/1hSuwV8A9t45URMhtdce4JMnb Xh75+j61QWwecn7unG5PMN/wK+tPAHMjEPbx45C0Ch+3IxECAwEAAaAlMCMGCSqG SIb3DQEJBzEWExRBIGNoYWxsZW5nZSBwYXNzd29yZDANBgkqhkiG9w0BAQUFAANB AF+AfG64hNyYHum46m6i7RgnUBrJSOynGjs23TekV4he3QdMSAAPPqbll8W14+y3 vOo7/yQ2v2uTqxCjakUNPPs= -----END CERTIFICATE REQUEST----- node-v0.10.25~dfsg2/test/fixtures/keys/agent1-key.pem0000644000000000000000000000076112270121457021074 0ustar rootroot-----BEGIN RSA PRIVATE KEY----- MIIBOwIBAAJBAJ86QKnKF2cVic/1hSuwV8A9t45URMhtdce4JMnbXh75+j61QWwe cn7unG5PMN/wK+tPAHMjEPbx45C0Ch+3IxECAwEAAQJBAI2cU1IuR+4IO87WPyAB 76kruoo87AeNQkjjvuQ/00+b/6IS45mcEP5Kw0NukbqBhIw2di9uQ9J51DJ/ZfQr +YECIQDUHaN3ZjIdJ7/w8Yq9Zzz+3kY2F/xEz6e4ftOFW8bY2QIhAMAref+WYckC oECgOLAvAxB1lI4j7oCbAaawfxKdnPj5AiEAi95rXx09aGpAsBGmSdScrPdG1v6j 83/2ebrvoZ1uFqkCIB0AssnrRVjUB6GZTNTyU3ERfdkx/RX1zvr8WkFR/lXpAiB7 cUZ1i8ZkZrPrdVgw2cb28UJM7qZHQnXcMHTXFFvxeQ== -----END RSA PRIVATE KEY----- node-v0.10.25~dfsg2/test/fixtures/keys/agent4-csr.pem0000644000000000000000000000104612270121457021073 0ustar rootroot-----BEGIN CERTIFICATE REQUEST----- MIIBXTCCAQcCAQAwfTELMAkGA1UEBhMCVVMxCzAJBgNVBAgTAkNBMQswCQYDVQQH EwJTRjEPMA0GA1UEChMGSm95ZW50MRAwDgYDVQQLEwdOb2RlLmpzMQ8wDQYDVQQD EwZhZ2VudDQxIDAeBgkqhkiG9w0BCQEWEXJ5QHRpbnljbG91ZHMub3JnMFwwDQYJ KoZIhvcNAQEBBQADSwAwSAJBAM3/Ix+ZDzN2+aOUaTtvcyfrBjYWNoxvhzkQ0lfX m/JiEpLXOHHqfSRAifa9/rKobu07k6TPYgmIP1JrTqYroasCAwEAAaAlMCMGCSqG SIb3DQEJBzEWExRBIGNoYWxsZW5nZSBwYXNzd29yZDANBgkqhkiG9w0BAQUFAANB AMzo7GUOBtGm5MSck1rrEE2C1bU3qoVvXVuiN3A/57zXeNeq24FZMLnkDeL9U+/b Kj646XFou04gla982Xp74p0= -----END CERTIFICATE REQUEST----- node-v0.10.25~dfsg2/test/fixtures/keys/agent4-cert.pem0000644000000000000000000000152312270121457021241 0ustar rootroot-----BEGIN CERTIFICATE----- MIICSDCCAbGgAwIBAgIJAIMGvn3huwmaMA0GCSqGSIb3DQEBBQUAMHoxCzAJBgNV BAYTAlVTMQswCQYDVQQIEwJDQTELMAkGA1UEBxMCU0YxDzANBgNVBAoTBkpveWVu dDEQMA4GA1UECxMHTm9kZS5qczEMMAoGA1UEAxMDY2EyMSAwHgYJKoZIhvcNAQkB FhFyeUB0aW55Y2xvdWRzLm9yZzAeFw0xMTAzMTQxODI5MTJaFw0zODA3MjkxODI5 MTJaMH0xCzAJBgNVBAYTAlVTMQswCQYDVQQIEwJDQTELMAkGA1UEBxMCU0YxDzAN BgNVBAoTBkpveWVudDEQMA4GA1UECxMHTm9kZS5qczEPMA0GA1UEAxMGYWdlbnQ0 MSAwHgYJKoZIhvcNAQkBFhFyeUB0aW55Y2xvdWRzLm9yZzBcMA0GCSqGSIb3DQEB AQUAA0sAMEgCQQDN/yMfmQ8zdvmjlGk7b3Mn6wY2FjaMb4c5ENJX15vyYhKS1zhx 6n0kQIn2vf6yqG7tO5Okz2IJiD9Sa06mK6GrAgMBAAGjFzAVMBMGA1UdJQQMMAoG CCsGAQUFBwMCMA0GCSqGSIb3DQEBBQUAA4GBAA8FXpRmdrHBdlofNvxa14zLvv0N WnUGUmxVklFLKXvpVWTanOhVgI2TDCMrT5WvCRTD25iT1EUKWxjDhFJrklQJ+IfC KC6fsgO7AynuxWSfSkc8/acGiAH+20vW9QxR53HYiIDMXEV/wnE0KVcr3t/d70lr ImanTrunagV+3O4O -----END CERTIFICATE----- node-v0.10.25~dfsg2/test/fixtures/keys/agent4-key.pem0000644000000000000000000000075512270121457021102 0ustar rootroot-----BEGIN RSA PRIVATE KEY----- MIIBOQIBAAJBAM3/Ix+ZDzN2+aOUaTtvcyfrBjYWNoxvhzkQ0lfXm/JiEpLXOHHq fSRAifa9/rKobu07k6TPYgmIP1JrTqYroasCAwEAAQJAN8RQb+dx1A7rejtdWbfM Rww7PD07Oz2eL/a72wgFsdIabRuVypIoHunqV0sAegYtNJt9yu+VhREw0R5tx/qz EQIhAPY+nmzp0b4iFRk7mtGUmCTr9iwwzoqzITwphE7FpQnFAiEA1ihUHFT9YPHO f85skM6qZv77NEgXHO8NJmQZ5GX1ZK8CICzle+Mluo0tD6W7HV4q9pZ8wzSJbY8S W/PpKetm09F1AiAWTw8sAGKAtc/IGo3Oq+iuYAN1F8lolzJsfGMCGujsOwIgAJKP t3eXilwX3ZlsDWSklWNZ7iYcfYrvAc3JqU6gFCE= -----END RSA PRIVATE KEY----- node-v0.10.25~dfsg2/test/fixtures/keys/ca2-database.txt0000644000000000000000000000020512270121457021365 0ustar rootrootR 380729182912Z 110314182914Z 8306BE7DE1BB099A unknown /C=US/ST=CA/L=SF/O=Joyent/OU=Node.js/CN=agent4/emailAddress=ry@tinyclouds.org node-v0.10.25~dfsg2/test/fixtures/keys/ca2-key.pem0000644000000000000000000000202112270121457020351 0ustar rootroot-----BEGIN ENCRYPTED PRIVATE KEY----- MIICxjBABgkqhkiG9w0BBQ0wMzAbBgkqhkiG9w0BBQwwDgQIbhsCgrscf9MCAggA MBQGCCqGSIb3DQMHBAjz0LdWOB2KVQSCAoDu+sHRLP6v6QiEwqynnF43yP02/F+8 Jssz6cgFPpm4MWm+xwzvMsS4ET0UYE68OTZz/QgihwH0mp/34tkUnP0HqtdbnTH1 fkG47hb8fVSEyDQSzs1ha/u31GIachNURKyhWR5mr15AJxu2B94Z3ldNv1yjI+Fy M1muuyx/cdkKTdpfpYr6n//wF1tup2u8Y7nkKsFus/mCuRlpItxKcRb1+nvW0s+K 3bSR8CTlEWd1Tx6Qx+ogRbP8gwqd6gelcz/Zj8nInx/Y0gTkQ4eodmLJ5iqsvC36 SgQB5LuP12ujTyXB3Hwqb8LJ4lULERX6AYHAa7h0c+fxuFr0W9/8atplrd22hoiP zZhgPHeH3R1fibB4M4xW2xgtbysOHj74RYlhQm1TCXLlqvzKkvT2oQ1bk7tUUqoR ozRxVzdL9oKWLzvR4LF8S67i35JlnOPU1AhcxD2+5ywRvTpugPyCE1mZOeVLHlGW 2pdmSKbdd2gm2iSfadDPJ1DPdHLp844jRg/D6XDs4rlBnt9FjMWaXYo+ELmokoYe Yljv2MGfy6zsb5iKcNsx+llu04xGXfZ9BAuG+aT6DLCIcDIVvE0d6asc4Lz1xZli BrgyB8el2a/PomPbbf1vI2vtDi3Rg/pQhu/2++ODI08jI9Rudz1EltQQ4Lo38Ton nSZegTAy6afXiEh2ty09KxMo4sWs+F2I46e5Q3zGY9b/K19bbQTFxeBf2Rfwa8BF cf8Xs+DlcOMz5w0U2iBQfT1cV7dWLlaop7avYkpQ0fLa1pConlNhpguezcaAB8Lb VCfpoTh6VfHRtCLokQlkq0mlKPUSlMr/JAyVdvppp/T6Abt0VirM9ILV -----END ENCRYPTED PRIVATE KEY----- node-v0.10.25~dfsg2/test/fixtures/keys/agent2.cnf0000644000000000000000000000077612270121457020302 0ustar rootroot[ req ] default_bits = 1024 days = 999 distinguished_name = req_distinguished_name attributes = req_attributes prompt = no [ req_distinguished_name ] C = US ST = CA L = SF O = Joyent OU = Node.js CN = agent2 emailAddress = ry@tinyclouds.org [ req_attributes ] challengePassword = A challenge password node-v0.10.25~dfsg2/test/fixtures/keys/ca2-serial0000644000000000000000000000000312270121457020256 0ustar rootroot01 node-v0.10.25~dfsg2/test/fixtures/keys/ca2-cert.srl0000644000000000000000000000002112270121457020533 0ustar rootroot8306BE7DE1BB099A node-v0.10.25~dfsg2/test/fixtures/keys/ca2.cnf0000644000000000000000000000135112270121457017555 0ustar rootroot[ ca ] default_ca = CA_default [ CA_default ] serial = ca2-serial crl = ca2-crl.pem database = ca2-database.txt name_opt = CA_default cert_opt = CA_default default_crl_days = 999 default_md = md5 [ req ] default_bits = 1024 days = 999 distinguished_name = req_distinguished_name attributes = req_attributes prompt = no output_password = password [ req_distinguished_name ] C = US ST = CA L = SF O = Joyent OU = Node.js CN = ca2 emailAddress = ry@tinyclouds.org [ req_attributes ] challengePassword = A challenge password node-v0.10.25~dfsg2/test/fixtures/keys/agent2-cert.pem0000644000000000000000000000133112270121457021234 0ustar rootroot-----BEGIN CERTIFICATE----- MIIB7DCCAZYCCQC7gs0MDNn6MTANBgkqhkiG9w0BAQUFADB9MQswCQYDVQQGEwJV UzELMAkGA1UECBMCQ0ExCzAJBgNVBAcTAlNGMQ8wDQYDVQQKEwZKb3llbnQxEDAO BgNVBAsTB05vZGUuanMxDzANBgNVBAMTBmFnZW50MjEgMB4GCSqGSIb3DQEJARYR cnlAdGlueWNsb3Vkcy5vcmcwHhcNMTEwMzE0MTgyOTEyWhcNMzgwNzI5MTgyOTEy WjB9MQswCQYDVQQGEwJVUzELMAkGA1UECBMCQ0ExCzAJBgNVBAcTAlNGMQ8wDQYD VQQKEwZKb3llbnQxEDAOBgNVBAsTB05vZGUuanMxDzANBgNVBAMTBmFnZW50MjEg MB4GCSqGSIb3DQEJARYRcnlAdGlueWNsb3Vkcy5vcmcwXDANBgkqhkiG9w0BAQEF AANLADBIAkEAyXb8FrRdKbhrKLgLSsn61i1C7w7fVVVd7OQsmV/7p9WB2lWFiDlC WKGU9SiIz/A6wNZDUAuc2E+VwtpCT561AQIDAQABMA0GCSqGSIb3DQEBBQUAA0EA C8HzpuNhFLCI3A5KkBS5zHAQax6TFUOhbpBCR0aTDbJ6F1liDTK1lmU/BjvPoj+9 1LHwrmh29rK8kBPEjmymCQ== -----END CERTIFICATE----- node-v0.10.25~dfsg2/test/fixtures/keys/ca2-cert.pem0000644000000000000000000000160312270121457020523 0ustar rootroot-----BEGIN CERTIFICATE----- MIICazCCAdQCCQDVGbMO4Y2VUTANBgkqhkiG9w0BAQUFADB6MQswCQYDVQQGEwJV UzELMAkGA1UECBMCQ0ExCzAJBgNVBAcTAlNGMQ8wDQYDVQQKEwZKb3llbnQxEDAO BgNVBAsTB05vZGUuanMxDDAKBgNVBAMTA2NhMjEgMB4GCSqGSIb3DQEJARYRcnlA dGlueWNsb3Vkcy5vcmcwHhcNMTEwMzE0MTgyOTEyWhcNMzgwNzI5MTgyOTEyWjB6 MQswCQYDVQQGEwJVUzELMAkGA1UECBMCQ0ExCzAJBgNVBAcTAlNGMQ8wDQYDVQQK EwZKb3llbnQxEDAOBgNVBAsTB05vZGUuanMxDDAKBgNVBAMTA2NhMjEgMB4GCSqG SIb3DQEJARYRcnlAdGlueWNsb3Vkcy5vcmcwgZ8wDQYJKoZIhvcNAQEBBQADgY0A MIGJAoGBAMOOtRmmjoBZmyYreB1D1fjftMW6sEGBzfSKZRcn+kiEpqXELq21O/TV jLJGbo+0PDqxECQyDbOgoQZXcCevFnFhdsSQOYb+0O2kAiMVYGxDtqoKM5g8wj0D BiE6fnyZoQTDv5lEuvfG0+youCtXlxiK/9cfhikI+hVXuTgwQXt9AgMBAAEwDQYJ KoZIhvcNAQEFBQADgYEAbMrLydFajwfZXDH3PfpKtDPCm+yV3qvEMGWLfjBdN50g PwsZE/OIp+KJttdS+MjMG1TfwfWIqa5zGG2ctxx+fHsKH+t3NsO76Eol1p+dKqZp PdFp2UhViMgURkrpP593AsTTO9BGaz+awSaESDHm8pO+cLaeGKQp93W0sgC0lHQ= -----END CERTIFICATE----- node-v0.10.25~dfsg2/test/fixtures/keys/Makefile0000644000000000000000000000642512270121457020067 0ustar rootrootall: agent1-cert.pem agent2-cert.pem agent3-cert.pem agent4-cert.pem ca2-crl.pem # # Create Certificate Authority: ca1 # ('password' is used for the CA password.) # ca1-cert.pem: ca1.cnf openssl req -new -x509 -days 9999 -config ca1.cnf -keyout ca1-key.pem -out ca1-cert.pem # # Create Certificate Authority: ca2 # ('password' is used for the CA password.) # ca2-cert.pem: ca2.cnf openssl req -new -x509 -days 9999 -config ca2.cnf -keyout ca2-key.pem -out ca2-cert.pem echo '01' > ca2-serial touch ca2-database.txt # # agent1 is signed by ca1. # agent1-key.pem: openssl genrsa -out agent1-key.pem 1024 agent1-csr.pem: agent1.cnf agent1-key.pem openssl req -new -config agent1.cnf -key agent1-key.pem -out agent1-csr.pem agent1-cert.pem: agent1-csr.pem ca1-cert.pem ca1-key.pem openssl x509 -req \ -days 9999 \ -passin "pass:password" \ -in agent1-csr.pem \ -CA ca1-cert.pem \ -CAkey ca1-key.pem \ -CAcreateserial \ -out agent1-cert.pem agent1-verify: agent1-cert.pem ca1-cert.pem openssl verify -CAfile ca1-cert.pem agent1-cert.pem # # agent2 has a self signed cert # # Generate new private key agent2-key.pem: openssl genrsa -out agent2-key.pem 1024 # Create a Certificate Signing Request for the key agent2-csr.pem: agent2-key.pem agent2.cnf openssl req -new -config agent2.cnf -key agent2-key.pem -out agent2-csr.pem # Create a Certificate for the agent. agent2-cert.pem: agent2-csr.pem agent2-key.pem openssl x509 -req \ -days 9999 \ -in agent2-csr.pem \ -signkey agent2-key.pem \ -out agent2-cert.pem agent2-verify: agent2-cert.pem openssl verify -CAfile agent2-cert.pem agent2-cert.pem # # agent3 is signed by ca2. # agent3-key.pem: openssl genrsa -out agent3-key.pem 1024 agent3-csr.pem: agent3.cnf agent3-key.pem openssl req -new -config agent3.cnf -key agent3-key.pem -out agent3-csr.pem agent3-cert.pem: agent3-csr.pem ca2-cert.pem ca2-key.pem openssl x509 -req \ -days 9999 \ -passin "pass:password" \ -in agent3-csr.pem \ -CA ca2-cert.pem \ -CAkey ca2-key.pem \ -CAcreateserial \ -out agent3-cert.pem agent3-verify: agent3-cert.pem ca2-cert.pem openssl verify -CAfile ca2-cert.pem agent3-cert.pem # # agent4 is signed by ca2 (client cert) # agent4-key.pem: openssl genrsa -out agent4-key.pem 1024 agent4-csr.pem: agent4.cnf agent4-key.pem openssl req -new -config agent4.cnf -key agent4-key.pem -out agent4-csr.pem agent4-cert.pem: agent4-csr.pem ca2-cert.pem ca2-key.pem openssl x509 -req \ -days 9999 \ -passin "pass:password" \ -in agent4-csr.pem \ -CA ca2-cert.pem \ -CAkey ca2-key.pem \ -CAcreateserial \ -extfile agent4.cnf \ -extensions ext_key_usage \ -out agent4-cert.pem agent4-verify: agent4-cert.pem ca2-cert.pem openssl verify -CAfile ca2-cert.pem agent4-cert.pem # # Make CRL with agent4 being rejected # ca2-crl.pem: ca2-key.pem ca2-cert.pem ca2.cnf openssl ca -revoke agent4-cert.pem \ -keyfile ca2-key.pem \ -cert ca2-cert.pem \ -config ca2.cnf \ -passin 'pass:password' openssl ca \ -keyfile ca2-key.pem \ -cert ca2-cert.pem \ -config ca2.cnf \ -gencrl \ -out ca2-crl.pem \ -passin 'pass:password' clean: rm -f *.pem *.srl ca2-database.txt ca2-serial test: agent1-verify agent2-verify agent3-verify agent4-verify .PHONY: all clean test agent1-verify agent2-verify agent3-verify agent4-verify node-v0.10.25~dfsg2/test/fixtures/keys/ca1.cnf0000644000000000000000000000103512270121457017553 0ustar rootroot[ req ] default_bits = 1024 days = 999 distinguished_name = req_distinguished_name attributes = req_attributes prompt = no output_password = password [ req_distinguished_name ] C = US ST = CA L = SF O = Joyent OU = Node.js CN = ca1 emailAddress = ry@tinyclouds.org [ req_attributes ] challengePassword = A challenge password node-v0.10.25~dfsg2/test/fixtures/keys/ca1-key.pem0000644000000000000000000000202112270121457020350 0ustar rootroot-----BEGIN ENCRYPTED PRIVATE KEY----- MIICxjBABgkqhkiG9w0BBQ0wMzAbBgkqhkiG9w0BBQwwDgQIrulhMUmafvECAggA MBQGCCqGSIb3DQMHBAjsjahmkf3zGwSCAoANt0xX8ZZT2CxeyUadbOuku6NrHoFy YBvnEFvuq3TGm3NB72BxprvfMUNR5Xi6e6rJgtRQttPRX6oN2qfB8+W11vFBeFWG gxarEotklca4bujPMwxRowyMT20n+yXvRc+Fd5tYrMcaBeweQZD69J242HJMJJmq Lzvo2qYGaOxjpc8aUDzeDsv8cnlh5Xk1ZcRucRPM9j26KOPSt0wOd4RdN83AE8cW Xu+k5TSMlPQLWihjS+KzEQ8Rs9CuubxrdmecF6DM70u0kYCLZ1Ex7+kBZu06CUpJ PODaLca4W92XkBq4X25WgAAaCAj4nZZmgn0X0Fwl1lBqjOK5nEnYpjxuwjjJ2KVz 3j+kBK5tW6RBE4BM37r7NiM1FAzi8sgNYSVS9oa4m1qGfadEEQdhaMsAfM0SZ/8M 6NUPKlQmoDda9aCO7rqRuQ7pYQ9mpNxcWEBQi0cG6/3VXtqi/TewAKT1T5DToAzg pL4eOTqeDp4VKif5r2u7Nj0EiM4j2TT88onGsdgRtjgUpNmJCRWYaCzs3QZggdYE nLZt7ZRXpJ11tERKG3b28qrIw9jHULRAjjWEkEGbxYTpAlrgXklV/04XXnxxAVOP 0YjDzbfx5QCRCq5UHV4Gl3ELoBaOuxcIIN8YrE2oC1CY9uV/HSk4CSlxHNtWyxbA WbCU2SoEHnwBVlTPbZyfErM33c3u4LJyNx6ah7NzMh5AoQ+cPXlzxFBEGIyAmW37 pItxDNwL1PzXHGpfOM/QZ5wjzGIwXsh8j94jDNB+TIMG4+dm4aXkolevPjJrYAeG XZC5mvfMsntNGNFszT/8iXLwt7tlMlQQQl/2b5m6L5yffy6m39wGqTVa -----END ENCRYPTED PRIVATE KEY----- node-v0.10.25~dfsg2/test/fixtures/keys/ca1-cert.pem0000644000000000000000000000160312270121457020522 0ustar rootroot-----BEGIN CERTIFICATE----- MIICazCCAdQCCQDTlFdg2h0DBjANBgkqhkiG9w0BAQUFADB6MQswCQYDVQQGEwJV UzELMAkGA1UECBMCQ0ExCzAJBgNVBAcTAlNGMQ8wDQYDVQQKEwZKb3llbnQxEDAO BgNVBAsTB05vZGUuanMxDDAKBgNVBAMTA2NhMTEgMB4GCSqGSIb3DQEJARYRcnlA dGlueWNsb3Vkcy5vcmcwHhcNMTEwMzE0MTgyOTEyWhcNMzgwNzI5MTgyOTEyWjB6 MQswCQYDVQQGEwJVUzELMAkGA1UECBMCQ0ExCzAJBgNVBAcTAlNGMQ8wDQYDVQQK EwZKb3llbnQxEDAOBgNVBAsTB05vZGUuanMxDDAKBgNVBAMTA2NhMTEgMB4GCSqG SIb3DQEJARYRcnlAdGlueWNsb3Vkcy5vcmcwgZ8wDQYJKoZIhvcNAQEBBQADgY0A MIGJAoGBAKxbsLdJbi53pcP1pzg8lgJhLEvcNlV2ogr97WURp+gPjK+HFXj2xl9w qDQrxpmvTya+urBG7OagTjV1E7dRE7PTr4TkEqehmxF026Opb0PZewuIBOKX4UgG PSfk0fksrje6YJb+OkiBfA/q7eznZF8cmq7MRrs7LWe9A6Bic/apAgMBAAEwDQYJ KoZIhvcNAQEFBQADgYEAk6hlYgjCBihG4dM+3324W1WsvjU8QscsTXu8SGL0y9b6 82zZikj0W9FU6u98WHtXwuFt3mKlGCcou2pluZvj02T2iVKSMs2oYL8JOlvM8hVf GEeg2EriLlzmdxNz4/I86DlBiyoTijZh8/qrItsK7+a56P0exH8ouXzlhL1Bhjw= -----END CERTIFICATE----- node-v0.10.25~dfsg2/test/fixtures/keys/agent1-cert.pem0000644000000000000000000000145212270121457021237 0ustar rootroot-----BEGIN CERTIFICATE----- MIICKjCCAZMCCQDQ8o4kHKdCPDANBgkqhkiG9w0BAQUFADB6MQswCQYDVQQGEwJV UzELMAkGA1UECBMCQ0ExCzAJBgNVBAcTAlNGMQ8wDQYDVQQKEwZKb3llbnQxEDAO BgNVBAsTB05vZGUuanMxDDAKBgNVBAMTA2NhMTEgMB4GCSqGSIb3DQEJARYRcnlA dGlueWNsb3Vkcy5vcmcwHhcNMTEwMzE0MTgyOTEyWhcNMzgwNzI5MTgyOTEyWjB9 MQswCQYDVQQGEwJVUzELMAkGA1UECBMCQ0ExCzAJBgNVBAcTAlNGMQ8wDQYDVQQK EwZKb3llbnQxEDAOBgNVBAsTB05vZGUuanMxDzANBgNVBAMTBmFnZW50MTEgMB4G CSqGSIb3DQEJARYRcnlAdGlueWNsb3Vkcy5vcmcwXDANBgkqhkiG9w0BAQEFAANL ADBIAkEAnzpAqcoXZxWJz/WFK7BXwD23jlREyG11x7gkydteHvn6PrVBbB5yfu6c bk8w3/Ar608AcyMQ9vHjkLQKH7cjEQIDAQABMA0GCSqGSIb3DQEBBQUAA4GBAKha HqjCfTIut+m/idKy3AoFh48tBHo3p9Nl5uBjQJmahKdZAaiksL24Pl+NzPQ8LIU+ FyDHFp6OeJKN6HzZ72Bh9wpBVu6Uj1hwhZhincyTXT80wtSI/BoUAW8Ls2kwPdus 64LsJhhxqj2m4vPKNRbHB2QxnNrGi30CUf3kt3Ia -----END CERTIFICATE----- node-v0.10.25~dfsg2/test/fixtures/keys/agent1.cnf0000644000000000000000000000077612270121457020301 0ustar rootroot[ req ] default_bits = 1024 days = 999 distinguished_name = req_distinguished_name attributes = req_attributes prompt = no [ req_distinguished_name ] C = US ST = CA L = SF O = Joyent OU = Node.js CN = agent1 emailAddress = ry@tinyclouds.org [ req_attributes ] challengePassword = A challenge password node-v0.10.25~dfsg2/test/fixtures/keys/agent3-csr.pem0000644000000000000000000000104612270121457021072 0ustar rootroot-----BEGIN CERTIFICATE REQUEST----- MIIBXTCCAQcCAQAwfTELMAkGA1UEBhMCVVMxCzAJBgNVBAgTAkNBMQswCQYDVQQH EwJTRjEPMA0GA1UEChMGSm95ZW50MRAwDgYDVQQLEwdOb2RlLmpzMQ8wDQYDVQQD EwZhZ2VudDMxIDAeBgkqhkiG9w0BCQEWEXJ5QHRpbnljbG91ZHMub3JnMFwwDQYJ KoZIhvcNAQEBBQADSwAwSAJBALZTQ2fmx3gSNAdoA/yFqgOwKtYcLJ0uPl6Zy3rI 00HC9icBRaZEdKFq8Mo62IQqIIu3OYIyqy2RdXdiQ+SYB4ECAwEAAaAlMCMGCSqG SIb3DQEJBzEWExRBIGNoYWxsZW5nZSBwYXNzd29yZDANBgkqhkiG9w0BAQUFAANB AEGo76iH+a8pnE+RWQT+wg9/BL+iIuqrcFXLs0rbGonqderrwXAe15ODwql/Bfu3 zgMt8ooTsgMPcMX9EgmubEM= -----END CERTIFICATE REQUEST----- node-v0.10.25~dfsg2/test/fixtures/keys/agent2-key.pem0000644000000000000000000000075512270121457021100 0ustar rootroot-----BEGIN RSA PRIVATE KEY----- MIIBOgIBAAJBAMl2/Ba0XSm4ayi4C0rJ+tYtQu8O31VVXezkLJlf+6fVgdpVhYg5 QlihlPUoiM/wOsDWQ1ALnNhPlcLaQk+etQECAwEAAQJBAMT6Bf34+UHKY1ObpsbH 9u2jsVblFq1rWvs8GPMY6oertzvwm3DpuSUp7PTgOB1nLTLYtCERbQ4ovtN8tn3p OHUCIQDzIEGsoCr5vlxXvy2zJwu+fxYuhTZWMVuo1397L0VyhwIhANQh+yzqUgaf WRtSB4T2W7ADtJI35ET61jKBty3CqJY3AiAIwju7dVW3A5WeD6Qc1SZGKZvp9yCb AFI2BfVwwaY11wIgXF3PeGcvACMyMWsuSv7aPXHfliswAbkWuzcwA4TW01ECIGWa cgsDvVFxmfM5NPSuT/UDTa6R5BFISB5ea0N0AR3I -----END RSA PRIVATE KEY----- node-v0.10.25~dfsg2/test/fixtures/keys/ca2-crl.pem0000644000000000000000000000102012270121457020337 0ustar rootroot-----BEGIN X509 CRL----- MIIBXTCBxzANBgkqhkiG9w0BAQQFADB6MQswCQYDVQQGEwJVUzELMAkGA1UECBMC Q0ExCzAJBgNVBAcTAlNGMQ8wDQYDVQQKEwZKb3llbnQxEDAOBgNVBAsTB05vZGUu anMxDDAKBgNVBAMTA2NhMjEgMB4GCSqGSIb3DQEJARYRcnlAdGlueWNsb3Vkcy5v cmcXDTExMDMxNDE4MjkxNloXDTEzMTIwNzE4MjkxNlowHDAaAgkAgwa+feG7CZoX DTExMDMxNDE4MjkxNFowDQYJKoZIhvcNAQEEBQADgYEArRKuEkOla61fm4zlZtHe LTXFV0Hgo21PScHAp6JqPol4rN5R9+EmUkv7gPCVVBJ9VjIgxSosHiLsDiz3zR+u txHemhzbdIVANAIiChnFct8sEqH2eL4N6XNUIlMIR06NjNl7NbN8w8haqiearnuT wmnaL4TThPmpbpKAF7N7JqQ= -----END X509 CRL----- node-v0.10.25~dfsg2/test/fixtures/keys/agent3.cnf0000644000000000000000000000077612270121457020303 0ustar rootroot[ req ] default_bits = 1024 days = 999 distinguished_name = req_distinguished_name attributes = req_attributes prompt = no [ req_distinguished_name ] C = US ST = CA L = SF O = Joyent OU = Node.js CN = agent3 emailAddress = ry@tinyclouds.org [ req_attributes ] challengePassword = A challenge password node-v0.10.25~dfsg2/test/fixtures/keys/ca1-cert.srl0000644000000000000000000000002112270121457020532 0ustar rootrootD0F28E241CA7423C node-v0.10.25~dfsg2/test/fixtures/keys/agent4.cnf0000644000000000000000000000106412270121457020273 0ustar rootroot[ req ] default_bits = 1024 days = 999 distinguished_name = req_distinguished_name attributes = req_attributes prompt = no [ req_distinguished_name ] C = US ST = CA L = SF O = Joyent OU = Node.js CN = agent4 emailAddress = ry@tinyclouds.org [ req_attributes ] challengePassword = A challenge password [ ext_key_usage ] extendedKeyUsage = clientAuth node-v0.10.25~dfsg2/test/fixtures/keys/agent2-csr.pem0000644000000000000000000000104612270121457021071 0ustar rootroot-----BEGIN CERTIFICATE REQUEST----- MIIBXTCCAQcCAQAwfTELMAkGA1UEBhMCVVMxCzAJBgNVBAgTAkNBMQswCQYDVQQH EwJTRjEPMA0GA1UEChMGSm95ZW50MRAwDgYDVQQLEwdOb2RlLmpzMQ8wDQYDVQQD EwZhZ2VudDIxIDAeBgkqhkiG9w0BCQEWEXJ5QHRpbnljbG91ZHMub3JnMFwwDQYJ KoZIhvcNAQEBBQADSwAwSAJBAMl2/Ba0XSm4ayi4C0rJ+tYtQu8O31VVXezkLJlf +6fVgdpVhYg5QlihlPUoiM/wOsDWQ1ALnNhPlcLaQk+etQECAwEAAaAlMCMGCSqG SIb3DQEJBzEWExRBIGNoYWxsZW5nZSBwYXNzd29yZDANBgkqhkiG9w0BAQUFAANB AJnll2pt5l0pzskQSpjjLVTlFDFmJr/AZ3UK8v0WxBjYjCe5Jx4YehkChpxIyDUm U3J9q9MDUf0+Y2+EGkssFfk= -----END CERTIFICATE REQUEST----- node-v0.10.25~dfsg2/test/fixtures/keys/agent3-key.pem0000644000000000000000000000076112270121457021076 0ustar rootroot-----BEGIN RSA PRIVATE KEY----- MIIBOwIBAAJBALZTQ2fmx3gSNAdoA/yFqgOwKtYcLJ0uPl6Zy3rI00HC9icBRaZE dKFq8Mo62IQqIIu3OYIyqy2RdXdiQ+SYB4ECAwEAAQJAIk+G9s2SKgFa8y3a2jGZ LfqABSzmJGooaIsOpLuYLd6eCC31XUDlT4rPVGRhysKQCQ4+NMjgdnj9ZqNnvXY/ RQIhAOgbdltr3Ey2hy7RuDW5rmOeJTuVqCrZ7QI8ifyCEbYTAiEAyRfvWSvvASeP kZTMUhATRUpuyDQW+058NE0oJSinTpsCIQCR/FPhBGI3TcaQyA9Ym0T4GwvIAkUX TqInefRAAX8qSQIgZVJPAdIWGbHSL9sWW97HpukLCorcbYEtKbkamiZyrjMCIQCX lX76ttkeId5OsJGQcF67eFMMr2UGZ1WMf6M39lCYHQ== -----END RSA PRIVATE KEY----- node-v0.10.25~dfsg2/test/fixtures/keys/agent3-cert.pem0000644000000000000000000000145212270121457021241 0ustar rootroot-----BEGIN CERTIFICATE----- MIICKjCCAZMCCQCDBr594bsJmTANBgkqhkiG9w0BAQUFADB6MQswCQYDVQQGEwJV UzELMAkGA1UECBMCQ0ExCzAJBgNVBAcTAlNGMQ8wDQYDVQQKEwZKb3llbnQxEDAO BgNVBAsTB05vZGUuanMxDDAKBgNVBAMTA2NhMjEgMB4GCSqGSIb3DQEJARYRcnlA dGlueWNsb3Vkcy5vcmcwHhcNMTEwMzE0MTgyOTEyWhcNMzgwNzI5MTgyOTEyWjB9 MQswCQYDVQQGEwJVUzELMAkGA1UECBMCQ0ExCzAJBgNVBAcTAlNGMQ8wDQYDVQQK EwZKb3llbnQxEDAOBgNVBAsTB05vZGUuanMxDzANBgNVBAMTBmFnZW50MzEgMB4G CSqGSIb3DQEJARYRcnlAdGlueWNsb3Vkcy5vcmcwXDANBgkqhkiG9w0BAQEFAANL ADBIAkEAtlNDZ+bHeBI0B2gD/IWqA7Aq1hwsnS4+XpnLesjTQcL2JwFFpkR0oWrw yjrYhCogi7c5gjKrLZF1d2JD5JgHgQIDAQABMA0GCSqGSIb3DQEBBQUAA4GBAJoK bXwsImk7vJz9649yrmsXwnuGbEKVYMvqcGyjaZNP9lYEG41y5CeRzxhWy2rlYdhE f2nqE2lg75oJP7LQqfQY7aCqwahM3q/GQbsfKVCGjF7TVyq9TQzd8iW+FEJIQzSE 3aN85hR67+3VAXeSzmkGSVBO2m1SJIug4qftIkc2 -----END CERTIFICATE----- node-v0.10.25~dfsg2/test/fixtures/recvfd.js0000644000000000000000000000470212270121457017257 0ustar rootroot// Copyright Joyent, Inc. and other Node contributors. // // Permission is hereby granted, free of charge, to any person obtaining a // copy of this software and associated documentation files (the // "Software"), to deal in the Software without restriction, including // without limitation the rights to use, copy, modify, merge, publish, // distribute, sublicense, and/or sell copies of the Software, and to permit // persons to whom the Software is furnished to do so, subject to the // following conditions: // // The above copyright notice and this permission notice shall be included // in all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS // OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF // MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN // NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, // DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR // OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE // USE OR OTHER DEALINGS IN THE SOFTWARE. // See test/simple/test-sendfd.js for a complete description of what this // script is doing and how it fits into the test as a whole. var net = require('net'); var receivedData = []; var receivedFDs = []; var numSentMessages = 0; function processData(s) { if (receivedData.length == 0 || receivedFDs.length == 0) { return; } var fd = receivedFDs.shift(); var d = receivedData.shift(); // Augment our received object before sending it back across the pipe. d.pid = process.pid; // Create a stream around the FD that we received and send a serialized // version of our modified object back. Clean up when we're done. var pipeStream = new net.Stream(fd); var drainFunc = function() { pipeStream.destroy(); if (++numSentMessages == 2) { s.destroy(); } }; pipeStream.on('drain', drainFunc); pipeStream.resume(); if (pipeStream.write(JSON.stringify(d) + '\n')) { drainFunc(); } } // Create a UNIX socket to the path defined by argv[2] and read a file // descriptor and misc data from it. var s = new net.Stream(); s.on('fd', function(fd) { receivedFDs.unshift(fd); processData(s); }); s.on('data', function(data) { data.toString('utf8').trim().split('\n').forEach(function(d) { receivedData.unshift(JSON.parse(d)); }); processData(s); }); s.connect(process.argv[2]); // vim:ts=2 sw=2 et node-v0.10.25~dfsg2/test/fixtures/print-10-lines.js0000644000000000000000000000225412270121457020470 0ustar rootroot// Copyright Joyent, Inc. and other Node contributors. // // Permission is hereby granted, free of charge, to any person obtaining a // copy of this software and associated documentation files (the // "Software"), to deal in the Software without restriction, including // without limitation the rights to use, copy, modify, merge, publish, // distribute, sublicense, and/or sell copies of the Software, and to permit // persons to whom the Software is furnished to do so, subject to the // following conditions: // // The above copyright notice and this permission notice shall be included // in all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS // OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF // MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN // NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, // DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR // OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE // USE OR OTHER DEALINGS IN THE SOFTWARE. for (var i = 0; i < 10; i++) { console.log('count ' + i); } node-v0.10.25~dfsg2/test/fixtures/msca.pem0000644000000000000000000000157212270121457017100 0ustar rootroot-----BEGIN CERTIFICATE----- MIICWjCCAcMCAgGlMA0GCSqGSIb3DQEBBAUAMHUxCzAJBgNVBAYTAlVTMRgwFgYD VQQKEw9HVEUgQ29ycG9yYXRpb24xJzAlBgNVBAsTHkdURSBDeWJlclRydXN0IFNv bHV0aW9ucywgSW5jLjEjMCEGA1UEAxMaR1RFIEN5YmVyVHJ1c3QgR2xvYmFsIFJv b3QwHhcNOTgwODEzMDAyOTAwWhcNMTgwODEzMjM1OTAwWjB1MQswCQYDVQQGEwJV UzEYMBYGA1UEChMPR1RFIENvcnBvcmF0aW9uMScwJQYDVQQLEx5HVEUgQ3liZXJU cnVzdCBTb2x1dGlvbnMsIEluYy4xIzAhBgNVBAMTGkdURSBDeWJlclRydXN0IEds b2JhbCBSb290MIGfMA0GCSqGSIb3DQEBAQUAA4GNADCBiQKBgQCVD6C28FCc6HrH iM3dFw4usJTQGz0O9pTAipTHBsiQl8i4ZBp6fmw8U+E3KHNgf7KXUwefU/ltWJTS r41tiGeA5u2ylc9yMcqlHHK6XALnZELn+aks1joNrI1CqiQBOeacPwGFVw1Yh0X4 04Wqk2kmhXBIgD8SFcd5tB8FLztimQIDAQABMA0GCSqGSIb3DQEBBAUAA4GBAG3r GwnpXtlR22ciYaQqPEh346B8pt5zohQDhT37qw4wxYMWM4ETCJ57NE7fQMh017l9 3PR2VX2bY1QY6fDq81yx2YtCHrnAlU66+tXifPVoYb+O7AWXX1uw16OFNMQkpw0P lZPvy5TYnh+dXIVtx6quTx8itc2VrbqnzPmrC3p/ -----END CERTIFICATE----- node-v0.10.25~dfsg2/test/fixtures/print-chars.js0000644000000000000000000000245012270121457020236 0ustar rootroot// Copyright Joyent, Inc. and other Node contributors. // // Permission is hereby granted, free of charge, to any person obtaining a // copy of this software and associated documentation files (the // "Software"), to deal in the Software without restriction, including // without limitation the rights to use, copy, modify, merge, publish, // distribute, sublicense, and/or sell copies of the Software, and to permit // persons to whom the Software is furnished to do so, subject to the // following conditions: // // The above copyright notice and this permission notice shall be included // in all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS // OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF // MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN // NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, // DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR // OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE // USE OR OTHER DEALINGS IN THE SOFTWARE. var common = require('../common'); var assert = require('assert'); var n = parseInt(process.argv[2]); var s = ''; for (var i = 0; i < n; i++) { s += 'c'; } process.stdout.write(s); node-v0.10.25~dfsg2/test/fixtures/echo.js0000644000000000000000000000250512270121457016723 0ustar rootroot// Copyright Joyent, Inc. and other Node contributors. // // Permission is hereby granted, free of charge, to any person obtaining a // copy of this software and associated documentation files (the // "Software"), to deal in the Software without restriction, including // without limitation the rights to use, copy, modify, merge, publish, // distribute, sublicense, and/or sell copies of the Software, and to permit // persons to whom the Software is furnished to do so, subject to the // following conditions: // // The above copyright notice and this permission notice shall be included // in all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS // OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF // MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN // NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, // DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR // OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE // USE OR OTHER DEALINGS IN THE SOFTWARE. var common = require('../common'); var assert = require('assert'); common.print('hello world\r\n'); var stdin = process.openStdin(); stdin.on('data', function(data) { process.stdout.write(data.toString()); }); node-v0.10.25~dfsg2/test/fixtures/agent.crt0000644000000000000000000000231512270121457017256 0ustar rootroot-----BEGIN CERTIFICATE----- MIIDXTCCAkWgAwIBAgIJAMUSOvlaeyQHMA0GCSqGSIb3DQEBBQUAMEUxCzAJBgNV BAYTAkFVMRMwEQYDVQQIDApTb21lLVN0YXRlMSEwHwYDVQQKDBhJbnRlcm5ldCBX aWRnaXRzIFB0eSBMdGQwHhcNMTAxMTE2MDkzMjQ5WhcNMTMxMTE1MDkzMjQ5WjBF MQswCQYDVQQGEwJBVTETMBEGA1UECAwKU29tZS1TdGF0ZTEhMB8GA1UECgwYSW50 ZXJuZXQgV2lkZ2l0cyBQdHkgTHRkMIIBIjANBgkqhkiG9w0BAQEFAAOCAQ8AMIIB CgKCAQEAz+LXZOjcQCJq3+ZKUFabj71oo/ex/XsBcFqtBThjjTw9CVEVwfPQQp4X wtPiB204vnYXwQ1/R2NdTQqCZu47l79LssL/u2a5Y9+0NEU3nQA5qdt+1FAE0c5o exPimXOrR3GWfKz7PmZ2O0117IeCUUXPG5U8umhDe/4mDF4ZNJiKc404WthquTqg S7rLQZHhZ6D0EnGnOkzlmxJMYPNHSOY1/6ivdNUUcC87awNEA3lgfhy25IyBK3QJ c+aYKNTbt70Lery3bu2wWLFGtmNiGlQTS4JsxImRsECTI727ObS7/FWAQsqW+COL 0Sa5BuMFrFIpjPrEe0ih7vRRbdmXRwIDAQABo1AwTjAdBgNVHQ4EFgQUDnV4d6mD tOnluLoCjkUHTX/n4agwHwYDVR0jBBgwFoAUDnV4d6mDtOnluLoCjkUHTX/n4agw DAYDVR0TBAUwAwEB/zANBgkqhkiG9w0BAQUFAAOCAQEAFwV4MQfTo+qMv9JMiyno IEiqfOz4RgtmBqRnXUffcjS2dhc7/z+FPZnM79Kej8eLHoVfxCyWRHFlzm93vEdv wxOCrD13EDOi08OOZfxWyIlCa6Bg8cMAKqQzd2OvQOWqlRWBTThBJIhWflU33izX Qn5GdmYqhfpc+9ZHHGhvXNydtRQkdxVK2dZNzLBvBlLlRmtoClU7xm3A+/5dddeP AQHEPtyFlUw49VYtZ3ru6KqPms7MKvcRhYLsy9rwSfuuniMlx4d0bDR7TOkw0QQS A0N8MGQRQpzl4mw4jLzyM5d5QtuGBh2P6hPGa0YQxtI3RPT/p6ENzzBiAKXiSfzo xw== -----END CERTIFICATE----- node-v0.10.25~dfsg2/test/fixtures/person.jpg0000644000000000000000000016111012270121457017455 0ustar rootrootJFIFHH XICC_PROFILE HLinomntrRGB XYZ  1acspMSFTIEC sRGB-HP cprtP3desclwtptbkptrXYZgXYZ,bXYZ@dmndTpdmddvuedLview$lumimeas $tech0 rTRC< gTRC< bTRC< textCopyright (c) 1998 Hewlett-Packard CompanydescsRGB IEC61966-2.1sRGB IEC61966-2.1XYZ QXYZ XYZ o8XYZ bXYZ $descIEC http://www.iec.chIEC http://www.iec.chdesc.IEC 61966-2.1 Default RGB colour space - sRGB.IEC 61966-2.1 Default RGB colour space - sRGBdesc,Reference Viewing Condition in IEC61966-2.1,Reference Viewing Condition in IEC61966-2.1view_. \XYZ L VPWmeassig CRT curv #(-27;@EJOTY^chmrw| %+28>ELRY`gnu| &/8AKT]gqz !-8COZfr~ -;HUcq~ +:IXgw'7HYj{+=Oat 2FZn  % : O d y  ' = T j " 9 Q i  * C \ u & @ Z t .Id %A^z &Ca~1Om&Ed#Cc'Ij4Vx&IlAe@e Ek*Qw;c*R{Gp@j>i  A l !!H!u!!!"'"U"""# #8#f###$$M$|$$% %8%h%%%&'&W&&&''I'z''( (?(q(())8)k))**5*h**++6+i++,,9,n,,- -A-v--..L.../$/Z///050l0011J1112*2c223 3F3334+4e4455M555676r667$7`7788P8899B999:6:t::;-;k;;<' >`>>?!?a??@#@d@@A)AjAAB0BrBBC:C}CDDGDDEEUEEF"FgFFG5G{GHHKHHIIcIIJ7J}JK KSKKL*LrLMMJMMN%NnNOOIOOP'PqPQQPQQR1R|RSS_SSTBTTU(UuUVV\VVWDWWX/X}XYYiYZZVZZ[E[[\5\\]']x]^^l^__a_``W``aOaabIbbcCccd@dde=eef=ffg=ggh?hhiCiijHjjkOkklWlmm`mnnknooxop+ppq:qqrKrss]sttptu(uuv>vvwVwxxnxy*yyzFz{{c{|!||}A}~~b~#G k͂0WGrׇ;iΉ3dʋ0cʍ1fΏ6n֑?zM _ɖ4 uL$h՛BdҞ@iءG&vVǥ8nRĩ7u\ЭD-u`ֲK³8%yhYѹJº;.! zpg_XQKFAǿ=ȼ:ɹ8ʷ6˶5̵5͵6ζ7ϸ9к<Ѿ?DINU\dlvۀ܊ݖޢ)߯6DScs 2F[p(@Xr4Pm8Ww)KmJPhotoshop 3.08BIM8BIM\action conference copenhagencphdenmarkrebootreboot118BIM I@@IAdobed           s!1AQa"q2B#R3b$r%C4Scs5D'6Tdt& EFVU(eufv7GWgw8HXhx)9IYiy*:JZjzm!1AQa"q2#BRbr3$4CS%cs5DT &6E'dtU7()󄔤euFVfvGWgw8HXhx9IYiy*:JZjz ?~X,a7UXWMpAH_56I:h4}b]G҂ʓBrs^,5h9rHCpˈ$xI*R.ՖKWbX癧~|?}2\d~OyNllPt~=Օ%TV(׋) śD%<']^o/LSޡ&HEۯ')HR:HP[I!*e#!oY?RE=4}$O5<~Y8l?(-5E$H9D=GrJr,7Y93wޢNL9A/GgY+.<јڭ^_Z.JebTJӝY,oC;f(9/RI7V u VT/.ekՙCr?"j >.e l T 4$#SP+ïd&dOI/?ycN^KRCEi#9 %WYo"owPޓ|KQ^$ l1zc6]ZSnq`{ qkS%CFs"3c @AZRmV,q[G+L#t=0(n$tߙEdHMKޤckH S_eZs,X3? iKz}z Mdz6.x[퀁i-o\R\J'IQHj8ـT#c--|$f89g~QWn9L0XɢkW24[=|UQ1,BPqU1Rlp @U4OK0ᏤZ@_Vgbhb}/ qrO$ԭRoSd(DQnMO[C^>IW_>\KZsYu7RQx.(J7=˫l9 c.t2Hz]<*i_# kҔAjQi~kmq2&]yEVl8ɐZ=-}EL( Gs.RRU;e eG^!腙ܗ(3!6Y5Vcp}Vi#U(P8帀<(ϾL KQ ~뗎I,D+,b/_-i:MjrDзU?@ !~n׬g{T 095݉fAHE~^mKΔMH(欫&Eh^~Ω\B V̜w+O3H!`*Ȩ"hH8fJ`Wb]私|9f{NNՃlJI &Y5orIBÊ!PBb?S)5}= 6kIm>kJ$`5pC8ɫ]F/hCxʫ<)|U_˚4y9 }k}RX[]Io_?VVG8̃t̄,㶺ēړ#5կLHEknY9"?Rm=2#2NmgKU? c(q'bƿ<Mwډa2q2NyYΞgм{uF-~ JbX=I4SFbGrHA6+t(YVrDDC|(gq_v-mIDb<PbH(=u.FP%AW8evȖ Uت;RbzPx* c#C4 8M94? W0@&_7wV ު伆b3Cӧ4ÿ6|k}UZ+%QVj>ڡ<[K1;FO{<ϡy.d6ڟG*7f cIGă: LXbNU{표E7F #}SWMjA$-_$~'~_HO>-O.qYWd}T#kj` $O$/7i,׏IqlՆwS{/\TR"n &.əD;ْivҖWCF80XS Rv< @5h-4 k_B _:d|!2k}ŲxO\ҷ= RVnbʴZ g#5,cZY _yScrq@7C w$9l1U1%-4ŞQRFޝ~ُ7aSu,i\^sPҊ&`@ve qg]}mRFp^=v*UkaCӹEԢY(p(^9 j|9-= bR@4)@v,(\l SAǞ UfVF ܿt@YW \ 2,reeDj=VYfy1YLTԴ1<њt[KH9#SʽlƕX~ޅ%G7Rnזw/۰;5b*QYUxN\Sy"&At5kgcl-ܑna^4J=0%*yp̿g'@ y ٧4>KB-r=.@ S@qe>~,#oEm:]H%@yF*ՙke Aoyѣi"x kVlX'LIZثz0\BK)o6MrA&=D0zUi~ B; &;~h򧔭/A;gMReeЏ?gY8,4#xu1ۿڷ S#GS PUثPRJ'a+[X[m1 bO&ZȂ60@Dw5?g98ryw夫l$i$'Mۊ?pjG)r<ɃkGoC]Jo,b(%: jD7jPBJB< bnը?#'Z~:"X~Qژg^Bwu :u ; կ}a_P֔AnX;\C#FԲ H9|G`f"#>FwIG7fƈ@h˕EY"x=Krzۉ\8y|M醮cS/q,uk(~||䫩UE@U e;d+z%Z\r0P‹[^"N]Z֥C'O_MV 9Zih)\i:q o2*(䢵.'c̶eT$/܌ Ioh]K5ᗚ9iAcwa 3D,v:c1%/$0mMlyw,+:vzc r, ȳ{}LQfбzaXaIG[6Isnx9N)݆2K B eʮAwO[Lڏ$7c_Wzqk`?D;W9Elyjߚ6~RY$E+ȫ͔ %\Da5ҵ'v.մ)$"7d^TUUkaCI懐el/NQ*殄2IE≈T)/kheԍmG,LGd4R>ҷl2dknYe|qM>WǕٵ%X>!#bjn(H_tK-mPQ"Q (Mk_Z,$'d)5[#sl[ SqZ+5PhWbc/h/RViI%d5@5OִIt)lRz&;e6C˼mך!8eqrLK2IZX]-ȷRYh<rK-厥p'&f(ԃ}Aחq? ꥀ^fE'qf|ȞiBmy g>*> 2rLҠiڄ7vs"9G:+s"O~HclPc.;b"M>귶zd% my b7_>$?g1BdiE[M}|~UEP0*e%[(o\žDAkE;q Yq-՜?WoL eF`+Z6eės@ȴq? >1k) ]4d.\[F!P+L>ն<:$p?.mb:I-̆IX3*n)ZŨF1YcP+ѾUz'")rr^6n4o@@#Ăr>^-H#qB~S^2VcCLmõ$*Yf+~GԄC 'Pef< ^ k&OZEf]_$?$*> mޙ~Ͷc嗎l$9& vVU@b ݾ VTE+OJ2D7e \8{np^7#~1~g 'LQA@zm4f_$ߘ]?چsg:ު1̆(~k˖aGF{EEvVYc:\LqHb!a}IWyq8 +A^yg:ƣrj`ĄIh_2ju*1p~9!vS6yMTyZS^DuHX8&)d+ܷ0oԮN5{D9}һͯ䊶јd(ݨƤSlE≭= R:[b7 k1dE/י.l!cY$|4')XZ}5&mtAS:)z嵦5:ipx3uF~Dps##yy^@巈L>j(Oˣ+.4H\=5[3=v֣w/֭!a;dx[8=[$ThI Ei琕G41#N !F+]{l2oW6CZZZA9y?-y~d@NaHH\t%0ݖ ˽9P~ pl\#b8ZWb&;mʿN)Kw$}4.uJ}$dK zsI;&hZƝMkn=j@iUNAkK>$'&[c jiAYiȞȶ*M#*L O_dwԅeЩ1O(0aV f&C\WkI)x`SYqx9~$Lʆ^#դN Kh8Ud+ /qP*ZɒHڳ[7zLVyUJ^r+rW -A}KZ0oM9@z ̈ fH&xeROPA+A+dH.uwPG=UI^3L(gzKN R/dHmi% RHbo4$x/?͐'2cO}RIo Dɽ+@Os'f>J u[DhcKj#u4R~_S +هZ UE7 = PN {v-Y^I}?֭b) /NURzwRyuY9g@HӿE-:^B vCMTPl~|x7~njܲ%ߖ+`K$N,QpMՂZ~ce\ǫ~?ʞ1ˤ:l\z\&+y#wػ'1!z-3+E9Eo59XHȺwTC&*fK,J;lQŅټKo beG_k9-054PPݖdO+1.-R~Eyl6DіFI4UB)>7&1FuI&# e#5vSsY>BisH[%.K: 08r]~ňypN9AOb-!դd)bQTEBkzrf\x8fW"Q4O)GȺvՒZgKk |Xp,>^"mMCt[ߣC|ۢc^/Ͷ!~"-R:kƠq .(* ɱQ^m P@eEZ #0yޮ?QĤ#lŔ"̈TĊ(WpA\l`'ɵiN@+Cܡ 6esLO cb5%;{;Hu)g5G6*Yx߷~cfG(bV7 *)vsX̂?g15z_Xq0۪k˩]OWFÍ#v+deQl5 8h03U~zҎο𿵌J[#tux8sFGqnFs,aXxmNGS@A}SLk~>ۺ銀 >GE^3E]I#%a<^;T/HpoOķl'1[}b$dWNUE߷Ԭ֒I؅K˳ $Wq[gvf мf?g9D3qْU5ϥϤd ]QV6n_.2;.Ey4f+sw¥I٤Os&#Qdۗ1:q<q749"L_ %R')t6nG-]qHq+7_>fds>Y<$}V;F{\#Q(m/% SE* rڃ $̭lOUF9,;|'jq2I4eeUUN$azev$#Y@Pn+L^|kZlcV41 !$Qѿ [^p/&6+ ŀ,֊@o.^(l_:yR֢ңKDJb`U%Qg*AFQE ny ҹ␫J#G+3/NMl‘@$tp5ֈ+Aq?K Dx< )Ɔq ݄J-.PC rժ.} &Y4KBfJWiF#dɖ*7,H|0%cP]ojP)tOJn6:}ɶ#UQɏ2it*YcG{K1<I8myKI]joHZd+ܚ(?r-)ᄆrvPv_a/׀j=i(b |AQ Zka-ID[4qo1FBL;nͳ/(&}?_L߈e 15o&ԋs0HJ v0y6F4[tit>KQ)xg+1ɶo&ƴYkTZIHÒG7_-_Z~aoy61HU R߂er}\Ώ$ߚ_OelO"aQ݃ Qkx=YV0BOUOcg)Qj708,tb;6`!N6oUnREGÈfJ|-G%O|j2$G-C~h37aʳDzFbޢZx c">jͩ[SԪ||[f?YՇN?0f4F`HP?yHZq`jnsCUe sp{?4<]=, `WySf, G{fMO6N)fN ,B~URk<#TriSj+K)DQٕKS]P%is٠=)( 8&%^N#ETׯcC"n:V(i=+{԰ #<2reUbpӥJկb',Gs i@v r8Q8;w-: #Msx']9#?zJO$&P7ѨnD̨PycTwZc_{4SGnT*| ~ʧrn5}r $SZ&l5JQӞ0,㘼v\Oj2=TBvWgl9cYf1* u܃R ?! y{:?(G^.GN^*je~uf40<|lc/"ҿ,|}`ywx]/JQj7j(rXdIهw_Z*W97,ai F/J#@j0KC4B ^εn%Csi}U0 cD2coz M&2/evE(8!ɸ ٛ٠뉡e埘Λc7,j๱88|fE 9LEیБ =K?j73ԲHGj>O}4FLi(TBH(0kSF 0Y)60;LԡEg-AVSrɮQ_-͵4a>̈Jd4ziW3j5VqQ`\rݜ2ʛ R*pnJ*0|\f1e6i%S#Rĉ}䜈6NV,WicS*M?7%J:U̐i-ܩ8ѩeN_QciI=o$(u)!dYWu}f"NJmڽ+(b{d6):aOѓ?oÂOf~uMFtzwSMu5;#W_S-l9Sl󮝡YJa)xz: -."";qVBG&5e_H%ұ4&->;daH 18'.i;Db*H9, fqq6hfakIu*A#sU*Kpfٜ 4j^kQO<ͪS\䆐t;a֊Q-w1·7MK߄Y]R-[4ab&gg%`yWx5KDd/: fɫж$S _ַHOG'@y_PLoĖ\ IR*4"e-Vwj UN]:bBFM؆i2ES+4c$_ʚ{hqq$.ȪOel]`X䖝~y5-ޢNB脅%KL Kxоdkܾi6uYXbu|Y)x̭CʼoyaPT^t㔯ٌ1z;͞~뚼MЁ/Zb6_K#t__QVŜWo N R fոU-5󞯭 J JiD?RWfAG IsDyXF45Oo724<2r*wf݆j'in9H(__҉EeL8_5ifX^$Ct>;MsFw%ݸ viգ+4E]% gDD05$Tצ=8$@zuU呝`FM6e>Ɖv d|ѨXKf[*y1c.jY Umi_jJwma;$-:n薒>«5 U8!@ְ45~Y `ZFpt6W짗&~ȷ& yn-!,5՟ԥW1C8K7#9FBtow;-3ȗ#[iEdk#om=dߝ>s:ot[sѼלv%Q*>6L@'/x_Gԯ7GT0x䏡~`"܎Qܓ-ń9yF(7։iYx&#4 "G 2<Õ-̟D)VsfxbKh՗byM/Ooo,DRʹuߑ\6%B `z1R`2ӑl Բ{OYdk۵7{d*A0,kZ6Lo_YRX' ZML~h. Қ"H0O*i${ĨF*ȊTec>Q&REE6I6FMZSքS!m Eb݇UU#aۆT%z^ ȱzxOJP  9іUZ>PӭŧO gRĵ*vC~tn-例QzpijEI$,e Mw,`Do_Խ9yp) 31fS9?Iw3pՖGsA3Q')`2tXՈ/}i(_t$kf%n%A+Սw 'E[D-Z*~wluY4{CStHWooU5;eA1}WS]}k!Nӓ" U#om#Tt+l*Wd[T|Wb@z_$w'l? Ad~Um⽈Y45 FL AjZ#04go3@k 1WU<֭z`]co$CP)hL~tV5gcC̗, ĂX+M1[\%̲s ‹gEƬŒ(k~!JSVk2'2lQlQl,rURxOn4[5\@K5G\xS|\f <(C5?gٍ,D6!L~Wv2N24f&@PdCK,}SDe}VYe Pw=&c/V;w";YazV"4ʹ:sCM7gTM(.82}3m1djqRj&&$(rYίiZ՜Gc +}i#xf$HۄYھh9gYݞS7P7lOk$8o8PI, fhP( 5T05oLX,=TՓz7}& # 2vad-^G@8 zUc}T2>{WUaokSAFe)T8rv8~m$\:fϫڄj~"J@sysB0L-΃uhTIa2h&#;f;r$aҢ֭#`2C ̭.2j4BYcYYI}<4c2QSYe{numK dQŠ:( `X{Fif eπĤAg(iz %/?,uпKN 9"Er FRlUQ%hd>d|qTMW2mHUV8Pcڎ|K+ȤOq/Hᒐe@; i\|~=E:HaG[a&OqJZ='7 p+7&kG'm->[XUw#n y ՠLYZj7IU_-K{I6wa2Ft+y)NA[B7Ե4kW:yhijPgf)ȯ 9LzokwyF4C˧|izpM,U22?a(%8*=BioL78dP>C<l1D~+fc+_ nhܢV('C2pq3sd:Vfkؠ4-"7HضJ?Eʼ%/-RzYד䳱zC-rA3pU0?# 8tl j{qbZ* P=7,?Bo-F"(>u1a7[߾'@<% B`Mﰠ {{b_ -{Zx[q.B1*SJlGWĞLRּw/嶉SDѕH)trN[| *P*N"+|Zj^f]B6L}D-(aK5~)n%^DHwa+B*x }OfPjR -9jK$8RP8X_*_OoYjLU3 ETu*r' 65LK2=j=Fe[=L֬/FEYn.E5vOcQQaڀ1TTOlj _"0\yX!(iYz3XX "OS jǿт3 {ԝ#2;2}CN Ddb222FQ&goUxVrGH 7ˀk%럗?q.$"#yI6*hJٗP6e$RM[ӖLԜ^*Fy 2(89y[v֒#G,kv j9&@P49dm8B |30}. Ȝ]J.YðOP1 TgDZp]EE,7"Ey@* Ɵ^26TײVYI\((X_g+Yumߚt;KZ ة}tXոD BFfiv|,n$UUJemW,@MtIU4ԕt37j>󟚊C*#ۃ0ٗIIrW1dEJt#!4ESIySr07ׂv5coqp,c%ʻGo†Ah D%2E?wӊ@Jߗ!„-Ő ݱT{9#bzPR'Ÿ,. =A"W--5 y.eq) |1rJzYel]̕!3pKzXPSr0ٛILZoD b7־?X!UvqBN*P]G4eBQ[.x$&^NH8z/LI;v0W[uQN* ޫ}Jr>B丕[sKfr֞'W'4&P\VsE+T ƕ4sIKWҀC<+K$ʪ~U>z Gu3'O%=f -،}..Q8BIM%jCW6K<*G#xXMP://ns.adobe.com/xap/1.0/ action conference copenhagen cph denmark reboot reboot11 0, 0 255, 255 C     C     J !1"AQa2q #BRb$3Cr%Ss5!1AQaq"2#3BR$C ?<^ 54RS3D,F;)8ف9Vq؊v k9In$$yi_5#wKƦf,)fEjvLFK1#=;0ר:0$\܀Hutˋ nuD%"Q"ʆ f z1ƣ5%\Z$$=I.zhZOK{Mi4: 1312aA9qƐ ܠg%RIzYY i}.M+"*HK #aP#{3QEi D.aV/ R`W(hB[a;a/;/ [[sO{%㪪ZEL+LsN  c1T<$xD:Sj[V^:)s2c:D|Ř.䬢<3똖]Uq0b"ee=FP܃g8ҨUflm=xrzi7:zH;zybZ8'C,T8ǟ0݁-8#SAN@ph==]T}+jo^O(q!; u\Cvwg3MPdXdcIhokuYOgTaZydŹ 4&]܉MTw!"罚(֒+E *BLc>GJNt] . H@%Y^Fv>6;r#1SUZO|SeE"3蚇ǟmOhDYUP TAӸ`g9d@T{#jNxԇ]E>UҡbHۉpGuHЫ*h*Sh*4,f,K4$ 8Ƿ) )HrACʋ_޴ZfKbAKpj|*LrK;Drpq꼀ܠ4@d-/Yt=eM6K*妮 ybWF;mvpn5h^OdZД)nKfPU,ŊV`z1G1X8_/3gݫ`[hi*(fcŀ`)NGM 5N^o6:IԶql*@ ##0o}-dD%^&ߖZSњe҄,&Nv+; &ʭ'u9G95N&-,a >)bx)!,Fq9ݖM>!H'ފs~sX[59]W]SY5mt],#4UKI dϨM*oָur`a[.T:i(TM`8"\UH=OXR2fm鮞PsIiZIRΐ5v33 `9@썎 ;X t9JNU֚[u=ޖd}CB*H\c=q߆QԫۢsV })hݵېJdaǎo5E& i,g@OxXaC̶[i-+Ֆjk"Ebd  7p>j-,-ZUDHc<͎FSkɒ>%Z#F(K#ʎ7| ) M*x3նo #4J1UssO@IMʠ&`$v2N1C~|-7Dko?!GPC.F1&QFN$N ?vIgqN(!KRaq=j:D0܉׬_#}6Wo%{}{qS"GPKιRvU _QoosU$HCV4EXeSǑRteS_TVu-EWN#,*A~]-CW I#}u( 1J[݊]Yr ]M+ΒRTfAts 6uJ"g@A@5{_sVHҚTbzZ^]*<ӗɺbP(n'Jn2 gSs362H`F [ki*!&a8d\ 4W3L_ӂ(;[Z,5D4Uj+nXgûшr`76(d.6ߚϩ: Ii-4ݪjI"2#GT 9e#HTZOnJH_˷0UY0gŊ?Rvg7 Wjw*.|Trl4PUX D*a'圎 0R8ݥMqe2ԛ|OC.{)ZeZ6c?6`Dž,|0;i9sYG WG4NpzQ$w@6lߖܹkmmѼHҳ˹ٔ({8MC\[E'yfZwEts!&#uGV'-q=x-#ihwUYI$䡓rZWM%!#<[72=as{\WϙM ۆEWpFȹ=~M WFP2nB˴e;0T*$qmkK@8l"*X1ia9eԍ쨊\I96ٌ]q"fA$)9]s7Z*ͧZ=3?/1tpNc*j'yit<\)ʅ,wcu8`2ƟO~-joׅ`w=s}x۩p:kDMp[*0fz-e Z4msOZoퟩ1Ӟ aR/(L\񐚏2Y$2r?nA` vjt3Nԟ`>|Cc<E*cn6/)܎~*e[~~#6`i6ۭFR. c]4ܒ2*8:"kDNgqRfV[|}UxçtUֆsx#K !,8e?rFF=8ЩDܘK/OQBPQR\4EcU+Հ1$d$f}T#(NmJTkbЈn5Ì(SsG:KQ5Bs)i*MhuWI#+Qvkms~g~=lQFi_]kafƋSl⏺ņh5lbu(w%vâq'DT۟4TQ蛾6`1MU&wXu' K] UauQ]#WT$DȎ;0rŁ}De6˗ej뾣EJR4R$30X1ok~5nVe*J`I$ q᲻~ 2n~VWI[MIQ nЬn(È$ % %3tU'JI}WMKUS#,EY9_qu:n[aA\m"P@ae^ۄu닽} ]h(ķY~w2\2.W`9`v Z- Lƚ|7B$l[׎ҢygN׿ tHlkcnׯrxÈV5! F{(玂Qt[T8;$Pˑ:|pf[a꩘mʭ8^;χĄ@+ƬR%!'Vdw珯PnZMliAQnVW-X)&5ڞ544vꘁ͑xUwWÃ<"H ]:XNX!XIOi Z*v̦"Iu5FfNox1PcDl9aԒQ-mI2(kЪ-tY׿IxlXI!|/̖Wt:SCSRiީȟ$ž#MWRs2FbqsTyCN.vacHXjyo&QA?C8;F Z6myrEIkb=a L!*rTuN5M7FI׈cQ#c] rxlwIjJ)te5͖'F]j#2Ld_| Ӈ&*MtS({QQ^a }8>ҥI;t3"B"]3^È^_pIkq!@ 3ⷻ(LPzK y*(Vs& V$s5pZh6F T mknU4u~ O[PE29_X0Nk<?åS[iꤠEO+ΒH Iݼ ($O }k*n-c?ˍaĤO.$ PIۤgIx;d?w*iem PD:~ݱPӉq{}GրWP },L(:_nc3EQ5F2TQ;ihw4KbU@:}NI.9mPT(f5zK 6Zt̲HC$񀥼F-R)V ::>x(}~H[LoԖ 3I ~+:7Ftxi3"#ͱ2ApQ 4D+ Eo~y?`TyRikJ %9YP=(`hk ki i[K(-ujkܱ2̦DHcU c|pa!}%&B4;U->Ԍ'G7S4;2":*Q&@? ࡺBd˅${bZa16u0[%EۗMV#oQL ^]컒5ߎ4w 3g{۶llZClcFR63" 1tjb\.1.dJ+!tJ'hXPgFX6\;q5R9(̓W=:Z%]j*C-<%|u̒Fa ۮ9E^$m&6f#p&+DtTTUO)$(Ua_S w=HH<#)vw(@`_s5Jy\2"+eb8BoSM$|mm§<"tL:"o,򥳦žt8ٷ)5z>BIKK7ls,jsn+t54SOjIYp;gX>Z-UgP̄9WUՇ8)7k58SQ NA۰ [̠(6&Y%TJwa?NX?k9l xVrG9ӗֱ W=LQX%QZ zcxus+Z_^UE<+fIjwSRYB&UhԻ73 B:Y"Y11?V{.D- jI^FKrYapH:@*뤫R "V)( ZXR 0vRh *[1ܣ?,V|mq4HcywEuZ]a7hY $kRbjIVX"a dp.&S!5#0uE*!\N͡$qTA_uȩVYFۖ;xjKjtMh}!ĝu;hq4iX>m7&ں1Ӥb5xݦܬ`WyT], $$<$jzsR`ik vwc8zvk7f$i>Zd5NS>.hŠm[o)j4yܿ2p#c` + Iܢ|cvl4 nT#d/p̪1ߩxm[nv(|Y kIy S*T}G܎m'Vu-M|r^ܤiTɧ4&RP7o#MQԃ>j w!$"dH 9mnr1߯^&˴-0aW4\h7TFe,:R>/Do暂Ke?f1B>: T{Q dfLqM^$˾tFiZz8vqF}ȠnwgW`y@HLTtUvեۤ땣Yç稒 <"aQRiz8$IL46S+(*7JҴvE]Nlۢ^j;cO:;5-ZcM,pT\9cKv=zt0 hZx4eZI譱# BXE8\g9e3R4%8{oCr^⎚ͤYZXK9b0G˄=6x)"J ɭuzuq5&_66]d}۝XbAg<ʬ<:h.L W%^?qʻ5.uSG426TF%CHC=36O 5I_Hm-TK4Oe`? KF[EtZ rH8 G,e$7忇o/Ywer԰Ԣc3 q2vQfj(.*:9Z)㩌)c)e_ %1rәSM7PȌ$Jø8 oRGU-&8$tpxۘ(hs꥜pj[mjK O99~C=O B脺XsTo=2;Lf@1"n.e̎|ϤIj=a[6|+lZ4+㠒"Hڤ2s$ .14j@=z,RxTSD& IkP{|޿.JbJj٭56m4f=u@*W̏+ԝh;I F0g2Ӭ u < L _hzT$hMUDס5MjaDn03NjnTE A?E-:*S֌7 j_(PZ,lG/8.h3mO ƑPzl|4!RK3 ٴw'`wh+J!N5>:B-A:ԦL<`/0ȌX`FQ2eǾTܸ*tnnϴ+D,2 7W?YG_Uo5t1,L$$XjvU9څ΢>- > RMVJg`n-p6 Az Bh]驷P&ܒ1=zSUh%Eč i&jy* y# ÿ#ꕿR^n ` .{ \dLj^X۠hҞb iGNzmx9Znqd(vK&?f+hr:y8RQ~|rmSQVSm5HED=՛ @kQLSsRMh)1bnyq$ٽ؎M>洚/ }yWOqWADpvt'zqB .gqF`[@`z|)h6=53uD,Yujq&ex/uddo7?9],]7$X*ב'hlf@OUUei"ƻP. ٵ͂E,0GR03߆ e =w_+Rꥦ TZPF@ `0~\<((IzDǃj]-?+Gn7X' ʂ3qqV4ә|SkZ~+t ,w)O> ?m2sPsT|Ls:7Y-SP0Ri!ЁtУP=,k(oOjY @w!w1'=1@W@WL `_cĘuOSdՕ`U(/jnZ[mvLu;$#%WӀU^:!%-j>`KYQ3K0=I2c8>A'FpAX8?N v($nH*o$HI#pXD#]0+O/<$3I`+=%:ij(,Xꙙoʅ0>gs+8c=F鶋ط&k5 +-~\yĒNs;Wq2<p3Ϧ6e"& UCݫTMXu)#wc=U)yO;Y=-0xL[~jg]QYF2KGbQ7A%ܣ|@^ofjA-!$I/9\x[*7.zbYK-] [c֎YRD/U\! pAeBwoSc'Rv\*sۊ% 38d/V{ʱ%ULp4r{tToeZ ]$QR1TO8PԥǥT6xLMC. 8I$1!fDŽH} MtvDFgX!R(3='pf5%r &]mHZfP4ɾ}x/ҔPZỉG.Ioޗ;@ʻ j̃4`9F@ g5|g](֢Z6R\E  (^=+'JFSy $œԁM~`ײ|d%<4{G+Hf|E}bseydb/bڂ1k2ClS=SOh1%)$"ϙ`^ͣ1#>rKh cA\O㍓zW66B3eU?xءbWk2%M2xTW.뎇 ?=/!5wjMr3ARʪ',N0gQ:ϯE~ 3T6O[Tj}7ISWwi%E?62QC:T:=@@:yIA؎rqб"hX| aNI?hJ[SC3+JezR[#ڸQD:I"I'ĹFnǿo^q!Fɖ)~ߚ-B79a#`q5];Fxz;>S ^jX)3'Q%cFex6AʺZq5T(p%HS*{m==Qf3s~qї?dw-Ux-ZJDЧBF·шf>n{Ng&מegoA%Kb.uQGS=4P]^eYwbG`UTy1o?i1g뿽zw;C{Er[u)djS!p,0YdLx2C+xm5ͨƳ VIIYU_}]KnAyDtH`g<ӚI=nPڒ}Ca{}\ @O=HT?̀'܌80 4M)REY#ݯsIAmI]*=$z6Z&5t~OU]5Ay#KZ|5T$u7;0gŮes:5M4"f ==C^Z 5.5Oz_{bAU^BeZ:w`q0]N"G$Ѱ"HT3=>UB+bW>a^[uKhRKVފWF DH 2PGvt8Ym[1=6~f݅ڲBՄ5L4H7IQKˁJV PZA9uMC]+wϹm TڒiBD'wϠe'ĠnvM,#@[o'1@3*CbU<7%]rTfˬ=(LqSUld}yl@l'4nګCPK}G+.BUJW^/!^562b.us2GƂ\鎧IymPԺ"فߪ0.Jqʟ&I, ;Ӏ!]+;kR& ZM2zp;x@!e/|j9GFӷc~930+ g<\S :\#,rFfS:)MkI "ʁH?Җ|Κ#?WjHڎJF' =4dp8#}F~@mxkZe]t II"f52,EX w1=-l*  3Si{#ERzi$(*ۛx1yX.-s60O 5%KQ{hz[o+m+jYQ>84ޠ@Vs՚xZPI:[K'rkg恾!Fk+MnxQj8*Bk6 q Ǯ~\n,, j  uj=ޕ%0'H g$?xrC#U5óO*G]*$H$PxVuHep0>dܹFU#;KX,z"^OO!4S" AP6^]6yqG-d%4UvcbIwS:u e:~\lz#1gVú_݃êeGYWSIZ=\[PT(9JmHEoT52i C 0Eţ]_ET !T>BʭWM9[ R$$Ol l e]iWt/ۧ p)O^?NV^s<5),q2$/bhT -b7NaM«@;=[tW̽KFfiG,&!P(rw1t?/uDC@cY^5F }U}!g M榤İb r^01IfTjԫw8mZgSw!5r eOoWg%|O@Y!cEY iRG\@'izcpuh[U٨aO42pۊ",FӨzS#zt|uQ14*'!`i`hjC1r$=cpJDBC{п~frj씺j(2[-/Ne_1} a|Ą{TɆIj6Sd+ a8sOwdlsƋYTh*qOjRVGs"68VaV!f$"@7Y6ɒ#MSK~X+zzO|v}thDhxځ&}@.>f*oh3KxL<eOy{eAd+ 4qUNze3ܔM)WdǢ&:ZcGh-S[[iȑ;cK?ez*k#Mw[4-WN/_R-һƕajES1" b )xN`5#qV82mRGuHK/ C968`x 㒠`i2yL#y7_鬷1R-:e]ȧ9=~|i׮\Ȧ5|$tO|*MuxX*oUr:6*C$` :5MTlt>vK?hfc\@r{OPq/?ҔGE A!Ocj LePrN$#) p!8|U&GISE_SK=™Q0Fذ=ؒERkUFGjs5>}I' Vd/T{Vo.ЧJ[^nU $*Kgsۮz uq7*8~;t 4e铜u cd -/wҷrB.Tbxi")vg$}@2Xʦf 8ҦIS4PLLvǿ&+tt h>ds@ 2qB =uΓ7Bs*5 WbY8Rb8eĞ\D?~=Cxn{ OpU47:$vj(Hz8'O a3U|( ZV Gl:n!YVzj+kR8 eKpQX֓r߇ nBګ>;KX:U0V1dWs@ıe \>_XѴOկBi/uKtj jVS.ߧAb~|sUyv t6\<7QA[6`1է4MݰD=Lj_X8c;hU*g ZF$=3_dx"7-4-$v]fU馾=kҜ#ţ Q805Qmf0zoV}qʻ 9* 7x*i˓ː{}3]X|lS*pQTf{fH^cs1p8a/2vSm'94[4tO +*TJ&x1ŽA#Ł`ǩki4B檺S$tݓAVS,nQqJ*=XJHN2Ӧ H:yvL,Ufh/SޖXT}'rgv8%:X4WzL#GTf6Qa Qcӆګ%ěu0TjVIC>.F>`c'x y)W8<*W:|:JI˘USD.< `|}DY 'aK J1\LYk]O Lp%BH P} &`]O铗5VdGXᩖ4p <+)q*g3I@~Ȯ?O7t2H' `ؒsӿs:, DUPE ҆452CQղ2) {1v;W ;nwQu"ϛzDor,׮^R]Zy(+MV"%ǟ4@H*W=sƃ\2g90>sϯP.$)R7*ؐ=j 5M&]!X0*(*N2k,>>E-0>/_M;L@!v @3?N2+Tv00{o0·}曹_F4rNx[fz{|De:ZR^m"DT[s!")՗ go)IgzFXb1d1/ iժlȅ{cZJ6(,bucjhh皎a@< #FW=u/p{łi\稫xH Hz֫YN5hB7vgΆCNTNeɎmJ#߼TMM?NI& &0 V# ˜g>2ݬKg R]P7HO auL5+)fcxrB #iQTbNtYGI7 #+ ǘaH q!Teu &fm~i[n[Qf,ȦQ0y`;>*4H{wsmD eIh==I- sd~ p8ibS$elgV\D  Pg |0"[YnyȰZ "$42a~08 9OWgZ7|\ Xj4E\0+,~s ,q U`3+w,kk3o%^2TzsUTWNU7Y`qWz9yZhfFL;Nb;@ q䜟P|V MϒңB2۝-]4B9vYHU@l\١ttp8_DΟr|уlՑJrT}i7 . iecSo% .x^IW\ޥY%z];75椊nt}sy*7yd5N5[+_OqrAOK'`mˌP:n#j`EXFpxܲtSK-=+İC2OSf0r^oDiyzvI;Lf\w9j$AqD;??g5qq J`>|q 9Q 'R55G3,7"ij_ee vP dq!X֐e$5ݙi.=ښ$};0D@U~_v50U]'/8p諦ujâ YY7jwZb_)[ D6zzx5ټzV̏Dt? 4CD\S}GA'-{ OSr_(ae%'<_$`!6U*R P7L)ځp@^!dhTTUt@ >cU*J [> ,3ԅiCHIO'ߒ<pV(WTUT2Q4J}ΟJE)xc]:l_sN;Gf x?긮S-#nW m5Vzv",Sj'?BI㎸$0f I"OA4c|Ǹ{q㟜WEhcHUvk9taׯ ZItu\[eG=sitH{צIc@$<')5薚T*6ئeK5 I YI}[TaFuvQl>ls-+6뤔UD:HAj>ˉMnby,A+W2v}8 ) yrSLl7e'dl p%ADUkf6P"55—YA7c N{8iqnZjQ 'ywpcWiX5:z0p1ψPphm3jN4Mʋ'I}ᑆHn%2t`\}SFYikf?uDU dqWvjYGPM2ǩ8RHtW hyͺ=]jI LџKqt `+b8 "z 4% %գaWtpǶB}f+jwLq}v ̺&t:iJN*ˤ4v3uU R j#l"BX'1o@<[.~sOS{ y=zc j#dp$cw]zӌ耎]Cæyy9tE[^1|(TyV/OGIJ^/3V3m쯅Ui̔J[,$cԎ8n.h'=XCYP #8o>IS$Ų۰$-dV!9=b&# ݔQOB_4{tuJM}{mA-`=?'w u\.RD5C{Q^=JaHt5:" l,R/2ùBYV[WTuu|! ӝO[QSBcU $]L3g,NT-;:[?>ω(Fg55m%]ƞEaҿ*lS ucI59u/0i3[q8}%Hб~V6%kLֈ+igPDUQ: 2dHr!ۢ{ʁV ÎӚKTP\ʶ2P~!*]bUXoWv5MMبt Tv :G%3gCrsWVNNO`zE> 'S\5ؗԌKztD/ ~Ԗ9m!<.69*/zL tEWJrTR eY,F3ԀJsFǨ$I{zUyu4ݧ-TMU'$^ !`Ͼ1HH+%>U|$ә*ʢa_JkKs5$t9q&BPJ;C;STFRH%QW?1 kd* ZI] 0Cd)#GiiTHKcc?."fJ0\O<2poPdžNApzJ2 y98ඵD1; Nz#)DLW]Ut+\t4%Gp2FYv6>ڨϗP]>ң<ܼ6?AHP eY.[#ݬ c3ߨ Z7Jc7y2 /ᑃ32OЫct[ ]5mUV[^2"9I,׷+E 0Op5j IJ_u'0qAqMs\Bjhfa5+(p@2 U[@a]D::M ~i.+m0 Kʆ8ݔ+V0ΤυL,4 qQHUyFO,=JFcrFHzK_`%TU 52v:IG[QU#8 H?~& Dl-TqT/`/$߯ˉ9@ET '}擞s8$ON})Jw,qaۅ %P}?,pӧ o(@v)#@I=Q!IU* ?DJmeg$aUSݪ%z6OG,]7m@8$ + UfTl2< gՃqSX/ z6R`v}%%%Dc1 xx Kgz0vf}ϙk˯$ͻu5ɦiuQGI\@#KXI+D"w&15;hs8, Pz3O~h LrXimq驚_.Vv&xSF9NCJ 5V%n>PۥsIaVݖDG}N;9䆦ٴvkMTBJ5@;7/GtE#=qqrUnY5kMUV[SSq(08 O]92e\(\RI}®U4S=4er8''rPI[ HEJ5I+#Ez=;gA>E!8QkУpSVUC>ݪv${6;"J&\g'1Im|Z Vpk2_ny,U*jB*+mZIl lwH6z3uۓ->nRDw#OP[-u%*l3Mx5o-K$bFFr )`Ct42@ls Ys%Y9oR]蠦-5EM-27HIO~q-AHd*ys"5,M䎋cq}{?z.uuFҦ1h%r.z\\j3M+;sqKt=ޅ $2٨|e_ӄmhUնԃӆNG%H-JI:oK!=IJYA 4S6|Րl4<5U1GIOLf'䞘~\"l5uf4m$^KRіkӋ ( iqO+yVJAQ„Cq# &͡Bw#ߧ %ֺUE*YUrz `?=7.$TA2;|, &tXJ X Ok 'LL`,}F2>_N"Z 52Z[VZ}t+AA$:w7: CWǑ<Rzڻ5@ZˎTH`bdS*Jݞ)hvkc*uS.x<ߪ6sOGrޣ{|v4 M`S+T*>OWvƁk]m;=nC54WjIBr RO(Gn((ZnPK$#j`N\ |L<骉Ȣ%dRS:"*:qӘ tTQ ҫeK(['㎤evWeEx NIu-95 *ervc#)q\en<.iҷaIӄM;ЇIq0at?ˇBVYjie J͟[(J%e$LI$?Ϸ9Y Vw v~G(exG{◰8AN ^'PieҢѬCi|[?χas.אIEӔLJ<=(d.2n Xwj[Ϊ+'bzp># fӷ=]+gjIj(.&*Tܻ F[}/BY t?E.-mBK sW:b[7 %S~fȏe+>q8)| E *;I}Ԥ/H#$o x8ڭ+0=ILGO pTSl2w~(/;D$Wc_ㄔt)]*^;rX O\ dg *dRkk'S4s$K!3<(NRcxM+jJ̐* #`xh JU+<~ᠧSq,c$[#>Ӆ) r#y[\jj1 Gj2 B\dОR4wGa+Cn'dڨ^,i>eZy]Ng :$ P\/Z枢KQMwHwfxàOmz/*tp*oY|zY@XpI?OӍ_node-v0.10.25~dfsg2/test/fixtures/cert.pem0000644000000000000000000000401712270121457017107 0ustar rootroot-----BEGIN CERTIFICATE----- MIIDNDCCAp2gAwIBAgIJAJvXLQpGPpm7MA0GCSqGSIb3DQEBBQUAMHAxCzAJBgNV BAYTAkdCMRAwDgYDVQQIEwdHd3luZWRkMREwDwYDVQQHEwhXYXVuZmF3cjEUMBIG A1UEChMLQWNrbmFjayBMdGQxEjAQBgNVBAsTCVRlc3QgQ2VydDESMBAGA1UEAxMJ bG9jYWxob3N0MB4XDTA5MTEwMjE5MzMwNVoXDTEwMTEwMjE5MzMwNVowcDELMAkG A1UEBhMCR0IxEDAOBgNVBAgTB0d3eW5lZGQxETAPBgNVBAcTCFdhdW5mYXdyMRQw EgYDVQQKEwtBY2tuYWNrIEx0ZDESMBAGA1UECxMJVGVzdCBDZXJ0MRIwEAYDVQQD Ewlsb2NhbGhvc3QwgZ8wDQYJKoZIhvcNAQEBBQADgY0AMIGJAoGBANdym7nGe2yw 6LlJfJrQtC5TmKOGrSXiyolYCbGOy4xZI4KD31d3097jhlQFJyF+10gwkE62DuJe fLvBZDUsvLe1R8bzlVhZnBVn+3QJyUIWQAL+DsRj8P3KoD7k363QN5dIaA1GOAg2 vZcPy1HCUsvOgvDXGRUCZqNLAyt+h/cpAgMBAAGjgdUwgdIwHQYDVR0OBBYEFK4s VBV4shKUj3UX/fvSJnFaaPBjMIGiBgNVHSMEgZowgZeAFK4sVBV4shKUj3UX/fvS JnFaaPBjoXSkcjBwMQswCQYDVQQGEwJHQjEQMA4GA1UECBMHR3d5bmVkZDERMA8G A1UEBxMIV2F1bmZhd3IxFDASBgNVBAoTC0Fja25hY2sgTHRkMRIwEAYDVQQLEwlU ZXN0IENlcnQxEjAQBgNVBAMTCWxvY2FsaG9zdIIJAJvXLQpGPpm7MAwGA1UdEwQF MAMBAf8wDQYJKoZIhvcNAQEFBQADgYEAFxR7BA1mUlsYqPiogtxSIfLzHWh+s0bJ SBuhNrHes4U8QxS8+x/KWjd/81gzsf9J1C2VzTlFaydAgigz3SkQYgs+TMnFkT2o 9jqoJrcdf4WpZ2DQXUALaZgwNzPumMUSx8Ac5gO+BY/RHyP6fCodYvdNwyKslnI3 US7eCSHZsVo= -----END CERTIFICATE----- -----BEGIN RSA PRIVATE KEY----- MIICXgIBAAKBgQDXcpu5xntssOi5SXya0LQuU5ijhq0l4sqJWAmxjsuMWSOCg99X d9Pe44ZUBSchftdIMJBOtg7iXny7wWQ1LLy3tUfG85VYWZwVZ/t0CclCFkAC/g7E Y/D9yqA+5N+t0DeXSGgNRjgINr2XD8tRwlLLzoLw1xkVAmajSwMrfof3KQIDAQAB AoGBAIBHR/tT93ce2mJAJAXV0AJpWc+7x2pwX2FpXtQujnlxNZhnRlrBCRCD7h4m t0bVS/86kyGaesBDvAbavfx/N5keYzzmmSp5Ht8IPqKPydGWdigk4x90yWvktai7 dWuRKF94FXr0GUuBONb/dfHdp4KBtzN7oIF9WydYGGXA9ZmBAkEA8/k01bfwQZIu AgcdNEM94Zcug1gSspXtUu8exNQX4+PNVbadghZb1+OnUO4d3gvWfqvAnaXD3KV6 N4OtUhQQ0QJBAOIRbKMfaymQ9yE3CQQxYfKmEhHXWARXVwuYqIFqjmhSjSXx0l/P 7mSHz1I9uDvxkJev8sQgu1TKIyTOdqPH1tkCQQDPa6H1yYoj1Un0Q2Qa2Mg1kTjk Re6vkjPQ/KcmJEOjZjtekgFbZfLzmwLXFXqjG2FjFFaQMSxR3QYJSJQEYjbhAkEA sy7OZcjcXnjZeEkv61Pc57/7qIp/6Aj2JGnefZ1gvI1Z9Q5kCa88rA/9Iplq8pA4 ZBKAoDW1ZbJGAsFmxc/6mQJAdPilhci0qFN86IGmf+ZBnwsDflIwHKDaVofti4wQ sPWhSOb9VQjMXekI4Y2l8fqAVTS2Fn6+8jkVKxXBywSVCw== -----END RSA PRIVATE KEY----- node-v0.10.25~dfsg2/test/fixtures/child-process-persistent.js0000644000000000000000000000004212270121457022734 0ustar rootrootsetInterval(function () {}, 500); node-v0.10.25~dfsg2/test/fixtures/invalid.json0000644000000000000000000000010612270121457017763 0ustar rootroot{ "name": "foo", "version": "0.0.1" "description": "im broken" }node-v0.10.25~dfsg2/test/fixtures/throws_error.js0000644000000000000000000000220712270121457020543 0ustar rootroot// Copyright Joyent, Inc. and other Node contributors. // // Permission is hereby granted, free of charge, to any person obtaining a // copy of this software and associated documentation files (the // "Software"), to deal in the Software without restriction, including // without limitation the rights to use, copy, modify, merge, publish, // distribute, sublicense, and/or sell copies of the Software, and to permit // persons to whom the Software is furnished to do so, subject to the // following conditions: // // The above copyright notice and this permission notice shall be included // in all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS // OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF // MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN // NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, // DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR // OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE // USE OR OTHER DEALINGS IN THE SOFTWARE. throw new Error('blah'); node-v0.10.25~dfsg2/test/fixtures/test_rsa_pubkey_2.pem0000644000000000000000000000036712270121457021602 0ustar rootroot-----BEGIN RSA PUBLIC KEY----- MIGHAoGBAKwyBF3HER55exw++oXOn/r8gh2h4pKUGfvfrUVZnAxBQbSoJutdi11c /KqnYHgZOG+IiqJolkhMJNjzsKJXtsW8faWZQwkuwJzcFpDhcVBsRTkPmM0V8/uD vwwQpsJv2sR9gwjYQbBt8pFRlSth4Fp3MgwcQwQcPKIFesKiFNcxAgEj -----END RSA PUBLIC KEY----- node-v0.10.25~dfsg2/test/fixtures/destroy-stdin.js0000644000000000000000000000003112270121457020605 0ustar rootrootprocess.stdin.destroy(); node-v0.10.25~dfsg2/test/fixtures/semicolon.js0000644000000000000000000000216012270121457017772 0ustar rootroot// Copyright Joyent, Inc. and other Node contributors. // // Permission is hereby granted, free of charge, to any person obtaining a // copy of this software and associated documentation files (the // "Software"), to deal in the Software without restriction, including // without limitation the rights to use, copy, modify, merge, publish, // distribute, sublicense, and/or sell copies of the Software, and to permit // persons to whom the Software is furnished to do so, subject to the // following conditions: // // The above copyright notice and this permission notice shall be included // in all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS // OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF // MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN // NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, // DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR // OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE // USE OR OTHER DEALINGS IN THE SOFTWARE. ; node-v0.10.25~dfsg2/test/fixtures/nested-index/0000755000000000000000000000000012270121457020034 5ustar rootrootnode-v0.10.25~dfsg2/test/fixtures/nested-index/three/0000755000000000000000000000000012270121457021143 5ustar rootrootnode-v0.10.25~dfsg2/test/fixtures/nested-index/three/index.js0000644000000000000000000000215612270121457022614 0ustar rootroot// Copyright Joyent, Inc. and other Node contributors. // // Permission is hereby granted, free of charge, to any person obtaining a // copy of this software and associated documentation files (the // "Software"), to deal in the Software without restriction, including // without limitation the rights to use, copy, modify, merge, publish, // distribute, sublicense, and/or sell copies of the Software, and to permit // persons to whom the Software is furnished to do so, subject to the // following conditions: // // The above copyright notice and this permission notice shall be included // in all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS // OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF // MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN // NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, // DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR // OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE // USE OR OTHER DEALINGS IN THE SOFTWARE. node-v0.10.25~dfsg2/test/fixtures/nested-index/two/0000755000000000000000000000000012270121457020645 5ustar rootrootnode-v0.10.25~dfsg2/test/fixtures/nested-index/two/hello.js0000644000000000000000000000222212270121457022304 0ustar rootroot// Copyright Joyent, Inc. and other Node contributors. // // Permission is hereby granted, free of charge, to any person obtaining a // copy of this software and associated documentation files (the // "Software"), to deal in the Software without restriction, including // without limitation the rights to use, copy, modify, merge, publish, // distribute, sublicense, and/or sell copies of the Software, and to permit // persons to whom the Software is furnished to do so, subject to the // following conditions: // // The above copyright notice and this permission notice shall be included // in all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS // OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF // MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN // NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, // DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR // OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE // USE OR OTHER DEALINGS IN THE SOFTWARE. exports.hello = 'hello from two!'; node-v0.10.25~dfsg2/test/fixtures/nested-index/two/index.js0000644000000000000000000000223012270121457022307 0ustar rootroot// Copyright Joyent, Inc. and other Node contributors. // // Permission is hereby granted, free of charge, to any person obtaining a // copy of this software and associated documentation files (the // "Software"), to deal in the Software without restriction, including // without limitation the rights to use, copy, modify, merge, publish, // distribute, sublicense, and/or sell copies of the Software, and to permit // persons to whom the Software is furnished to do so, subject to the // following conditions: // // The above copyright notice and this permission notice shall be included // in all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS // OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF // MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN // NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, // DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR // OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE // USE OR OTHER DEALINGS IN THE SOFTWARE. exports.hello = require('./hello').hello; node-v0.10.25~dfsg2/test/fixtures/nested-index/three.js0000644000000000000000000000215612270121457021505 0ustar rootroot// Copyright Joyent, Inc. and other Node contributors. // // Permission is hereby granted, free of charge, to any person obtaining a // copy of this software and associated documentation files (the // "Software"), to deal in the Software without restriction, including // without limitation the rights to use, copy, modify, merge, publish, // distribute, sublicense, and/or sell copies of the Software, and to permit // persons to whom the Software is furnished to do so, subject to the // following conditions: // // The above copyright notice and this permission notice shall be included // in all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS // OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF // MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN // NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, // DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR // OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE // USE OR OTHER DEALINGS IN THE SOFTWARE. node-v0.10.25~dfsg2/test/fixtures/nested-index/one/0000755000000000000000000000000012270121457020615 5ustar rootrootnode-v0.10.25~dfsg2/test/fixtures/nested-index/one/hello.js0000644000000000000000000000222212270121457022254 0ustar rootroot// Copyright Joyent, Inc. and other Node contributors. // // Permission is hereby granted, free of charge, to any person obtaining a // copy of this software and associated documentation files (the // "Software"), to deal in the Software without restriction, including // without limitation the rights to use, copy, modify, merge, publish, // distribute, sublicense, and/or sell copies of the Software, and to permit // persons to whom the Software is furnished to do so, subject to the // following conditions: // // The above copyright notice and this permission notice shall be included // in all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS // OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF // MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN // NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, // DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR // OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE // USE OR OTHER DEALINGS IN THE SOFTWARE. exports.hello = 'hello from one!'; node-v0.10.25~dfsg2/test/fixtures/nested-index/one/index.js0000644000000000000000000000223012270121457022257 0ustar rootroot// Copyright Joyent, Inc. and other Node contributors. // // Permission is hereby granted, free of charge, to any person obtaining a // copy of this software and associated documentation files (the // "Software"), to deal in the Software without restriction, including // without limitation the rights to use, copy, modify, merge, publish, // distribute, sublicense, and/or sell copies of the Software, and to permit // persons to whom the Software is furnished to do so, subject to the // following conditions: // // The above copyright notice and this permission notice shall be included // in all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS // OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF // MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN // NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, // DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR // OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE // USE OR OTHER DEALINGS IN THE SOFTWARE. exports.hello = require('./hello').hello; node-v0.10.25~dfsg2/test/fixtures/print-chars-from-buffer.js0000644000000000000000000000246512270121457022454 0ustar rootroot// Copyright Joyent, Inc. and other Node contributors. // // Permission is hereby granted, free of charge, to any person obtaining a // copy of this software and associated documentation files (the // "Software"), to deal in the Software without restriction, including // without limitation the rights to use, copy, modify, merge, publish, // distribute, sublicense, and/or sell copies of the Software, and to permit // persons to whom the Software is furnished to do so, subject to the // following conditions: // // The above copyright notice and this permission notice shall be included // in all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS // OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF // MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN // NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, // DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR // OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE // USE OR OTHER DEALINGS IN THE SOFTWARE. var common = require('../common'); var assert = require('assert'); var n = parseInt(process.argv[2]); var b = new Buffer(n); for (var i = 0; i < n; i++) { b[i] = 100; } process.stdout.write(b); node-v0.10.25~dfsg2/test/fixtures/test_rsa_privkey.pem0000644000000000000000000000157312270121457021553 0ustar rootroot-----BEGIN RSA PRIVATE KEY----- MIICXgIBAAKBgQDCFENGw33yGihy92pDjZQhl0C36rPJj+CvfSC8+q28hxA161QF NUd13wuCTUcq0Qd2qsBe/2hFyc2DCJJg0h1L78+6Z4UMR7EOcpfdUE9Hf3m/hs+F UR45uBJeDK1HSFHD8bHKD6kv8FPGfJTotc+2xjJwoYi+1hqp1fIekaxsyQIDAQAB AoGBAJR8ZkCUvx5kzv+utdl7T5MnordT1TvoXXJGXK7ZZ+UuvMNUCdN2QPc4sBiA QWvLw1cSKt5DsKZ8UETpYPy8pPYnnDEz2dDYiaew9+xEpubyeW2oH4Zx71wqBtOK kqwrXa/pzdpiucRRjk6vE6YY7EBBs/g7uanVpGibOVAEsqH1AkEA7DkjVH28WDUg f1nqvfn2Kj6CT7nIcE3jGJsZZ7zlZmBmHFDONMLUrXR/Zm3pR5m0tCmBqa5RK95u 412jt1dPIwJBANJT3v8pnkth48bQo/fKel6uEYyboRtA5/uHuHkZ6FQF7OUkGogc mSJluOdc5t6hI1VsLn0QZEjQZMEOWr+wKSMCQQCC4kXJEsHAve77oP6HtG/IiEn7 kpyUXRNvFsDE0czpJJBvL/aRFUJxuRK91jhjC68sA7NsKMGg5OXb5I5Jj36xAkEA gIT7aFOYBFwGgQAQkWNKLvySgKbAZRTeLBacpHMuQdl1DfdntvAyqpAZ0lY0RKmW G6aFKaqQfOXKCyWoUiVknQJAXrlgySFci/2ueKlIE1QqIiLSZ8V8OlpFLRnb1pzI 7U1yQXnTAEFYM560yJlzUpOb1V4cScGd365tiSMvxLOvTA== -----END RSA PRIVATE KEY----- node-v0.10.25~dfsg2/test/fixtures/x.txt0000644000000000000000000000000412270121457016447 0ustar rootrootxyz node-v0.10.25~dfsg2/test/fixtures/deprecated.js0000644000000000000000000000005112270121457020077 0ustar rootrootrequire('util').p('This is deprecated'); node-v0.10.25~dfsg2/test/fixtures/pass-csr.pem0000644000000000000000000000107612270121457017707 0ustar rootroot-----BEGIN CERTIFICATE REQUEST----- MIIBcDCB2gIBADAxMQswCQYDVQQGEwJKUDEOMAwGA1UECBMFVG9reW8xEjAQBgNV BAoUCW5vZGVqc19qcDCBnzANBgkqhkiG9w0BAQEFAAOBjQAwgYkCgYEAoZkHhcLG qJrUG8PTZueQ5+ikkfW5GPDw66EFHkzWvdAZSG4RrCmJuJe2xEWmrBYDq5HEKZOO X3Q1WD4ysa2mYhl1yo0iA2HgwCAv/gpMECq3o4Aj5ibOIFeIPp6b8ItYFa9jQIO3 5CTshFtkw6eHbAA/KrRvAJpdAtYSV8BWJgcCAwEAAaAAMA0GCSqGSIb3DQEBBQUA A4GBAC9g7s3rG6G7JSTUOizY1u9Ij6QM9Y6PqQthr4OJHa+Hln5FJQahpgJmA4kC WYoWvBMBgFPFBCYAj0yMPohrlAwlbd9MADe4gg3lxuO9UxXDzp/lOVRBAEa4n5i+ Lw7VEiJtPha4NXgeNzxi5OyBJwxAOPFwsyCdR0SynlifTFHI -----END CERTIFICATE REQUEST----- node-v0.10.25~dfsg2/test/fixtures/sample.png0000644000000000000000000002231012270121457017432 0ustar rootrootJFIF;CREATOR: gd-jpeg v1.0 (using IJG JPEG v62), quality = 90 C     C   " }!1AQa"q2#BR$3br %&'()*456789:CDEFGHIJSTUVWXYZcdefghijstuvwxyz w!1AQaq"2B #3Rbr $4%&'()*56789:CDEFGHIJSTUVWXYZcdefghijstuvwxyz ?ƞ#%_}NJrR9 팓~:#۳򤑾vL22NG6u[jtM^1;=\Ǯ:xÞ0X+j?a6Jrjx7s]X'kGZuœRLz#o\+׾\o!e{uH OaMծ/}&O$ m}O%?`mƃtɦ&?#sXI7:Ƨv<Bq6{Tjϖ QþiK9RO;Y$e|a4ؒ&tVS5O~(فRWK ïWqdzuRQ=^eOp[xfU\f~_&NJ]ZAKn H5,$t5C[?`b}Lz$ l;w 󟔎٬/lmvQN`c~FsOR(x-$Ҽݶ~[9_ܹ<r0oZ'ZleӮfLq@KwO?{]?PMƑY s(X.񝼨#Z2&ЯT|By + 7~ҟnREKOsf0s(Yݑ9Êρo,3񮢞8ra\d{׃FE׈|GG#ĭ*e 6~D<|$^}+Tbf<1= ŧdȳ[xjXc=ZQ2ȁ#"#ωbܰ̾W6pU|ĎU9V\)m8N:2IsFj&|w~?WՂO2h،<@j2GNGqL'H4Z—* ڽM|s?DzKOZԯdʵC7}+ix~={E-eW`99C܂M_CZ\^쫥UFS{ʬFieT$:'4y?xS庐- (/B#K&A$Znq(PP xcX^|Bx;Gx' m{tIo \qZYJSұKN4j}WǞ0A؏&F2}\{YxY5aCQ嵒8EE<Ws/^\DIU r8z Y\iėcyದ2=*3ht>7[]XN`֡] rm;85zi5 ۬5$ia vI䚥wAmY- ${ n * 0 ֯|Y-,} QL:y;c NՒi+u .}&v'`nORc&MPCW-_Ga m;ʩ2c'GZEZP6?j{&_~leu/434%ZN Ot>6 =EE+(pNII=?ʾ6OH;vZ{b`#4c!-kD%nnkOI. ޱk[ɐ[zޱy˹o E!.{|;awTaEo3Z1[+b\Hyf5NkiVp, 8ע,AFּ9jwNɍ܃=h^󰎿~;|mڵv) L4蠞MspĚ셴? V]U S|oOW5i$ּC7޽lP01׶y<עj(+lψ::Ki3Kߕ^+"e d}+ź?oA e}Q'Ԭk|(†z&G5^Yʰ#9uUpH'`8p>24_.Dt/Zt1;nz}Y}Mm r{ kω猯|g ۿ hlb/#?w'>_j+7jxV,0g+v5_wL6.n;ZJv'Ooƴ9kv6Y3%,7vaOzk&{:m"&hB.@AJ+/^-u yc! 2wm+c𾘾fkI@ q8\rY?i]ad1Xx3Xn## 6y  u|yh(g{o i$Ci):1rxd|vMzUͺ,1e2[  ⾢iRj:V6QVg  r+I5?OWCXY[pOSz۾g&ugB2  -ۻ=.Iu'E9{v|:K| З\&+7I!?+$cy$`~:4gP]ys!3,P*k;v7QYM*E@9>J  _<~w:էϡwIqil_jR'q^|(ښ_ɥ4[qIϾi(ZDеOKMme  {׾2Q-Q**}Ny^~=4q|9"x,sש2op~"q,O0w#'ңnoA_YIXaI8np"BՖuý+R^KDs']>|p] 1 I?lYob9`I3vǿoG{I=% NcߍH Ϡױx[I9<0>xp#҄u+zŗ?hυ̯qmqnphH+ꠠ9_!PxN-Ķac@ u)TC:r*fFLUOáM޷sU;Js^$h~t[[x?5~ _~#RI.=2Zǵz㠬ڳn⽈4bH۪7 tQQU aSE5q)֑|l|9nMOnRuDdi@b_FOZX[&(n@W;O+׽tB?xJxi?P\j7KinR."fQӚj6N^^Ho$ERX |(S7^IojZ(VAu0`In nAmrm#4WCz2̧^v]< OFqÍqcau]VV8WO3,08yeBouo[NgZjkLy FcOsMw:k ]יþ{k5,$ArW?J|SxtZ6].]I NY{^>ZЮ:-)yZK ZE$`\szɦj3Ԡ@M]#wd@^iwcⷄ<3Ekb[&Fc>|33i&pjmG,T0ӯnςt-o.FumB- ,2vsQ _&ɌZH`XWHAv&PլK$WnNph$"u?5OZ-Z5.)"֞ |Gm̽|ef?ag|rN#h'+돽֢@z_N+YtMwU[%1I`O5oZEsm*MC2*c.[krȬ0 fx'z_>K  &rFI!@ Yt./S@'f@88"LZu okmM,p/@"ZL:lGz1ӭr>࿆mq8l ɖWefRE6yrֽ+߱/7VwmL'(aٗʭ2鴟sᯇc5-# c'o^~ oGB&䃂I'n:jIxo_أC4d|`>Q4Ma_~rzc=d~wt fI]5֛Ĥxuu͕֯{wlcs&64udW介"K N3F6zܔͥͨjL$sSWݗ[SCxVkK-5|1Lk?/E5It~ZeK5sypz]x_kF%5?͏K11v 8cgW:Fd̺|@\_ݎ'89MICc346B+]7ytn'z|Gm]qQ0<2pxZ^񕮛^k3l56"o,xWQ<5)K1M5W#(GsUnw1}`-z1xkɔxVyRDn;uck/"MrJƨn( C.9\u_Q?hS=k'`fUTp0)=;э;o 5t?LZlq*(Vs~L]:=ORtɚ1qN0Up=>eb.whQ,2GpX#çx/yii;G9K`n{ >zX`,.==S]1ZvW';\zK}/v43_2vpX7f|EcY1>ИQ8l:ݦ⮓?܆nvn ~(OwR-5b+yr@|LwZ^ QSOF|ڬ'֓w EVa՗is@I>W q[CжO8^\=-+N$׳>?(2NHqɧG&MG;E`7VpnXS~%Bl HO .1q;z[VRľ"]JX4Uj煇[*Oxk?[Qsi~X∳s*+F򋟖,w.s;J5|;Џ-g5oNN:FmVT񆁪 "c^𭭦}ܹ=2wcƢ|QmPG Fc=AJ oֺܢ1fRz6=ѽw'[E5 猓_'Lt/xᗊ]RSM(ʮ 9>GGTL3^ >0.v67`o=Hb핶crA8aY5ˣi?>kSr8HGƼIѡ|"$ZKߑ\qO&s{Js8 V~ }HK"x\8 q]w8[PcC{7 9Xʮr9"9kuNJMᖉƲ멢)&GC9>s1x[4]Vk5=3c6.dt=,#|{o܁%nuA"_μq4}UM0]Au$F/068 dDfx,iF `K9~ӘW,y^i&=PDp2 4#M{G_IIYdL%>|MLỶ?,l=:u4-UZ:|g,o.V0<^\O+6dܗ2 POE]ֻO}ok[ú~={f=RҾŐHnn{9`x]r>&[b[HEup:K1!nv׊!^PDv=̟y:|%cc(^H䙘f=r9X#QIe#oe* #}=tK~9ɂEfr oe::W]/u&q0%qHo[_ |o F[ ; K~{b9_HfW!@cb~gA3ō|?Uu?V+oO1s7y`2kVp3Ms %;~GUD<:;pSʉc44|gҜxPFE|g|"|sKOxh_bU{;DTcɻK`;Ւ(t*@ |)> )ִ^i F=757#/^i qw xӮ7gR ey]vQ#P߁c4wJ~#-8A<\ZlkZʒLX60 1) { expectedData.shift(); } else { // time to shut down fdHighway.close(); sender.close(); client.forceClose(); } }); }); tests_run += 1; sender.listen(port); }); fdHighway.connect(path); }; receiver.on('output', function(data) { var initialized = false; if ((! initialized) && (data == 'ready')) { initializeSender(); initialized = true; } }); } fdPassingTest('/tmp/passing-socket-test', 31075); process.on('exit', function() { assert.equal(1, tests_run); }); node-v0.10.25~dfsg2/test/disabled/test-idle-watcher.js0000644000000000000000000000264112270121457021231 0ustar rootroot// Copyright Joyent, Inc. and other Node contributors. // // Permission is hereby granted, free of charge, to any person obtaining a // copy of this software and associated documentation files (the // "Software"), to deal in the Software without restriction, including // without limitation the rights to use, copy, modify, merge, publish, // distribute, sublicense, and/or sell copies of the Software, and to permit // persons to whom the Software is furnished to do so, subject to the // following conditions: // // The above copyright notice and this permission notice shall be included // in all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS // OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF // MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN // NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, // DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR // OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE // USE OR OTHER DEALINGS IN THE SOFTWARE. var common = require('../common'); var assert = require('assert'); var complete = false; var idle = new process.IdleWatcher(); idle.callback = function() { complete = true; idle.stop(); }; idle.setPriority(process.EVMAXPRI); idle.start(); process.on('exit', function() { assert.ok(complete); }); node-v0.10.25~dfsg2/test/disabled/test-dgram-send-error.js0000644000000000000000000000522512270121457022032 0ustar rootroot// Copyright Joyent, Inc. and other Node contributors. // // Permission is hereby granted, free of charge, to any person obtaining a // copy of this software and associated documentation files (the // "Software"), to deal in the Software without restriction, including // without limitation the rights to use, copy, modify, merge, publish, // distribute, sublicense, and/or sell copies of the Software, and to permit // persons to whom the Software is furnished to do so, subject to the // following conditions: // // The above copyright notice and this permission notice shall be included // in all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS // OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF // MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN // NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, // DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR // OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE // USE OR OTHER DEALINGS IN THE SOFTWARE. // Some operating systems report errors when an UDP message is sent to an // unreachable host. This error can be reported by sendto() and even by // recvfrom(). Node should not propagate this error to the user. // We test this by sending a bunch of packets to random IPs. In the meantime // we also send packets to ourselves to verify that after receiving an error // we can still receive packets successfully. var ITERATIONS = 1000; var assert = require('assert'), common = require('../common'), dgram = require('dgram'); var buf = new Buffer(1024); buf.fill(42); var packetsReceived = 0, packetsSent = 0; var socket = dgram.createSocket('udp4'); socket.on('message', onMessage); socket.on('listening', doSend); socket.bind(common.PORT); function onMessage(message, info) { packetsReceived++; if (packetsReceived < ITERATIONS) { doSend(); } else { socket.close(); } } function afterSend(err) { if (err) throw err; packetsSent++; } function doSend() { // Generate a random IP. var parts = []; for (var i = 0; i < 4; i++) { // Generate a random number in the range 1..254. parts.push(Math.floor(Math.random() * 254) + 1); } var ip = parts.join('.'); socket.send(buf, 0, buf.length, 1, ip, afterSend); socket.send(buf, 0, buf.length, common.PORT, '127.0.0.1', afterSend); } process.on('exit', function() { console.log(packetsSent + ' UDP packets sent, ' + packetsReceived + ' received'); assert.strictEqual(packetsSent, ITERATIONS * 2); assert.strictEqual(packetsReceived, ITERATIONS); }); node-v0.10.25~dfsg2/test/disabled/test-child-process-uid-gid.js0000644000000000000000000000554012270121457022741 0ustar rootroot// Copyright Joyent, Inc. and other Node contributors. // // Permission is hereby granted, free of charge, to any person obtaining a // copy of this software and associated documentation files (the // "Software"), to deal in the Software without restriction, including // without limitation the rights to use, copy, modify, merge, publish, // distribute, sublicense, and/or sell copies of the Software, and to permit // persons to whom the Software is furnished to do so, subject to the // following conditions: // // The above copyright notice and this permission notice shall be included // in all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS // OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF // MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN // NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, // DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR // OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE // USE OR OTHER DEALINGS IN THE SOFTWARE. var common = require('../common'); var assert = require('assert'); var spawn = require('child_process').spawn; var fs = require('fs'); var myUid = process.getuid(); var myGid = process.getgid(); if (myUid != 0) { console.error('must be run as root, otherwise the gid/uid setting will' + ' fail.'); process.exit(1); } // get a different user. // don't care who it is, as long as it's not root var passwd = fs.readFileSync('/etc/passwd', 'utf8'); passwd = passwd.trim().split(/\n/); for (var i = 0, l = passwd.length; i < l; i++) { if (passwd[i].charAt(0) === '#') continue; passwd[i] = passwd[i].split(':'); var otherName = passwd[i][0]; var otherUid = +passwd[i][2]; var otherGid = +passwd[i][3]; if (otherUid && otherUid !== myUid && otherGid && otherGid !== myGid && otherUid > 0) { break; } } if (!otherUid && !otherGid) throw new Error('failed getting passwd info.'); console.error('name, id, gid = %j', [otherName, otherUid, otherGid]); var whoNumber = spawn('id', [], { uid: otherUid, gid: otherGid }); var whoName = spawn('id', [], { uid: otherName, gid: otherGid }); whoNumber.stdout.buf = 'byNumber:'; whoName.stdout.buf = 'byName:'; whoNumber.stdout.on('data', onData); whoName.stdout.on('data', onData); function onData(c) { this.buf += c; } whoNumber.on('exit', onExit); whoName.on('exit', onExit); function onExit(code) { var buf = this.stdout.buf; console.log(buf); var expr = new RegExp('^(byName|byNumber):uid=' + otherUid + '\\(' + otherName + '\\) gid=' + otherGid + '\\('); assert.ok(buf.match(expr), 'uid and gid should match ' + otherName); } node-v0.10.25~dfsg2/test/disabled/test-eio-race.js0000644000000000000000000000513412270121457020345 0ustar rootroot// Copyright Joyent, Inc. and other Node contributors. // // Permission is hereby granted, free of charge, to any person obtaining a // copy of this software and associated documentation files (the // "Software"), to deal in the Software without restriction, including // without limitation the rights to use, copy, modify, merge, publish, // distribute, sublicense, and/or sell copies of the Software, and to permit // persons to whom the Software is furnished to do so, subject to the // following conditions: // // The above copyright notice and this permission notice shall be included // in all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS // OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF // MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN // NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, // DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR // OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE // USE OR OTHER DEALINGS IN THE SOFTWARE. var common = require('../common'); var assert = require('assert'); var count = 100; var fs = require('fs'); // person.jpg is 57kb. We just need some file that is sufficently large. var filename = require('path').join(common.fixturesDir, 'person.jpg'); function tryToKillEventLoop() { console.log('trying to kill event loop ...'); fs.stat(__filename, function(err) { if (err) { throw new Exception('first fs.stat failed'); } else { fs.stat(__filename, function(err) { if (err) { throw new Exception('second fs.stat failed'); } else { console.log('could not kill event loop, retrying...'); setTimeout(function() { if (--count) { tryToKillEventLoop(); } else { console.log('done trying to kill event loop'); process.exit(0); } }, 1); } }); } }); } // Generate a lot of thread pool events var pos = 0; fs.open(filename, 'r', 0666, function(err, fd) { if (err) throw err; function readChunk() { fs.read(fd, 1024, 0, 'binary', function(err, chunk, bytesRead) { if (err) throw err; if (chunk) { pos += bytesRead; //console.log(pos); readChunk(); } else { fs.closeSync(fd); throw new Exception("Shouldn't get EOF"); } }); } readChunk(); }); tryToKillEventLoop(); process.on('exit', function() { console.log('done with test'); assert.ok(pos > 10000); }); node-v0.10.25~dfsg2/test/disabled/test-readline.js0000644000000000000000000000775212270121457020454 0ustar rootroot// Copyright Joyent, Inc. and other Node contributors. // // Permission is hereby granted, free of charge, to any person obtaining a // copy of this software and associated documentation files (the // "Software"), to deal in the Software without restriction, including // without limitation the rights to use, copy, modify, merge, publish, // distribute, sublicense, and/or sell copies of the Software, and to permit // persons to whom the Software is furnished to do so, subject to the // following conditions: // // The above copyright notice and this permission notice shall be included // in all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS // OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF // MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN // NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, // DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR // OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE // USE OR OTHER DEALINGS IN THE SOFTWARE. // Can't test this when 'make test' doesn't assign a tty to the stdout. // Yet another use-case for require('tty').spawn ? var common = require('../common'); var assert = require('assert'); var readline = require('readline'); var key = { xterm: { home: [27, 91, 72], end: [27, 91, 70], metab: [27, 98], metaf: [27, 102], metad: [27, 100] }, gnome: { home: [27, 79, 72], end: [27, 79, 70] }, rxvt: { home: [27, 91, 55], end: [27, 91, 56] }, putty: { home: [27, 91, 49, 126], end: [27, 91, 52, 126] } }; var readlineFakeStream = function() { var written_bytes = []; var rl = readline.createInterface( { fd: 1, write: function(b) { written_bytes.push(b); } }, function(text) { return [[], '']; }); rl.written_bytes = written_bytes; return rl; }; var rl = readlineFakeStream(); var written_bytes_length, refreshed; rl.write('foo'); assert.equal(3, rl.cursor); rl.write(key.xterm.home); assert.equal(0, rl.cursor); rl.write(key.xterm.end); assert.equal(3, rl.cursor); rl.write(key.rxvt.home); assert.equal(0, rl.cursor); rl.write(key.rxvt.end); assert.equal(3, rl.cursor); rl.write(key.gnome.home); assert.equal(0, rl.cursor); rl.write(key.gnome.end); assert.equal(3, rl.cursor); rl.write(key.putty.home); assert.equal(0, rl.cursor); rl.write(key.putty.end); assert.equal(3, rl.cursor); rl = readlineFakeStream(); rl.write('foo bar.hop/zoo'); rl.write(key.xterm.home); written_bytes_length = rl.written_bytes.length; rl.write(key.xterm.metaf); assert.equal(3, rl.cursor); refreshed = written_bytes_length !== rl.written_bytes.length; assert.equal(true, refreshed); rl.write(key.xterm.metaf); assert.equal(7, rl.cursor); rl.write(key.xterm.metaf); assert.equal(11, rl.cursor); written_bytes_length = rl.written_bytes.length; rl.write(key.xterm.metaf); assert.equal(15, rl.cursor); refreshed = written_bytes_length !== rl.written_bytes.length; assert.equal(true, refreshed); written_bytes_length = rl.written_bytes.length; rl.write(key.xterm.metab); assert.equal(12, rl.cursor); refreshed = written_bytes_length !== rl.written_bytes.length; assert.equal(true, refreshed); rl.write(key.xterm.metab); assert.equal(8, rl.cursor); rl.write(key.xterm.metab); assert.equal(4, rl.cursor); written_bytes_length = rl.written_bytes.length; rl.write(key.xterm.metab); assert.equal(0, rl.cursor); refreshed = written_bytes_length !== rl.written_bytes.length; assert.equal(true, refreshed); rl = readlineFakeStream(); rl.write('foo bar.hop/zoo'); rl.write(key.xterm.home); rl.write(key.xterm.metad); assert.equal(0, rl.cursor); assert.equal(' bar.hop/zoo', rl.line); rl.write(key.xterm.metad); assert.equal(0, rl.cursor); assert.equal('.hop/zoo', rl.line); rl.write(key.xterm.metad); assert.equal(0, rl.cursor); assert.equal('/zoo', rl.line); rl.write(key.xterm.metad); assert.equal(0, rl.cursor); assert.equal('', rl.line); node-v0.10.25~dfsg2/test/disabled/test-cat.js0000644000000000000000000000434712270121457017435 0ustar rootroot// Copyright Joyent, Inc. and other Node contributors. // // Permission is hereby granted, free of charge, to any person obtaining a // copy of this software and associated documentation files (the // "Software"), to deal in the Software without restriction, including // without limitation the rights to use, copy, modify, merge, publish, // distribute, sublicense, and/or sell copies of the Software, and to permit // persons to whom the Software is furnished to do so, subject to the // following conditions: // // The above copyright notice and this permission notice shall be included // in all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS // OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF // MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN // NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, // DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR // OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE // USE OR OTHER DEALINGS IN THE SOFTWARE. var common = require('../common.js'); var assert = require('assert'); var http = require('http'); console.log('hello world'); var body = 'exports.A = function() { return "A";}'; var server = http.createServer(function(req, res) { console.log('req?'); res.sendHeader(200, { 'Content-Length': body.length, 'Content-Type': 'text/plain' }); res.sendBody(body); res.finish(); }); server.listen(common.PORT); var errors = 0; var successes = 0; var promise = process.cat('http://localhost:' + common.PORT, 'utf8'); promise.addCallback(function(content) { assert.equal(body, content); server.close(); successes += 1; }); promise.addErrback(function() { errors += 1; }); var dirname = process.path.dirname(__filename); var fixtures = process.path.join(dirname, 'fixtures'); var x = process.path.join(fixtures, 'x.txt'); promise = process.cat(x, 'utf8'); promise.addCallback(function(content) { assert.equal('xyz', content.replace(/[\r\n]/, '')); successes += 1; }); promise.addErrback(function() { errors += 1; }); process.on('exit', function() { assert.equal(2, successes); assert.equal(0, errors); }); node-v0.10.25~dfsg2/test/disabled/test-child-process-custom-fds.js0000644000000000000000000000730712270121457023506 0ustar rootroot// Copyright Joyent, Inc. and other Node contributors. // // Permission is hereby granted, free of charge, to any person obtaining a // copy of this software and associated documentation files (the // "Software"), to deal in the Software without restriction, including // without limitation the rights to use, copy, modify, merge, publish, // distribute, sublicense, and/or sell copies of the Software, and to permit // persons to whom the Software is furnished to do so, subject to the // following conditions: // // The above copyright notice and this permission notice shall be included // in all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS // OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF // MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN // NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, // DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR // OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE // USE OR OTHER DEALINGS IN THE SOFTWARE. var common = require('../common'); var assert = require('assert'); var assert = require('assert'); var spawn = require('child_process').spawn; var path = require('path'); var fs = require('fs'); function fixtPath(p) { return path.join(common.fixturesDir, p); } var expected = 'hello world'; // Test the equivalent of: // $ /bin/echo 'hello world' > hello.txt var helloPath = path.join(common.tmpDir, 'hello.txt'); function test1(next) { console.log('Test 1...'); fs.open(helloPath, 'w', 400, function(err, fd) { if (err) throw err; var child = spawn('/bin/echo', [expected], {customFds: [-1, fd]}); assert.notEqual(child.stdin, null); assert.equal(child.stdout, null); assert.notEqual(child.stderr, null); child.on('exit', function(err) { if (err) throw err; fs.close(fd, function(error) { if (error) throw error; fs.readFile(helloPath, function(err, data) { if (err) throw err; assert.equal(data.toString(), expected + '\n'); console.log(' File was written.'); next(test3); }); }); }); }); } // Test the equivalent of: // $ node ../fixture/stdio-filter.js < hello.txt function test2(next) { console.log('Test 2...'); fs.open(helloPath, 'r', undefined, function(err, fd) { var child = spawn(process.argv[0], [fixtPath('stdio-filter.js'), 'o', 'a'], {customFds: [fd, -1, -1]}); assert.equal(child.stdin, null); var actualData = ''; child.stdout.on('data', function(data) { actualData += data.toString(); }); child.on('exit', function(code) { if (err) throw err; assert.equal(actualData, 'hella warld\n'); console.log(' File was filtered successfully'); fs.close(fd, function() { next(test3); }); }); }); } // Test the equivalent of: // $ /bin/echo 'hello world' | ../stdio-filter.js a o function test3(next) { console.log('Test 3...'); var filter = spawn(process.argv[0], [fixtPath('stdio-filter.js'), 'o', 'a']); var echo = spawn('/bin/echo', [expected], {customFds: [-1, filter.fds[0]]}); var actualData = ''; filter.stdout.on('data', function(data) { console.log(' Got data --> ' + data); actualData += data; }); filter.on('exit', function(code) { if (code) throw 'Return code was ' + code; assert.equal(actualData, 'hella warld\n'); console.log(' Talked to another process successfully'); }); echo.on('exit', function(code) { if (code) throw 'Return code was ' + code; filter.stdin.end(); fs.unlinkSync(helloPath); }); } test1(test2); node-v0.10.25~dfsg2/test/disabled/test-tls-large-push.js0000644000000000000000000000460612270121457021533 0ustar rootroot// Copyright Joyent, Inc. and other Node contributors. // // Permission is hereby granted, free of charge, to any person obtaining a // copy of this software and associated documentation files (the // "Software"), to deal in the Software without restriction, including // without limitation the rights to use, copy, modify, merge, publish, // distribute, sublicense, and/or sell copies of the Software, and to permit // persons to whom the Software is furnished to do so, subject to the // following conditions: // // The above copyright notice and this permission notice shall be included // in all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS // OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF // MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN // NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, // DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR // OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE // USE OR OTHER DEALINGS IN THE SOFTWARE. // Server sends a large string. Client counts bytes and pauses every few // seconds. Makes sure that pause and resume work properly. var common = require('../common'); var assert = require('assert'); var tls = require('tls'); var fs = require('fs'); var body = ''; process.stdout.write('build body...'); for (var i = 0; i < 10 * 1024 * 1024; i++) { body += 'hello world\n'; } process.stdout.write('done\n'); var options = { key: fs.readFileSync(common.fixturesDir + '/keys/agent2-key.pem'), cert: fs.readFileSync(common.fixturesDir + '/keys/agent2-cert.pem') }; var connections = 0; var server = tls.Server(options, function(socket) { socket.end(body); connections++; }); var recvCount = 0; server.listen(common.PORT, function() { var client = tls.connect(common.PORT); client.on('data', function(d) { process.stdout.write('.'); recvCount += d.length; /* client.pause(); process.nextTick(function () { client.resume(); }); */ }); client.on('close', function() { debugger; console.log('close'); server.close(); }); }); process.on('exit', function() { assert.equal(1, connections); console.log('body.length: %d', body.length); console.log(' recvCount: %d', recvCount); assert.equal(body.length, recvCount); }); node-v0.10.25~dfsg2/test/disabled/test-http-big-proxy-responses.js0000644000000000000000000000672012270121457023577 0ustar rootroot// Copyright Joyent, Inc. and other Node contributors. // // Permission is hereby granted, free of charge, to any person obtaining a // copy of this software and associated documentation files (the // "Software"), to deal in the Software without restriction, including // without limitation the rights to use, copy, modify, merge, publish, // distribute, sublicense, and/or sell copies of the Software, and to permit // persons to whom the Software is furnished to do so, subject to the // following conditions: // // The above copyright notice and this permission notice shall be included // in all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS // OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF // MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN // NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, // DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR // OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE // USE OR OTHER DEALINGS IN THE SOFTWARE. var common = require('../common'); var assert = require('assert'); var util = require('util'), fs = require('fs'), http = require('http'), url = require('url'); var chunk = '01234567890123456789'; // Produce a very large response. var chargen = http.createServer(function(req, res) { var len = parseInt(req.headers['x-len'], 10); assert.ok(len > 0); res.writeHead(200, {'transfer-encoding': 'chunked'}); for (var i = 0; i < len; i++) { if (i % 1000 == 0) common.print(','); res.write(chunk); } res.end(); }); chargen.listen(9000, ready); // Proxy to the chargen server. var proxy = http.createServer(function(req, res) { var len = parseInt(req.headers['x-len'], 10); assert.ok(len > 0); var sent = 0; function onError(e) { console.log('proxy client error. sent ' + sent); throw e; } var proxy_req = http.request({ host: 'localhost', port: 9000, method: req.method, path: req.url, headers: req.headers }, function(proxy_res) { res.writeHead(proxy_res.statusCode, proxy_res.headers); var count = 0; proxy_res.on('data', function(d) { if (count++ % 1000 == 0) common.print('.'); res.write(d); sent += d.length; assert.ok(sent <= (len * chunk.length)); }); proxy_res.on('end', function() { res.end(); }); }); proxy_req.on('error', onError); proxy_req.end(); }); proxy.listen(9001, ready); var done = false; function call_chargen(list) { if (list.length > 0) { var len = list.shift(); common.debug('calling chargen for ' + len + ' chunks.'); var recved = 0; var req = http.request({ port: 9001, host: 'localhost', path: '/', headers: {'x-len': len} }, function(res) { res.on('data', function(d) { recved += d.length; assert.ok(recved <= (len * chunk.length)); }); res.on('end', function() { assert.ok(recved <= (len * chunk.length)); common.debug('end for ' + len + ' chunks.'); call_chargen(list); }); }); req.end(); } else { console.log('End of list. closing servers'); proxy.close(); chargen.close(); done = true; } } var serversRunning = 0; function ready() { if (++serversRunning < 2) return; call_chargen([100, 1000, 10000, 100000, 1000000]); } process.on('exit', function() { assert.ok(done); }); node-v0.10.25~dfsg2/test/disabled/test-setuidgid.js0000644000000000000000000000326212270121457020642 0ustar rootroot// Copyright Joyent, Inc. and other Node contributors. // // Permission is hereby granted, free of charge, to any person obtaining a // copy of this software and associated documentation files (the // "Software"), to deal in the Software without restriction, including // without limitation the rights to use, copy, modify, merge, publish, // distribute, sublicense, and/or sell copies of the Software, and to permit // persons to whom the Software is furnished to do so, subject to the // following conditions: // // The above copyright notice and this permission notice shall be included // in all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS // OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF // MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN // NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, // DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR // OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE // USE OR OTHER DEALINGS IN THE SOFTWARE. // Requires special privlages var common = require('../common'); var assert = require('assert'); var oldgid = process.getgid(); process.setgid('nobody'); var newgid = process.getgid(); assert.notEqual(newgid, oldgid, 'gids expected to be different'); var olduid = process.getuid(); process.setuid('nobody'); var newuid = process.getuid(); assert.notEqual(newuid, olduid, 'uids expected to be different'); try { process.setuid('nobody1234'); } catch (e) { assert.equal(e.message, 'failed to resolve group', 'unexpected error message' ); } node-v0.10.25~dfsg2/test/disabled/tls-client.js0000644000000000000000000000307112270121457017760 0ustar rootroot// Copyright Joyent, Inc. and other Node contributors. // // Permission is hereby granted, free of charge, to any person obtaining a // copy of this software and associated documentation files (the // "Software"), to deal in the Software without restriction, including // without limitation the rights to use, copy, modify, merge, publish, // distribute, sublicense, and/or sell copies of the Software, and to permit // persons to whom the Software is furnished to do so, subject to the // following conditions: // // The above copyright notice and this permission notice shall be included // in all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS // OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF // MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN // NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, // DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR // OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE // USE OR OTHER DEALINGS IN THE SOFTWARE. var common = require('../common'); var tls = require('tls'); var fs = require('fs'); // most servers don't require certificates var options = { key: fs.readFileSync(common.fixturesDir + '/keys/agent1-key.pem') }; var s = tls.connect(443, 'joyent.com', options, function() { if (!s.authorized) { console.error('CONNECTED: ' + s.authorizationError); s.destroy(); return; } s.pipe(process.stdout); process.openStdin().pipe(s); }); node-v0.10.25~dfsg2/test/disabled/test-process-title.js0000644000000000000000000000435312270121457021460 0ustar rootroot// Copyright Joyent, Inc. and other Node contributors. // // Permission is hereby granted, free of charge, to any person obtaining a // copy of this software and associated documentation files (the // "Software"), to deal in the Software without restriction, including // without limitation the rights to use, copy, modify, merge, publish, // distribute, sublicense, and/or sell copies of the Software, and to permit // persons to whom the Software is furnished to do so, subject to the // following conditions: // // The above copyright notice and this permission notice shall be included // in all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS // OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF // MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN // NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, // DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR // OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE // USE OR OTHER DEALINGS IN THE SOFTWARE. var common = require('../common'); var assert = require('assert'); var spawn = require('child_process').spawn; if (process.title === '') { console.log('skipping test -- not implemented for the host platform'); //return; } // disabled because of two things // - not tested on linux (can ps show process title on Linux?) // - unable to verify effect on Darwin/OS X (only avail through GUI tools AFAIK) function verifyProcessName(str, callback) { process.title = str; var buf = ''; ps = spawn('ps'); ps.stdout.setEncoding('utf8'); ps.stdout.on('data', function(s) { buf += s; }); ps.on('exit', function(c) { try { assert.equal(0, c); assert.ok(new RegExp(process.pid + ' ', 'm').test(buf)); assert.ok(new RegExp(str, 'm').test(buf)); callback(); } catch (err) { callback(err); } }); } verifyProcessName('3kd023mslkfp--unique-string--sksdf', function(err) { if (err) throw err; console.log('title is now %j', process.title); verifyProcessName('3kd023mslxxx--unique-string--xxx', function(err) { if (err) throw err; console.log('title is now %j', process.title); }); }); node-v0.10.25~dfsg2/test/disabled/test-sendfd.js0000644000000000000000000001215012270121457020120 0ustar rootroot// Copyright Joyent, Inc. and other Node contributors. // // Permission is hereby granted, free of charge, to any person obtaining a // copy of this software and associated documentation files (the // "Software"), to deal in the Software without restriction, including // without limitation the rights to use, copy, modify, merge, publish, // distribute, sublicense, and/or sell copies of the Software, and to permit // persons to whom the Software is furnished to do so, subject to the // following conditions: // // The above copyright notice and this permission notice shall be included // in all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS // OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF // MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN // NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, // DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR // OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE // USE OR OTHER DEALINGS IN THE SOFTWARE. // Test sending and receiving a file descriptor. // // This test is pretty complex. It ends up spawning test/fixtures/recvfd.js // as a child to test desired behavior. What happens is // // 1. Create an in-memory pipe via pipe(2). These two file descriptors // are not visible to any other process, and so make a good test-case // for sharing. // 2. Create a a UNIX socket at SOCK_PATH. When a client connects to this // path, they are sent the write end of the pipe from above. // 3. The client is sent n JSON representations of the DATA variable, each // with a different ordinal. We send these delimited by '\n' strings // so that the receiving end can avoid any coalescing that hapepns // due to the stream nature of the socket (e.g. '{}{}' is not a valid // JSON string). // 4. The child process receives file descriptors and JSON blobs and, // whenever it has at least one of each, writes a modified JSON blob // to the FD. The blob is modified to include the child's process ID. // 5. Once the child process has sent n responses, it closes the write end // of the pipe, which signals to the parent that there is no more data // coming. // 6. The parent listens to the read end of the pipe, accumulating JSON // blobs (again, delimited by '\n') and verifying that a) the 'pid' // attribute belongs to the child and b) the 'ord' field has not been // seen in a response yet. This is intended to ensure that all blobs // sent out have been relayed back to us. var common = require('../common'); var assert = require('assert'); var buffer = require('buffer'); var child_process = require('child_process'); var fs = require('fs'); var net = require('net'); var netBinding = process.binding('net'); var path = require('path'); var DATA = { 'ppid' : process.pid, 'ord' : 0 }; var SOCK_PATH = path.join(__dirname, '..', path.basename(__filename, '.js') + '.sock'); var logChild = function(d) { if (typeof d == 'object') { d = d.toString(); } d.split('\n').forEach(function(l) { if (l.length > 0) { common.debug('CHILD: ' + l); } }); }; // Create a pipe // // We establish a listener on the read end of the pipe so that we can // validate any data sent back by the child. We send the write end of the // pipe to the child and close it off in our process. var pipeFDs = netBinding.pipe(); assert.equal(pipeFDs.length, 2); var seenOrdinals = []; var pipeReadStream = new net.Stream(); pipeReadStream.on('data', function(data) { data.toString('utf8').trim().split('\n').forEach(function(d) { var rd = JSON.parse(d); assert.equal(rd.pid, cpp); assert.equal(seenOrdinals.indexOf(rd.ord), -1); seenOrdinals.unshift(rd.ord); }); }); pipeReadStream.open(pipeFDs[0]); pipeReadStream.resume(); // Create a UNIX socket at SOCK_PATH and send DATA and the write end // of the pipe to whoever connects. // // We send two messages here, both with the same pipe FD: one string, and // one buffer. We want to make sure that both datatypes are handled // correctly. var srv = net.createServer(function(s) { var str = JSON.stringify(DATA) + '\n'; DATA.ord = DATA.ord + 1; var buf = new buffer.Buffer(str.length); buf.write(JSON.stringify(DATA) + '\n', 'utf8'); s.write(str, 'utf8', pipeFDs[1]); if (s.write(buf, pipeFDs[1])) { netBinding.close(pipeFDs[1]); } else { s.on('drain', function() { netBinding.close(pipeFDs[1]); }); } }); srv.listen(SOCK_PATH); // Spawn a child running test/fixtures/recvfd.js var cp = child_process.spawn(process.argv[0], [path.join(common.fixturesDir, 'recvfd.js'), SOCK_PATH]); cp.stdout.on('data', logChild); cp.stderr.on('data', logChild); // When the child exits, clean up and validate its exit status var cpp = cp.pid; cp.on('exit', function(code, signal) { srv.close(); // fs.unlinkSync(SOCK_PATH); assert.equal(code, 0); assert.equal(seenOrdinals.length, 2); }); // vim:ts=2 sw=2 et node-v0.10.25~dfsg2/test/disabled/test-remote-module-loading.js0000644000000000000000000000420512270121457023050 0ustar rootroot// Copyright Joyent, Inc. and other Node contributors. // // Permission is hereby granted, free of charge, to any person obtaining a // copy of this software and associated documentation files (the // "Software"), to deal in the Software without restriction, including // without limitation the rights to use, copy, modify, merge, publish, // distribute, sublicense, and/or sell copies of the Software, and to permit // persons to whom the Software is furnished to do so, subject to the // following conditions: // // The above copyright notice and this permission notice shall be included // in all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS // OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF // MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN // NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, // DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR // OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE // USE OR OTHER DEALINGS IN THE SOFTWARE. var common = require('../common'); var assert = require('assert'); var http = require('http'); var util = require('util'); var url = require('url'); var modulesLoaded = 0; var server = http.createServer(function(req, res) { var body = 'exports.httpPath = function() {' + 'return ' + JSON.stringify(url.parse(req.url).pathname) + ';' + '};'; res.writeHead(200, {'Content-Type': 'text/javascript'}); res.write(body); res.end(); }); server.listen(common.PORT); assert.throws(function() { var httpModule = require('http://localhost:' + common.PORT + '/moduleA.js'); assert.equal('/moduleA.js', httpModule.httpPath()); modulesLoaded++; }); var nodeBinary = process.ARGV[0]; var cmd = 'NODE_PATH=' + common.libDir + ' ' + nodeBinary + ' http://localhost:' + common.PORT + '/moduleB.js'; util.exec(cmd, function(err, stdout, stderr) { if (err) throw err; console.log('success!'); modulesLoaded++; server.close(); }); process.on('exit', function() { assert.equal(1, modulesLoaded); }); node-v0.10.25~dfsg2/test/disabled/test-http-default-port.js0000644000000000000000000000432012270121457022240 0ustar rootroot// Copyright Joyent, Inc. and other Node contributors. // // Permission is hereby granted, free of charge, to any person obtaining a // copy of this software and associated documentation files (the // "Software"), to deal in the Software without restriction, including // without limitation the rights to use, copy, modify, merge, publish, // distribute, sublicense, and/or sell copies of the Software, and to permit // persons to whom the Software is furnished to do so, subject to the // following conditions: // // The above copyright notice and this permission notice shall be included // in all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS // OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF // MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN // NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, // DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR // OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE // USE OR OTHER DEALINGS IN THE SOFTWARE. // This must be run as root. var common = require('../common'); var http = require('http'), https = require('https'), PORT = 80, SSLPORT = 443, assert = require('assert'), hostExpect = 'localhost', fs = require('fs'), path = require('path'), fixtures = path.resolve(__dirname, '../fixtures/keys'), options = { key: fs.readFileSync(fixtures + '/agent1-key.pem'), cert: fs.readFileSync(fixtures + '/agent1-cert.pem') }; http.createServer(function(req, res) { console.error(req.headers); assert.equal(req.headers.host, hostExpect); res.writeHead(200); res.end('ok'); this.close(); }).listen(PORT); https.createServer(options, function(req, res) { console.error(req.headers); assert.equal(req.headers.host, hostExpect); res.writeHead(200); res.end('ok'); this.close(); }).listen(SSLPORT); http .get({ host: 'localhost', port: PORT, headers: { 'x-port': PORT } }) .on('response', function(res) {}); https .get({ host: 'localhost', port: SSLPORT, headers: { 'x-port': SSLPORT } }) .on('response', function(res) {}); node-v0.10.25~dfsg2/test/disabled/test-http-tls.js0000644000000000000000000001320612270121457020437 0ustar rootroot// Copyright Joyent, Inc. and other Node contributors. // // Permission is hereby granted, free of charge, to any person obtaining a // copy of this software and associated documentation files (the // "Software"), to deal in the Software without restriction, including // without limitation the rights to use, copy, modify, merge, publish, // distribute, sublicense, and/or sell copies of the Software, and to permit // persons to whom the Software is furnished to do so, subject to the // following conditions: // // The above copyright notice and this permission notice shall be included // in all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS // OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF // MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN // NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, // DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR // OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE // USE OR OTHER DEALINGS IN THE SOFTWARE. var common = require('../common'); var assert = require('assert'); var net = require('net'); var http = require('http'); var url = require('url'); var qs = require('querystring'); var fs = require('fs'); var have_openssl; try { var crypto = require('crypto'); var dummy_server = http.createServer(function() {}); dummy_server.setSecure(); have_openssl = true; } catch (e) { have_openssl = false; console.log('Not compiled with OPENSSL support.'); process.exit(); } var request_number = 0; var requests_sent = 0; var server_response = ''; var client_got_eof = false; var caPem = fs.readFileSync(common.fixturesDir + '/test_ca.pem', 'ascii'); var certPem = fs.readFileSync(common.fixturesDir + '/test_cert.pem', 'ascii'); var keyPem = fs.readFileSync(common.fixturesDir + '/test_key.pem', 'ascii'); try { var credentials = crypto.createCredentials( { key: keyPem, cert: certPem, ca: caPem }); } catch (e) { console.log('Not compiled with OPENSSL support.'); process.exit(); } var https_server = http.createServer(function(req, res) { res.id = request_number; req.id = request_number++; var verified = res.connection.verifyPeer(); var peerDN = JSON.stringify(req.connection.getPeerCertificate()); assert.equal(verified, true); assert.equal(peerDN, '{"subject":"/C=UK/ST=Acknack Ltd/L=Rhys Jones' + '/O=node.js/OU=Test TLS Certificate/CN=localhost",' + '"issuer":"/C=UK/ST=Acknack Ltd/L=Rhys Jones/O=node.js' + '/OU=Test TLS Certificate/CN=localhost",' + '"valid_from":"Nov 11 09:52:22 2009 GMT",' + '"valid_to":"Nov 6 09:52:22 2029 GMT",' + '"fingerprint":"2A:7A:C2:DD:E5:F9:CC:53:72:35:99:7A:02:' + '5A:71:38:52:EC:8A:DF"}'); if (req.id == 0) { assert.equal('GET', req.method); assert.equal('/hello', url.parse(req.url).pathname); assert.equal('world', qs.parse(url.parse(req.url).query).hello); assert.equal('b==ar', qs.parse(url.parse(req.url).query).foo); } if (req.id == 1) { assert.equal('POST', req.method); assert.equal('/quit', url.parse(req.url).pathname); } if (req.id == 2) { assert.equal('foo', req.headers['x-x']); } if (req.id == 3) { assert.equal('bar', req.headers['x-x']); this.close(); //console.log('server closed'); } setTimeout(function() { res.writeHead(200, {'Content-Type': 'text/plain'}); res.write(url.parse(req.url).pathname); res.end(); }, 1); }); https_server.setSecure(credentials); https_server.listen(common.PORT); https_server.on('listening', function() { var c = net.createConnection(common.PORT); c.setEncoding('utf8'); c.on('connect', function() { c.setSecure(credentials); }); c.on('secure', function() { var verified = c.verifyPeer(); var peerDN = JSON.stringify(c.getPeerCertificate()); assert.equal(verified, true); assert.equal(peerDN, '{"subject":"/C=UK/ST=Acknack Ltd/L=Rhys Jones' + '/O=node.js/OU=Test TLS Certificate/CN=localhost",' + '"issuer":"/C=UK/ST=Acknack Ltd/L=Rhys Jones/O=node.js' + '/OU=Test TLS Certificate/CN=localhost",' + '"valid_from":"Nov 11 09:52:22 2009 GMT",' + '"valid_to":"Nov 6 09:52:22 2029 GMT",' + '"fingerprint":"2A:7A:C2:DD:E5:F9:CC:53:72:35:99:7A:02:' + '5A:71:38:52:EC:8A:DF"}'); c.write('GET /hello?hello=world&foo=b==ar HTTP/1.1\r\n\r\n'); requests_sent += 1; }); c.on('data', function(chunk) { server_response += chunk; if (requests_sent == 1) { c.write('POST /quit HTTP/1.1\r\n\r\n'); requests_sent += 1; } if (requests_sent == 2) { c.write('GET / HTTP/1.1\r\nX-X: foo\r\n\r\n' + 'GET / HTTP/1.1\r\nX-X: bar\r\n\r\n'); c.end(); assert.equal(c.readyState, 'readOnly'); requests_sent += 2; } }); c.on('end', function() { client_got_eof = true; }); c.on('close', function() { assert.equal(c.readyState, 'closed'); }); }); process.on('exit', function() { assert.equal(4, request_number); assert.equal(4, requests_sent); var hello = new RegExp('/hello'); assert.equal(true, hello.exec(server_response) != null); var quit = new RegExp('/quit'); assert.equal(true, quit.exec(server_response) != null); assert.equal(true, client_got_eof); }); node-v0.10.25~dfsg2/test/disabled/test-http-stress.js0000644000000000000000000000434012270121457021157 0ustar rootroot// Copyright Joyent, Inc. and other Node contributors. // // Permission is hereby granted, free of charge, to any person obtaining a // copy of this software and associated documentation files (the // "Software"), to deal in the Software without restriction, including // without limitation the rights to use, copy, modify, merge, publish, // distribute, sublicense, and/or sell copies of the Software, and to permit // persons to whom the Software is furnished to do so, subject to the // following conditions: // // The above copyright notice and this permission notice shall be included // in all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS // OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF // MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN // NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, // DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR // OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE // USE OR OTHER DEALINGS IN THE SOFTWARE. var common = require('../common'); var assert = require('assert'); var http = require('http'); var request_count = 1000; var body = '{"ok": true}'; var server = http.createServer(function(req, res) { res.writeHead(200, {'Content-Type': 'text/javascript'}); res.write(body); res.end(); }); server.listen(common.PORT); var requests_ok = 0; var requests_complete = 0; server.on('listening', function() { for (var i = 0; i < request_count; i++) { http.cat('http://localhost:' + common.PORT + '/', 'utf8', function(err, content) { requests_complete++; if (err) { common.print('-'); } else { assert.equal(body, content); common.print('.'); requests_ok++; } if (requests_complete == request_count) { console.log('\nrequests ok: ' + requests_ok); server.close(); } }); } }); process.on('exit', function() { assert.equal(request_count, requests_complete); assert.equal(request_count, requests_ok); }); node-v0.10.25~dfsg2/test/disabled/tls_server.js0000644000000000000000000000440012270121457020067 0ustar rootroot// Copyright Joyent, Inc. and other Node contributors. // // Permission is hereby granted, free of charge, to any person obtaining a // copy of this software and associated documentation files (the // "Software"), to deal in the Software without restriction, including // without limitation the rights to use, copy, modify, merge, publish, // distribute, sublicense, and/or sell copies of the Software, and to permit // persons to whom the Software is furnished to do so, subject to the // following conditions: // // The above copyright notice and this permission notice shall be included // in all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS // OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF // MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN // NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, // DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR // OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE // USE OR OTHER DEALINGS IN THE SOFTWARE. var common = require('../common'); var assert = require('assert'); var util = require('util'); var net = require('net'); var fs = require('fs'); var crypto = require('crypto'); var keyPem = fs.readFileSync(common.fixturesDir + '/cert.pem'); var certPem = fs.readFileSync(common.fixturesDir + '/cert.pem'); try { var credentials = crypto.createCredentials({key: keyPem, cert: certPem}); } catch (e) { console.log('Not compiled with OPENSSL support.'); process.exit(); } var i = 0; var server = net.createServer(function(connection) { connection.setSecure(credentials); connection.setEncoding('binary'); connection.on('secure', function() { //console.log('Secure'); }); connection.on('data', function(chunk) { console.log('recved: ' + JSON.stringify(chunk)); connection.write('HTTP/1.0 200 OK\r\n' + 'Content-type: text/plain\r\n' + 'Content-length: 9\r\n' + '\r\n' + 'OK : ' + i + '\r\n\r\n'); i = i + 1; connection.end(); }); connection.on('end', function() { connection.end(); }); }); server.listen(4443); node-v0.10.25~dfsg2/test/disabled/test-eio-race2.js0000644000000000000000000000324712270121457020432 0ustar rootroot// Copyright Joyent, Inc. and other Node contributors. // // Permission is hereby granted, free of charge, to any person obtaining a // copy of this software and associated documentation files (the // "Software"), to deal in the Software without restriction, including // without limitation the rights to use, copy, modify, merge, publish, // distribute, sublicense, and/or sell copies of the Software, and to permit // persons to whom the Software is furnished to do so, subject to the // following conditions: // // The above copyright notice and this permission notice shall be included // in all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS // OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF // MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN // NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, // DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR // OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE // USE OR OTHER DEALINGS IN THE SOFTWARE. var common = require('../common'); var assert = require('assert'); var path = require('path'); var testTxt = path.join(common.fixturesDir, 'x.txt'); var fs = require('fs'); setTimeout(function() { // put this in a timeout, just so it doesn't get bunched up with the // require() calls.. var N = 30; for (var i = 0; i < N; i++) { console.log('start ' + i); fs.readFile(testTxt, function(err, data) { if (err) { console.log('error! ' + e); process.exit(1); } else { console.log('finish'); } }); } }, 100); node-v0.10.25~dfsg2/test/disabled/test-http-agent2.js0000644000000000000000000000436112270121457021017 0ustar rootroot// Copyright Joyent, Inc. and other Node contributors. // // Permission is hereby granted, free of charge, to any person obtaining a // copy of this software and associated documentation files (the // "Software"), to deal in the Software without restriction, including // without limitation the rights to use, copy, modify, merge, publish, // distribute, sublicense, and/or sell copies of the Software, and to permit // persons to whom the Software is furnished to do so, subject to the // following conditions: // // The above copyright notice and this permission notice shall be included // in all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS // OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF // MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN // NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, // DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR // OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE // USE OR OTHER DEALINGS IN THE SOFTWARE. var common = require('../common'); var assert = require('assert'); var http = require('http'); var reqEndCount = 0; var server = http.Server(function(req, res) { res.writeHead(200); res.end('hello world\n'); var buffer = ''; req.setEncoding('utf8'); req.on('data', function(s) { buffer += s; }); req.on('end', function() { reqEndCount++; assert.equal(body, buffer); }); }); var responses = 0; var N = 10; var M = 10; var body = ''; for (var i = 0; i < 1000; i++) { body += 'hello world'; } var options = { port: common.PORT, path: '/', method: 'PUT' }; server.listen(common.PORT, function() { for (var i = 0; i < N; i++) { setTimeout(function() { for (var j = 0; j < M; j++) { var req = http.request(options, function(res) { console.log(res.statusCode); if (++responses == N * M) server.close(); }).on('error', function(e) { console.log(e.message); process.exit(1); }); req.end(body); } }, i); } }); process.on('exit', function() { assert.equal(N * M, responses); assert.equal(N * M, reqEndCount); }); node-v0.10.25~dfsg2/test/disabled/test-eio-race4.js0000644000000000000000000000306112270121457020426 0ustar rootroot// Copyright Joyent, Inc. and other Node contributors. // // Permission is hereby granted, free of charge, to any person obtaining a // copy of this software and associated documentation files (the // "Software"), to deal in the Software without restriction, including // without limitation the rights to use, copy, modify, merge, publish, // distribute, sublicense, and/or sell copies of the Software, and to permit // persons to whom the Software is furnished to do so, subject to the // following conditions: // // The above copyright notice and this permission notice shall be included // in all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS // OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF // MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN // NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, // DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR // OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE // USE OR OTHER DEALINGS IN THE SOFTWARE. var common = require('../common'); var assert = require('assert'); var fs = require('fs'); var N = 100; var j = 0; for (var i = 0; i < N; i++) { // these files don't exist fs.stat('does-not-exist-' + i, function(err) { if (err) { j++; // only makes it to about 17 console.log('finish ' + j); } else { throw new Error('this shouldn\'t be called'); } }); } process.on('exit', function() { assert.equal(N, j); }); node-v0.10.25~dfsg2/test/disabled/test-debug-brk-file.js0000644000000000000000000000676312270121457021451 0ustar rootroot// Copyright Joyent, Inc. and other Node contributors. // // Permission is hereby granted, free of charge, to any person obtaining a // copy of this software and associated documentation files (the // "Software"), to deal in the Software without restriction, including // without limitation the rights to use, copy, modify, merge, publish, // distribute, sublicense, and/or sell copies of the Software, and to permit // persons to whom the Software is furnished to do so, subject to the // following conditions: // // The above copyright notice and this permission notice shall be included // in all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS // OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF // MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN // NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, // DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR // OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE // USE OR OTHER DEALINGS IN THE SOFTWARE. var common = require('../common'); var assert = require('assert'); var spawn = require('child_process').spawn; var path = require('path'); var net = require('net'); var isDone = false; var targetPath = path.resolve(common.fixturesDir, 'debug-target.js'); var child = spawn(process.execPath, ['--debug-brk=' + common.PORT, targetPath]); child.stderr.on('data', function() { child.emit('debug_start'); }); child.on('exit', function() { assert(isDone); console.log('ok'); }); child.once('debug_start', function() { // delayed for some time until debug agent is ready setTimeout(function() { debug_client_connect(); }, 200); }); function debug_client_connect() { var msg = null; var tmpBuf = ''; var conn = net.connect({port: common.PORT}); conn.setEncoding('utf8'); conn.on('data', function(data) { tmpBuf += data; parse(); }); function parse() { if (!msg) { msg = { headers: null, contentLength: 0 }; } if (!msg.headers) { var offset = tmpBuf.indexOf('\r\n\r\n'); if (offset < 0) return; msg.headers = tmpBuf.substring(0, offset); tmpBuf = tmpBuf.slice(offset + 4); var matches = /Content-Length: (\d+)/.exec(msg.headers); if (matches[1]) { msg.contentLength = +(matches[1]); } } if (msg.headers && Buffer.byteLength(tmpBuf) >= msg.contentLength) { try { var b = Buffer(tmpBuf); var body = b.toString('utf8', 0, msg.contentLength); tmpBuf = b.toString('utf8', msg.contentLength, b.length); // get breakpoint list and check if it exists on line 0 if (!body.length) { var req = JSON.stringify({'seq': 1, 'type': 'request', 'command': 'listbreakpoints'}); conn.write('Content-Length: ' + req.length + '\r\n\r\n' + req); return; } var obj = JSON.parse(body); if (obj.type === 'response' && obj.command === 'listbreakpoints' && !obj.running) { obj.body.breakpoints.forEach(function(bpoint) { if (bpoint.line === 0) isDone = true; }); } var req = JSON.stringify({'seq': 100, 'type': 'request', 'command': 'disconnect'}); conn.write('Content-Length: ' + req.length + '\r\n\r\n' + req); } finally { msg = null; parse(); } } } } node-v0.10.25~dfsg2/test/disabled/test-dgram-unix.js0000644000000000000000000000507212270121457020735 0ustar rootroot// Copyright Joyent, Inc. and other Node contributors. // // Permission is hereby granted, free of charge, to any person obtaining a // copy of this software and associated documentation files (the // "Software"), to deal in the Software without restriction, including // without limitation the rights to use, copy, modify, merge, publish, // distribute, sublicense, and/or sell copies of the Software, and to permit // persons to whom the Software is furnished to do so, subject to the // following conditions: // // The above copyright notice and this permission notice shall be included // in all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS // OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF // MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN // NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, // DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR // OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE // USE OR OTHER DEALINGS IN THE SOFTWARE. var common = require('../common'); var assert = require('assert'); var fs = require('fs'); var dgram = require('dgram'); // TODO use common.tmpDir here var serverPath = '/tmp/dgram_server_sock'; var clientPath = '/tmp/dgram_client_sock'; var msgToSend = new Buffer('A message to send'); var server = dgram.createSocket('unix_dgram'); server.on('message', function(msg, rinfo) { console.log('server got: ' + msg + ' from ' + rinfo.address); assert.strictEqual(rinfo.address, clientPath); assert.strictEqual(msg.toString(), msgToSend.toString()); server.send(msg, 0, msg.length, rinfo.address); }); server.on('listening', function() { console.log('server is listening'); var client = dgram.createSocket('unix_dgram'); client.on('message', function(msg, rinfo) { console.log('client got: ' + msg + ' from ' + rinfo.address); assert.strictEqual(rinfo.address, serverPath); assert.strictEqual(msg.toString(), msgToSend.toString()); client.close(); server.close(); }); client.on('listening', function() { console.log('client is listening'); client.send(msgToSend, 0, msgToSend.length, serverPath, function(err, bytes) { if (err) { console.log('Caught error in client send.'); throw err; } console.log('client wrote ' + bytes + ' bytes.'); assert.strictEqual(bytes, msgToSend.length); }); }); client.bind(clientPath); }); server.bind(serverPath); node-v0.10.25~dfsg2/test/disabled/test-dns.js0000644000000000000000000001531112270121457017443 0ustar rootroot// Copyright Joyent, Inc. and other Node contributors. // // Permission is hereby granted, free of charge, to any person obtaining a // copy of this software and associated documentation files (the // "Software"), to deal in the Software without restriction, including // without limitation the rights to use, copy, modify, merge, publish, // distribute, sublicense, and/or sell copies of the Software, and to permit // persons to whom the Software is furnished to do so, subject to the // following conditions: // // The above copyright notice and this permission notice shall be included // in all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS // OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF // MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN // NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, // DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR // OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE // USE OR OTHER DEALINGS IN THE SOFTWARE. var common = require('../common'); var assert = require('assert'); var dns = require('dns'), child_process = require('child_process'); // Try resolution without callback assert.throws(function() { dns.resolve('google.com', 'A'); }); assert.throws(function() { dns.resolve('127.0.0.1', 'PTR'); }); var hosts = ['example.com', 'example.org', 'ietf.org', // AAAA 'google.com', // MX, multiple A records '_xmpp-client._tcp.google.com', // SRV 'oakalynhall.co.uk' // Multiple PTR replies ]; var records = ['A', 'AAAA', 'MX', 'TXT', 'SRV']; var i = hosts.length; while (i--) { var j = records.length; while (j--) { var hostCmd = 'dig -t ' + records[j] + ' ' + hosts[i] + '| grep "^' + hosts[i] + '\\.\\W.*IN.*' + records[j] + '"' + '| sed -E "s/[[:space:]]+/ /g" | cut -d " " -f 5- ' + '| sed -e "s/\\.$//"'; child_process.exec(hostCmd, checkDnsRecord(hosts[i], records[j])); } } // CNAME should resolve var resolveCNAME = 'before'; dns.resolve('labs.nrcmedia.nl', 'CNAME', function(err, result) { assert.deepEqual(result, ['nrcmedia.nl']); assert.equal(resolveCNAME, 'beforeafter'); }); resolveCNAME += 'after'; // CNAME should not resolve dns.resolve('nrcmedia.nl', 'CNAME', function(err, result) { assert.ok(err.errno, dns.NODATA); }); function checkDnsRecord(host, record) { var myHost = host, myRecord = record; return function(err, stdout) { var expected = []; var footprints = 'before'; if (stdout.length) expected = stdout.substr(0, stdout.length - 1).split('\n'); switch (myRecord) { case 'A': case 'AAAA': dns.resolve(myHost, myRecord, function(error, result, ttl, cname) { if (error) result = []; cmpResults(expected, result, ttl, cname); // do reverse lookup check var ll = result.length; while (ll--) { var ip = result[ll]; var reverseCmd = 'host ' + ip + '| cut -d " " -f 5-' + '| sed -e "s/\\.$//"'; child_process.exec(reverseCmd, checkReverse(ip)); } assert.equal(footprints, 'beforeafter'); }); break; case 'MX': dns.resolve(myHost, myRecord, function(error, result, ttl, cname) { if (error) result = []; var strResult = []; var ll = result.length; while (ll--) { strResult.push(result[ll].priority + ' ' + result[ll].exchange); } cmpResults(expected, strResult, ttl, cname); assert.equal(footprints, 'beforeafter'); }); break; case 'TXT': dns.resolve(myHost, myRecord, function(error, result, ttl, cname) { if (error) result = []; var strResult = []; var ll = result.length; while (ll--) { strResult.push('"' + result[ll] + '"'); } cmpResults(expected, strResult, ttl, cname); assert.equal(footprints, 'beforeafter'); }); break; case 'SRV': dns.resolve(myHost, myRecord, function(error, result, ttl, cname) { if (error) result = []; var strResult = []; var ll = result.length; while (ll--) { strResult.push(result[ll].priority + ' ' + result[ll].weight + ' ' + result[ll].port + ' ' + result[ll].name); } cmpResults(expected, strResult, ttl, cname); assert.equal(footprints, 'beforeafter'); }); break; } footprints += 'after'; } } function checkReverse(ip) { var myIp = ip; return function(errr, stdout) { var expected = stdout.substr(0, stdout.length - 1).split('\n'); var reversing = dns.reverse(myIp, function(error, domains, ttl, cname) { if (error) domains = []; cmpResults(expected, domains, ttl, cname); }); } } function cmpResults(expected, result, ttl, cname) { if (expected.length != result.length) { if (expected.length == 1 && expected[0] == '3(NXDOMAIN)' && result.length == 0) { // it's ok, dig returns NXDOMAIN, while dns module returns nothing } else { console.log('---WARNING---\nexpected ' + expected + '\nresult ' + result + '\n-------------'); } return; } expected.sort(); result.sort(); var ll = expected.length; while (ll--) { assert.equal(result[ll], expected[ll]); console.log('Result ' + result[ll] + ' was equal to expected ' + expected[ll]); } } // #1164 var getHostByName = 'before'; dns.getHostByName('localhost', function() { assert.equal(getHostByName, 'beforeafter'); }); getHostByName += 'after'; var getHostByAddr = 'before'; dns.getHostByAddr('127.0.0.1', function() { assert.equal(getHostByAddr, 'beforeafter'); }); getHostByAddr += 'after'; var lookupEmpty = 'before'; dns.lookup('', function() { assert.equal(lookupEmpty, 'beforeafter'); }); lookupEmpty += 'after'; var lookupIp = 'before'; dns.lookup('127.0.0.1', function() { assert.equal(lookupIp, 'beforeafter'); }); lookupIp += 'after'; var lookupIp4 = 'before'; dns.lookup('127.0.0.1', 4, function() { assert.equal(lookupIp4, 'beforeafter'); }); lookupIp4 += 'after'; var lookupIp6 = 'before'; dns.lookup('ietf.org', 6, function() { assert.equal(lookupIp6, 'beforeafter'); }); lookupIp6 += 'after'; var lookupLocal = 'before'; dns.lookup('localhost', function() { assert.equal(lookupLocal, 'beforeafter'); }); lookupLocal += 'after'; node-v0.10.25~dfsg2/test/disabled/test-eio-race3.js0000644000000000000000000000304512270121457020427 0ustar rootroot// Copyright Joyent, Inc. and other Node contributors. // // Permission is hereby granted, free of charge, to any person obtaining a // copy of this software and associated documentation files (the // "Software"), to deal in the Software without restriction, including // without limitation the rights to use, copy, modify, merge, publish, // distribute, sublicense, and/or sell copies of the Software, and to permit // persons to whom the Software is furnished to do so, subject to the // following conditions: // // The above copyright notice and this permission notice shall be included // in all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS // OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF // MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN // NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, // DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR // OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE // USE OR OTHER DEALINGS IN THE SOFTWARE. /* XXX Can this test be modified to not call the now-removed wait()? */ var common = require('../common'); var assert = require('assert'); console.log('first stat ...'); fs.stat(__filename) .addCallback(function(stats) { console.log('second stat ...'); fs.stat(__filename) .timeout(1000) .wait(); console.log('test passed'); }) .addErrback(function() { throw new Exception(); }); node-v0.10.25~dfsg2/test/disabled/test-dgram-multicast.js0000644000000000000000000000706612270121457021764 0ustar rootroot// Copyright Joyent, Inc. and other Node contributors. // // Permission is hereby granted, free of charge, to any person obtaining a // copy of this software and associated documentation files (the // "Software"), to deal in the Software without restriction, including // without limitation the rights to use, copy, modify, merge, publish, // distribute, sublicense, and/or sell copies of the Software, and to permit // persons to whom the Software is furnished to do so, subject to the // following conditions: // // The above copyright notice and this permission notice shall be included // in all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS // OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF // MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN // NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, // DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR // OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE // USE OR OTHER DEALINGS IN THE SOFTWARE. var common = require('../common'); var assert = require('assert'); var dgram = require('dgram'), util = require('util'), assert = require('assert'), Buffer = require('buffer').Buffer; var LOCAL_BROADCAST_HOST = '224.0.0.1'; var sendMessages = [ new Buffer('First message to send'), new Buffer('Second message to send'), new Buffer('Third message to send'), new Buffer('Fourth message to send') ]; var listenSockets = []; var sendSocket = dgram.createSocket('udp4'); sendSocket.on('close', function() { console.error('sendSocket closed'); }); sendSocket.setBroadcast(true); sendSocket.setMulticastTTL(1); sendSocket.setMulticastLoopback(true); var i = 0; sendSocket.sendNext = function() { var buf = sendMessages[i++]; if (!buf) { try { sendSocket.close(); } catch (e) {} return; } sendSocket.send(buf, 0, buf.length, common.PORT, LOCAL_BROADCAST_HOST, function(err) { if (err) throw err; console.error('sent %s to %s', util.inspect(buf.toString()), LOCAL_BROADCAST_HOST + common.PORT); process.nextTick(sendSocket.sendNext); }); }; var listener_count = 0; function mkListener() { var receivedMessages = []; var listenSocket = dgram.createSocket('udp4'); listenSocket.addMembership(LOCAL_BROADCAST_HOST); listenSocket.on('message', function(buf, rinfo) { console.error('received %s from %j', util.inspect(buf.toString()), rinfo); receivedMessages.push(buf); if (receivedMessages.length == sendMessages.length) { listenSocket.dropMembership(LOCAL_BROADCAST_HOST); process.nextTick(function() { // TODO should be changed to below. // listenSocket.dropMembership(LOCAL_BROADCAST_HOST, function() { listenSocket.close(); }); } }); listenSocket.on('close', function() { console.error('listenSocket closed -- checking received messages'); var count = 0; receivedMessages.forEach(function(buf) { for (var i = 0; i < sendMessages.length; ++i) { if (buf.toString() === sendMessages[i].toString()) { count++; break; } } }); console.error('count %d', count); //assert.strictEqual(count, sendMessages.length); }); listenSocket.on('listening', function() { listenSockets.push(listenSocket); if (listenSockets.length == 3) { sendSocket.sendNext(); } }); listenSocket.bind(common.PORT); } mkListener(); mkListener(); mkListener(); node-v0.10.25~dfsg2/test/disabled/test-https-loop-to-google.js0000644000000000000000000000342512270121457022665 0ustar rootroot// Copyright Joyent, Inc. and other Node contributors. // // Permission is hereby granted, free of charge, to any person obtaining a // copy of this software and associated documentation files (the // "Software"), to deal in the Software without restriction, including // without limitation the rights to use, copy, modify, merge, publish, // distribute, sublicense, and/or sell copies of the Software, and to permit // persons to whom the Software is furnished to do so, subject to the // following conditions: // // The above copyright notice and this permission notice shall be included // in all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS // OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF // MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN // NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, // DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR // OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE // USE OR OTHER DEALINGS IN THE SOFTWARE. // Failing test for https // Will fail with "socket hang up" for 4 out of 10 requests // Tested on node 0.5.0-pre commit 9851574 var common = require('../common'); var https = require('https'); for (var i = 0; i < 10; ++i) { https.get( { host: 'www.google.com', path: '/accounts/o8/id', port: 443 }, function(res) { var data = ''; res.on('data', function(chunk) { data += chunk; }); res.on('end', function() { console.log(res.statusCode); }); }).on('error', function(error) { console.log(error); }); } node-v0.10.25~dfsg2/test/disabled/test-tls-server.js0000644000000000000000000000405212270121457020765 0ustar rootroot// Copyright Joyent, Inc. and other Node contributors. // // Permission is hereby granted, free of charge, to any person obtaining a // copy of this software and associated documentation files (the // "Software"), to deal in the Software without restriction, including // without limitation the rights to use, copy, modify, merge, publish, // distribute, sublicense, and/or sell copies of the Software, and to permit // persons to whom the Software is furnished to do so, subject to the // following conditions: // // The above copyright notice and this permission notice shall be included // in all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS // OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF // MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN // NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, // DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR // OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE // USE OR OTHER DEALINGS IN THE SOFTWARE. // Example of new TLS API. Test with: // // $> openssl s_client -connect localhost:12346 \ // -key test/fixtures/agent.key -cert test/fixtures/agent.crt // // $> openssl s_client -connect localhost:12346 // var common = require('../common'); var tls = require('tls'); var fs = require('fs'); var join = require('path').join; var key = fs.readFileSync(join(common.fixturesDir, 'agent.key')).toString(); var cert = fs.readFileSync(join(common.fixturesDir, 'agent.crt')).toString(); s = tls.Server({ key: key, cert: cert, ca: [], requestCert: true, rejectUnauthorized: true }); s.listen(common.PORT, function() { console.log('TLS server on 127.0.0.1:%d', common.PORT); }); s.on('authorized', function(c) { console.log('authed connection'); c.end('bye authorized friend.\n'); }); s.on('unauthorized', function(c, e) { console.log('unauthed connection: %s', e); c.end('bye unauthorized person.\n'); }); node-v0.10.25~dfsg2/test/disabled/test-tty-stdio.js0000644000000000000000000000302212270121457020613 0ustar rootroot// Copyright Joyent, Inc. and other Node contributors. // // Permission is hereby granted, free of charge, to any person obtaining a // copy of this software and associated documentation files (the // "Software"), to deal in the Software without restriction, including // without limitation the rights to use, copy, modify, merge, publish, // distribute, sublicense, and/or sell copies of the Software, and to permit // persons to whom the Software is furnished to do so, subject to the // following conditions: // // The above copyright notice and this permission notice shall be included // in all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS // OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF // MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN // NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, // DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR // OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE // USE OR OTHER DEALINGS IN THE SOFTWARE. // Can't test this when 'make test' doesn't assign a tty to the stdout. var common = require('../common'); var assert = require('assert'); var tty = require('tty'); assert.ok(process.stdin instanceof tty.ReadStream); assert.ok(process.stdin.readable); assert.ok(!process.stdin.writable); assert.ok(process.stdout instanceof tty.WriteStream); assert.ok(!process.stdout.readable); assert.ok(process.stdout.writable); node-v0.10.25~dfsg2/test/disabled/test-http-head-request.js0000644000000000000000000000414112270121457022222 0ustar rootroot// Copyright Joyent, Inc. and other Node contributors. // // Permission is hereby granted, free of charge, to any person obtaining a // copy of this software and associated documentation files (the // "Software"), to deal in the Software without restriction, including // without limitation the rights to use, copy, modify, merge, publish, // distribute, sublicense, and/or sell copies of the Software, and to permit // persons to whom the Software is furnished to do so, subject to the // following conditions: // // The above copyright notice and this permission notice shall be included // in all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS // OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF // MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN // NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, // DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR // OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE // USE OR OTHER DEALINGS IN THE SOFTWARE. var common = require('../common'); var assert = require('assert'); var assert = require('assert'); var http = require('http'); var util = require('util'); var body = 'hello world'; var server = http.createServer(function(req, res) { res.writeHeader(200, {'Content-Length': body.length.toString(), 'Content-Type': 'text/plain' }); console.log('method: ' + req.method); if (req.method != 'HEAD') res.write(body); res.end(); }); server.listen(common.PORT); var gotEnd = false; server.on('listening', function() { var request = http.request({ port: common.PORT, method: 'HEAD', path: '/' }, function(response) { console.log('got response'); response.on('data', function() { process.exit(2); }); response.on('end', function() { process.exit(0); }); }); request.end(); }); //give a bit of time for the server to respond before we check it setTimeout(function() { process.exit(1); }, 2000); node-v0.10.25~dfsg2/node.gyp0000644000000000000000000003503512270121457014271 0ustar rootroot{ 'variables': { 'v8_use_snapshot%': 'true', # Turn off -Werror in V8 # See http://codereview.chromium.org/8159015 'werror': '', 'node_use_dtrace%': 'false', 'node_use_etw%': 'false', 'node_use_perfctr%': 'false', 'node_has_winsdk%': 'false', 'node_shared_v8%': 'false', 'node_shared_zlib%': 'false', 'node_shared_http_parser%': 'false', 'node_shared_cares%': 'false', 'node_shared_libuv%': 'false', 'node_use_openssl%': 'true', 'node_use_systemtap%': 'false', 'node_shared_openssl%': 'false', 'library_files': [ 'src/node.js', 'lib/_debugger.js', 'lib/_linklist.js', 'lib/assert.js', 'lib/buffer.js', 'lib/child_process.js', 'lib/console.js', 'lib/constants.js', 'lib/crypto.js', 'lib/cluster.js', 'lib/dgram.js', 'lib/dns.js', 'lib/domain.js', 'lib/events.js', 'lib/freelist.js', 'lib/fs.js', 'lib/http.js', 'lib/https.js', 'lib/module.js', 'lib/net.js', 'lib/os.js', 'lib/path.js', 'lib/punycode.js', 'lib/querystring.js', 'lib/readline.js', 'lib/repl.js', 'lib/stream.js', 'lib/_stream_readable.js', 'lib/_stream_writable.js', 'lib/_stream_duplex.js', 'lib/_stream_transform.js', 'lib/_stream_passthrough.js', 'lib/string_decoder.js', 'lib/sys.js', 'lib/timers.js', 'lib/tls.js', 'lib/tty.js', 'lib/url.js', 'lib/util.js', 'lib/vm.js', 'lib/zlib.js', ], }, 'targets': [ { 'target_name': 'node', 'type': 'executable', 'dependencies': [ 'node_js2c#host', ], 'include_dirs': [ 'src', 'tools/msvs/genfiles', 'deps/uv/src/ares', '<(SHARED_INTERMEDIATE_DIR)' # for node_natives.h ], 'sources': [ 'src/fs_event_wrap.cc', 'src/cares_wrap.cc', 'src/handle_wrap.cc', 'src/node.cc', 'src/node_buffer.cc', 'src/node_constants.cc', 'src/node_extensions.cc', 'src/node_file.cc', 'src/node_http_parser.cc', 'src/node_javascript.cc', 'src/node_main.cc', 'src/node_os.cc', 'src/node_script.cc', 'src/node_stat_watcher.cc', 'src/node_string.cc', 'src/node_zlib.cc', 'src/pipe_wrap.cc', 'src/signal_wrap.cc', 'src/string_bytes.cc', 'src/stream_wrap.cc', 'src/slab_allocator.cc', 'src/tcp_wrap.cc', 'src/timer_wrap.cc', 'src/tty_wrap.cc', 'src/process_wrap.cc', 'src/v8_typed_array.cc', 'src/udp_wrap.cc', # headers to make for a more pleasant IDE experience 'src/handle_wrap.h', 'src/node.h', 'src/node_buffer.h', 'src/node_constants.h', 'src/node_crypto.h', 'src/node_extensions.h', 'src/node_file.h', 'src/node_http_parser.h', 'src/node_javascript.h', 'src/node_os.h', 'src/node_root_certs.h', 'src/node_script.h', 'src/node_string.h', 'src/node_version.h', 'src/ngx-queue.h', 'src/pipe_wrap.h', 'src/tty_wrap.h', 'src/tcp_wrap.h', 'src/udp_wrap.h', 'src/req_wrap.h', 'src/slab_allocator.h', 'src/string_bytes.h', 'src/stream_wrap.h', 'src/tree.h', 'src/v8_typed_array.h', 'deps/http_parser/http_parser.h', '<(SHARED_INTERMEDIATE_DIR)/node_natives.h', # javascript files to make for an even more pleasant IDE experience '<@(library_files)', # node.gyp is added to the project by default. 'common.gypi', ], 'defines': [ 'NODE_WANT_INTERNALS=1', 'ARCH="<(target_arch)"', 'PLATFORM="<(OS)"', 'NODE_TAG="<(node_tag)"', ], 'conditions': [ [ 'node_use_openssl=="true"', { 'defines': [ 'HAVE_OPENSSL=1' ], 'sources': [ 'src/node_crypto.cc' ], 'conditions': [ [ 'node_shared_openssl=="false"', { 'dependencies': [ './deps/openssl/openssl.gyp:openssl' ], }]] }, { 'defines': [ 'HAVE_OPENSSL=0' ] }], [ 'node_use_dtrace=="true"', { 'defines': [ 'HAVE_DTRACE=1' ], 'dependencies': [ 'node_dtrace_header' ], 'include_dirs': [ '<(SHARED_INTERMEDIATE_DIR)' ], # # DTrace is supported on solaris, mac, and bsd. There are three # object files associated with DTrace support, but they're not all # used all the time: # # node_dtrace.o all configurations # node_dtrace_ustack.o not supported on OS X # node_dtrace_provider.o All except OS X. "dtrace -G" is not # used on OS X. # # Note that node_dtrace_provider.cc and node_dtrace_ustack.cc do not # actually exist. They're listed here to trick GYP into linking the # corresponding object files into the final "node" executable. These # object files are generated by "dtrace -G" using custom actions # below, and the GYP-generated Makefiles will properly build them when # needed. # 'sources': [ 'src/node_dtrace.cc', ], 'conditions': [ [ 'OS!="mac"', { 'sources': [ 'src/node_dtrace_ustack.cc', 'src/node_dtrace_provider.cc', ] } ] ] } ], [ 'node_use_systemtap=="true"', { 'defines': [ 'HAVE_SYSTEMTAP=1', 'STAP_SDT_V1=1' ], 'dependencies': [ 'node_systemtap_header' ], 'include_dirs': [ '<(SHARED_INTERMEDIATE_DIR)' ], 'sources': [ 'src/node_dtrace.cc', '<(SHARED_INTERMEDIATE_DIR)/node_systemtap.h', ], } ], [ 'node_use_etw=="true"', { 'defines': [ 'HAVE_ETW=1' ], 'dependencies': [ 'node_etw' ], 'sources': [ 'src/node_win32_etw_provider.h', 'src/node_win32_etw_provider-inl.h', 'src/node_win32_etw_provider.cc', 'src/node_dtrace.cc', 'tools/msvs/genfiles/node_etw_provider.h', 'tools/msvs/genfiles/node_etw_provider.rc', ] } ], [ 'node_use_perfctr=="true"', { 'defines': [ 'HAVE_PERFCTR=1' ], 'dependencies': [ 'node_perfctr' ], 'sources': [ 'src/node_win32_perfctr_provider.h', 'src/node_win32_perfctr_provider.cc', 'src/node_counters.cc', 'src/node_counters.h', 'tools/msvs/genfiles/node_perfctr_provider.rc', ] } ], [ 'node_shared_v8=="false"', { 'sources': [ 'deps/v8/include/v8.h', 'deps/v8/include/v8-debug.h', ], 'dependencies': [ 'deps/v8/tools/gyp/v8.gyp:v8' ], }], [ 'node_shared_zlib=="false"', { 'dependencies': [ 'deps/zlib/zlib.gyp:zlib' ], }], [ 'node_shared_http_parser=="false"', { 'dependencies': [ 'deps/http_parser/http_parser.gyp:http_parser' ], }], [ 'node_shared_cares=="false"', { 'dependencies': [ 'deps/cares/cares.gyp:cares' ], }], [ 'node_shared_libuv=="false"', { 'dependencies': [ 'deps/uv/uv.gyp:libuv' ], }], [ 'OS=="win"', { 'sources': [ 'src/res/node.rc', ], 'defines': [ 'FD_SETSIZE=1024', # we need to use node's preferred "win32" rather than gyp's preferred "win" 'PLATFORM="win32"', '_UNICODE=1', ], 'libraries': [ '-lpsapi.lib' ] }, { # POSIX 'defines': [ '__POSIX__' ], }], [ 'OS=="mac"', { 'libraries': [ '-framework Carbon' ], 'defines!': [ 'PLATFORM="mac"', ], 'defines': [ # we need to use node's preferred "darwin" rather than gyp's preferred "mac" 'PLATFORM="darwin"', ], }], [ 'OS=="freebsd"', { 'libraries': [ '-lutil', '-lkvm', ], }], [ 'OS=="solaris"', { 'libraries': [ '-lkstat', '-lumem', ], 'defines!': [ 'PLATFORM="solaris"', ], 'defines': [ # we need to use node's preferred "sunos" # rather than gyp's preferred "solaris" 'PLATFORM="sunos"', ], }], [ 'OS=="linux" and node_shared_v8=="false"', { 'ldflags': [ '-Wl,--whole-archive <(V8_BASE) -Wl,--no-whole-archive', ], }], ], 'msvs_settings': { 'VCLinkerTool': { 'SubSystem': 1, # /subsystem:console }, }, }, # generate ETW header and resource files { 'target_name': 'node_etw', 'type': 'none', 'conditions': [ [ 'node_use_etw=="true" and node_has_winsdk=="true"', { 'actions': [ { 'action_name': 'node_etw', 'inputs': [ 'src/res/node_etw_provider.man' ], 'outputs': [ 'tools/msvs/genfiles/node_etw_provider.rc', 'tools/msvs/genfiles/node_etw_provider.h', 'tools/msvs/genfiles/node_etw_providerTEMP.BIN', ], 'action': [ 'mc <@(_inputs) -h tools/msvs/genfiles -r tools/msvs/genfiles' ] } ] } ] ] }, # generate perf counter header and resource files { 'target_name': 'node_perfctr', 'type': 'none', 'conditions': [ [ 'node_use_perfctr=="true" and node_has_winsdk=="true"', { 'actions': [ { 'action_name': 'node_perfctr_man', 'inputs': [ 'src/res/node_perfctr_provider.man' ], 'outputs': [ 'tools/msvs/genfiles/node_perfctr_provider.h', 'tools/msvs/genfiles/node_perfctr_provider.rc', 'tools/msvs/genfiles/MSG00001.BIN', ], 'action': [ 'ctrpp <@(_inputs) ' '-o tools/msvs/genfiles/node_perfctr_provider.h ' '-rc tools/msvs/genfiles/node_perfctr_provider.rc' ] }, ], } ] ] }, { 'target_name': 'node_js2c', 'type': 'none', 'toolsets': ['host'], 'actions': [ { 'action_name': 'node_js2c', 'inputs': [ '<@(library_files)', './config.gypi', ], 'outputs': [ '<(SHARED_INTERMEDIATE_DIR)/node_natives.h', ], 'conditions': [ [ 'node_use_dtrace=="false"' ' and node_use_etw=="false"' ' and node_use_systemtap=="false"', { 'inputs': ['src/macros.py'] } ], [ 'node_use_perfctr=="false"', { 'inputs': [ 'src/perfctr_macros.py' ] }] ], 'action': [ '<(python)', 'tools/js2c.py', '<@(_outputs)', '<@(_inputs)', ], }, ], }, # end node_js2c { 'target_name': 'node_dtrace_header', 'type': 'none', 'conditions': [ [ 'node_use_dtrace=="true"', { 'actions': [ { 'action_name': 'node_dtrace_header', 'inputs': [ 'src/node_provider.d' ], 'outputs': [ '<(SHARED_INTERMEDIATE_DIR)/node_provider.h' ], 'action': [ 'dtrace', '-h', '-xnolibs', '-s', '<@(_inputs)', '-o', '<@(_outputs)' ] } ] } ] ] }, { 'target_name': 'node_systemtap_header', 'type': 'none', 'conditions': [ [ 'node_use_systemtap=="true"', { 'actions': [ { 'action_name': 'node_systemtap_header', 'inputs': [ 'src/node_systemtap.d' ], 'outputs': [ '<(SHARED_INTERMEDIATE_DIR)/node_systemtap.h' ], 'action': [ 'dtrace', '-h', '-C', '-s', '<@(_inputs)', '-o', '<@(_outputs)' ] } ] } ] ] }, { 'target_name': 'node_dtrace_provider', 'type': 'none', 'conditions': [ [ 'node_use_dtrace=="true" and OS!="mac"', { 'actions': [ { 'action_name': 'node_dtrace_provider_o', 'inputs': [ 'src/node_provider.d', '<(OBJ_DIR)/node/src/node_dtrace.o' ], 'outputs': [ '<(OBJ_DIR)/node/src/node_dtrace_provider.o' ], 'action': [ 'dtrace', '-G', '-xnolibs', '-s', '<@(_inputs)', '-o', '<@(_outputs)' ] } ] } ] ] }, { 'target_name': 'node_dtrace_ustack', 'type': 'none', 'conditions': [ [ 'node_use_dtrace=="true" and OS!="mac"', { 'actions': [ { 'action_name': 'node_dtrace_ustack_constants', 'inputs': [ '<(V8_BASE)' ], 'outputs': [ '<(SHARED_INTERMEDIATE_DIR)/v8constants.h' ], 'action': [ 'tools/genv8constants.py', '<@(_outputs)', '<@(_inputs)' ] }, { 'action_name': 'node_dtrace_ustack', 'inputs': [ 'src/v8ustack.d', '<(SHARED_INTERMEDIATE_DIR)/v8constants.h' ], 'outputs': [ '<(OBJ_DIR)/node/src/node_dtrace_ustack.o' ], 'conditions': [ [ 'target_arch=="ia32"', { 'action': [ 'dtrace', '-32', '-I<(SHARED_INTERMEDIATE_DIR)', '-Isrc', '-C', '-G', '-s', 'src/v8ustack.d', '-o', '<@(_outputs)', ] } ], [ 'target_arch=="x64"', { 'action': [ 'dtrace', '-64', '-I<(SHARED_INTERMEDIATE_DIR)', '-Isrc', '-C', '-G', '-s', 'src/v8ustack.d', '-o', '<@(_outputs)', ] } ], ] } ] } ], ] } ] # end targets } node-v0.10.25~dfsg2/lib/0000755000000000000000000000000012270121457013363 5ustar rootrootnode-v0.10.25~dfsg2/lib/crypto.js0000644000000000000000000004021012270121457015236 0ustar rootroot// Copyright Joyent, Inc. and other Node contributors. // // Permission is hereby granted, free of charge, to any person obtaining a // copy of this software and associated documentation files (the // "Software"), to deal in the Software without restriction, including // without limitation the rights to use, copy, modify, merge, publish, // distribute, sublicense, and/or sell copies of the Software, and to permit // persons to whom the Software is furnished to do so, subject to the // following conditions: // // The above copyright notice and this permission notice shall be included // in all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS // OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF // MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN // NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, // DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR // OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE // USE OR OTHER DEALINGS IN THE SOFTWARE. // Note: In 0.8 and before, crypto functions all defaulted to using // binary-encoded strings rather than buffers. exports.DEFAULT_ENCODING = 'buffer'; try { var binding = process.binding('crypto'); var SecureContext = binding.SecureContext; var randomBytes = binding.randomBytes; var pseudoRandomBytes = binding.pseudoRandomBytes; var getCiphers = binding.getCiphers; var getHashes = binding.getHashes; var crypto = true; } catch (e) { var crypto = false; } var stream = require('stream'); var util = require('util'); // This is here because many functions accepted binary strings without // any explicit encoding in older versions of node, and we don't want // to break them unnecessarily. function toBuf(str, encoding) { encoding = encoding || 'binary'; if (typeof str === 'string') { if (encoding === 'buffer') encoding = 'binary'; str = new Buffer(str, encoding); } return str; } var assert = require('assert'); var StringDecoder = require('string_decoder').StringDecoder; function Credentials(secureProtocol, flags, context) { if (!(this instanceof Credentials)) { return new Credentials(secureProtocol, flags, context); } if (!crypto) { throw new Error('node.js not compiled with openssl crypto support.'); } if (context) { this.context = context; } else { this.context = new SecureContext(); if (secureProtocol) { this.context.init(secureProtocol); } else { this.context.init(); } } if (flags) this.context.setOptions(flags); } exports.Credentials = Credentials; exports.createCredentials = function(options, context) { if (!options) options = {}; var c = new Credentials(options.secureProtocol, options.secureOptions, context); if (context) return c; if (options.key) { if (options.passphrase) { c.context.setKey(options.key, options.passphrase); } else { c.context.setKey(options.key); } } if (options.cert) c.context.setCert(options.cert); if (options.ciphers) c.context.setCiphers(options.ciphers); if (options.ca) { if (Array.isArray(options.ca)) { for (var i = 0, len = options.ca.length; i < len; i++) { c.context.addCACert(options.ca[i]); } } else { c.context.addCACert(options.ca); } } else { c.context.addRootCerts(); } if (options.crl) { if (Array.isArray(options.crl)) { for (var i = 0, len = options.crl.length; i < len; i++) { c.context.addCRL(options.crl[i]); } } else { c.context.addCRL(options.crl); } } if (options.sessionIdContext) { c.context.setSessionIdContext(options.sessionIdContext); } if (options.pfx) { var pfx = options.pfx; var passphrase = options.passphrase; pfx = toBuf(pfx); if (passphrase) passphrase = toBuf(passphrase); if (passphrase) { c.context.loadPKCS12(pfx, passphrase); } else { c.context.loadPKCS12(pfx); } } return c; }; function LazyTransform(options) { this._options = options; } util.inherits(LazyTransform, stream.Transform); [ '_readableState', '_writableState', '_transformState' ].forEach(function(prop, i, props) { Object.defineProperty(LazyTransform.prototype, prop, { get: function() { stream.Transform.call(this, this._options); this._writableState.decodeStrings = false; this._writableState.defaultEncoding = 'binary'; return this[prop]; }, set: function(val) { Object.defineProperty(this, prop, { value: val, enumerable: true, configurable: true, writable: true }); }, configurable: true, enumerable: true }); }); exports.createHash = exports.Hash = Hash; function Hash(algorithm, options) { if (!(this instanceof Hash)) return new Hash(algorithm, options); this._binding = new binding.Hash(algorithm); LazyTransform.call(this, options); } util.inherits(Hash, LazyTransform); Hash.prototype._transform = function(chunk, encoding, callback) { this._binding.update(chunk, encoding); callback(); }; Hash.prototype._flush = function(callback) { var encoding = this._readableState.encoding || 'buffer'; this.push(this._binding.digest(encoding), encoding); callback(); }; Hash.prototype.update = function(data, encoding) { encoding = encoding || exports.DEFAULT_ENCODING; if (encoding === 'buffer' && typeof data === 'string') encoding = 'binary'; this._binding.update(data, encoding); return this; }; Hash.prototype.digest = function(outputEncoding) { outputEncoding = outputEncoding || exports.DEFAULT_ENCODING; return this._binding.digest(outputEncoding); }; exports.createHmac = exports.Hmac = Hmac; function Hmac(hmac, key, options) { if (!(this instanceof Hmac)) return new Hmac(hmac, key, options); this._binding = new binding.Hmac(); this._binding.init(hmac, toBuf(key)); LazyTransform.call(this, options); } util.inherits(Hmac, LazyTransform); Hmac.prototype.update = Hash.prototype.update; Hmac.prototype.digest = Hash.prototype.digest; Hmac.prototype._flush = Hash.prototype._flush; Hmac.prototype._transform = Hash.prototype._transform; function getDecoder(decoder, encoding) { if (encoding === 'utf-8') encoding = 'utf8'; // Normalize encoding. decoder = decoder || new StringDecoder(encoding); assert(decoder.encoding === encoding, 'Cannot change encoding'); return decoder; } exports.createCipher = exports.Cipher = Cipher; function Cipher(cipher, password, options) { if (!(this instanceof Cipher)) return new Cipher(cipher, password, options); this._binding = new binding.Cipher; this._binding.init(cipher, toBuf(password)); this._decoder = null; LazyTransform.call(this, options); } util.inherits(Cipher, LazyTransform); Cipher.prototype._transform = function(chunk, encoding, callback) { this.push(this._binding.update(chunk, encoding)); callback(); }; Cipher.prototype._flush = function(callback) { try { this.push(this._binding.final()); } catch (e) { callback(e); return; } callback(); }; Cipher.prototype.update = function(data, inputEncoding, outputEncoding) { inputEncoding = inputEncoding || exports.DEFAULT_ENCODING; outputEncoding = outputEncoding || exports.DEFAULT_ENCODING; var ret = this._binding.update(data, inputEncoding); if (outputEncoding && outputEncoding !== 'buffer') { this._decoder = getDecoder(this._decoder, outputEncoding); ret = this._decoder.write(ret); } return ret; }; Cipher.prototype.final = function(outputEncoding) { outputEncoding = outputEncoding || exports.DEFAULT_ENCODING; var ret = this._binding.final(); if (outputEncoding && outputEncoding !== 'buffer') { this._decoder = getDecoder(this._decoder, outputEncoding); ret = this._decoder.end(ret); } return ret; }; Cipher.prototype.setAutoPadding = function(ap) { this._binding.setAutoPadding(ap); return this; }; exports.createCipheriv = exports.Cipheriv = Cipheriv; function Cipheriv(cipher, key, iv, options) { if (!(this instanceof Cipheriv)) return new Cipheriv(cipher, key, iv, options); this._binding = new binding.Cipher(); this._binding.initiv(cipher, toBuf(key), toBuf(iv)); this._decoder = null; LazyTransform.call(this, options); } util.inherits(Cipheriv, LazyTransform); Cipheriv.prototype._transform = Cipher.prototype._transform; Cipheriv.prototype._flush = Cipher.prototype._flush; Cipheriv.prototype.update = Cipher.prototype.update; Cipheriv.prototype.final = Cipher.prototype.final; Cipheriv.prototype.setAutoPadding = Cipher.prototype.setAutoPadding; exports.createDecipher = exports.Decipher = Decipher; function Decipher(cipher, password, options) { if (!(this instanceof Decipher)) return new Decipher(cipher, password, options); this._binding = new binding.Decipher; this._binding.init(cipher, toBuf(password)); this._decoder = null; LazyTransform.call(this, options); } util.inherits(Decipher, LazyTransform); Decipher.prototype._transform = Cipher.prototype._transform; Decipher.prototype._flush = Cipher.prototype._flush; Decipher.prototype.update = Cipher.prototype.update; Decipher.prototype.final = Cipher.prototype.final; Decipher.prototype.finaltol = Cipher.prototype.final; Decipher.prototype.setAutoPadding = Cipher.prototype.setAutoPadding; exports.createDecipheriv = exports.Decipheriv = Decipheriv; function Decipheriv(cipher, key, iv, options) { if (!(this instanceof Decipheriv)) return new Decipheriv(cipher, key, iv, options); this._binding = new binding.Decipher; this._binding.initiv(cipher, toBuf(key), toBuf(iv)); this._decoder = null; LazyTransform.call(this, options); } util.inherits(Decipheriv, LazyTransform); Decipheriv.prototype._transform = Cipher.prototype._transform; Decipheriv.prototype._flush = Cipher.prototype._flush; Decipheriv.prototype.update = Cipher.prototype.update; Decipheriv.prototype.final = Cipher.prototype.final; Decipheriv.prototype.finaltol = Cipher.prototype.final; Decipheriv.prototype.setAutoPadding = Cipher.prototype.setAutoPadding; exports.createSign = exports.Sign = Sign; function Sign(algorithm, options) { if (!(this instanceof Sign)) return new Sign(algorithm, options); this._binding = new binding.Sign(); this._binding.init(algorithm); stream.Writable.call(this, options); } util.inherits(Sign, stream.Writable); Sign.prototype._write = function(chunk, encoding, callback) { this._binding.update(chunk, encoding); callback(); }; Sign.prototype.update = Hash.prototype.update; Sign.prototype.sign = function(key, encoding) { encoding = encoding || exports.DEFAULT_ENCODING; var ret = this._binding.sign(toBuf(key)); if (encoding && encoding !== 'buffer') ret = ret.toString(encoding); return ret; }; exports.createVerify = exports.Verify = Verify; function Verify(algorithm, options) { if (!(this instanceof Verify)) return new Verify(algorithm, options); this._binding = new binding.Verify; this._binding.init(algorithm); stream.Writable.call(this, options); } util.inherits(Verify, stream.Writable); Verify.prototype._write = Sign.prototype._write; Verify.prototype.update = Sign.prototype.update; Verify.prototype.verify = function(object, signature, sigEncoding) { sigEncoding = sigEncoding || exports.DEFAULT_ENCODING; return this._binding.verify(toBuf(object), toBuf(signature, sigEncoding)); }; exports.createDiffieHellman = exports.DiffieHellman = DiffieHellman; function DiffieHellman(sizeOrKey, encoding) { if (!(this instanceof DiffieHellman)) return new DiffieHellman(sizeOrKey, encoding); if (!sizeOrKey) this._binding = new binding.DiffieHellman(); else { encoding = encoding || exports.DEFAULT_ENCODING; sizeOrKey = toBuf(sizeOrKey, encoding); this._binding = new binding.DiffieHellman(sizeOrKey); } } exports.DiffieHellmanGroup = exports.createDiffieHellmanGroup = exports.getDiffieHellman = DiffieHellmanGroup; function DiffieHellmanGroup(name) { if (!(this instanceof DiffieHellmanGroup)) return new DiffieHellmanGroup(name); this._binding = new binding.DiffieHellmanGroup(name); } DiffieHellmanGroup.prototype.generateKeys = DiffieHellman.prototype.generateKeys = dhGenerateKeys; function dhGenerateKeys(encoding) { var keys = this._binding.generateKeys(); encoding = encoding || exports.DEFAULT_ENCODING; if (encoding && encoding !== 'buffer') keys = keys.toString(encoding); return keys; } DiffieHellmanGroup.prototype.computeSecret = DiffieHellman.prototype.computeSecret = dhComputeSecret; function dhComputeSecret(key, inEnc, outEnc) { inEnc = inEnc || exports.DEFAULT_ENCODING; outEnc = outEnc || exports.DEFAULT_ENCODING; var ret = this._binding.computeSecret(toBuf(key, inEnc)); if (outEnc && outEnc !== 'buffer') ret = ret.toString(outEnc); return ret; } DiffieHellmanGroup.prototype.getPrime = DiffieHellman.prototype.getPrime = dhGetPrime; function dhGetPrime(encoding) { var prime = this._binding.getPrime(); encoding = encoding || exports.DEFAULT_ENCODING; if (encoding && encoding !== 'buffer') prime = prime.toString(encoding); return prime; } DiffieHellmanGroup.prototype.getGenerator = DiffieHellman.prototype.getGenerator = dhGetGenerator; function dhGetGenerator(encoding) { var generator = this._binding.getGenerator(); encoding = encoding || exports.DEFAULT_ENCODING; if (encoding && encoding !== 'buffer') generator = generator.toString(encoding); return generator; } DiffieHellmanGroup.prototype.getPublicKey = DiffieHellman.prototype.getPublicKey = dhGetPublicKey; function dhGetPublicKey(encoding) { var key = this._binding.getPublicKey(); encoding = encoding || exports.DEFAULT_ENCODING; if (encoding && encoding !== 'buffer') key = key.toString(encoding); return key; } DiffieHellmanGroup.prototype.getPrivateKey = DiffieHellman.prototype.getPrivateKey = dhGetPrivateKey; function dhGetPrivateKey(encoding) { var key = this._binding.getPrivateKey(); encoding = encoding || exports.DEFAULT_ENCODING; if (encoding && encoding !== 'buffer') key = key.toString(encoding); return key; } DiffieHellman.prototype.setPublicKey = function(key, encoding) { encoding = encoding || exports.DEFAULT_ENCODING; this._binding.setPublicKey(toBuf(key, encoding)); return this; }; DiffieHellman.prototype.setPrivateKey = function(key, encoding) { encoding = encoding || exports.DEFAULT_ENCODING; this._binding.setPrivateKey(toBuf(key, encoding)); return this; }; exports.pbkdf2 = function(password, salt, iterations, keylen, callback) { if (typeof callback !== 'function') throw new Error('No callback provided to pbkdf2'); return pbkdf2(password, salt, iterations, keylen, callback); }; exports.pbkdf2Sync = function(password, salt, iterations, keylen) { return pbkdf2(password, salt, iterations, keylen); }; function pbkdf2(password, salt, iterations, keylen, callback) { password = toBuf(password); salt = toBuf(salt); if (exports.DEFAULT_ENCODING === 'buffer') return binding.PBKDF2(password, salt, iterations, keylen, callback); // at this point, we need to handle encodings. var encoding = exports.DEFAULT_ENCODING; if (callback) { binding.PBKDF2(password, salt, iterations, keylen, function(er, ret) { if (ret) ret = ret.toString(encoding); callback(er, ret); }); } else { var ret = binding.PBKDF2(password, salt, iterations, keylen); return ret.toString(encoding); } } exports.randomBytes = randomBytes; exports.pseudoRandomBytes = pseudoRandomBytes; exports.rng = randomBytes; exports.prng = pseudoRandomBytes; exports.getCiphers = function() { return filterDuplicates(getCiphers.call(null, arguments)); }; exports.getHashes = function() { return filterDuplicates(getHashes.call(null, arguments)); }; function filterDuplicates(names) { // Drop all-caps names in favor of their lowercase aliases, // for example, 'sha1' instead of 'SHA1'. var ctx = {}; names.forEach(function(name) { if (/^[0-9A-Z\-]+$/.test(name)) name = name.toLowerCase(); ctx[name] = true; }); return Object.getOwnPropertyNames(ctx).sort(); } node-v0.10.25~dfsg2/lib/zlib.js0000644000000000000000000003103512270121457014663 0ustar rootroot// Copyright Joyent, Inc. and other Node contributors. // // Permission is hereby granted, free of charge, to any person obtaining a // copy of this software and associated documentation files (the // "Software"), to deal in the Software without restriction, including // without limitation the rights to use, copy, modify, merge, publish, // distribute, sublicense, and/or sell copies of the Software, and to permit // persons to whom the Software is furnished to do so, subject to the // following conditions: // // The above copyright notice and this permission notice shall be included // in all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS // OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF // MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN // NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, // DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR // OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE // USE OR OTHER DEALINGS IN THE SOFTWARE. var Transform = require('_stream_transform'); var binding = process.binding('zlib'); var util = require('util'); var assert = require('assert').ok; // zlib doesn't provide these, so kludge them in following the same // const naming scheme zlib uses. binding.Z_MIN_WINDOWBITS = 8; binding.Z_MAX_WINDOWBITS = 15; binding.Z_DEFAULT_WINDOWBITS = 15; // fewer than 64 bytes per chunk is stupid. // technically it could work with as few as 8, but even 64 bytes // is absurdly low. Usually a MB or more is best. binding.Z_MIN_CHUNK = 64; binding.Z_MAX_CHUNK = Infinity; binding.Z_DEFAULT_CHUNK = (16 * 1024); binding.Z_MIN_MEMLEVEL = 1; binding.Z_MAX_MEMLEVEL = 9; binding.Z_DEFAULT_MEMLEVEL = 8; binding.Z_MIN_LEVEL = -1; binding.Z_MAX_LEVEL = 9; binding.Z_DEFAULT_LEVEL = binding.Z_DEFAULT_COMPRESSION; // expose all the zlib constants Object.keys(binding).forEach(function(k) { if (k.match(/^Z/)) exports[k] = binding[k]; }); // translation table for return codes. exports.codes = { Z_OK: binding.Z_OK, Z_STREAM_END: binding.Z_STREAM_END, Z_NEED_DICT: binding.Z_NEED_DICT, Z_ERRNO: binding.Z_ERRNO, Z_STREAM_ERROR: binding.Z_STREAM_ERROR, Z_DATA_ERROR: binding.Z_DATA_ERROR, Z_MEM_ERROR: binding.Z_MEM_ERROR, Z_BUF_ERROR: binding.Z_BUF_ERROR, Z_VERSION_ERROR: binding.Z_VERSION_ERROR }; Object.keys(exports.codes).forEach(function(k) { exports.codes[exports.codes[k]] = k; }); exports.Deflate = Deflate; exports.Inflate = Inflate; exports.Gzip = Gzip; exports.Gunzip = Gunzip; exports.DeflateRaw = DeflateRaw; exports.InflateRaw = InflateRaw; exports.Unzip = Unzip; exports.createDeflate = function(o) { return new Deflate(o); }; exports.createInflate = function(o) { return new Inflate(o); }; exports.createDeflateRaw = function(o) { return new DeflateRaw(o); }; exports.createInflateRaw = function(o) { return new InflateRaw(o); }; exports.createGzip = function(o) { return new Gzip(o); }; exports.createGunzip = function(o) { return new Gunzip(o); }; exports.createUnzip = function(o) { return new Unzip(o); }; // Convenience methods. // compress/decompress a string or buffer in one step. exports.deflate = function(buffer, callback) { zlibBuffer(new Deflate(), buffer, callback); }; exports.gzip = function(buffer, callback) { zlibBuffer(new Gzip(), buffer, callback); }; exports.deflateRaw = function(buffer, callback) { zlibBuffer(new DeflateRaw(), buffer, callback); }; exports.unzip = function(buffer, callback) { zlibBuffer(new Unzip(), buffer, callback); }; exports.inflate = function(buffer, callback) { zlibBuffer(new Inflate(), buffer, callback); }; exports.gunzip = function(buffer, callback) { zlibBuffer(new Gunzip(), buffer, callback); }; exports.inflateRaw = function(buffer, callback) { zlibBuffer(new InflateRaw(), buffer, callback); }; function zlibBuffer(engine, buffer, callback) { var buffers = []; var nread = 0; engine.on('error', onError); engine.on('end', onEnd); engine.end(buffer); flow(); function flow() { var chunk; while (null !== (chunk = engine.read())) { buffers.push(chunk); nread += chunk.length; } engine.once('readable', flow); } function onError(err) { engine.removeListener('end', onEnd); engine.removeListener('readable', flow); callback(err); } function onEnd() { var buf = Buffer.concat(buffers, nread); buffers = []; callback(null, buf); engine.close(); } } // generic zlib // minimal 2-byte header function Deflate(opts) { if (!(this instanceof Deflate)) return new Deflate(opts); Zlib.call(this, opts, binding.DEFLATE); } function Inflate(opts) { if (!(this instanceof Inflate)) return new Inflate(opts); Zlib.call(this, opts, binding.INFLATE); } // gzip - bigger header, same deflate compression function Gzip(opts) { if (!(this instanceof Gzip)) return new Gzip(opts); Zlib.call(this, opts, binding.GZIP); } function Gunzip(opts) { if (!(this instanceof Gunzip)) return new Gunzip(opts); Zlib.call(this, opts, binding.GUNZIP); } // raw - no header function DeflateRaw(opts) { if (!(this instanceof DeflateRaw)) return new DeflateRaw(opts); Zlib.call(this, opts, binding.DEFLATERAW); } function InflateRaw(opts) { if (!(this instanceof InflateRaw)) return new InflateRaw(opts); Zlib.call(this, opts, binding.INFLATERAW); } // auto-detect header. function Unzip(opts) { if (!(this instanceof Unzip)) return new Unzip(opts); Zlib.call(this, opts, binding.UNZIP); } // the Zlib class they all inherit from // This thing manages the queue of requests, and returns // true or false if there is anything in the queue when // you call the .write() method. function Zlib(opts, mode) { this._opts = opts = opts || {}; this._chunkSize = opts.chunkSize || exports.Z_DEFAULT_CHUNK; Transform.call(this, opts); if (opts.flush) { if (opts.flush !== binding.Z_NO_FLUSH && opts.flush !== binding.Z_PARTIAL_FLUSH && opts.flush !== binding.Z_SYNC_FLUSH && opts.flush !== binding.Z_FULL_FLUSH && opts.flush !== binding.Z_FINISH && opts.flush !== binding.Z_BLOCK) { throw new Error('Invalid flush flag: ' + opts.flush); } } this._flushFlag = opts.flush || binding.Z_NO_FLUSH; if (opts.chunkSize) { if (opts.chunkSize < exports.Z_MIN_CHUNK || opts.chunkSize > exports.Z_MAX_CHUNK) { throw new Error('Invalid chunk size: ' + opts.chunkSize); } } if (opts.windowBits) { if (opts.windowBits < exports.Z_MIN_WINDOWBITS || opts.windowBits > exports.Z_MAX_WINDOWBITS) { throw new Error('Invalid windowBits: ' + opts.windowBits); } } if (opts.level) { if (opts.level < exports.Z_MIN_LEVEL || opts.level > exports.Z_MAX_LEVEL) { throw new Error('Invalid compression level: ' + opts.level); } } if (opts.memLevel) { if (opts.memLevel < exports.Z_MIN_MEMLEVEL || opts.memLevel > exports.Z_MAX_MEMLEVEL) { throw new Error('Invalid memLevel: ' + opts.memLevel); } } if (opts.strategy) { if (opts.strategy != exports.Z_FILTERED && opts.strategy != exports.Z_HUFFMAN_ONLY && opts.strategy != exports.Z_RLE && opts.strategy != exports.Z_FIXED && opts.strategy != exports.Z_DEFAULT_STRATEGY) { throw new Error('Invalid strategy: ' + opts.strategy); } } if (opts.dictionary) { if (!Buffer.isBuffer(opts.dictionary)) { throw new Error('Invalid dictionary: it should be a Buffer instance'); } } this._binding = new binding.Zlib(mode); var self = this; this._hadError = false; this._binding.onerror = function(message, errno) { // there is no way to cleanly recover. // continuing only obscures problems. self._binding = null; self._hadError = true; var error = new Error(message); error.errno = errno; error.code = exports.codes[errno]; self.emit('error', error); }; var level = exports.Z_DEFAULT_COMPRESSION; if (typeof opts.level === 'number') level = opts.level; var strategy = exports.Z_DEFAULT_STRATEGY; if (typeof opts.strategy === 'number') strategy = opts.strategy; this._binding.init(opts.windowBits || exports.Z_DEFAULT_WINDOWBITS, level, opts.memLevel || exports.Z_DEFAULT_MEMLEVEL, strategy, opts.dictionary); this._buffer = new Buffer(this._chunkSize); this._offset = 0; this._closed = false; this.once('end', this.close); } util.inherits(Zlib, Transform); Zlib.prototype.reset = function reset() { return this._binding.reset(); }; // This is the _flush function called by the transform class, // internally, when the last chunk has been written. Zlib.prototype._flush = function(callback) { this._transform(new Buffer(0), '', callback); }; Zlib.prototype.flush = function(callback) { var ws = this._writableState; if (ws.ended) { if (callback) process.nextTick(callback); } else if (ws.ending) { if (callback) this.once('end', callback); } else if (ws.needDrain) { var self = this; this.once('drain', function() { self.flush(callback); }); } else { this._flushFlag = binding.Z_FULL_FLUSH; this.write(new Buffer(0), '', callback); } }; Zlib.prototype.close = function(callback) { if (callback) process.nextTick(callback); if (this._closed) return; this._closed = true; this._binding.close(); var self = this; process.nextTick(function() { self.emit('close'); }); }; Zlib.prototype._transform = function(chunk, encoding, cb) { var flushFlag; var ws = this._writableState; var ending = ws.ending || ws.ended; var last = ending && (!chunk || ws.length === chunk.length); if (chunk !== null && !Buffer.isBuffer(chunk)) return cb(new Error('invalid input')); // If it's the last chunk, or a final flush, we use the Z_FINISH flush flag. // If it's explicitly flushing at some other time, then we use // Z_FULL_FLUSH. Otherwise, use Z_NO_FLUSH for maximum compression // goodness. if (last) flushFlag = binding.Z_FINISH; else { flushFlag = this._flushFlag; // once we've flushed the last of the queue, stop flushing and // go back to the normal behavior. if (chunk.length >= ws.length) { this._flushFlag = this._opts.flush || binding.Z_NO_FLUSH; } } var availInBefore = chunk && chunk.length; var availOutBefore = this._chunkSize - this._offset; var inOff = 0; var req = this._binding.write(flushFlag, chunk, // in inOff, // in_off availInBefore, // in_len this._buffer, // out this._offset, //out_off availOutBefore); // out_len req.buffer = chunk; req.callback = callback; var self = this; function callback(availInAfter, availOutAfter, buffer) { if (self._hadError) return; var have = availOutBefore - availOutAfter; assert(have >= 0, 'have should not go down'); if (have > 0) { var out = self._buffer.slice(self._offset, self._offset + have); self._offset += have; // serve some output to the consumer. self.push(out); } // exhausted the output buffer, or used all the input create a new one. if (availOutAfter === 0 || self._offset >= self._chunkSize) { availOutBefore = self._chunkSize; self._offset = 0; self._buffer = new Buffer(self._chunkSize); } if (availOutAfter === 0) { // Not actually done. Need to reprocess. // Also, update the availInBefore to the availInAfter value, // so that if we have to hit it a third (fourth, etc.) time, // it'll have the correct byte counts. inOff += (availInBefore - availInAfter); availInBefore = availInAfter; var newReq = self._binding.write(flushFlag, chunk, inOff, availInBefore, self._buffer, self._offset, self._chunkSize); newReq.callback = callback; // this same function newReq.buffer = chunk; return; } // finished with the chunk. cb(); } }; util.inherits(Deflate, Zlib); util.inherits(Inflate, Zlib); util.inherits(Gzip, Zlib); util.inherits(Gunzip, Zlib); util.inherits(DeflateRaw, Zlib); util.inherits(InflateRaw, Zlib); util.inherits(Unzip, Zlib); node-v0.10.25~dfsg2/lib/os.js0000644000000000000000000000417412270121457014350 0ustar rootroot// Copyright Joyent, Inc. and other Node contributors. // // Permission is hereby granted, free of charge, to any person obtaining a // copy of this software and associated documentation files (the // "Software"), to deal in the Software without restriction, including // without limitation the rights to use, copy, modify, merge, publish, // distribute, sublicense, and/or sell copies of the Software, and to permit // persons to whom the Software is furnished to do so, subject to the // following conditions: // // The above copyright notice and this permission notice shall be included // in all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS // OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF // MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN // NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, // DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR // OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE // USE OR OTHER DEALINGS IN THE SOFTWARE. var binding = process.binding('os'); var util = require('util'); exports.endianness = binding.getEndianness; exports.hostname = binding.getHostname; exports.loadavg = binding.getLoadAvg; exports.uptime = binding.getUptime; exports.freemem = binding.getFreeMem; exports.totalmem = binding.getTotalMem; exports.cpus = binding.getCPUs; exports.type = binding.getOSType; exports.release = binding.getOSRelease; exports.networkInterfaces = binding.getInterfaceAddresses; exports.arch = function() { return process.arch; }; exports.platform = function() { return process.platform; }; exports.tmpdir = function() { return process.env.TMPDIR || process.env.TMP || process.env.TEMP || (process.platform === 'win32' ? 'c:\\windows\\temp' : '/tmp'); }; exports.tmpDir = exports.tmpdir; exports.getNetworkInterfaces = util.deprecate(function() { return exports.networkInterfaces(); }, 'getNetworkInterfaces is now called `os.networkInterfaces`.'); exports.EOL = process.platform === 'win32' ? '\r\n' : '\n'; node-v0.10.25~dfsg2/lib/stream.js0000644000000000000000000000676112270121457015226 0ustar rootroot// Copyright Joyent, Inc. and other Node contributors. // // Permission is hereby granted, free of charge, to any person obtaining a // copy of this software and associated documentation files (the // "Software"), to deal in the Software without restriction, including // without limitation the rights to use, copy, modify, merge, publish, // distribute, sublicense, and/or sell copies of the Software, and to permit // persons to whom the Software is furnished to do so, subject to the // following conditions: // // The above copyright notice and this permission notice shall be included // in all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS // OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF // MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN // NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, // DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR // OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE // USE OR OTHER DEALINGS IN THE SOFTWARE. module.exports = Stream; var EE = require('events').EventEmitter; var util = require('util'); util.inherits(Stream, EE); Stream.Readable = require('_stream_readable'); Stream.Writable = require('_stream_writable'); Stream.Duplex = require('_stream_duplex'); Stream.Transform = require('_stream_transform'); Stream.PassThrough = require('_stream_passthrough'); // Backwards-compat with node 0.4.x Stream.Stream = Stream; // old-style streams. Note that the pipe method (the only relevant // part of this class) is overridden in the Readable class. function Stream() { EE.call(this); } Stream.prototype.pipe = function(dest, options) { var source = this; function ondata(chunk) { if (dest.writable) { if (false === dest.write(chunk) && source.pause) { source.pause(); } } } source.on('data', ondata); function ondrain() { if (source.readable && source.resume) { source.resume(); } } dest.on('drain', ondrain); // If the 'end' option is not supplied, dest.end() will be called when // source gets the 'end' or 'close' events. Only dest.end() once. if (!dest._isStdio && (!options || options.end !== false)) { source.on('end', onend); source.on('close', onclose); } var didOnEnd = false; function onend() { if (didOnEnd) return; didOnEnd = true; dest.end(); } function onclose() { if (didOnEnd) return; didOnEnd = true; if (typeof dest.destroy === 'function') dest.destroy(); } // don't leave dangling pipes when there are errors. function onerror(er) { cleanup(); if (EE.listenerCount(this, 'error') === 0) { throw er; // Unhandled stream error in pipe. } } source.on('error', onerror); dest.on('error', onerror); // remove all the event listeners that were added. function cleanup() { source.removeListener('data', ondata); dest.removeListener('drain', ondrain); source.removeListener('end', onend); source.removeListener('close', onclose); source.removeListener('error', onerror); dest.removeListener('error', onerror); source.removeListener('end', cleanup); source.removeListener('close', cleanup); dest.removeListener('close', cleanup); } source.on('end', cleanup); source.on('close', cleanup); dest.on('close', cleanup); dest.emit('pipe', source); // Allow for unix-like usage: A.pipe(B).pipe(C) return dest; }; node-v0.10.25~dfsg2/lib/punycode.js0000644000000000000000000003351212270121457015553 0ustar rootroot/*! http://mths.be/punycode v1.2.0 by @mathias */ ;(function(root) { /** * The `punycode` object. * @name punycode * @type Object */ var punycode, /** Detect free variables `define`, `exports`, `module` and `require` */ freeDefine = typeof define == 'function' && typeof define.amd == 'object' && define.amd && define, freeExports = typeof exports == 'object' && exports, freeModule = typeof module == 'object' && module, freeRequire = typeof require == 'function' && require, /** Highest positive signed 32-bit float value */ maxInt = 2147483647, // aka. 0x7FFFFFFF or 2^31-1 /** Bootstring parameters */ base = 36, tMin = 1, tMax = 26, skew = 38, damp = 700, initialBias = 72, initialN = 128, // 0x80 delimiter = '-', // '\x2D' /** Regular expressions */ regexPunycode = /^xn--/, regexNonASCII = /[^ -~]/, // unprintable ASCII chars + non-ASCII chars regexSeparators = /\x2E|\u3002|\uFF0E|\uFF61/g, // RFC 3490 separators /** Error messages */ errors = { 'overflow': 'Overflow: input needs wider integers to process', 'not-basic': 'Illegal input >= 0x80 (not a basic code point)', 'invalid-input': 'Invalid input' }, /** Convenience shortcuts */ baseMinusTMin = base - tMin, floor = Math.floor, stringFromCharCode = String.fromCharCode, /** Temporary variable */ key; /*--------------------------------------------------------------------------*/ /** * A generic error utility function. * @private * @param {String} type The error type. * @returns {Error} Throws a `RangeError` with the applicable error message. */ function error(type) { throw RangeError(errors[type]); } /** * A generic `Array#map` utility function. * @private * @param {Array} array The array to iterate over. * @param {Function} callback The function that gets called for every array * item. * @returns {Array} A new array of values returned by the callback function. */ function map(array, fn) { var length = array.length; while (length--) { array[length] = fn(array[length]); } return array; } /** * A simple `Array#map`-like wrapper to work with domain name strings. * @private * @param {String} domain The domain name. * @param {Function} callback The function that gets called for every * character. * @returns {Array} A new string of characters returned by the callback * function. */ function mapDomain(string, fn) { return map(string.split(regexSeparators), fn).join('.'); } /** * Creates an array containing the decimal code points of each Unicode * character in the string. While JavaScript uses UCS-2 internally, * this function will convert a pair of surrogate halves (each of which * UCS-2 exposes as separate characters) into a single code point, * matching UTF-16. * @see `punycode.ucs2.encode` * @see * @memberOf punycode.ucs2 * @name decode * @param {String} string The Unicode input string (UCS-2). * @returns {Array} The new array of code points. */ function ucs2decode(string) { var output = [], counter = 0, length = string.length, value, extra; while (counter < length) { value = string.charCodeAt(counter++); if ((value & 0xF800) == 0xD800 && counter < length) { // high surrogate, and there is a next character extra = string.charCodeAt(counter++); if ((extra & 0xFC00) == 0xDC00) { // low surrogate output.push(((value & 0x3FF) << 10) + (extra & 0x3FF) + 0x10000); } else { output.push(value, extra); } } else { output.push(value); } } return output; } /** * Creates a string based on an array of decimal code points. * @see `punycode.ucs2.decode` * @memberOf punycode.ucs2 * @name encode * @param {Array} codePoints The array of decimal code points. * @returns {String} The new Unicode string (UCS-2). */ function ucs2encode(array) { return map(array, function(value) { var output = ''; if (value > 0xFFFF) { value -= 0x10000; output += stringFromCharCode(value >>> 10 & 0x3FF | 0xD800); value = 0xDC00 | value & 0x3FF; } output += stringFromCharCode(value); return output; }).join(''); } /** * Converts a basic code point into a digit/integer. * @see `digitToBasic()` * @private * @param {Number} codePoint The basic (decimal) code point. * @returns {Number} The numeric value of a basic code point (for use in * representing integers) in the range `0` to `base - 1`, or `base` if * the code point does not represent a value. */ function basicToDigit(codePoint) { return codePoint - 48 < 10 ? codePoint - 22 : codePoint - 65 < 26 ? codePoint - 65 : codePoint - 97 < 26 ? codePoint - 97 : base; } /** * Converts a digit/integer into a basic code point. * @see `basicToDigit()` * @private * @param {Number} digit The numeric value of a basic code point. * @returns {Number} The basic code point whose value (when used for * representing integers) is `digit`, which needs to be in the range * `0` to `base - 1`. If `flag` is non-zero, the uppercase form is * used; else, the lowercase form is used. The behavior is undefined * if flag is non-zero and `digit` has no uppercase form. */ function digitToBasic(digit, flag) { // 0..25 map to ASCII a..z or A..Z // 26..35 map to ASCII 0..9 return digit + 22 + 75 * (digit < 26) - ((flag != 0) << 5); } /** * Bias adaptation function as per section 3.4 of RFC 3492. * http://tools.ietf.org/html/rfc3492#section-3.4 * @private */ function adapt(delta, numPoints, firstTime) { var k = 0; delta = firstTime ? floor(delta / damp) : delta >> 1; delta += floor(delta / numPoints); for (/* no initialization */; delta > baseMinusTMin * tMax >> 1; k += base) { delta = floor(delta / baseMinusTMin); } return floor(k + (baseMinusTMin + 1) * delta / (delta + skew)); } /** * Converts a basic code point to lowercase if `flag` is falsy, or to * uppercase if `flag` is truthy. The code point is unchanged if it's * caseless. The behavior is undefined if `codePoint` is not a basic code * point. * @private * @param {Number} codePoint The numeric value of a basic code point. * @returns {Number} The resulting basic code point. */ function encodeBasic(codePoint, flag) { codePoint -= (codePoint - 97 < 26) << 5; return codePoint + (!flag && codePoint - 65 < 26) << 5; } /** * Converts a Punycode string of ASCII code points to a string of Unicode * code points. * @memberOf punycode * @param {String} input The Punycode string of ASCII code points. * @returns {String} The resulting string of Unicode code points. */ function decode(input) { // Don't use UCS-2 var output = [], inputLength = input.length, out, i = 0, n = initialN, bias = initialBias, basic, j, index, oldi, w, k, digit, t, length, /** Cached calculation results */ baseMinusT; // Handle the basic code points: let `basic` be the number of input code // points before the last delimiter, or `0` if there is none, then copy // the first basic code points to the output. basic = input.lastIndexOf(delimiter); if (basic < 0) { basic = 0; } for (j = 0; j < basic; ++j) { // if it's not a basic code point if (input.charCodeAt(j) >= 0x80) { error('not-basic'); } output.push(input.charCodeAt(j)); } // Main decoding loop: start just after the last delimiter if any basic code // points were copied; start at the beginning otherwise. for (index = basic > 0 ? basic + 1 : 0; index < inputLength; /* no final expression */) { // `index` is the index of the next character to be consumed. // Decode a generalized variable-length integer into `delta`, // which gets added to `i`. The overflow checking is easier // if we increase `i` as we go, then subtract off its starting // value at the end to obtain `delta`. for (oldi = i, w = 1, k = base; /* no condition */; k += base) { if (index >= inputLength) { error('invalid-input'); } digit = basicToDigit(input.charCodeAt(index++)); if (digit >= base || digit > floor((maxInt - i) / w)) { error('overflow'); } i += digit * w; t = k <= bias ? tMin : (k >= bias + tMax ? tMax : k - bias); if (digit < t) { break; } baseMinusT = base - t; if (w > floor(maxInt / baseMinusT)) { error('overflow'); } w *= baseMinusT; } out = output.length + 1; bias = adapt(i - oldi, out, oldi == 0); // `i` was supposed to wrap around from `out` to `0`, // incrementing `n` each time, so we'll fix that now: if (floor(i / out) > maxInt - n) { error('overflow'); } n += floor(i / out); i %= out; // Insert `n` at position `i` of the output output.splice(i++, 0, n); } return ucs2encode(output); } /** * Converts a string of Unicode code points to a Punycode string of ASCII * code points. * @memberOf punycode * @param {String} input The string of Unicode code points. * @returns {String} The resulting Punycode string of ASCII code points. */ function encode(input) { var n, delta, handledCPCount, basicLength, bias, j, m, q, k, t, currentValue, output = [], /** `inputLength` will hold the number of code points in `input`. */ inputLength, /** Cached calculation results */ handledCPCountPlusOne, baseMinusT, qMinusT; // Convert the input in UCS-2 to Unicode input = ucs2decode(input); // Cache the length inputLength = input.length; // Initialize the state n = initialN; delta = 0; bias = initialBias; // Handle the basic code points for (j = 0; j < inputLength; ++j) { currentValue = input[j]; if (currentValue < 0x80) { output.push(stringFromCharCode(currentValue)); } } handledCPCount = basicLength = output.length; // `handledCPCount` is the number of code points that have been handled; // `basicLength` is the number of basic code points. // Finish the basic string - if it is not empty - with a delimiter if (basicLength) { output.push(delimiter); } // Main encoding loop: while (handledCPCount < inputLength) { // All non-basic code points < n have been handled already. Find the next // larger one: for (m = maxInt, j = 0; j < inputLength; ++j) { currentValue = input[j]; if (currentValue >= n && currentValue < m) { m = currentValue; } } // Increase `delta` enough to advance the decoder's state to , // but guard against overflow handledCPCountPlusOne = handledCPCount + 1; if (m - n > floor((maxInt - delta) / handledCPCountPlusOne)) { error('overflow'); } delta += (m - n) * handledCPCountPlusOne; n = m; for (j = 0; j < inputLength; ++j) { currentValue = input[j]; if (currentValue < n && ++delta > maxInt) { error('overflow'); } if (currentValue == n) { // Represent delta as a generalized variable-length integer for (q = delta, k = base; /* no condition */; k += base) { t = k <= bias ? tMin : (k >= bias + tMax ? tMax : k - bias); if (q < t) { break; } qMinusT = q - t; baseMinusT = base - t; output.push( stringFromCharCode(digitToBasic(t + qMinusT % baseMinusT, 0)) ); q = floor(qMinusT / baseMinusT); } output.push(stringFromCharCode(digitToBasic(q, 0))); bias = adapt(delta, handledCPCountPlusOne, handledCPCount == basicLength); delta = 0; ++handledCPCount; } } ++delta; ++n; } return output.join(''); } /** * Converts a Punycode string representing a domain name to Unicode. Only the * Punycoded parts of the domain name will be converted, i.e. it doesn't * matter if you call it on a string that has already been converted to * Unicode. * @memberOf punycode * @param {String} domain The Punycode domain name to convert to Unicode. * @returns {String} The Unicode representation of the given Punycode * string. */ function toUnicode(domain) { return mapDomain(domain, function(string) { return regexPunycode.test(string) ? decode(string.slice(4).toLowerCase()) : string; }); } /** * Converts a Unicode string representing a domain name to Punycode. Only the * non-ASCII parts of the domain name will be converted, i.e. it doesn't * matter if you call it with a domain that's already in ASCII. * @memberOf punycode * @param {String} domain The domain name to convert, as a Unicode string. * @returns {String} The Punycode representation of the given domain name. */ function toASCII(domain) { return mapDomain(domain, function(string) { return regexNonASCII.test(string) ? 'xn--' + encode(string) : string; }); } /*--------------------------------------------------------------------------*/ /** Define the public API */ punycode = { /** * A string representing the current Punycode.js version number. * @memberOf punycode * @type String */ 'version': '1.2.0', /** * An object of methods to convert from JavaScript's internal character * representation (UCS-2) to decimal Unicode code points, and back. * @see * @memberOf punycode * @type Object */ 'ucs2': { 'decode': ucs2decode, 'encode': ucs2encode }, 'decode': decode, 'encode': encode, 'toASCII': toASCII, 'toUnicode': toUnicode }; /** Expose `punycode` */ if (freeExports) { if (freeModule && freeModule.exports == freeExports) { // in Node.js or Ringo 0.8+ freeModule.exports = punycode; } else { // in Narwhal or Ringo 0.7- for (key in punycode) { punycode.hasOwnProperty(key) && (freeExports[key] = punycode[key]); } } } else if (freeDefine) { // via curl.js or RequireJS define('punycode', punycode); } else { // in a browser or Rhino root.punycode = punycode; } }(this)); node-v0.10.25~dfsg2/lib/_debugger.js0000644000000000000000000011675112270121457015657 0ustar rootroot// Copyright Joyent, Inc. and other Node contributors. // // Permission is hereby granted, free of charge, to any person obtaining a // copy of this software and associated documentation files (the // "Software"), to deal in the Software without restriction, including // without limitation the rights to use, copy, modify, merge, publish, // distribute, sublicense, and/or sell copies of the Software, and to permit // persons to whom the Software is furnished to do so, subject to the // following conditions: // // The above copyright notice and this permission notice shall be included // in all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS // OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF // MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN // NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, // DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR // OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE // USE OR OTHER DEALINGS IN THE SOFTWARE. var util = require('util'), path = require('path'), net = require('net'), vm = require('vm'), repl = require('repl'), inherits = util.inherits, spawn = require('child_process').spawn; exports.start = function(argv, stdin, stdout) { argv || (argv = process.argv.slice(2)); if (argv.length < 1) { console.error('Usage: node debug script.js'); process.exit(1); } // Setup input/output streams stdin = stdin || process.stdin; stdout = stdout || process.stdout; var args = ['--debug-brk'].concat(argv), interface_ = new Interface(stdin, stdout, args); stdin.resume(); process.on('uncaughtException', function(e) { console.error("There was an internal error in Node's debugger. " + 'Please report this bug.'); console.error(e.message); console.error(e.stack); if (interface_.child) interface_.child.kill(); process.exit(1); }); }; exports.port = 5858; // // Parser/Serializer for V8 debugger protocol // http://code.google.com/p/v8/wiki/DebuggerProtocol // // Usage: // p = new Protocol(); // // p.onResponse = function(res) { // // do stuff with response from V8 // }; // // socket.setEncoding('utf8'); // socket.on('data', function(s) { // // Pass strings into the protocol // p.execute(s); // }); // // function Protocol() { this._newRes(); } exports.Protocol = Protocol; Protocol.prototype._newRes = function(raw) { this.res = { raw: raw || '', headers: {} }; this.state = 'headers'; this.reqSeq = 1; this.execute(''); }; Protocol.prototype.execute = function(d) { var res = this.res; res.raw += d; switch (this.state) { case 'headers': var endHeaderIndex = res.raw.indexOf('\r\n\r\n'); if (endHeaderIndex < 0) break; var rawHeader = res.raw.slice(0, endHeaderIndex); var endHeaderByteIndex = Buffer.byteLength(rawHeader, 'utf8'); var lines = rawHeader.split('\r\n'); for (var i = 0; i < lines.length; i++) { var kv = lines[i].split(/: +/); res.headers[kv[0]] = kv[1]; } this.contentLength = +res.headers['Content-Length']; this.bodyStartByteIndex = endHeaderByteIndex + 4; this.state = 'body'; var len = Buffer.byteLength(res.raw, 'utf8'); if (len - this.bodyStartByteIndex < this.contentLength) { break; } // pass thru case 'body': var resRawByteLength = Buffer.byteLength(res.raw, 'utf8'); if (resRawByteLength - this.bodyStartByteIndex >= this.contentLength) { var buf = new Buffer(resRawByteLength); buf.write(res.raw, 0, resRawByteLength, 'utf8'); res.body = buf.slice(this.bodyStartByteIndex, this.bodyStartByteIndex + this.contentLength).toString('utf8'); // JSON parse body? res.body = res.body.length ? JSON.parse(res.body) : {}; // Done! this.onResponse(res); this._newRes(buf.slice(this.bodyStartByteIndex + this.contentLength).toString('utf8')); } break; default: throw new Error('Unknown state'); break; } }; Protocol.prototype.serialize = function(req) { req.type = 'request'; req.seq = this.reqSeq++; var json = JSON.stringify(req); return 'Content-Length: ' + Buffer.byteLength(json, 'utf8') + '\r\n\r\n' + json; }; var NO_FRAME = -1; function Client() { net.Stream.call(this); var protocol = this.protocol = new Protocol(this); this._reqCallbacks = []; var socket = this; this.currentFrame = NO_FRAME; this.currentSourceLine = -1; this.currentSource = null; this.handles = {}; this.scripts = {}; this.breakpoints = []; // Note that 'Protocol' requires strings instead of Buffers. socket.setEncoding('utf8'); socket.on('data', function(d) { protocol.execute(d); }); protocol.onResponse = this._onResponse.bind(this); } inherits(Client, net.Stream); exports.Client = Client; Client.prototype._addHandle = function(desc) { if (typeof desc != 'object' || typeof desc.handle != 'number') { return; } this.handles[desc.handle] = desc; if (desc.type == 'script') { this._addScript(desc); } }; var natives = process.binding('natives'); Client.prototype._addScript = function(desc) { this.scripts[desc.id] = desc; if (desc.name) { desc.isNative = (desc.name.replace('.js', '') in natives) || desc.name == 'node.js'; } }; Client.prototype._removeScript = function(desc) { this.scripts[desc.id] = undefined; }; Client.prototype._onResponse = function(res) { var cb, index = -1; this._reqCallbacks.some(function(fn, i) { if (fn.request_seq == res.body.request_seq) { cb = fn; index = i; return true; } }); var self = this; var handled = false; if (res.headers.Type == 'connect') { // Request a list of scripts for our own storage. self.reqScripts(); self.emit('ready'); handled = true; } else if (res.body && res.body.event == 'break') { this.emit('break', res.body); handled = true; } else if (res.body && res.body.event == 'exception') { this.emit('exception', res.body); handled = true; } else if (res.body && res.body.event == 'afterCompile') { this._addHandle(res.body.body.script); handled = true; } else if (res.body && res.body.event == 'scriptCollected') { // ??? this._removeScript(res.body.body.script); handled = true; } if (cb) { this._reqCallbacks.splice(index, 1); handled = true; var err = res.success === false && (res.message || true) || res.body.success === false && (res.body.message || true); cb(err, res.body && res.body.body || res.body, res); } if (!handled) this.emit('unhandledResponse', res.body); }; Client.prototype.req = function(req, cb) { this.write(this.protocol.serialize(req)); cb.request_seq = req.seq; this._reqCallbacks.push(cb); }; Client.prototype.reqVersion = function(cb) { cb = cb || function() {}; this.req({ command: 'version' } , function(err, body, res) { if (err) return cb(err); cb(null, res.body.body.V8Version, res.body.running); }); }; Client.prototype.reqLookup = function(refs, cb) { var self = this; // TODO: We have a cache of handle's we've already seen in this.handles // This can be used if we're careful. var req = { command: 'lookup', arguments: { handles: refs } }; cb = cb || function() {}; this.req(req, function(err, res) { if (err) return cb(err); for (var ref in res) { if (typeof res[ref] == 'object') { self._addHandle(res[ref]); } } cb(null, res); }); }; Client.prototype.reqScopes = function(cb) { var self = this, req = { command: 'scopes', arguments: {} }; cb = cb || function() {}; this.req(req, function(err, res) { if (err) return cb(err); var refs = res.scopes.map(function(scope) { return scope.object.ref; }); self.reqLookup(refs, function(err, res) { if (err) return cb(err); var globals = Object.keys(res).map(function(key) { return res[key].properties.map(function(prop) { return prop.name; }); }); cb(null, globals.reverse()); }); }); }; // This is like reqEval, except it will look up the expression in each of the // scopes associated with the current frame. Client.prototype.reqEval = function(expression, cb) { var self = this; if (this.currentFrame == NO_FRAME) { // Only need to eval in global scope. this.reqFrameEval(expression, NO_FRAME, cb); return; } cb = cb || function() {}; // Otherwise we need to get the current frame to see which scopes it has. this.reqBacktrace(function(err, bt) { if (err || !bt.frames) { // ?? return cb(null, {}); } var frame = bt.frames[self.currentFrame]; var evalFrames = frame.scopes.map(function(s) { if (!s) return; var x = bt.frames[s.index]; if (!x) return; return x.index; }); self._reqFramesEval(expression, evalFrames, cb); }); }; // Finds the first scope in the array in which the epxression evals. Client.prototype._reqFramesEval = function(expression, evalFrames, cb) { if (evalFrames.length == 0) { // Just eval in global scope. this.reqFrameEval(expression, NO_FRAME, cb); return; } var self = this; var i = evalFrames.shift(); cb = cb || function() {}; this.reqFrameEval(expression, i, function(err, res) { if (!err) return cb(null, res); self._reqFramesEval(expression, evalFrames, cb); }); }; Client.prototype.reqFrameEval = function(expression, frame, cb) { var self = this; var req = { command: 'evaluate', arguments: { expression: expression } }; if (frame == NO_FRAME) { req.arguments.global = true; } else { req.arguments.frame = frame; } cb = cb || function() {}; this.req(req, function(err, res) { if (!err) self._addHandle(res); cb(err, res); }); }; // reqBacktrace(cb) // TODO: from, to, bottom Client.prototype.reqBacktrace = function(cb) { this.req({ command: 'backtrace', arguments: { inlineRefs: true } } , cb); }; // reqSetExceptionBreak(type, cb) // TODO: from, to, bottom Client.prototype.reqSetExceptionBreak = function(type, cb) { this.req({ command: 'setexceptionbreak', arguments: { type: type, enabled: true } }, cb); }; // Returns an array of objects like this: // // { handle: 11, // type: 'script', // name: 'node.js', // id: 14, // lineOffset: 0, // columnOffset: 0, // lineCount: 562, // sourceStart: '(function(process) {\n\n ', // sourceLength: 15939, // scriptType: 2, // compilationType: 0, // context: { ref: 10 }, // text: 'node.js (lines: 562)' } // Client.prototype.reqScripts = function(cb) { var self = this; cb = cb || function() {}; this.req({ command: 'scripts' } , function(err, res) { if (err) return cb(err); for (var i = 0; i < res.length; i++) { self._addHandle(res[i]); } cb(null); }); }; Client.prototype.reqContinue = function(cb) { this.currentFrame = NO_FRAME; this.req({ command: 'continue' }, cb); }; Client.prototype.listbreakpoints = function(cb) { this.req({ command: 'listbreakpoints' }, cb); }; Client.prototype.setBreakpoint = function(req, cb) { req = { command: 'setbreakpoint', arguments: req }; this.req(req, cb); }; Client.prototype.clearBreakpoint = function(req, cb) { var req = { command: 'clearbreakpoint', arguments: req }; this.req(req, cb); }; Client.prototype.reqSource = function(from, to, cb) { var req = { command: 'source', fromLine: from, toLine: to }; this.req(req, cb); }; // client.next(1, cb); Client.prototype.step = function(action, count, cb) { var req = { command: 'continue', arguments: { stepaction: action, stepcount: count } }; this.currentFrame = NO_FRAME; this.req(req, cb); }; Client.prototype.mirrorObject = function(handle, depth, cb) { var self = this; var val; if (handle.type === 'object') { // The handle looks something like this: // { handle: 8, // type: 'object', // className: 'Object', // constructorFunction: { ref: 9 }, // protoObject: { ref: 4 }, // prototypeObject: { ref: 2 }, // properties: [ { name: 'hello', propertyType: 1, ref: 10 } ], // text: '#' } // For now ignore the className and constructor and prototype. // TJ's method of object inspection would probably be good for this: // https://groups.google.com/forum/?pli=1#!topic/nodejs-dev/4gkWBOimiOg var propertyRefs = handle.properties.map(function(p) { return p.ref; }); cb = cb || function() {}; this.reqLookup(propertyRefs, function(err, res) { if (err) { console.error('problem with reqLookup'); cb(null, handle); return; } var mirror, waiting = 1; if (handle.className == 'Array') { mirror = []; } else if (handle.className == 'Date') { mirror = new Date(handle.value); } else { mirror = {}; } var keyValues = []; handle.properties.forEach(function(prop, i) { var value = res[prop.ref]; var mirrorValue; if (value) { mirrorValue = value.value ? value.value : value.text; } else { mirrorValue = '[?]'; } if (Array.isArray(mirror) && typeof prop.name != 'number') { // Skip the 'length' property. return; } keyValues[i] = { name: prop.name, value: mirrorValue }; if (value && value.handle && depth > 0) { waiting++; self.mirrorObject(value, depth - 1, function(err, result) { if (!err) keyValues[i].value = result; waitForOthers(); }); } }); waitForOthers(); function waitForOthers() { if (--waiting === 0 && cb) { keyValues.forEach(function(kv) { mirror[kv.name] = kv.value; }); cb(null, mirror); } }; }); return; } else if (handle.type === 'function') { val = function() {}; } else if (handle.type === 'null') { val = null; } else if (handle.value !== undefined) { val = handle.value; } else if (handle.type === 'undefined') { val = undefined; } else { val = handle; } process.nextTick(function() { cb(null, val); }); }; Client.prototype.fullTrace = function(cb) { var self = this; cb = cb || function() {}; this.reqBacktrace(function(err, trace) { if (err) return cb(err); if (trace.totalFrames <= 0) return cb(Error('No frames')); var refs = []; for (var i = 0; i < trace.frames.length; i++) { var frame = trace.frames[i]; // looks like this: // { type: 'frame', // index: 0, // receiver: { ref: 1 }, // func: { ref: 0 }, // script: { ref: 7 }, // constructCall: false, // atReturn: false, // debuggerFrame: false, // arguments: [], // locals: [], // position: 160, // line: 7, // column: 2, // sourceLineText: ' debugger;', // scopes: [ { type: 1, index: 0 }, { type: 0, index: 1 } ], // text: '#00 blah() /home/ryan/projects/node/test-debug.js l...' } refs.push(frame.script.ref); refs.push(frame.func.ref); refs.push(frame.receiver.ref); } self.reqLookup(refs, function(err, res) { if (err) return cb(err); for (var i = 0; i < trace.frames.length; i++) { var frame = trace.frames[i]; frame.script = res[frame.script.ref]; frame.func = res[frame.func.ref]; frame.receiver = res[frame.receiver.ref]; } cb(null, trace); }); }); }; var commands = [ [ 'run (r)', 'cont (c)', 'next (n)', 'step (s)', 'out (o)', 'backtrace (bt)', 'setBreakpoint (sb)', 'clearBreakpoint (cb)' ], [ 'watch', 'unwatch', 'watchers', 'repl', 'restart', 'kill', 'list', 'scripts', 'breakOnException', 'breakpoints', 'version' ] ]; var helpMessage = 'Commands: ' + commands.map(function(group) { return group.join(', '); }).join(',\n'); function SourceUnderline(sourceText, position, repl) { if (!sourceText) return ''; var head = sourceText.slice(0, position), tail = sourceText.slice(position); // Colourize char if stdout supports colours if (repl.useColors) { tail = tail.replace(/(.+?)([^\w]|$)/, '\u001b[32m$1\u001b[39m$2'); } // Return source line with coloured char at `position` return [ head, tail ].join(''); } function SourceInfo(body) { var result = body.exception ? 'exception in ' : 'break in '; if (body.script) { if (body.script.name) { var name = body.script.name, dir = path.resolve() + '/'; // Change path to relative, if possible if (name.indexOf(dir) === 0) { name = name.slice(dir.length); } result += name; } else { result += '[unnamed]'; } } result += ':'; result += body.sourceLine + 1; if (body.exception) result += '\n' + body.exception.text; return result; } // This class is the repl-enabled debugger interface which is invoked on // "node debug" function Interface(stdin, stdout, args) { var self = this, child; this.stdin = stdin; this.stdout = stdout; this.args = args; // Two eval modes are available: controlEval and debugEval // But controlEval is used by default var opts = { prompt: 'debug> ', input: this.stdin, output: this.stdout, eval: this.controlEval.bind(this), useGlobal: false, ignoreUndefined: true }; if (parseInt(process.env['NODE_NO_READLINE'], 10)) { opts.terminal = false; } else if (parseInt(process.env['NODE_FORCE_READLINE'], 10)) { opts.terminal = true; // Emulate Ctrl+C if we're emulating terminal if (!this.stdout.isTTY) { process.on('SIGINT', function() { self.repl.rli.emit('SIGINT'); }); } } if (parseInt(process.env['NODE_DISABLE_COLORS'], 10)) { opts.useColors = false; } this.repl = repl.start(opts); // Do not print useless warning repl._builtinLibs.splice(repl._builtinLibs.indexOf('repl'), 1); // Kill child process when main process dies this.repl.on('exit', function() { process.exit(0); }); // Handle all possible exits process.on('exit', this.killChild.bind(this)); process.once('SIGTERM', process.exit.bind(process, 0)); process.once('SIGHUP', process.exit.bind(process, 0)); var proto = Interface.prototype, ignored = ['pause', 'resume', 'exitRepl', 'handleBreak', 'requireConnection', 'killChild', 'trySpawn', 'controlEval', 'debugEval', 'print', 'childPrint', 'clearline'], shortcut = { 'run': 'r', 'cont': 'c', 'next': 'n', 'step': 's', 'out': 'o', 'backtrace': 'bt', 'setBreakpoint': 'sb', 'clearBreakpoint': 'cb', 'pause_': 'pause' }; function defineProperty(key, protoKey) { // Check arity var fn = proto[protoKey].bind(self); if (proto[protoKey].length === 0) { Object.defineProperty(self.repl.context, key, { get: fn, enumerable: true, configurable: false }); } else { self.repl.context[key] = fn; } }; // Copy all prototype methods in repl context // Setup them as getters if possible for (var i in proto) { if (Object.prototype.hasOwnProperty.call(proto, i) && ignored.indexOf(i) === -1) { defineProperty(i, i); if (shortcut[i]) defineProperty(shortcut[i], i); } } this.killed = false; this.waiting = null; this.paused = 0; this.context = this.repl.context; this.history = { debug: [], control: [] }; this.breakpoints = []; this._watchers = []; // Run script automatically this.pause(); // XXX Need to figure out why we need this delay setTimeout(function() { self.run(function() { self.resume(); }); }, 10); } // Stream control Interface.prototype.pause = function() { if (this.killed || this.paused++ > 0) return false; this.repl.rli.pause(); this.stdin.pause(); }; Interface.prototype.resume = function(silent) { if (this.killed || this.paused === 0 || --this.paused !== 0) return false; this.repl.rli.resume(); if (silent !== true) { this.repl.displayPrompt(); } this.stdin.resume(); if (this.waiting) { this.waiting(); this.waiting = null; } }; // Clear current line Interface.prototype.clearline = function() { if (this.stdout.isTTY) { this.stdout.cursorTo(0); this.stdout.clearLine(1); } else { this.stdout.write('\b'); } }; // Print text to output stream Interface.prototype.print = function(text, oneline) { if (this.killed) return; this.clearline(); this.stdout.write(typeof text === 'string' ? text : util.inspect(text)); if (oneline !== true) { this.stdout.write('\n'); } }; // Format and print text from child process Interface.prototype.childPrint = function(text) { this.print(text.toString().split(/\r\n|\r|\n/g).filter(function(chunk) { return chunk; }).map(function(chunk) { return '< ' + chunk; }).join('\n')); this.repl.displayPrompt(true); }; // Errors formatting Interface.prototype.error = function(text) { this.print(text); this.resume(); }; // Debugger's `break` event handler Interface.prototype.handleBreak = function(r) { var self = this; this.pause(); // Save execution context's data this.client.currentSourceLine = r.sourceLine; this.client.currentSourceLineText = r.sourceLineText; this.client.currentSourceColumn = r.sourceColumn; this.client.currentFrame = 0; this.client.currentScript = r.script && r.script.name; // Print break data this.print(SourceInfo(r)); // Show watchers' values this.watchers(true, function(err) { if (err) return self.error(err); // And list source self.list(2); self.resume(true); }); }; // Internal method for checking connection state Interface.prototype.requireConnection = function() { if (!this.client) { this.error('App isn\'t running... Try `run` instead'); return false; } return true; }; // Evals // Used for debugger's commands evaluation and execution Interface.prototype.controlEval = function(code, context, filename, callback) { try { // Repeat last command if empty line are going to be evaluated if (this.repl.rli.history && this.repl.rli.history.length > 0) { if (code === '(\n)') { code = '(' + this.repl.rli.history[0] + '\n)'; } } var result = vm.runInContext(code, context, filename); // Repl should not ask for next command // if current one was asynchronous. if (this.paused === 0) return callback(null, result); // Add a callback for asynchronous command // (it will be automatically invoked by .resume() method this.waiting = function() { callback(null, result); }; } catch (e) { callback(e); } }; // Used for debugger's remote evaluation (`repl`) commands Interface.prototype.debugEval = function(code, context, filename, callback) { if (!this.requireConnection()) return; var self = this, client = this.client; // Repl asked for scope variables if (code === '.scope') { client.reqScopes(callback); return; } var frame = client.currentFrame === NO_FRAME ? frame : undefined; self.pause(); // Request remote evaluation globally or in current frame client.reqFrameEval(code, frame, function(err, res) { if (err) { callback(err); self.resume(true); return; } // Request object by handles (and it's sub-properties) client.mirrorObject(res, 3, function(err, mirror) { callback(null, mirror); self.resume(true); }); }); }; // Utils // Returns number of digits (+1) function intChars(n) { // TODO dumb: if (n < 50) { return 3; } else if (n < 950) { return 4; } else if (n < 9950) { return 5; } else { return 6; } } // Adds spaces and prefix to number function leftPad(n, prefix) { var s = n.toString(), nchars = intChars(n), nspaces = nchars - s.length - 1; prefix || (prefix = ' '); for (var i = 0; i < nspaces; i++) { prefix += ' '; } return prefix + s; } // Commands // Print help message Interface.prototype.help = function() { this.print(helpMessage); }; // Run script Interface.prototype.run = function() { var callback = arguments[0]; if (this.child) { this.error('App is already running... Try `restart` instead'); callback && callback(true); } else { this.trySpawn(callback); } }; // Restart script Interface.prototype.restart = function() { if (!this.requireConnection()) return; var self = this; self.pause(); self.killChild(); // XXX need to wait a little bit for the restart to work? setTimeout(function() { self.trySpawn(); self.resume(); }, 1000); }; // Print version Interface.prototype.version = function() { if (!this.requireConnection()) return; var self = this; this.pause(); this.client.reqVersion(function(err, v) { if (err) { self.error(err); } else { self.print(v); } self.resume(); }); }; // List source code Interface.prototype.list = function(delta) { if (!this.requireConnection()) return; delta || (delta = 5); var self = this, client = this.client, from = client.currentSourceLine - delta + 1, to = client.currentSourceLine + delta + 1; self.pause(); client.reqSource(from, to, function(err, res) { if (err || !res) { self.error('You can\'t list source code right now'); self.resume(); return; } var lines = res.source.split('\n'); for (var i = 0; i < lines.length; i++) { var lineno = res.fromLine + i + 1; if (lineno < from || lineno > to) continue; var current = lineno == 1 + client.currentSourceLine, breakpoint = client.breakpoints.some(function(bp) { return bp.script === client.currentScript && bp.line == lineno; }); if (lineno == 1) { // The first line needs to have the module wrapper filtered out of // it. var wrapper = require('module').wrapper[0]; lines[i] = lines[i].slice(wrapper.length); client.currentSourceColumn -= wrapper.length; } // Highlight executing statement var line; if (current) { line = SourceUnderline(lines[i], client.currentSourceColumn, self.repl); } else { line = lines[i]; } self.print(leftPad(lineno, breakpoint && '*') + ' ' + line); } self.resume(); }); }; // Print backtrace Interface.prototype.backtrace = function() { if (!this.requireConnection()) return; var self = this, client = this.client; self.pause(); client.fullTrace(function(err, bt) { if (err) { self.error('Can\'t request backtrace now'); self.resume(); return; } if (bt.totalFrames == 0) { self.print('(empty stack)'); } else { var trace = [], firstFrameNative = bt.frames[0].script.isNative; for (var i = 0; i < bt.frames.length; i++) { var frame = bt.frames[i]; if (!firstFrameNative && frame.script.isNative) break; var text = '#' + i + ' '; if (frame.func.inferredName && frame.func.inferredName.length > 0) { text += frame.func.inferredName + ' '; } text += path.basename(frame.script.name) + ':'; text += (frame.line + 1) + ':' + (frame.column + 1); trace.push(text); } self.print(trace.join('\n')); } self.resume(); }); }; // First argument tells if it should display internal node scripts or not // (available only for internal debugger's functions) Interface.prototype.scripts = function() { if (!this.requireConnection()) return; var client = this.client, displayNatives = arguments[0] || false, scripts = []; this.pause(); for (var id in client.scripts) { var script = client.scripts[id]; if (typeof script == 'object' && script.name) { if (displayNatives || script.name == client.currentScript || !script.isNative) { scripts.push( (script.name == client.currentScript ? '* ' : ' ') + id + ': ' + path.basename(script.name) ); } } } this.print(scripts.join('\n')); this.resume(); }; // Continue execution of script Interface.prototype.cont = function() { if (!this.requireConnection()) return; this.pause(); var self = this; this.client.reqContinue(function(err) { if (err) self.error(err); self.resume(); }); }; // Step commands generator Interface.stepGenerator = function(type, count) { return function() { if (!this.requireConnection()) return; var self = this; self.pause(); self.client.step(type, count, function(err, res) { if (err) self.error(err); self.resume(); }); }; }; // Jump to next command Interface.prototype.next = Interface.stepGenerator('next', 1); // Step in Interface.prototype.step = Interface.stepGenerator('in', 1); // Step out Interface.prototype.out = Interface.stepGenerator('out', 1); // Watch Interface.prototype.watch = function(expr) { this._watchers.push(expr); }; // Unwatch Interface.prototype.unwatch = function(expr) { var index = this._watchers.indexOf(expr); // Unwatch by expression // or // Unwatch by watcher number this._watchers.splice(index !== -1 ? index : +expr, 1); }; // List watchers Interface.prototype.watchers = function() { var self = this, verbose = arguments[0] || false, callback = arguments[1] || function() {}, waiting = this._watchers.length, values = []; this.pause(); if (!waiting) { this.resume(); return callback(); } this._watchers.forEach(function(watcher, i) { self.debugEval(watcher, null, null, function(err, value) { values[i] = err ? '' : value; wait(); }); }); function wait() { if (--waiting === 0) { if (verbose) self.print('Watchers:'); self._watchers.forEach(function(watcher, i) { self.print(leftPad(i, ' ') + ': ' + watcher + ' = ' + JSON.stringify(values[i])); }); if (verbose) self.print(''); self.resume(); callback(null); } } }; // Break on exception Interface.prototype.breakOnException = function breakOnException() { if (!this.requireConnection()) return; var self = this; // Break on exceptions this.pause(); this.client.reqSetExceptionBreak('all', function(err, res) { self.resume(); }); }; // Add breakpoint Interface.prototype.setBreakpoint = function(script, line, condition, silent) { if (!this.requireConnection()) return; var self = this, scriptId, ambiguous; // setBreakpoint() should insert breakpoint on current line if (script === undefined) { script = this.client.currentScript; line = this.client.currentSourceLine + 1; } // setBreakpoint(line-number) should insert breakpoint in current script if (line === undefined && typeof script === 'number') { line = script; script = this.client.currentScript; } if (/\(\)$/.test(script)) { // setBreakpoint('functionname()'); var req = { type: 'function', target: script.replace(/\(\)$/, ''), condition: condition }; } else { // setBreakpoint('scriptname') if (script != +script && !this.client.scripts[script]) { var scripts = this.client.scripts; Object.keys(scripts).forEach(function(id) { if (scripts[id] && scripts[id].name && scripts[id].name.indexOf(script) !== -1) { if (scriptId) { ambiguous = true; } scriptId = id; } }); } else { scriptId = script; } if (ambiguous) return this.error('Script name is ambiguous'); if (line <= 0) return this.error('Line should be a positive value'); var req; if (scriptId) { req = { type: 'scriptId', target: scriptId, line: line - 1, condition: condition }; } else { this.print('Warning: script \'' + script + '\' was not loaded yet.'); var escapedPath = script.replace(/([/\\.?*()^${}|[\]])/g, '\\$1'); var scriptPathRegex = '^(.*[\\/\\\\])?' + escapedPath + '$'; req = { type: 'scriptRegExp', target: scriptPathRegex, line: line - 1, condition: condition }; } } self.pause(); self.client.setBreakpoint(req, function(err, res) { if (err) { if (!silent) { self.error(err); } } else { if (!silent) { self.list(5); } // Try load scriptId and line from response if (!scriptId) { scriptId = res.script_id; line = res.line + 1; } // Remember this breakpoint even if scriptId is not resolved yet self.client.breakpoints.push({ id: res.breakpoint, scriptId: scriptId, script: (self.client.scripts[scriptId] || {}).name, line: line, condition: condition, scriptReq: script }); } self.resume(); }); }; // Clear breakpoint Interface.prototype.clearBreakpoint = function(script, line) { if (!this.requireConnection()) return; var ambiguous, breakpoint, index; this.client.breakpoints.some(function(bp, i) { if (bp.scriptId === script || bp.scriptReq === script || (bp.script && bp.script.indexOf(script) !== -1)) { if (index !== undefined) { ambiguous = true; } if (bp.line === line) { index = i; breakpoint = bp.id; return true; } } }); if (ambiguous) return this.error('Script name is ambiguous'); if (breakpoint === undefined) { return this.error('Script : ' + script + ' not found'); } var self = this, req = { breakpoint: breakpoint }; self.pause(); self.client.clearBreakpoint(req, function(err, res) { if (err) { self.error(err); } else { self.client.breakpoints.splice(index, 1); self.list(5); } self.resume(); }); }; // Show breakpoints Interface.prototype.breakpoints = function() { if (!this.requireConnection()) return; this.pause(); var self = this; this.client.listbreakpoints(function(err, res) { if (err) { self.error(err); } else { self.print(res); self.resume(); } }); }; // Pause child process Interface.prototype.pause_ = function() { if (!this.requireConnection()) return; var self = this, cmd = 'process._debugPause();'; this.pause(); this.client.reqFrameEval(cmd, NO_FRAME, function(err, res) { if (err) { self.error(err); } else { self.resume(); } }); }; // Kill child process Interface.prototype.kill = function() { if (!this.child) return; this.killChild(); }; // Activate debug repl Interface.prototype.repl = function() { if (!this.requireConnection()) return; var self = this; self.print('Press Ctrl + C to leave debug repl'); // Don't display any default messages var listeners = this.repl.rli.listeners('SIGINT').slice(0); this.repl.rli.removeAllListeners('SIGINT'); // Exit debug repl on Ctrl + C this.repl.rli.once('SIGINT', function() { // Restore all listeners process.nextTick(function() { listeners.forEach(function(listener) { self.repl.rli.on('SIGINT', listener); }); }); // Exit debug repl self.exitRepl(); }); // Set new this.repl.eval = this.debugEval.bind(this); this.repl.context = {}; // Swap history this.history.control = this.repl.rli.history; this.repl.rli.history = this.history.debug; this.repl.prompt = '> '; this.repl.rli.setPrompt('> '); this.repl.displayPrompt(); }; // Exit debug repl Interface.prototype.exitRepl = function() { // Restore eval this.repl.eval = this.controlEval.bind(this); // Swap history this.history.debug = this.repl.rli.history; this.repl.rli.history = this.history.control; this.repl.context = this.context; this.repl.prompt = 'debug> '; this.repl.rli.setPrompt('debug> '); this.repl.displayPrompt(); }; // Quit Interface.prototype.quit = function() { this.killChild(); process.exit(0); }; // Kills child process Interface.prototype.killChild = function() { if (this.child) { this.child.kill(); this.child = null; } if (this.client) { // Save breakpoints this.breakpoints = this.client.breakpoints; this.client.destroy(); this.client = null; } }; // Spawns child process (and restores breakpoints) Interface.prototype.trySpawn = function(cb) { var self = this, breakpoints = this.breakpoints || [], port = exports.port, host = 'localhost', childArgs = this.args; this.killChild(); if (this.args.length === 2) { var match = this.args[1].match(/^([^:]+):(\d+)$/); if (match) { // Connecting to remote debugger // `node debug localhost:5858` host = match[1]; port = parseInt(match[2], 10); this.child = { kill: function() { // TODO Do we really need to handle it? } }; } } else if (this.args.length === 3) { // `node debug -p pid` if (this.args[1] === '-p' && /^\d+$/.test(this.args[2])) { this.child = { kill: function() { // TODO Do we really need to handle it? } }; process._debugProcess(parseInt(this.args[2], 10)); } else { var match = this.args[1].match(/^--port=(\d+)$/); if (match) { // Start debugger on custom port // `node debug --port=5858 app.js` port = parseInt(match[1], 10); childArgs = ['--debug-brk=' + port].concat(this.args.slice(2)); } } } if (!this.child) { this.child = spawn(process.execPath, childArgs); this.child.stdout.on('data', this.childPrint.bind(this)); this.child.stderr.on('data', this.childPrint.bind(this)); } this.pause(); var client = self.client = new Client(), connectionAttempts = 0; client.once('ready', function() { self.stdout.write(' ok\n'); // Restore breakpoints breakpoints.forEach(function(bp) { self.print('Restoring breakpoint ' + bp.scriptReq + ':' + bp.line); self.setBreakpoint(bp.scriptReq, bp.line, bp.condition, true); }); client.on('close', function() { self.pause(); self.print('program terminated'); self.resume(); self.client = null; self.killChild(); }); if (cb) cb(); self.resume(); }); client.on('unhandledResponse', function(res) { self.pause(); self.print('\nunhandled res:' + JSON.stringify(res)); self.resume(); }); client.on('break', function(res) { self.handleBreak(res.body); }); client.on('exception', function(res) { self.handleBreak(res.body); }); client.on('error', connectError); function connectError() { // If it's failed to connect 4 times then don't catch the next error if (connectionAttempts >= 10) { client.removeListener('error', connectError); } setTimeout(attemptConnect, 500); } function attemptConnect() { ++connectionAttempts; self.stdout.write('.'); client.connect(port, host); } setTimeout(function() { self.print('connecting..', true); attemptConnect(); }, 50); }; node-v0.10.25~dfsg2/lib/module.js0000644000000000000000000003477512270121457015226 0ustar rootroot// Copyright Joyent, Inc. and other Node contributors. // // Permission is hereby granted, free of charge, to any person obtaining a // copy of this software and associated documentation files (the // "Software"), to deal in the Software without restriction, including // without limitation the rights to use, copy, modify, merge, publish, // distribute, sublicense, and/or sell copies of the Software, and to permit // persons to whom the Software is furnished to do so, subject to the // following conditions: // // The above copyright notice and this permission notice shall be included // in all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS // OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF // MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN // NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, // DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR // OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE // USE OR OTHER DEALINGS IN THE SOFTWARE. var NativeModule = require('native_module'); var Script = process.binding('evals').NodeScript; var runInThisContext = Script.runInThisContext; var runInNewContext = Script.runInNewContext; var assert = require('assert').ok; // If obj.hasOwnProperty has been overridden, then calling // obj.hasOwnProperty(prop) will break. // See: https://github.com/joyent/node/issues/1707 function hasOwnProperty(obj, prop) { return Object.prototype.hasOwnProperty.call(obj, prop); } function Module(id, parent) { this.id = id; this.exports = {}; this.parent = parent; if (parent && parent.children) { parent.children.push(this); } this.filename = null; this.loaded = false; this.children = []; } module.exports = Module; // Set the environ variable NODE_MODULE_CONTEXTS=1 to make node load all // modules in thier own context. Module._contextLoad = (+process.env['NODE_MODULE_CONTEXTS'] > 0); Module._cache = {}; Module._pathCache = {}; Module._extensions = {}; var modulePaths = []; Module.globalPaths = []; Module.wrapper = NativeModule.wrapper; Module.wrap = NativeModule.wrap; var path = NativeModule.require('path'); Module._debug = function() {}; if (process.env.NODE_DEBUG && /module/.test(process.env.NODE_DEBUG)) { Module._debug = function(x) { console.error(x); }; } // We use this alias for the preprocessor that filters it out var debug = Module._debug; // given a module name, and a list of paths to test, returns the first // matching file in the following precedence. // // require("a.") // -> a. // // require("a") // -> a // -> a. // -> a/index. function statPath(path) { var fs = NativeModule.require('fs'); try { return fs.statSync(path); } catch (ex) {} return false; } // check if the directory is a package.json dir var packageMainCache = {}; function readPackage(requestPath) { if (hasOwnProperty(packageMainCache, requestPath)) { return packageMainCache[requestPath]; } var fs = NativeModule.require('fs'); try { var jsonPath = path.resolve(requestPath, 'package.json'); var json = fs.readFileSync(jsonPath, 'utf8'); } catch (e) { return false; } try { var pkg = packageMainCache[requestPath] = JSON.parse(json).main; } catch (e) { e.path = jsonPath; e.message = 'Error parsing ' + jsonPath + ': ' + e.message; throw e; } return pkg; } function tryPackage(requestPath, exts) { var pkg = readPackage(requestPath); if (!pkg) return false; var filename = path.resolve(requestPath, pkg); return tryFile(filename) || tryExtensions(filename, exts) || tryExtensions(path.resolve(filename, 'index'), exts); } // In order to minimize unnecessary lstat() calls, // this cache is a list of known-real paths. // Set to an empty object to reset. Module._realpathCache = {}; // check if the file exists and is not a directory function tryFile(requestPath) { var fs = NativeModule.require('fs'); var stats = statPath(requestPath); if (stats && !stats.isDirectory()) { return fs.realpathSync(requestPath, Module._realpathCache); } return false; } // given a path check a the file exists with any of the set extensions function tryExtensions(p, exts) { for (var i = 0, EL = exts.length; i < EL; i++) { var filename = tryFile(p + exts[i]); if (filename) { return filename; } } return false; } Module._findPath = function(request, paths) { var exts = Object.keys(Module._extensions); if (request.charAt(0) === '/') { paths = ['']; } var trailingSlash = (request.slice(-1) === '/'); var cacheKey = JSON.stringify({request: request, paths: paths}); if (Module._pathCache[cacheKey]) { return Module._pathCache[cacheKey]; } // For each path for (var i = 0, PL = paths.length; i < PL; i++) { var basePath = path.resolve(paths[i], request); var filename; if (!trailingSlash) { // try to join the request to the path filename = tryFile(basePath); if (!filename && !trailingSlash) { // try it with each of the extensions filename = tryExtensions(basePath, exts); } } if (!filename) { filename = tryPackage(basePath, exts); } if (!filename) { // try it with each of the extensions at "index" filename = tryExtensions(path.resolve(basePath, 'index'), exts); } if (filename) { Module._pathCache[cacheKey] = filename; return filename; } } return false; }; // 'from' is the __dirname of the module. Module._nodeModulePaths = function(from) { // guarantee that 'from' is absolute. from = path.resolve(from); // note: this approach *only* works when the path is guaranteed // to be absolute. Doing a fully-edge-case-correct path.split // that works on both Windows and Posix is non-trivial. var splitRe = process.platform === 'win32' ? /[\/\\]/ : /\//; // yes, '/' works on both, but let's be a little canonical. var joiner = process.platform === 'win32' ? '\\' : '/'; var paths = []; var parts = from.split(splitRe); for (var tip = parts.length - 1; tip >= 0; tip--) { // don't search in .../node_modules/node_modules if (parts[tip] === 'node_modules') continue; var dir = parts.slice(0, tip + 1).concat('node_modules').join(joiner); paths.push(dir); } return paths; }; Module._resolveLookupPaths = function(request, parent) { if (NativeModule.exists(request)) { return [request, []]; } var start = request.substring(0, 2); if (start !== './' && start !== '..') { var paths = modulePaths; if (parent) { if (!parent.paths) parent.paths = []; paths = parent.paths.concat(paths); } return [request, paths]; } // with --eval, parent.id is not set and parent.filename is null if (!parent || !parent.id || !parent.filename) { // make require('./path/to/foo') work - normally the path is taken // from realpath(__filename) but with eval there is no filename var mainPaths = ['.'].concat(modulePaths); mainPaths = Module._nodeModulePaths('.').concat(mainPaths); return [request, mainPaths]; } // Is the parent an index module? // We can assume the parent has a valid extension, // as it already has been accepted as a module. var isIndex = /^index\.\w+?$/.test(path.basename(parent.filename)); var parentIdPath = isIndex ? parent.id : path.dirname(parent.id); var id = path.resolve(parentIdPath, request); // make sure require('./path') and require('path') get distinct ids, even // when called from the toplevel js file if (parentIdPath === '.' && id.indexOf('/') === -1) { id = './' + id; } debug('RELATIVE: requested:' + request + ' set ID to: ' + id + ' from ' + parent.id); return [id, [path.dirname(parent.filename)]]; }; Module._load = function(request, parent, isMain) { if (parent) { debug('Module._load REQUEST ' + (request) + ' parent: ' + parent.id); } var filename = Module._resolveFilename(request, parent); var cachedModule = Module._cache[filename]; if (cachedModule) { return cachedModule.exports; } if (NativeModule.exists(filename)) { // REPL is a special case, because it needs the real require. if (filename == 'repl') { var replModule = new Module('repl'); replModule._compile(NativeModule.getSource('repl'), 'repl.js'); NativeModule._cache.repl = replModule; return replModule.exports; } debug('load native module ' + request); return NativeModule.require(filename); } var module = new Module(filename, parent); if (isMain) { process.mainModule = module; module.id = '.'; } Module._cache[filename] = module; var hadException = true; try { module.load(filename); hadException = false; } finally { if (hadException) { delete Module._cache[filename]; } } return module.exports; }; Module._resolveFilename = function(request, parent) { if (NativeModule.exists(request)) { return request; } var resolvedModule = Module._resolveLookupPaths(request, parent); var id = resolvedModule[0]; var paths = resolvedModule[1]; // look up the filename first, since that's the cache key. debug('looking for ' + JSON.stringify(id) + ' in ' + JSON.stringify(paths)); var filename = Module._findPath(request, paths); if (!filename) { var err = new Error("Cannot find module '" + request + "'"); err.code = 'MODULE_NOT_FOUND'; throw err; } return filename; }; Module.prototype.load = function(filename) { debug('load ' + JSON.stringify(filename) + ' for module ' + JSON.stringify(this.id)); assert(!this.loaded); this.filename = filename; this.paths = Module._nodeModulePaths(path.dirname(filename)); var extension = path.extname(filename) || '.js'; if (!Module._extensions[extension]) extension = '.js'; Module._extensions[extension](this, filename); this.loaded = true; }; Module.prototype.require = function(path) { assert(typeof path === 'string', 'path must be a string'); assert(path, 'missing path'); return Module._load(path, this); }; // Resolved path to process.argv[1] will be lazily placed here // (needed for setting breakpoint when called with --debug-brk) var resolvedArgv; // Returns exception if any Module.prototype._compile = function(content, filename) { var self = this; // remove shebang content = content.replace(/^\#\!.*/, ''); function require(path) { return self.require(path); } require.resolve = function(request) { return Module._resolveFilename(request, self); }; Object.defineProperty(require, 'paths', { get: function() { throw new Error('require.paths is removed. Use ' + 'node_modules folders, or the NODE_PATH ' + 'environment variable instead.'); }}); require.main = process.mainModule; // Enable support to add extra extension types require.extensions = Module._extensions; require.registerExtension = function() { throw new Error('require.registerExtension() removed. Use ' + 'require.extensions instead.'); }; require.cache = Module._cache; var dirname = path.dirname(filename); if (Module._contextLoad) { if (self.id !== '.') { debug('load submodule'); // not root module var sandbox = {}; for (var k in global) { sandbox[k] = global[k]; } sandbox.require = require; sandbox.exports = self.exports; sandbox.__filename = filename; sandbox.__dirname = dirname; sandbox.module = self; sandbox.global = sandbox; sandbox.root = root; return runInNewContext(content, sandbox, filename, true); } debug('load root module'); // root module global.require = require; global.exports = self.exports; global.__filename = filename; global.__dirname = dirname; global.module = self; return runInThisContext(content, filename, true); } // create wrapper function var wrapper = Module.wrap(content); var compiledWrapper = runInThisContext(wrapper, filename, true); if (global.v8debug) { if (!resolvedArgv) { // we enter the repl if we're not given a filename argument. if (process.argv[1]) { resolvedArgv = Module._resolveFilename(process.argv[1], null); } else { resolvedArgv = 'repl'; } } // Set breakpoint on module start if (filename === resolvedArgv) { global.v8debug.Debug.setBreakPoint(compiledWrapper, 0, 0); } } var args = [self.exports, require, self, filename, dirname]; return compiledWrapper.apply(self.exports, args); }; function stripBOM(content) { // Remove byte order marker. This catches EF BB BF (the UTF-8 BOM) // because the buffer-to-string conversion in `fs.readFileSync()` // translates it to FEFF, the UTF-16 BOM. if (content.charCodeAt(0) === 0xFEFF) { content = content.slice(1); } return content; } // Native extension for .js Module._extensions['.js'] = function(module, filename) { var content = NativeModule.require('fs').readFileSync(filename, 'utf8'); module._compile(stripBOM(content), filename); }; // Native extension for .json Module._extensions['.json'] = function(module, filename) { var content = NativeModule.require('fs').readFileSync(filename, 'utf8'); try { module.exports = JSON.parse(stripBOM(content)); } catch (err) { err.message = filename + ': ' + err.message; throw err; } }; //Native extension for .node Module._extensions['.node'] = process.dlopen; // bootstrap main module. Module.runMain = function() { // Load the main module--the command line argument. Module._load(process.argv[1], null, true); // Handle any nextTicks added in the first tick of the program process._tickCallback(); }; Module._initPaths = function() { var isWindows = process.platform === 'win32'; if (isWindows) { var homeDir = process.env.USERPROFILE; } else { var homeDir = process.env.HOME; } var paths = [path.resolve(process.execPath, '..', '..', 'lib', 'node')]; if (homeDir) { paths.unshift(path.resolve(homeDir, '.node_libraries')); paths.unshift(path.resolve(homeDir, '.node_modules')); } if (process.env['NODE_PATH']) { var splitter = isWindows ? ';' : ':'; paths = process.env['NODE_PATH'].split(splitter).concat(paths); } modulePaths = paths; // clone as a read-only copy, for introspection. Module.globalPaths = modulePaths.slice(0); }; // bootstrap repl Module.requireRepl = function() { return Module._load('repl', '.'); }; Module._initPaths(); // backwards compatibility Module.Module = Module; node-v0.10.25~dfsg2/lib/dns.js0000644000000000000000000001454012270121457014511 0ustar rootroot// Copyright Joyent, Inc. and other Node contributors. // // Permission is hereby granted, free of charge, to any person obtaining a // copy of this software and associated documentation files (the // 'Software'), to deal in the Software without restriction, including // without limitation the rights to use, copy, modify, merge, publish, // distribute, sublicense, and/or sell copies of the Software, and to permit // persons to whom the Software is furnished to do so, subject to the // following conditions: // // The above copyright notice and this permission notice shall be included // in all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED 'AS IS', WITHOUT WARRANTY OF ANY KIND, EXPRESS // OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF // MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN // NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, // DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR // OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE // USE OR OTHER DEALINGS IN THE SOFTWARE. var cares = process.binding('cares_wrap'), net = require('net'), isIp = net.isIP; function errnoException(errorno, syscall) { // TODO make this more compatible with ErrnoException from src/node.cc // Once all of Node is using this function the ErrnoException from // src/node.cc should be removed. // For backwards compatibility. libuv returns ENOENT on NXDOMAIN. if (errorno == 'ENOENT') { errorno = 'ENOTFOUND'; } var e = new Error(syscall + ' ' + errorno); e.errno = e.code = errorno; e.syscall = syscall; return e; } // c-ares invokes a callback either synchronously or asynchronously, // but the dns API should always invoke a callback asynchronously. // // This function makes sure that the callback is invoked asynchronously. // It returns a function that invokes the callback within nextTick(). // // To avoid invoking unnecessary nextTick(), `immediately` property of // returned function should be set to true after c-ares returned. // // Usage: // // function someAPI(callback) { // callback = makeAsync(callback); // channel.someAPI(..., callback); // callback.immediately = true; // } function makeAsync(callback) { if (typeof callback !== 'function') { return callback; } return function asyncCallback() { if (asyncCallback.immediately) { // The API already returned, we can invoke the callback immediately. callback.apply(null, arguments); } else { var args = arguments; process.nextTick(function() { callback.apply(null, args); }); } }; } // Easy DNS A/AAAA look up // lookup(domain, [family,] callback) exports.lookup = function(domain, family, callback) { // parse arguments if (arguments.length === 2) { callback = family; family = 0; } else if (!family) { family = 0; } else { family = +family; if (family !== 4 && family !== 6) { throw new Error('invalid argument: `family` must be 4 or 6'); } } callback = makeAsync(callback); if (!domain) { callback(null, null, family === 6 ? 6 : 4); return {}; } // Hack required for Windows because Win7 removed the // localhost entry from c:\WINDOWS\system32\drivers\etc\hosts // See http://daniel.haxx.se/blog/2011/02/21/localhost-hack-on-windows/ // TODO Remove this once c-ares handles this problem. if (process.platform == 'win32' && domain == 'localhost') { callback(null, '127.0.0.1', 4); return {}; } var matchedFamily = net.isIP(domain); if (matchedFamily) { callback(null, domain, matchedFamily); return {}; } function onanswer(addresses) { if (addresses) { if (family) { callback(null, addresses[0], family); } else { callback(null, addresses[0], addresses[0].indexOf(':') >= 0 ? 6 : 4); } } else { callback(errnoException(process._errno, 'getaddrinfo')); } } var wrap = cares.getaddrinfo(domain, family); if (!wrap) { throw errnoException(process._errno, 'getaddrinfo'); } wrap.oncomplete = onanswer; callback.immediately = true; return wrap; }; function resolver(bindingName) { var binding = cares[bindingName]; return function query(name, callback) { function onanswer(status, result) { if (!status) { callback(null, result); } else { callback(errnoException(process._errno, bindingName)); } } callback = makeAsync(callback); var wrap = binding(name, onanswer); if (!wrap) { throw errnoException(process._errno, bindingName); } callback.immediately = true; return wrap; } } var resolveMap = {}; exports.resolve4 = resolveMap.A = resolver('queryA'); exports.resolve6 = resolveMap.AAAA = resolver('queryAaaa'); exports.resolveCname = resolveMap.CNAME = resolver('queryCname'); exports.resolveMx = resolveMap.MX = resolver('queryMx'); exports.resolveNs = resolveMap.NS = resolver('queryNs'); exports.resolveTxt = resolveMap.TXT = resolver('queryTxt'); exports.resolveSrv = resolveMap.SRV = resolver('querySrv'); exports.resolveNaptr = resolveMap.NAPTR = resolver('queryNaptr'); exports.reverse = resolveMap.PTR = resolver('getHostByAddr'); exports.resolve = function(domain, type_, callback_) { var resolver, callback; if (typeof type_ == 'string') { resolver = resolveMap[type_]; callback = callback_; } else { resolver = exports.resolve4; callback = type_; } if (typeof resolver === 'function') { return resolver(domain, callback); } else { throw new Error('Unknown type "' + type_ + '"'); } }; // ERROR CODES exports.NODATA = 'ENODATA'; exports.FORMERR = 'EFORMERR'; exports.SERVFAIL = 'ESERVFAIL'; exports.NOTFOUND = 'ENOTFOUND'; exports.NOTIMP = 'ENOTIMP'; exports.REFUSED = 'EREFUSED'; exports.BADQUERY = 'EBADQUERY'; exports.ADNAME = 'EADNAME'; exports.BADFAMILY = 'EBADFAMILY'; exports.BADRESP = 'EBADRESP'; exports.CONNREFUSED = 'ECONNREFUSED'; exports.TIMEOUT = 'ETIMEOUT'; exports.EOF = 'EOF'; exports.FILE = 'EFILE'; exports.NOMEM = 'ENOMEM'; exports.DESTRUCTION = 'EDESTRUCTION'; exports.BADSTR = 'EBADSTR'; exports.BADFLAGS = 'EBADFLAGS'; exports.NONAME = 'ENONAME'; exports.BADHINTS = 'EBADHINTS'; exports.NOTINITIALIZED = 'ENOTINITIALIZED'; exports.LOADIPHLPAPI = 'ELOADIPHLPAPI'; exports.ADDRGETNETWORKPARAMS = 'EADDRGETNETWORKPARAMS'; exports.CANCELLED = 'ECANCELLED'; node-v0.10.25~dfsg2/lib/_linklist.js0000644000000000000000000000414712270121457015717 0ustar rootroot// Copyright Joyent, Inc. and other Node contributors. // // Permission is hereby granted, free of charge, to any person obtaining a // copy of this software and associated documentation files (the // "Software"), to deal in the Software without restriction, including // without limitation the rights to use, copy, modify, merge, publish, // distribute, sublicense, and/or sell copies of the Software, and to permit // persons to whom the Software is furnished to do so, subject to the // following conditions: // // The above copyright notice and this permission notice shall be included // in all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS // OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF // MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN // NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, // DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR // OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE // USE OR OTHER DEALINGS IN THE SOFTWARE. function init(list) { list._idleNext = list; list._idlePrev = list; } exports.init = init; // show the most idle item function peek(list) { if (list._idlePrev == list) return null; return list._idlePrev; } exports.peek = peek; // remove the most idle item from the list function shift(list) { var first = list._idlePrev; remove(first); return first; } exports.shift = shift; // remove a item from its list function remove(item) { if (item._idleNext) { item._idleNext._idlePrev = item._idlePrev; } if (item._idlePrev) { item._idlePrev._idleNext = item._idleNext; } item._idleNext = null; item._idlePrev = null; } exports.remove = remove; // remove a item from its list and place at the end. function append(list, item) { remove(item); item._idleNext = list._idleNext; list._idleNext._idlePrev = item; item._idlePrev = list; list._idleNext = item; } exports.append = append; function isEmpty(list) { return list._idleNext === list; } exports.isEmpty = isEmpty; node-v0.10.25~dfsg2/lib/string_decoder.js0000644000000000000000000001336712270121457016726 0ustar rootroot// Copyright Joyent, Inc. and other Node contributors. // // Permission is hereby granted, free of charge, to any person obtaining a // copy of this software and associated documentation files (the // "Software"), to deal in the Software without restriction, including // without limitation the rights to use, copy, modify, merge, publish, // distribute, sublicense, and/or sell copies of the Software, and to permit // persons to whom the Software is furnished to do so, subject to the // following conditions: // // The above copyright notice and this permission notice shall be included // in all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS // OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF // MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN // NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, // DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR // OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE // USE OR OTHER DEALINGS IN THE SOFTWARE. function assertEncoding(encoding) { if (encoding && !Buffer.isEncoding(encoding)) { throw new Error('Unknown encoding: ' + encoding); } } var StringDecoder = exports.StringDecoder = function(encoding) { this.encoding = (encoding || 'utf8').toLowerCase().replace(/[-_]/, ''); assertEncoding(encoding); switch (this.encoding) { case 'utf8': // CESU-8 represents each of Surrogate Pair by 3-bytes this.surrogateSize = 3; break; case 'ucs2': case 'utf16le': // UTF-16 represents each of Surrogate Pair by 2-bytes this.surrogateSize = 2; this.detectIncompleteChar = utf16DetectIncompleteChar; break; case 'base64': // Base-64 stores 3 bytes in 4 chars, and pads the remainder. this.surrogateSize = 3; this.detectIncompleteChar = base64DetectIncompleteChar; break; default: this.write = passThroughWrite; return; } this.charBuffer = new Buffer(6); this.charReceived = 0; this.charLength = 0; }; StringDecoder.prototype.write = function(buffer) { var charStr = ''; var offset = 0; // if our last write ended with an incomplete multibyte character while (this.charLength) { // determine how many remaining bytes this buffer has to offer for this char var i = (buffer.length >= this.charLength - this.charReceived) ? this.charLength - this.charReceived : buffer.length; // add the new bytes to the char buffer buffer.copy(this.charBuffer, this.charReceived, offset, i); this.charReceived += (i - offset); offset = i; if (this.charReceived < this.charLength) { // still not enough chars in this buffer? wait for more ... return ''; } // get the character that was split charStr = this.charBuffer.slice(0, this.charLength).toString(this.encoding); // lead surrogate (D800-DBFF) is also the incomplete character var charCode = charStr.charCodeAt(charStr.length - 1); if (charCode >= 0xD800 && charCode <= 0xDBFF) { this.charLength += this.surrogateSize; charStr = ''; continue; } this.charReceived = this.charLength = 0; // if there are no more bytes in this buffer, just emit our char if (i == buffer.length) return charStr; // otherwise cut off the characters end from the beginning of this buffer buffer = buffer.slice(i, buffer.length); break; } var lenIncomplete = this.detectIncompleteChar(buffer); var end = buffer.length; if (this.charLength) { // buffer the incomplete character bytes we got buffer.copy(this.charBuffer, 0, buffer.length - lenIncomplete, end); this.charReceived = lenIncomplete; end -= lenIncomplete; } charStr += buffer.toString(this.encoding, 0, end); var end = charStr.length - 1; var charCode = charStr.charCodeAt(end); // lead surrogate (D800-DBFF) is also the incomplete character if (charCode >= 0xD800 && charCode <= 0xDBFF) { var size = this.surrogateSize; this.charLength += size; this.charReceived += size; this.charBuffer.copy(this.charBuffer, size, 0, size); this.charBuffer.write(charStr.charAt(charStr.length - 1), this.encoding); return charStr.substring(0, end); } // or just emit the charStr return charStr; }; StringDecoder.prototype.detectIncompleteChar = function(buffer) { // determine how many bytes we have to check at the end of this buffer var i = (buffer.length >= 3) ? 3 : buffer.length; // Figure out if one of the last i bytes of our buffer announces an // incomplete char. for (; i > 0; i--) { var c = buffer[buffer.length - i]; // See http://en.wikipedia.org/wiki/UTF-8#Description // 110XXXXX if (i == 1 && c >> 5 == 0x06) { this.charLength = 2; break; } // 1110XXXX if (i <= 2 && c >> 4 == 0x0E) { this.charLength = 3; break; } // 11110XXX if (i <= 3 && c >> 3 == 0x1E) { this.charLength = 4; break; } } return i; }; StringDecoder.prototype.end = function(buffer) { var res = ''; if (buffer && buffer.length) res = this.write(buffer); if (this.charReceived) { var cr = this.charReceived; var buf = this.charBuffer; var enc = this.encoding; res += buf.slice(0, cr).toString(enc); } return res; }; function passThroughWrite(buffer) { return buffer.toString(this.encoding); } function utf16DetectIncompleteChar(buffer) { var incomplete = this.charReceived = buffer.length % 2; this.charLength = incomplete ? 2 : 0; return incomplete; } function base64DetectIncompleteChar(buffer) { var incomplete = this.charReceived = buffer.length % 3; this.charLength = incomplete ? 3 : 0; return incomplete; } node-v0.10.25~dfsg2/lib/_stream_transform.js0000644000000000000000000001621612270121457017454 0ustar rootroot// Copyright Joyent, Inc. and other Node contributors. // // Permission is hereby granted, free of charge, to any person obtaining a // copy of this software and associated documentation files (the // "Software"), to deal in the Software without restriction, including // without limitation the rights to use, copy, modify, merge, publish, // distribute, sublicense, and/or sell copies of the Software, and to permit // persons to whom the Software is furnished to do so, subject to the // following conditions: // // The above copyright notice and this permission notice shall be included // in all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS // OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF // MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN // NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, // DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR // OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE // USE OR OTHER DEALINGS IN THE SOFTWARE. // a transform stream is a readable/writable stream where you do // something with the data. Sometimes it's called a "filter", // but that's not a great name for it, since that implies a thing where // some bits pass through, and others are simply ignored. (That would // be a valid example of a transform, of course.) // // While the output is causally related to the input, it's not a // necessarily symmetric or synchronous transformation. For example, // a zlib stream might take multiple plain-text writes(), and then // emit a single compressed chunk some time in the future. // // Here's how this works: // // The Transform stream has all the aspects of the readable and writable // stream classes. When you write(chunk), that calls _write(chunk,cb) // internally, and returns false if there's a lot of pending writes // buffered up. When you call read(), that calls _read(n) until // there's enough pending readable data buffered up. // // In a transform stream, the written data is placed in a buffer. When // _read(n) is called, it transforms the queued up data, calling the // buffered _write cb's as it consumes chunks. If consuming a single // written chunk would result in multiple output chunks, then the first // outputted bit calls the readcb, and subsequent chunks just go into // the read buffer, and will cause it to emit 'readable' if necessary. // // This way, back-pressure is actually determined by the reading side, // since _read has to be called to start processing a new chunk. However, // a pathological inflate type of transform can cause excessive buffering // here. For example, imagine a stream where every byte of input is // interpreted as an integer from 0-255, and then results in that many // bytes of output. Writing the 4 bytes {ff,ff,ff,ff} would result in // 1kb of data being output. In this case, you could write a very small // amount of input, and end up with a very large amount of output. In // such a pathological inflating mechanism, there'd be no way to tell // the system to stop doing the transform. A single 4MB write could // cause the system to run out of memory. // // However, even in such a pathological case, only a single written chunk // would be consumed, and then the rest would wait (un-transformed) until // the results of the previous transformed chunk were consumed. module.exports = Transform; var Duplex = require('_stream_duplex'); var util = require('util'); util.inherits(Transform, Duplex); function TransformState(options, stream) { this.afterTransform = function(er, data) { return afterTransform(stream, er, data); }; this.needTransform = false; this.transforming = false; this.writecb = null; this.writechunk = null; } function afterTransform(stream, er, data) { var ts = stream._transformState; ts.transforming = false; var cb = ts.writecb; if (!cb) return stream.emit('error', new Error('no writecb in Transform class')); ts.writechunk = null; ts.writecb = null; if (data !== null && data !== undefined) stream.push(data); if (cb) cb(er); var rs = stream._readableState; rs.reading = false; if (rs.needReadable || rs.length < rs.highWaterMark) { stream._read(rs.highWaterMark); } } function Transform(options) { if (!(this instanceof Transform)) return new Transform(options); Duplex.call(this, options); var ts = this._transformState = new TransformState(options, this); // when the writable side finishes, then flush out anything remaining. var stream = this; // start out asking for a readable event once data is transformed. this._readableState.needReadable = true; // we have implemented the _read method, and done the other things // that Readable wants before the first _read call, so unset the // sync guard flag. this._readableState.sync = false; this.once('finish', function() { if ('function' === typeof this._flush) this._flush(function(er) { done(stream, er); }); else done(stream); }); } Transform.prototype.push = function(chunk, encoding) { this._transformState.needTransform = false; return Duplex.prototype.push.call(this, chunk, encoding); }; // This is the part where you do stuff! // override this function in implementation classes. // 'chunk' is an input chunk. // // Call `push(newChunk)` to pass along transformed output // to the readable side. You may call 'push' zero or more times. // // Call `cb(err)` when you are done with this chunk. If you pass // an error, then that'll put the hurt on the whole operation. If you // never call cb(), then you'll never get another chunk. Transform.prototype._transform = function(chunk, encoding, cb) { throw new Error('not implemented'); }; Transform.prototype._write = function(chunk, encoding, cb) { var ts = this._transformState; ts.writecb = cb; ts.writechunk = chunk; ts.writeencoding = encoding; if (!ts.transforming) { var rs = this._readableState; if (ts.needTransform || rs.needReadable || rs.length < rs.highWaterMark) this._read(rs.highWaterMark); } }; // Doesn't matter what the args are here. // _transform does all the work. // That we got here means that the readable side wants more data. Transform.prototype._read = function(n) { var ts = this._transformState; if (ts.writechunk !== null && ts.writecb && !ts.transforming) { ts.transforming = true; this._transform(ts.writechunk, ts.writeencoding, ts.afterTransform); } else { // mark that we need a transform, so that any data that comes in // will get processed, now that we've asked for it. ts.needTransform = true; } }; function done(stream, er) { if (er) return stream.emit('error', er); // if there's nothing in the write buffer, then that means // that nothing more will ever be provided var ws = stream._writableState; var rs = stream._readableState; var ts = stream._transformState; if (ws.length) throw new Error('calling transform done when ws.length != 0'); if (ts.transforming) throw new Error('calling transform done when still transforming'); return stream.push(null); } node-v0.10.25~dfsg2/lib/assert.js0000644000000000000000000002501212270121457015222 0ustar rootroot// http://wiki.commonjs.org/wiki/Unit_Testing/1.0 // // THIS IS NOT TESTED NOR LIKELY TO WORK OUTSIDE V8! // // Originally from narwhal.js (http://narwhaljs.org) // Copyright (c) 2009 Thomas Robinson <280north.com> // // Permission is hereby granted, free of charge, to any person obtaining a copy // of this software and associated documentation files (the 'Software'), to // deal in the Software without restriction, including without limitation the // rights to use, copy, modify, merge, publish, distribute, sublicense, and/or // sell copies of the Software, and to permit persons to whom the Software is // furnished to do so, subject to the following conditions: // // The above copyright notice and this permission notice shall be included in // all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED 'AS IS', WITHOUT WARRANTY OF ANY KIND, EXPRESS OR // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE // AUTHORS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN // ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION // WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. // UTILITY var util = require('util'); var pSlice = Array.prototype.slice; // 1. The assert module provides functions that throw // AssertionError's when particular conditions are not met. The // assert module must conform to the following interface. var assert = module.exports = ok; // 2. The AssertionError is defined in assert. // new assert.AssertionError({ message: message, // actual: actual, // expected: expected }) assert.AssertionError = function AssertionError(options) { this.name = 'AssertionError'; this.actual = options.actual; this.expected = options.expected; this.operator = options.operator; this.message = options.message || getMessage(this); var stackStartFunction = options.stackStartFunction || fail; Error.captureStackTrace(this, stackStartFunction); }; // assert.AssertionError instanceof Error util.inherits(assert.AssertionError, Error); function replacer(key, value) { if (value === undefined) { return '' + value; } if (typeof value === 'number' && (isNaN(value) || !isFinite(value))) { return value.toString(); } if (typeof value === 'function' || value instanceof RegExp) { return value.toString(); } return value; } function truncate(s, n) { if (typeof s == 'string') { return s.length < n ? s : s.slice(0, n); } else { return s; } } function getMessage(self) { return truncate(JSON.stringify(self.actual, replacer), 128) + ' ' + self.operator + ' ' + truncate(JSON.stringify(self.expected, replacer), 128); } // At present only the three keys mentioned above are used and // understood by the spec. Implementations or sub modules can pass // other keys to the AssertionError's constructor - they will be // ignored. // 3. All of the following functions must throw an AssertionError // when a corresponding condition is not met, with a message that // may be undefined if not provided. All assertion methods provide // both the actual and expected values to the assertion error for // display purposes. function fail(actual, expected, message, operator, stackStartFunction) { throw new assert.AssertionError({ message: message, actual: actual, expected: expected, operator: operator, stackStartFunction: stackStartFunction }); } // EXTENSION! allows for well behaved errors defined elsewhere. assert.fail = fail; // 4. Pure assertion tests whether a value is truthy, as determined // by !!guard. // assert.ok(guard, message_opt); // This statement is equivalent to assert.equal(true, !!guard, // message_opt);. To test strictly for the value true, use // assert.strictEqual(true, guard, message_opt);. function ok(value, message) { if (!!!value) fail(value, true, message, '==', assert.ok); } assert.ok = ok; // 5. The equality assertion tests shallow, coercive equality with // ==. // assert.equal(actual, expected, message_opt); assert.equal = function equal(actual, expected, message) { if (actual != expected) fail(actual, expected, message, '==', assert.equal); }; // 6. The non-equality assertion tests for whether two objects are not equal // with != assert.notEqual(actual, expected, message_opt); assert.notEqual = function notEqual(actual, expected, message) { if (actual == expected) { fail(actual, expected, message, '!=', assert.notEqual); } }; // 7. The equivalence assertion tests a deep equality relation. // assert.deepEqual(actual, expected, message_opt); assert.deepEqual = function deepEqual(actual, expected, message) { if (!_deepEqual(actual, expected)) { fail(actual, expected, message, 'deepEqual', assert.deepEqual); } }; function _deepEqual(actual, expected) { // 7.1. All identical values are equivalent, as determined by ===. if (actual === expected) { return true; } else if (Buffer.isBuffer(actual) && Buffer.isBuffer(expected)) { if (actual.length != expected.length) return false; for (var i = 0; i < actual.length; i++) { if (actual[i] !== expected[i]) return false; } return true; // 7.2. If the expected value is a Date object, the actual value is // equivalent if it is also a Date object that refers to the same time. } else if (actual instanceof Date && expected instanceof Date) { return actual.getTime() === expected.getTime(); // 7.3 If the expected value is a RegExp object, the actual value is // equivalent if it is also a RegExp object with the same source and // properties (`global`, `multiline`, `lastIndex`, `ignoreCase`). } else if (actual instanceof RegExp && expected instanceof RegExp) { return actual.source === expected.source && actual.global === expected.global && actual.multiline === expected.multiline && actual.lastIndex === expected.lastIndex && actual.ignoreCase === expected.ignoreCase; // 7.4. Other pairs that do not both pass typeof value == 'object', // equivalence is determined by ==. } else if (typeof actual != 'object' && typeof expected != 'object') { return actual == expected; // 7.5 For all other Object pairs, including Array objects, equivalence is // determined by having the same number of owned properties (as verified // with Object.prototype.hasOwnProperty.call), the same set of keys // (although not necessarily the same order), equivalent values for every // corresponding key, and an identical 'prototype' property. Note: this // accounts for both named and indexed properties on Arrays. } else { return objEquiv(actual, expected); } } function isUndefinedOrNull(value) { return value === null || value === undefined; } function isArguments(object) { return Object.prototype.toString.call(object) == '[object Arguments]'; } function objEquiv(a, b) { if (isUndefinedOrNull(a) || isUndefinedOrNull(b)) return false; // an identical 'prototype' property. if (a.prototype !== b.prototype) return false; //~~~I've managed to break Object.keys through screwy arguments passing. // Converting to array solves the problem. if (isArguments(a)) { if (!isArguments(b)) { return false; } a = pSlice.call(a); b = pSlice.call(b); return _deepEqual(a, b); } try { var ka = Object.keys(a), kb = Object.keys(b), key, i; } catch (e) {//happens when one is a string literal and the other isn't return false; } // having the same number of owned properties (keys incorporates // hasOwnProperty) if (ka.length != kb.length) return false; //the same set of keys (although not necessarily the same order), ka.sort(); kb.sort(); //~~~cheap key test for (i = ka.length - 1; i >= 0; i--) { if (ka[i] != kb[i]) return false; } //equivalent values for every corresponding key, and //~~~possibly expensive deep test for (i = ka.length - 1; i >= 0; i--) { key = ka[i]; if (!_deepEqual(a[key], b[key])) return false; } return true; } // 8. The non-equivalence assertion tests for any deep inequality. // assert.notDeepEqual(actual, expected, message_opt); assert.notDeepEqual = function notDeepEqual(actual, expected, message) { if (_deepEqual(actual, expected)) { fail(actual, expected, message, 'notDeepEqual', assert.notDeepEqual); } }; // 9. The strict equality assertion tests strict equality, as determined by ===. // assert.strictEqual(actual, expected, message_opt); assert.strictEqual = function strictEqual(actual, expected, message) { if (actual !== expected) { fail(actual, expected, message, '===', assert.strictEqual); } }; // 10. The strict non-equality assertion tests for strict inequality, as // determined by !==. assert.notStrictEqual(actual, expected, message_opt); assert.notStrictEqual = function notStrictEqual(actual, expected, message) { if (actual === expected) { fail(actual, expected, message, '!==', assert.notStrictEqual); } }; function expectedException(actual, expected) { if (!actual || !expected) { return false; } if (Object.prototype.toString.call(expected) == '[object RegExp]') { return expected.test(actual); } else if (actual instanceof expected) { return true; } else if (expected.call({}, actual) === true) { return true; } return false; } function _throws(shouldThrow, block, expected, message) { var actual; if (typeof expected === 'string') { message = expected; expected = null; } try { block(); } catch (e) { actual = e; } message = (expected && expected.name ? ' (' + expected.name + ').' : '.') + (message ? ' ' + message : '.'); if (shouldThrow && !actual) { fail(actual, expected, 'Missing expected exception' + message); } if (!shouldThrow && expectedException(actual, expected)) { fail(actual, expected, 'Got unwanted exception' + message); } if ((shouldThrow && actual && expected && !expectedException(actual, expected)) || (!shouldThrow && actual)) { throw actual; } } // 11. Expected to throw an error: // assert.throws(block, Error_opt, message_opt); assert.throws = function(block, /*optional*/error, /*optional*/message) { _throws.apply(this, [true].concat(pSlice.call(arguments))); }; // EXTENSION! This is annoying to write outside this module. assert.doesNotThrow = function(block, /*optional*/message) { _throws.apply(this, [false].concat(pSlice.call(arguments))); }; assert.ifError = function(err) { if (err) {throw err;}}; node-v0.10.25~dfsg2/lib/readline.js0000644000000000000000000007332112270121457015512 0ustar rootroot// Copyright Joyent, Inc. and other Node contributors. // // Permission is hereby granted, free of charge, to any person obtaining a // copy of this software and associated documentation files (the // "Software"), to deal in the Software without restriction, including // without limitation the rights to use, copy, modify, merge, publish, // distribute, sublicense, and/or sell copies of the Software, and to permit // persons to whom the Software is furnished to do so, subject to the // following conditions: // // The above copyright notice and this permission notice shall be included // in all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS // OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF // MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN // NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, // DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR // OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE // USE OR OTHER DEALINGS IN THE SOFTWARE. // Inspiration for this code comes from Salvatore Sanfilippo's linenoise. // https://github.com/antirez/linenoise // Reference: // * http://invisible-island.net/xterm/ctlseqs/ctlseqs.html // * http://www.3waylabs.com/nw/WWW/products/wizcon/vt220.html var kHistorySize = 30; var kBufSize = 10 * 1024; var util = require('util'); var inherits = require('util').inherits; var EventEmitter = require('events').EventEmitter; exports.createInterface = function(input, output, completer, terminal) { var rl; if (arguments.length === 1) { rl = new Interface(input); } else { rl = new Interface(input, output, completer, terminal); } return rl; }; function Interface(input, output, completer, terminal) { if (!(this instanceof Interface)) { return new Interface(input, output, completer, terminal); } this._sawReturn = false; EventEmitter.call(this); if (arguments.length === 1) { // an options object was given output = input.output; completer = input.completer; terminal = input.terminal; input = input.input; } completer = completer || function() { return []; }; if (typeof completer !== 'function') { throw new TypeError('Argument \'completer\' must be a function'); } // backwards compat; check the isTTY prop of the output stream // when `terminal` was not specified if (typeof terminal == 'undefined') { terminal = !!output.isTTY; } var self = this; this.output = output; this.input = input; // Check arity, 2 - for async, 1 for sync this.completer = completer.length === 2 ? completer : function(v, callback) { callback(null, completer(v)); }; this.setPrompt('> '); this.terminal = !!terminal; function ondata(data) { self._normalWrite(data); } function onend() { self.close(); } function onkeypress(s, key) { self._ttyWrite(s, key); } function onresize() { self._refreshLine(); } if (!this.terminal) { input.on('data', ondata); input.on('end', onend); self.once('close', function() { input.removeListener('data', ondata); input.removeListener('end', onend); }); var StringDecoder = require('string_decoder').StringDecoder; // lazy load this._decoder = new StringDecoder('utf8'); } else { exports.emitKeypressEvents(input); // input usually refers to stdin input.on('keypress', onkeypress); // Current line this.line = ''; this._setRawMode(true); this.terminal = true; // Cursor position on the line. this.cursor = 0; this.history = []; this.historyIndex = -1; output.on('resize', onresize); self.once('close', function() { input.removeListener('keypress', onkeypress); output.removeListener('resize', onresize); }); } input.resume(); } inherits(Interface, EventEmitter); Interface.prototype.__defineGetter__('columns', function() { return this.output.columns || Infinity; }); Interface.prototype.setPrompt = function(prompt, length) { this._prompt = prompt; if (length) { this._promptLength = length; } else { var lines = prompt.split(/[\r\n]/); var lastLine = lines[lines.length - 1]; this._promptLength = lastLine.length; } }; Interface.prototype._setRawMode = function(mode) { if (typeof this.input.setRawMode === 'function') { return this.input.setRawMode(mode); } }; Interface.prototype.prompt = function(preserveCursor) { if (this.paused) this.resume(); if (this.terminal) { if (!preserveCursor) this.cursor = 0; this._refreshLine(); } else { this.output.write(this._prompt); } }; Interface.prototype.question = function(query, cb) { if (typeof cb === 'function') { if (this._questionCallback) { this.prompt(); } else { this._oldPrompt = this._prompt; this.setPrompt(query); this._questionCallback = cb; this.prompt(); } } }; Interface.prototype._onLine = function(line) { if (this._questionCallback) { var cb = this._questionCallback; this._questionCallback = null; this.setPrompt(this._oldPrompt); cb(line); } else { this.emit('line', line); } }; Interface.prototype._addHistory = function() { if (this.line.length === 0) return ''; if (this.history.length === 0 || this.history[0] !== this.line) { this.history.unshift(this.line); // Only store so many if (this.history.length > kHistorySize) this.history.pop(); } this.historyIndex = -1; return this.history[0]; }; Interface.prototype._refreshLine = function() { var columns = this.columns; // line length var line = this._prompt + this.line; var lineLength = line.length; var lineCols = lineLength % columns; var lineRows = (lineLength - lineCols) / columns; // cursor position var cursorPos = this._getCursorPos(); // first move to the bottom of the current line, based on cursor pos var prevRows = this.prevRows || 0; if (prevRows > 0) { exports.moveCursor(this.output, 0, -prevRows); } // Cursor to left edge. exports.cursorTo(this.output, 0); // erase data exports.clearScreenDown(this.output); // Write the prompt and the current buffer content. this.output.write(line); // Force terminal to allocate a new line if (lineCols === 0) { this.output.write(' '); } // Move cursor to original position. exports.cursorTo(this.output, cursorPos.cols); var diff = lineRows - cursorPos.rows; if (diff > 0) { exports.moveCursor(this.output, 0, -diff); } this.prevRows = cursorPos.rows; }; Interface.prototype.close = function() { if (this.closed) return; this.pause(); if (this.terminal) { this._setRawMode(false); } this.closed = true; this.emit('close'); }; Interface.prototype.pause = function() { if (this.paused) return; this.input.pause(); this.paused = true; this.emit('pause'); }; Interface.prototype.resume = function() { if (!this.paused) return; this.input.resume(); this.paused = false; this.emit('resume'); }; Interface.prototype.write = function(d, key) { if (this.paused) this.resume(); this.terminal ? this._ttyWrite(d, key) : this._normalWrite(d); }; // \r\n, \n, or \r followed by something other than \n var lineEnding = /\r?\n|\r(?!\n)/; Interface.prototype._normalWrite = function(b) { if (b === undefined) { return; } var string = this._decoder.write(b); if (this._sawReturn) { string = string.replace(/^\n/, ''); this._sawReturn = false; } if (this._line_buffer) { string = this._line_buffer + string; this._line_buffer = null; } if (lineEnding.test(string)) { this._sawReturn = /\r$/.test(string); // got one or more newlines; process into "line" events var lines = string.split(lineEnding); // either '' or (concievably) the unfinished portion of the next line string = lines.pop(); this._line_buffer = string; lines.forEach(function(line) { this._onLine(line); }, this); } else if (string) { // no newlines this time, save what we have for next time this._line_buffer = string; } }; Interface.prototype._insertString = function(c) { //BUG: Problem when adding tabs with following content. // Perhaps the bug is in _refreshLine(). Not sure. // A hack would be to insert spaces instead of literal '\t'. if (this.cursor < this.line.length) { var beg = this.line.slice(0, this.cursor); var end = this.line.slice(this.cursor, this.line.length); this.line = beg + c + end; this.cursor += c.length; this._refreshLine(); } else { this.line += c; this.cursor += c.length; if (this._getCursorPos().cols === 0) { this._refreshLine(); } else { this.output.write(c); } // a hack to get the line refreshed if it's needed this._moveCursor(0); } }; Interface.prototype._tabComplete = function() { var self = this; self.pause(); self.completer(self.line.slice(0, self.cursor), function(err, rv) { self.resume(); if (err) { // XXX Log it somewhere? return; } var completions = rv[0], completeOn = rv[1]; // the text that was completed if (completions && completions.length) { // Apply/show completions. if (completions.length === 1) { self._insertString(completions[0].slice(completeOn.length)); } else { self.output.write('\r\n'); var width = completions.reduce(function(a, b) { return a.length > b.length ? a : b; }).length + 2; // 2 space padding var maxColumns = Math.floor(self.columns / width) || 1; var group = [], c; for (var i = 0, compLen = completions.length; i < compLen; i++) { c = completions[i]; if (c === '') { handleGroup(self, group, width, maxColumns); group = []; } else { group.push(c); } } handleGroup(self, group, width, maxColumns); // If there is a common prefix to all matches, then apply that // portion. var f = completions.filter(function(e) { if (e) return e; }); var prefix = commonPrefix(f); if (prefix.length > completeOn.length) { self._insertString(prefix.slice(completeOn.length)); } } self._refreshLine(); } }); }; // this = Interface instance function handleGroup(self, group, width, maxColumns) { if (group.length == 0) { return; } var minRows = Math.ceil(group.length / maxColumns); for (var row = 0; row < minRows; row++) { for (var col = 0; col < maxColumns; col++) { var idx = row * maxColumns + col; if (idx >= group.length) { break; } var item = group[idx]; self.output.write(item); if (col < maxColumns - 1) { for (var s = 0, itemLen = item.length; s < width - itemLen; s++) { self.output.write(' '); } } } self.output.write('\r\n'); } self.output.write('\r\n'); } function commonPrefix(strings) { if (!strings || strings.length == 0) { return ''; } var sorted = strings.slice().sort(); var min = sorted[0]; var max = sorted[sorted.length - 1]; for (var i = 0, len = min.length; i < len; i++) { if (min[i] != max[i]) { return min.slice(0, i); } } return min; } Interface.prototype._wordLeft = function() { if (this.cursor > 0) { var leading = this.line.slice(0, this.cursor); var match = leading.match(/([^\w\s]+|\w+|)\s*$/); this._moveCursor(-match[0].length); } }; Interface.prototype._wordRight = function() { if (this.cursor < this.line.length) { var trailing = this.line.slice(this.cursor); var match = trailing.match(/^(\s+|\W+|\w+)\s*/); this._moveCursor(match[0].length); } }; Interface.prototype._deleteLeft = function() { if (this.cursor > 0 && this.line.length > 0) { this.line = this.line.slice(0, this.cursor - 1) + this.line.slice(this.cursor, this.line.length); this.cursor--; this._refreshLine(); } }; Interface.prototype._deleteRight = function() { this.line = this.line.slice(0, this.cursor) + this.line.slice(this.cursor + 1, this.line.length); this._refreshLine(); }; Interface.prototype._deleteWordLeft = function() { if (this.cursor > 0) { var leading = this.line.slice(0, this.cursor); var match = leading.match(/([^\w\s]+|\w+|)\s*$/); leading = leading.slice(0, leading.length - match[0].length); this.line = leading + this.line.slice(this.cursor, this.line.length); this.cursor = leading.length; this._refreshLine(); } }; Interface.prototype._deleteWordRight = function() { if (this.cursor < this.line.length) { var trailing = this.line.slice(this.cursor); var match = trailing.match(/^(\s+|\W+|\w+)\s*/); this.line = this.line.slice(0, this.cursor) + trailing.slice(match[0].length); this._refreshLine(); } }; Interface.prototype._deleteLineLeft = function() { this.line = this.line.slice(this.cursor); this.cursor = 0; this._refreshLine(); }; Interface.prototype._deleteLineRight = function() { this.line = this.line.slice(0, this.cursor); this._refreshLine(); }; Interface.prototype.clearLine = function() { this._moveCursor(+Infinity); this.output.write('\r\n'); this.line = ''; this.cursor = 0; this.prevRows = 0; }; Interface.prototype._line = function() { var line = this._addHistory(); this.clearLine(); this._onLine(line); }; Interface.prototype._historyNext = function() { if (this.historyIndex > 0) { this.historyIndex--; this.line = this.history[this.historyIndex]; this.cursor = this.line.length; // set cursor to end of line. this._refreshLine(); } else if (this.historyIndex === 0) { this.historyIndex = -1; this.cursor = 0; this.line = ''; this._refreshLine(); } }; Interface.prototype._historyPrev = function() { if (this.historyIndex + 1 < this.history.length) { this.historyIndex++; this.line = this.history[this.historyIndex]; this.cursor = this.line.length; // set cursor to end of line. this._refreshLine(); } }; // Returns current cursor's position and line Interface.prototype._getCursorPos = function() { var columns = this.columns; var cursorPos = this.cursor + this._promptLength; var cols = cursorPos % columns; var rows = (cursorPos - cols) / columns; return {cols: cols, rows: rows}; }; // This function moves cursor dx places to the right // (-dx for left) and refreshes the line if it is needed Interface.prototype._moveCursor = function(dx) { var oldcursor = this.cursor; var oldPos = this._getCursorPos(); this.cursor += dx; // bounds check if (this.cursor < 0) this.cursor = 0; if (this.cursor > this.line.length) this.cursor = this.line.length; var newPos = this._getCursorPos(); // check if cursors are in the same line if (oldPos.rows === newPos.rows) { exports.moveCursor(this.output, this.cursor - oldcursor, 0); this.prevRows = newPos.rows; } else { this._refreshLine(); } }; // handle a write from the tty Interface.prototype._ttyWrite = function(s, key) { key = key || {}; // Ignore escape key - Fixes #2876 if (key.name == 'escape') return; if (key.ctrl && key.shift) { /* Control and shift pressed */ switch (key.name) { case 'backspace': this._deleteLineLeft(); break; case 'delete': this._deleteLineRight(); break; } } else if (key.ctrl) { /* Control key pressed */ switch (key.name) { case 'c': if (EventEmitter.listenerCount(this, 'SIGINT') > 0) { this.emit('SIGINT'); } else { // This readline instance is finished this.close(); } break; case 'h': // delete left this._deleteLeft(); break; case 'd': // delete right or EOF if (this.cursor === 0 && this.line.length === 0) { // This readline instance is finished this.close(); } else if (this.cursor < this.line.length) { this._deleteRight(); } break; case 'u': // delete the whole line this.cursor = 0; this.line = ''; this._refreshLine(); break; case 'k': // delete from current to end of line this._deleteLineRight(); break; case 'a': // go to the start of the line this._moveCursor(-Infinity); break; case 'e': // go to the end of the line this._moveCursor(+Infinity); break; case 'b': // back one character this._moveCursor(-1); break; case 'f': // forward one character this._moveCursor(+1); break; case 'l': // clear the whole screen exports.cursorTo(this.output, 0, 0); exports.clearScreenDown(this.output); this._refreshLine(); break; case 'n': // next history item this._historyNext(); break; case 'p': // previous history item this._historyPrev(); break; case 'z': if (process.platform == 'win32') break; if (EventEmitter.listenerCount(this, 'SIGTSTP') > 0) { this.emit('SIGTSTP'); } else { process.once('SIGCONT', (function(self) { return function() { // Don't raise events if stream has already been abandoned. if (!self.paused) { // Stream must be paused and resumed after SIGCONT to catch // SIGINT, SIGTSTP, and EOF. self.pause(); self.emit('SIGCONT'); } // explictly re-enable "raw mode" and move the cursor to // the correct position. // See https://github.com/joyent/node/issues/3295. self._setRawMode(true); self._refreshLine(); }; })(this)); this._setRawMode(false); process.kill(process.pid, 'SIGTSTP'); } break; case 'w': // delete backwards to a word boundary case 'backspace': this._deleteWordLeft(); break; case 'delete': // delete forward to a word boundary this._deleteWordRight(); break; case 'backspace': this._deleteWordLeft(); break; case 'left': this._wordLeft(); break; case 'right': this._wordRight(); break; } } else if (key.meta) { /* Meta key pressed */ switch (key.name) { case 'b': // backward word this._wordLeft(); break; case 'f': // forward word this._wordRight(); break; case 'd': // delete forward word case 'delete': this._deleteWordRight(); break; case 'backspace': // delete backwards to a word boundary this._deleteWordLeft(); break; } } else { /* No modifier keys used */ // \r bookkeeping is only relevant if a \n comes right after. if (this._sawReturn && key.name !== 'enter') this._sawReturn = false; switch (key.name) { case 'return': // carriage return, i.e. \r this._sawReturn = true; this._line(); break; case 'enter': if (this._sawReturn) this._sawReturn = false; else this._line(); break; case 'backspace': this._deleteLeft(); break; case 'delete': this._deleteRight(); break; case 'tab': // tab completion this._tabComplete(); break; case 'left': this._moveCursor(-1); break; case 'right': this._moveCursor(+1); break; case 'home': this._moveCursor(-Infinity); break; case 'end': this._moveCursor(+Infinity); break; case 'up': this._historyPrev(); break; case 'down': this._historyNext(); break; default: if (Buffer.isBuffer(s)) s = s.toString('utf-8'); if (s) { var lines = s.split(/\r\n|\n|\r/); for (var i = 0, len = lines.length; i < len; i++) { if (i > 0) { this._line(); } this._insertString(lines[i]); } } } } }; exports.Interface = Interface; /** * accepts a readable Stream instance and makes it emit "keypress" events */ function emitKeypressEvents(stream) { if (stream._keypressDecoder) return; var StringDecoder = require('string_decoder').StringDecoder; // lazy load stream._keypressDecoder = new StringDecoder('utf8'); function onData(b) { if (EventEmitter.listenerCount(stream, 'keypress') > 0) { var r = stream._keypressDecoder.write(b); if (r) emitKey(stream, r); } else { // Nobody's watching anyway stream.removeListener('data', onData); stream.on('newListener', onNewListener); } } function onNewListener(event) { if (event == 'keypress') { stream.on('data', onData); stream.removeListener('newListener', onNewListener); } } if (EventEmitter.listenerCount(stream, 'keypress') > 0) { stream.on('data', onData); } else { stream.on('newListener', onNewListener); } } exports.emitKeypressEvents = emitKeypressEvents; /* Some patterns seen in terminal key escape codes, derived from combos seen at http://www.midnight-commander.org/browser/lib/tty/key.c ESC letter ESC [ letter ESC [ modifier letter ESC [ 1 ; modifier letter ESC [ num char ESC [ num ; modifier char ESC O letter ESC O modifier letter ESC O 1 ; modifier letter ESC N letter ESC [ [ num ; modifier char ESC [ [ 1 ; modifier letter ESC ESC [ num char ESC ESC O letter - char is usually ~ but $ and ^ also happen with rxvt - modifier is 1 + (shift * 1) + (left_alt * 2) + (ctrl * 4) + (right_alt * 8) - two leading ESCs apparently mean the same as one leading ESC */ // Regexes used for ansi escape code splitting var metaKeyCodeRe = /^(?:\x1b)([a-zA-Z0-9])$/; var functionKeyCodeRe = /^(?:\x1b+)(O|N|\[|\[\[)(?:(\d+)(?:;(\d+))?([~^$])|(?:1;)?(\d+)?([a-zA-Z]))/; function emitKey(stream, s) { var ch, key = { name: undefined, ctrl: false, meta: false, shift: false }, parts; if (Buffer.isBuffer(s)) { if (s[0] > 127 && s[1] === undefined) { s[0] -= 128; s = '\x1b' + s.toString(stream.encoding || 'utf-8'); } else { s = s.toString(stream.encoding || 'utf-8'); } } key.sequence = s; if (s === '\r') { // carriage return key.name = 'return'; } else if (s === '\n') { // enter, should have been called linefeed key.name = 'enter'; } else if (s === '\t') { // tab key.name = 'tab'; } else if (s === '\b' || s === '\x7f' || s === '\x1b\x7f' || s === '\x1b\b') { // backspace or ctrl+h key.name = 'backspace'; key.meta = (s.charAt(0) === '\x1b'); } else if (s === '\x1b' || s === '\x1b\x1b') { // escape key key.name = 'escape'; key.meta = (s.length === 2); } else if (s === ' ' || s === '\x1b ') { key.name = 'space'; key.meta = (s.length === 2); } else if (s.length === 1 && s <= '\x1a') { // ctrl+letter key.name = String.fromCharCode(s.charCodeAt(0) + 'a'.charCodeAt(0) - 1); key.ctrl = true; } else if (s.length === 1 && s >= 'a' && s <= 'z') { // lowercase letter key.name = s; } else if (s.length === 1 && s >= 'A' && s <= 'Z') { // shift+letter key.name = s.toLowerCase(); key.shift = true; } else if (parts = metaKeyCodeRe.exec(s)) { // meta+character key key.name = parts[1].toLowerCase(); key.meta = true; key.shift = /^[A-Z]$/.test(parts[1]); } else if (parts = functionKeyCodeRe.exec(s)) { // ansi escape sequence // reassemble the key code leaving out leading \x1b's, // the modifier key bitflag and any meaningless "1;" sequence var code = (parts[1] || '') + (parts[2] || '') + (parts[4] || '') + (parts[6] || ''), modifier = (parts[3] || parts[5] || 1) - 1; // Parse the key modifier key.ctrl = !!(modifier & 4); key.meta = !!(modifier & 10); key.shift = !!(modifier & 1); key.code = code; // Parse the key itself switch (code) { /* xterm/gnome ESC O letter */ case 'OP': key.name = 'f1'; break; case 'OQ': key.name = 'f2'; break; case 'OR': key.name = 'f3'; break; case 'OS': key.name = 'f4'; break; /* xterm/rxvt ESC [ number ~ */ case '[11~': key.name = 'f1'; break; case '[12~': key.name = 'f2'; break; case '[13~': key.name = 'f3'; break; case '[14~': key.name = 'f4'; break; /* from Cygwin and used in libuv */ case '[[A': key.name = 'f1'; break; case '[[B': key.name = 'f2'; break; case '[[C': key.name = 'f3'; break; case '[[D': key.name = 'f4'; break; case '[[E': key.name = 'f5'; break; /* common */ case '[15~': key.name = 'f5'; break; case '[17~': key.name = 'f6'; break; case '[18~': key.name = 'f7'; break; case '[19~': key.name = 'f8'; break; case '[20~': key.name = 'f9'; break; case '[21~': key.name = 'f10'; break; case '[23~': key.name = 'f11'; break; case '[24~': key.name = 'f12'; break; /* xterm ESC [ letter */ case '[A': key.name = 'up'; break; case '[B': key.name = 'down'; break; case '[C': key.name = 'right'; break; case '[D': key.name = 'left'; break; case '[E': key.name = 'clear'; break; case '[F': key.name = 'end'; break; case '[H': key.name = 'home'; break; /* xterm/gnome ESC O letter */ case 'OA': key.name = 'up'; break; case 'OB': key.name = 'down'; break; case 'OC': key.name = 'right'; break; case 'OD': key.name = 'left'; break; case 'OE': key.name = 'clear'; break; case 'OF': key.name = 'end'; break; case 'OH': key.name = 'home'; break; /* xterm/rxvt ESC [ number ~ */ case '[1~': key.name = 'home'; break; case '[2~': key.name = 'insert'; break; case '[3~': key.name = 'delete'; break; case '[4~': key.name = 'end'; break; case '[5~': key.name = 'pageup'; break; case '[6~': key.name = 'pagedown'; break; /* putty */ case '[[5~': key.name = 'pageup'; break; case '[[6~': key.name = 'pagedown'; break; /* rxvt */ case '[7~': key.name = 'home'; break; case '[8~': key.name = 'end'; break; /* rxvt keys with modifiers */ case '[a': key.name = 'up'; key.shift = true; break; case '[b': key.name = 'down'; key.shift = true; break; case '[c': key.name = 'right'; key.shift = true; break; case '[d': key.name = 'left'; key.shift = true; break; case '[e': key.name = 'clear'; key.shift = true; break; case '[2$': key.name = 'insert'; key.shift = true; break; case '[3$': key.name = 'delete'; key.shift = true; break; case '[5$': key.name = 'pageup'; key.shift = true; break; case '[6$': key.name = 'pagedown'; key.shift = true; break; case '[7$': key.name = 'home'; key.shift = true; break; case '[8$': key.name = 'end'; key.shift = true; break; case 'Oa': key.name = 'up'; key.ctrl = true; break; case 'Ob': key.name = 'down'; key.ctrl = true; break; case 'Oc': key.name = 'right'; key.ctrl = true; break; case 'Od': key.name = 'left'; key.ctrl = true; break; case 'Oe': key.name = 'clear'; key.ctrl = true; break; case '[2^': key.name = 'insert'; key.ctrl = true; break; case '[3^': key.name = 'delete'; key.ctrl = true; break; case '[5^': key.name = 'pageup'; key.ctrl = true; break; case '[6^': key.name = 'pagedown'; key.ctrl = true; break; case '[7^': key.name = 'home'; key.ctrl = true; break; case '[8^': key.name = 'end'; key.ctrl = true; break; /* misc. */ case '[Z': key.name = 'tab'; key.shift = true; break; default: key.name = 'undefined'; break; } } else if (s.length > 1 && s[0] !== '\x1b') { // Got a longer-than-one string of characters. // Probably a paste, since it wasn't a control sequence. Array.prototype.forEach.call(s, function(c) { emitKey(stream, c); }); return; } // Don't emit a key if no name was found if (key.name === undefined) { key = undefined; } if (s.length === 1) { ch = s; } if (key || ch) { stream.emit('keypress', ch, key); } } /** * moves the cursor to the x and y coordinate on the given stream */ function cursorTo(stream, x, y) { if (typeof x !== 'number' && typeof y !== 'number') return; if (typeof x !== 'number') throw new Error("Can't set cursor row without also setting it's column"); if (typeof y !== 'number') { stream.write('\x1b[' + (x + 1) + 'G'); } else { stream.write('\x1b[' + (y + 1) + ';' + (x + 1) + 'H'); } } exports.cursorTo = cursorTo; /** * moves the cursor relative to its current location */ function moveCursor(stream, dx, dy) { if (dx < 0) { stream.write('\x1b[' + (-dx) + 'D'); } else if (dx > 0) { stream.write('\x1b[' + dx + 'C'); } if (dy < 0) { stream.write('\x1b[' + (-dy) + 'A'); } else if (dy > 0) { stream.write('\x1b[' + dy + 'B'); } } exports.moveCursor = moveCursor; /** * clears the current line the cursor is on: * -1 for left of the cursor * +1 for right of the cursor * 0 for the entire line */ function clearLine(stream, dir) { if (dir < 0) { // to the beginning stream.write('\x1b[1K'); } else if (dir > 0) { // to the end stream.write('\x1b[0K'); } else { // entire line stream.write('\x1b[2K'); } } exports.clearLine = clearLine; /** * clears the screen from the current position of the cursor down */ function clearScreenDown(stream) { stream.write('\x1b[0J'); } exports.clearScreenDown = clearScreenDown; node-v0.10.25~dfsg2/lib/path.js0000644000000000000000000003371412270121457014665 0ustar rootroot// Copyright Joyent, Inc. and other Node contributors. // // Permission is hereby granted, free of charge, to any person obtaining a // copy of this software and associated documentation files (the // "Software"), to deal in the Software without restriction, including // without limitation the rights to use, copy, modify, merge, publish, // distribute, sublicense, and/or sell copies of the Software, and to permit // persons to whom the Software is furnished to do so, subject to the // following conditions: // // The above copyright notice and this permission notice shall be included // in all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS // OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF // MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN // NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, // DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR // OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE // USE OR OTHER DEALINGS IN THE SOFTWARE. var isWindows = process.platform === 'win32'; var util = require('util'); // resolves . and .. elements in a path array with directory names there // must be no slashes, empty elements, or device names (c:\) in the array // (so also no leading and trailing slashes - it does not distinguish // relative and absolute paths) function normalizeArray(parts, allowAboveRoot) { // if the path tries to go above the root, `up` ends up > 0 var up = 0; for (var i = parts.length - 1; i >= 0; i--) { var last = parts[i]; if (last === '.') { parts.splice(i, 1); } else if (last === '..') { parts.splice(i, 1); up++; } else if (up) { parts.splice(i, 1); up--; } } // if the path is allowed to go above the root, restore leading ..s if (allowAboveRoot) { for (; up--; up) { parts.unshift('..'); } } return parts; } if (isWindows) { // Regex to split a windows path into three parts: [*, device, slash, // tail] windows-only var splitDeviceRe = /^([a-zA-Z]:|[\\\/]{2}[^\\\/]+[\\\/]+[^\\\/]+)?([\\\/])?([\s\S]*?)$/; // Regex to split the tail part of the above into [*, dir, basename, ext] var splitTailRe = /^([\s\S]*?)((?:\.{1,2}|[^\\\/]+?|)(\.[^.\/\\]*|))(?:[\\\/]*)$/; // Function to split a filename into [root, dir, basename, ext] // windows version var splitPath = function(filename) { // Separate device+slash from tail var result = splitDeviceRe.exec(filename), device = (result[1] || '') + (result[2] || ''), tail = result[3] || ''; // Split the tail into dir, basename and extension var result2 = splitTailRe.exec(tail), dir = result2[1], basename = result2[2], ext = result2[3]; return [device, dir, basename, ext]; }; var normalizeUNCRoot = function(device) { return '\\\\' + device.replace(/^[\\\/]+/, '').replace(/[\\\/]+/g, '\\'); }; // path.resolve([from ...], to) // windows version exports.resolve = function() { var resolvedDevice = '', resolvedTail = '', resolvedAbsolute = false; for (var i = arguments.length - 1; i >= -1; i--) { var path; if (i >= 0) { path = arguments[i]; } else if (!resolvedDevice) { path = process.cwd(); } else { // Windows has the concept of drive-specific current working // directories. If we've resolved a drive letter but not yet an // absolute path, get cwd for that drive. We're sure the device is not // an unc path at this points, because unc paths are always absolute. path = process.env['=' + resolvedDevice]; // Verify that a drive-local cwd was found and that it actually points // to our drive. If not, default to the drive's root. if (!path || path.substr(0, 3).toLowerCase() !== resolvedDevice.toLowerCase() + '\\') { path = resolvedDevice + '\\'; } } // Skip empty and invalid entries if (typeof path !== 'string') { throw new TypeError('Arguments to path.resolve must be strings'); } else if (!path) { continue; } var result = splitDeviceRe.exec(path), device = result[1] || '', isUnc = device && device.charAt(1) !== ':', isAbsolute = !!result[2] || isUnc, // UNC paths are always absolute tail = result[3]; if (device && resolvedDevice && device.toLowerCase() !== resolvedDevice.toLowerCase()) { // This path points to another device so it is not applicable continue; } if (!resolvedDevice) { resolvedDevice = device; } if (!resolvedAbsolute) { resolvedTail = tail + '\\' + resolvedTail; resolvedAbsolute = isAbsolute; } if (resolvedDevice && resolvedAbsolute) { break; } } // Convert slashes to backslashes when `resolvedDevice` points to an UNC // root. Also squash multiple slashes into a single one where appropriate. if (isUnc) { resolvedDevice = normalizeUNCRoot(resolvedDevice); } // At this point the path should be resolved to a full absolute path, // but handle relative paths to be safe (might happen when process.cwd() // fails) // Normalize the tail path function f(p) { return !!p; } resolvedTail = normalizeArray(resolvedTail.split(/[\\\/]+/).filter(f), !resolvedAbsolute).join('\\'); return (resolvedDevice + (resolvedAbsolute ? '\\' : '') + resolvedTail) || '.'; }; // windows version exports.normalize = function(path) { var result = splitDeviceRe.exec(path), device = result[1] || '', isUnc = device && device.charAt(1) !== ':', isAbsolute = !!result[2] || isUnc, // UNC paths are always absolute tail = result[3], trailingSlash = /[\\\/]$/.test(tail); // Normalize the tail path tail = normalizeArray(tail.split(/[\\\/]+/).filter(function(p) { return !!p; }), !isAbsolute).join('\\'); if (!tail && !isAbsolute) { tail = '.'; } if (tail && trailingSlash) { tail += '\\'; } // Convert slashes to backslashes when `device` points to an UNC root. // Also squash multiple slashes into a single one where appropriate. if (isUnc) { device = normalizeUNCRoot(device); } return device + (isAbsolute ? '\\' : '') + tail; }; // windows version exports.join = function() { function f(p) { if (typeof p !== 'string') { throw new TypeError('Arguments to path.join must be strings'); } return p; } var paths = Array.prototype.filter.call(arguments, f); var joined = paths.join('\\'); // Make sure that the joined path doesn't start with two slashes, because // normalize() will mistake it for an UNC path then. // // This step is skipped when it is very clear that the user actually // intended to point at an UNC path. This is assumed when the first // non-empty string arguments starts with exactly two slashes followed by // at least one more non-slash character. // // Note that for normalize() to treat a path as an UNC path it needs to // have at least 2 components, so we don't filter for that here. // This means that the user can use join to construct UNC paths from // a server name and a share name; for example: // path.join('//server', 'share') -> '\\\\server\\share\') if (!/^[\\\/]{2}[^\\\/]/.test(paths[0])) { joined = joined.replace(/^[\\\/]{2,}/, '\\'); } return exports.normalize(joined); }; // path.relative(from, to) // it will solve the relative path from 'from' to 'to', for instance: // from = 'C:\\orandea\\test\\aaa' // to = 'C:\\orandea\\impl\\bbb' // The output of the function should be: '..\\..\\impl\\bbb' // windows version exports.relative = function(from, to) { from = exports.resolve(from); to = exports.resolve(to); // windows is not case sensitive var lowerFrom = from.toLowerCase(); var lowerTo = to.toLowerCase(); function trim(arr) { var start = 0; for (; start < arr.length; start++) { if (arr[start] !== '') break; } var end = arr.length - 1; for (; end >= 0; end--) { if (arr[end] !== '') break; } if (start > end) return []; return arr.slice(start, end - start + 1); } var toParts = trim(to.split('\\')); var lowerFromParts = trim(lowerFrom.split('\\')); var lowerToParts = trim(lowerTo.split('\\')); var length = Math.min(lowerFromParts.length, lowerToParts.length); var samePartsLength = length; for (var i = 0; i < length; i++) { if (lowerFromParts[i] !== lowerToParts[i]) { samePartsLength = i; break; } } if (samePartsLength == 0) { return to; } var outputParts = []; for (var i = samePartsLength; i < lowerFromParts.length; i++) { outputParts.push('..'); } outputParts = outputParts.concat(toParts.slice(samePartsLength)); return outputParts.join('\\'); }; exports.sep = '\\'; exports.delimiter = ';'; } else /* posix */ { // Split a filename into [root, dir, basename, ext], unix version // 'root' is just a slash, or nothing. var splitPathRe = /^(\/?|)([\s\S]*?)((?:\.{1,2}|[^\/]+?|)(\.[^.\/]*|))(?:[\/]*)$/; var splitPath = function(filename) { return splitPathRe.exec(filename).slice(1); }; // path.resolve([from ...], to) // posix version exports.resolve = function() { var resolvedPath = '', resolvedAbsolute = false; for (var i = arguments.length - 1; i >= -1 && !resolvedAbsolute; i--) { var path = (i >= 0) ? arguments[i] : process.cwd(); // Skip empty and invalid entries if (typeof path !== 'string') { throw new TypeError('Arguments to path.resolve must be strings'); } else if (!path) { continue; } resolvedPath = path + '/' + resolvedPath; resolvedAbsolute = path.charAt(0) === '/'; } // At this point the path should be resolved to a full absolute path, but // handle relative paths to be safe (might happen when process.cwd() fails) // Normalize the path resolvedPath = normalizeArray(resolvedPath.split('/').filter(function(p) { return !!p; }), !resolvedAbsolute).join('/'); return ((resolvedAbsolute ? '/' : '') + resolvedPath) || '.'; }; // path.normalize(path) // posix version exports.normalize = function(path) { var isAbsolute = path.charAt(0) === '/', trailingSlash = path.substr(-1) === '/'; // Normalize the path path = normalizeArray(path.split('/').filter(function(p) { return !!p; }), !isAbsolute).join('/'); if (!path && !isAbsolute) { path = '.'; } if (path && trailingSlash) { path += '/'; } return (isAbsolute ? '/' : '') + path; }; // posix version exports.join = function() { var paths = Array.prototype.slice.call(arguments, 0); return exports.normalize(paths.filter(function(p, index) { if (typeof p !== 'string') { throw new TypeError('Arguments to path.join must be strings'); } return p; }).join('/')); }; // path.relative(from, to) // posix version exports.relative = function(from, to) { from = exports.resolve(from).substr(1); to = exports.resolve(to).substr(1); function trim(arr) { var start = 0; for (; start < arr.length; start++) { if (arr[start] !== '') break; } var end = arr.length - 1; for (; end >= 0; end--) { if (arr[end] !== '') break; } if (start > end) return []; return arr.slice(start, end - start + 1); } var fromParts = trim(from.split('/')); var toParts = trim(to.split('/')); var length = Math.min(fromParts.length, toParts.length); var samePartsLength = length; for (var i = 0; i < length; i++) { if (fromParts[i] !== toParts[i]) { samePartsLength = i; break; } } var outputParts = []; for (var i = samePartsLength; i < fromParts.length; i++) { outputParts.push('..'); } outputParts = outputParts.concat(toParts.slice(samePartsLength)); return outputParts.join('/'); }; exports.sep = '/'; exports.delimiter = ':'; } exports.dirname = function(path) { var result = splitPath(path), root = result[0], dir = result[1]; if (!root && !dir) { // No dirname whatsoever return '.'; } if (dir) { // It has a dirname, strip trailing slash dir = dir.substr(0, dir.length - 1); } return root + dir; }; exports.basename = function(path, ext) { var f = splitPath(path)[2]; // TODO: make this comparison case-insensitive on windows? if (ext && f.substr(-1 * ext.length) === ext) { f = f.substr(0, f.length - ext.length); } return f; }; exports.extname = function(path) { return splitPath(path)[3]; }; exports.exists = util.deprecate(function(path, callback) { require('fs').exists(path, callback); }, 'path.exists is now called `fs.exists`.'); exports.existsSync = util.deprecate(function(path) { return require('fs').existsSync(path); }, 'path.existsSync is now called `fs.existsSync`.'); if (isWindows) { exports._makeLong = function(path) { // Note: this will *probably* throw somewhere. if (typeof path !== 'string') return path; if (!path) { return ''; } var resolvedPath = exports.resolve(path); if (/^[a-zA-Z]\:\\/.test(resolvedPath)) { // path is local filesystem path, which needs to be converted // to long UNC path. return '\\\\?\\' + resolvedPath; } else if (/^\\\\[^?.]/.test(resolvedPath)) { // path is network UNC path, which needs to be converted // to long UNC path. return '\\\\?\\UNC\\' + resolvedPath.substring(2); } return path; }; } else { exports._makeLong = function(path) { return path; }; } node-v0.10.25~dfsg2/lib/http.js0000644000000000000000000017053012270121457014706 0ustar rootroot// Copyright Joyent, Inc. and other Node contributors. // // Permission is hereby granted, free of charge, to any person obtaining a // copy of this software and associated documentation files (the // "Software"), to deal in the Software without restriction, including // without limitation the rights to use, copy, modify, merge, publish, // distribute, sublicense, and/or sell copies of the Software, and to permit // persons to whom the Software is furnished to do so, subject to the // following conditions: // // The above copyright notice and this permission notice shall be included // in all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS // OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF // MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN // NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, // DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR // OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE // USE OR OTHER DEALINGS IN THE SOFTWARE. var util = require('util'); var net = require('net'); var Stream = require('stream'); var timers = require('timers'); var url = require('url'); var EventEmitter = require('events').EventEmitter; var FreeList = require('freelist').FreeList; var HTTPParser = process.binding('http_parser').HTTPParser; var assert = require('assert').ok; var debug; if (process.env.NODE_DEBUG && /http/.test(process.env.NODE_DEBUG)) { debug = function(x) { console.error('HTTP: %s', x); }; } else { debug = function() { }; } function readStart(socket) { if (!socket || !socket._handle || !socket._handle.readStart || socket._paused) return; socket._handle.readStart(); } function readStop(socket) { if (!socket || !socket._handle || !socket._handle.readStop) return; socket._handle.readStop(); } // Only called in the slow case where slow means // that the request headers were either fragmented // across multiple TCP packets or too large to be // processed in a single run. This method is also // called to process trailing HTTP headers. function parserOnHeaders(headers, url) { // Once we exceeded headers limit - stop collecting them if (this.maxHeaderPairs <= 0 || this._headers.length < this.maxHeaderPairs) { this._headers = this._headers.concat(headers); } this._url += url; } // info.headers and info.url are set only if .onHeaders() // has not been called for this request. // // info.url is not set for response parsers but that's not // applicable here since all our parsers are request parsers. function parserOnHeadersComplete(info) { var parser = this; var headers = info.headers; var url = info.url; if (!headers) { headers = parser._headers; parser._headers = []; } if (!url) { url = parser._url; parser._url = ''; } parser.incoming = new IncomingMessage(parser.socket); parser.incoming.httpVersionMajor = info.versionMajor; parser.incoming.httpVersionMinor = info.versionMinor; parser.incoming.httpVersion = info.versionMajor + '.' + info.versionMinor; parser.incoming.url = url; var n = headers.length; // If parser.maxHeaderPairs <= 0 - assume that there're no limit if (parser.maxHeaderPairs > 0) { n = Math.min(n, parser.maxHeaderPairs); } for (var i = 0; i < n; i += 2) { var k = headers[i]; var v = headers[i + 1]; parser.incoming._addHeaderLine(k, v); } if (info.method) { // server only parser.incoming.method = info.method; } else { // client only parser.incoming.statusCode = info.statusCode; // CHECKME dead code? we're always a request parser } parser.incoming.upgrade = info.upgrade; var skipBody = false; // response to HEAD or CONNECT if (!info.upgrade) { // For upgraded connections and CONNECT method request, // we'll emit this after parser.execute // so that we can capture the first part of the new protocol skipBody = parser.onIncoming(parser.incoming, info.shouldKeepAlive); } return skipBody; } // XXX This is a mess. // TODO: http.Parser should be a Writable emits request/response events. function parserOnBody(b, start, len) { var parser = this; var stream = parser.incoming; // if the stream has already been removed, then drop it. if (!stream) return; var socket = stream.socket; // pretend this was the result of a stream._read call. if (len > 0 && !stream._dumped) { var slice = b.slice(start, start + len); var ret = stream.push(slice); if (!ret) readStop(socket); } } function parserOnMessageComplete() { var parser = this; var stream = parser.incoming; if (stream) { stream.complete = true; // Emit any trailing headers. var headers = parser._headers; if (headers) { for (var i = 0, n = headers.length; i < n; i += 2) { var k = headers[i]; var v = headers[i + 1]; parser.incoming._addHeaderLine(k, v); } parser._headers = []; parser._url = ''; } if (!stream.upgrade) // For upgraded connections, also emit this after parser.execute stream.push(null); } if (stream && !parser.incoming._pendings.length) { // For emit end event stream.push(null); } // force to read the next incoming message readStart(parser.socket); } var parsers = new FreeList('parsers', 1000, function() { var parser = new HTTPParser(HTTPParser.REQUEST); parser._headers = []; parser._url = ''; // Only called in the slow case where slow means // that the request headers were either fragmented // across multiple TCP packets or too large to be // processed in a single run. This method is also // called to process trailing HTTP headers. parser.onHeaders = parserOnHeaders; parser.onHeadersComplete = parserOnHeadersComplete; parser.onBody = parserOnBody; parser.onMessageComplete = parserOnMessageComplete; return parser; }); exports.parsers = parsers; var CRLF = '\r\n'; var STATUS_CODES = exports.STATUS_CODES = { 100 : 'Continue', 101 : 'Switching Protocols', 102 : 'Processing', // RFC 2518, obsoleted by RFC 4918 200 : 'OK', 201 : 'Created', 202 : 'Accepted', 203 : 'Non-Authoritative Information', 204 : 'No Content', 205 : 'Reset Content', 206 : 'Partial Content', 207 : 'Multi-Status', // RFC 4918 300 : 'Multiple Choices', 301 : 'Moved Permanently', 302 : 'Moved Temporarily', 303 : 'See Other', 304 : 'Not Modified', 305 : 'Use Proxy', 307 : 'Temporary Redirect', 400 : 'Bad Request', 401 : 'Unauthorized', 402 : 'Payment Required', 403 : 'Forbidden', 404 : 'Not Found', 405 : 'Method Not Allowed', 406 : 'Not Acceptable', 407 : 'Proxy Authentication Required', 408 : 'Request Time-out', 409 : 'Conflict', 410 : 'Gone', 411 : 'Length Required', 412 : 'Precondition Failed', 413 : 'Request Entity Too Large', 414 : 'Request-URI Too Large', 415 : 'Unsupported Media Type', 416 : 'Requested Range Not Satisfiable', 417 : 'Expectation Failed', 418 : 'I\'m a teapot', // RFC 2324 422 : 'Unprocessable Entity', // RFC 4918 423 : 'Locked', // RFC 4918 424 : 'Failed Dependency', // RFC 4918 425 : 'Unordered Collection', // RFC 4918 426 : 'Upgrade Required', // RFC 2817 428 : 'Precondition Required', // RFC 6585 429 : 'Too Many Requests', // RFC 6585 431 : 'Request Header Fields Too Large',// RFC 6585 500 : 'Internal Server Error', 501 : 'Not Implemented', 502 : 'Bad Gateway', 503 : 'Service Unavailable', 504 : 'Gateway Time-out', 505 : 'HTTP Version Not Supported', 506 : 'Variant Also Negotiates', // RFC 2295 507 : 'Insufficient Storage', // RFC 4918 509 : 'Bandwidth Limit Exceeded', 510 : 'Not Extended', // RFC 2774 511 : 'Network Authentication Required' // RFC 6585 }; var connectionExpression = /Connection/i; var transferEncodingExpression = /Transfer-Encoding/i; var closeExpression = /close/i; var chunkExpression = /chunk/i; var contentLengthExpression = /Content-Length/i; var dateExpression = /Date/i; var expectExpression = /Expect/i; var continueExpression = /100-continue/i; var dateCache; function utcDate() { if (!dateCache) { var d = new Date(); dateCache = d.toUTCString(); timers.enroll(utcDate, 1000 - d.getMilliseconds()); timers._unrefActive(utcDate); } return dateCache; } utcDate._onTimeout = function() { dateCache = undefined; }; /* Abstract base class for ServerRequest and ClientResponse. */ function IncomingMessage(socket) { Stream.Readable.call(this); // XXX This implementation is kind of all over the place // When the parser emits body chunks, they go in this list. // _read() pulls them out, and when it finds EOF, it ends. this.socket = socket; this.connection = socket; this.httpVersion = null; this.complete = false; this.headers = {}; this.trailers = {}; this.readable = true; this._pendings = []; this._pendingIndex = 0; // request (server) only this.url = ''; this.method = null; // response (client) only this.statusCode = null; this.client = this.socket; // flag for backwards compatibility grossness. this._consuming = false; // flag for when we decide that this message cannot possibly be // read by the user, so there's no point continuing to handle it. this._dumped = false; } util.inherits(IncomingMessage, Stream.Readable); exports.IncomingMessage = IncomingMessage; IncomingMessage.prototype.setTimeout = function(msecs, callback) { if (callback) this.on('timeout', callback); this.socket.setTimeout(msecs); }; IncomingMessage.prototype.read = function(n) { this._consuming = true; this.read = Stream.Readable.prototype.read; return this.read(n); }; IncomingMessage.prototype._read = function(n) { // We actually do almost nothing here, because the parserOnBody // function fills up our internal buffer directly. However, we // do need to unpause the underlying socket so that it flows. if (!this.socket.readable) this.push(null); else readStart(this.socket); }; // It's possible that the socket will be destroyed, and removed from // any messages, before ever calling this. In that case, just skip // it, since something else is destroying this connection anyway. IncomingMessage.prototype.destroy = function(error) { if (this.socket) this.socket.destroy(error); }; // Add the given (field, value) pair to the message // // Per RFC2616, section 4.2 it is acceptable to join multiple instances of the // same header with a ', ' if the header in question supports specification of // multiple values this way. If not, we declare the first instance the winner // and drop the second. Extended header fields (those beginning with 'x-') are // always joined. IncomingMessage.prototype._addHeaderLine = function(field, value) { var dest = this.complete ? this.trailers : this.headers; field = field.toLowerCase(); switch (field) { // Array headers: case 'set-cookie': if (dest[field] !== undefined) { dest[field].push(value); } else { dest[field] = [value]; } break; // Comma separate. Maybe make these arrays? case 'accept': case 'accept-charset': case 'accept-encoding': case 'accept-language': case 'connection': case 'cookie': case 'pragma': case 'link': case 'www-authenticate': case 'proxy-authenticate': case 'sec-websocket-extensions': case 'sec-websocket-protocol': if (dest[field] !== undefined) { dest[field] += ', ' + value; } else { dest[field] = value; } break; default: if (field.slice(0, 2) == 'x-') { // except for x- if (dest[field] !== undefined) { dest[field] += ', ' + value; } else { dest[field] = value; } } else { // drop duplicates if (dest[field] === undefined) dest[field] = value; } break; } }; // Call this instead of resume() if we want to just // dump all the data to /dev/null IncomingMessage.prototype._dump = function() { if (!this._dumped) { this._dumped = true; if (this.socket.parser) this.socket.parser.incoming = null; this.push(null); readStart(this.socket); this.read(); } }; function OutgoingMessage() { Stream.call(this); this.output = []; this.outputEncodings = []; this.writable = true; this._last = false; this.chunkedEncoding = false; this.shouldKeepAlive = true; this.useChunkedEncodingByDefault = true; this.sendDate = false; this._headerSent = false; this._header = ''; this._hasBody = true; this._trailer = ''; this.finished = false; this._hangupClose = false; this.socket = null; this.connection = null; } util.inherits(OutgoingMessage, Stream); exports.OutgoingMessage = OutgoingMessage; OutgoingMessage.prototype.setTimeout = function(msecs, callback) { if (callback) this.on('timeout', callback); if (!this.socket) { this.once('socket', function(socket) { socket.setTimeout(msecs); }); } else this.socket.setTimeout(msecs); }; // It's possible that the socket will be destroyed, and removed from // any messages, before ever calling this. In that case, just skip // it, since something else is destroying this connection anyway. OutgoingMessage.prototype.destroy = function(error) { if (this.socket) this.socket.destroy(error); else this.once('socket', function(socket) { socket.destroy(error); }); }; // This abstract either writing directly to the socket or buffering it. OutgoingMessage.prototype._send = function(data, encoding) { // This is a shameful hack to get the headers and first body chunk onto // the same packet. Future versions of Node are going to take care of // this at a lower level and in a more general way. if (!this._headerSent) { if (typeof data === 'string' && encoding !== 'hex' && encoding !== 'base64') { data = this._header + data; } else { this.output.unshift(this._header); this.outputEncodings.unshift('ascii'); } this._headerSent = true; } return this._writeRaw(data, encoding); }; OutgoingMessage.prototype._writeRaw = function(data, encoding) { if (data.length === 0) { return true; } if (this.connection && this.connection._httpMessage === this && this.connection.writable && !this.connection.destroyed) { // There might be pending data in the this.output buffer. while (this.output.length) { if (!this.connection.writable) { this._buffer(data, encoding); return false; } var c = this.output.shift(); var e = this.outputEncodings.shift(); this.connection.write(c, e); } // Directly write to socket. return this.connection.write(data, encoding); } else if (this.connection && this.connection.destroyed) { // The socket was destroyed. If we're still trying to write to it, // then we haven't gotten the 'close' event yet. return false; } else { // buffer, as long as we're not destroyed. this._buffer(data, encoding); return false; } }; OutgoingMessage.prototype._buffer = function(data, encoding) { this.output.push(data); this.outputEncodings.push(encoding); return false; }; OutgoingMessage.prototype._storeHeader = function(firstLine, headers) { // firstLine in the case of request is: 'GET /index.html HTTP/1.1\r\n' // in the case of response it is: 'HTTP/1.1 200 OK\r\n' var state = { sentConnectionHeader: false, sentContentLengthHeader: false, sentTransferEncodingHeader: false, sentDateHeader: false, sentExpect: false, messageHeader: firstLine }; var field, value; var self = this; if (headers) { var keys = Object.keys(headers); var isArray = (Array.isArray(headers)); var field, value; for (var i = 0, l = keys.length; i < l; i++) { var key = keys[i]; if (isArray) { field = headers[key][0]; value = headers[key][1]; } else { field = key; value = headers[key]; } if (Array.isArray(value)) { for (var j = 0; j < value.length; j++) { storeHeader(this, state, field, value[j]); } } else { storeHeader(this, state, field, value); } } } // Date header if (this.sendDate == true && state.sentDateHeader == false) { state.messageHeader += 'Date: ' + utcDate() + CRLF; } // Force the connection to close when the response is a 204 No Content or // a 304 Not Modified and the user has set a "Transfer-Encoding: chunked" // header. // // RFC 2616 mandates that 204 and 304 responses MUST NOT have a body but // node.js used to send out a zero chunk anyway to accommodate clients // that don't have special handling for those responses. // // It was pointed out that this might confuse reverse proxies to the point // of creating security liabilities, so suppress the zero chunk and force // the connection to close. var statusCode = this.statusCode; if ((statusCode == 204 || statusCode === 304) && this.chunkedEncoding === true) { debug(statusCode + ' response should not use chunked encoding,' + ' closing connection.'); this.chunkedEncoding = false; this.shouldKeepAlive = false; } // keep-alive logic if (state.sentConnectionHeader === false) { var shouldSendKeepAlive = this.shouldKeepAlive && (state.sentContentLengthHeader || this.useChunkedEncodingByDefault || this.agent); if (shouldSendKeepAlive) { state.messageHeader += 'Connection: keep-alive\r\n'; } else { this._last = true; state.messageHeader += 'Connection: close\r\n'; } } if (state.sentContentLengthHeader == false && state.sentTransferEncodingHeader == false) { if (this._hasBody) { if (this.useChunkedEncodingByDefault) { state.messageHeader += 'Transfer-Encoding: chunked\r\n'; this.chunkedEncoding = true; } else { this._last = true; } } else { // Make sure we don't end the 0\r\n\r\n at the end of the message. this.chunkedEncoding = false; } } this._header = state.messageHeader + CRLF; this._headerSent = false; // wait until the first body chunk, or close(), is sent to flush, // UNLESS we're sending Expect: 100-continue. if (state.sentExpect) this._send(''); }; function storeHeader(self, state, field, value) { // Protect against response splitting. The if statement is there to // minimize the performance impact in the common case. if (/[\r\n]/.test(value)) value = value.replace(/[\r\n]+[ \t]*/g, ''); state.messageHeader += field + ': ' + value + CRLF; if (connectionExpression.test(field)) { state.sentConnectionHeader = true; if (closeExpression.test(value)) { self._last = true; } else { self.shouldKeepAlive = true; } } else if (transferEncodingExpression.test(field)) { state.sentTransferEncodingHeader = true; if (chunkExpression.test(value)) self.chunkedEncoding = true; } else if (contentLengthExpression.test(field)) { state.sentContentLengthHeader = true; } else if (dateExpression.test(field)) { state.sentDateHeader = true; } else if (expectExpression.test(field)) { state.sentExpect = true; } } OutgoingMessage.prototype.setHeader = function(name, value) { if (arguments.length < 2) { throw new Error('`name` and `value` are required for setHeader().'); } if (this._header) { throw new Error('Can\'t set headers after they are sent.'); } var key = name.toLowerCase(); this._headers = this._headers || {}; this._headerNames = this._headerNames || {}; this._headers[key] = value; this._headerNames[key] = name; }; OutgoingMessage.prototype.getHeader = function(name) { if (arguments.length < 1) { throw new Error('`name` is required for getHeader().'); } if (!this._headers) return; var key = name.toLowerCase(); return this._headers[key]; }; OutgoingMessage.prototype.removeHeader = function(name) { if (arguments.length < 1) { throw new Error('`name` is required for removeHeader().'); } if (this._header) { throw new Error('Can\'t remove headers after they are sent.'); } if (!this._headers) return; var key = name.toLowerCase(); delete this._headers[key]; delete this._headerNames[key]; }; OutgoingMessage.prototype._renderHeaders = function() { if (this._header) { throw new Error('Can\'t render headers after they are sent to the client.'); } if (!this._headers) return {}; var headers = {}; var keys = Object.keys(this._headers); for (var i = 0, l = keys.length; i < l; i++) { var key = keys[i]; headers[this._headerNames[key]] = this._headers[key]; } return headers; }; Object.defineProperty(OutgoingMessage.prototype, 'headersSent', { configurable: true, enumerable: true, get: function() { return !!this._header; } }); // Convert a number in the range 0-15 to a lowercase hexadecimal digit. function hex(val) { // The comparison and bit hacks are deliberate. We could look up the // value in a buffer with hexdigits[val & 15] but that adds a couple // of bounds checks to each conversion. return val <= 9 ? (val | 48) : ((val - 9) | 96); } function chunkify(chunk, headers, trailers, last) { var chunklen = chunk.length; var buflen = chunklen + 4; // '\r\n' + chunk + '\r\n' var offset = 0; var octets = 1; // Skip expensive Buffer.byteLength() calls; only ISO-8859-1 characters // are allowed in HTTP headers, therefore: // // headers.length == Buffer.byteLength(headers.length) // trailers.length == Buffer.byteLength(trailers.length) // // Note: the actual encoding that is used is ASCII. That's de jure // a violation of the spec but de facto correct because many HTTP // clients get confused by non-ASCII headers. if (last === true) buflen += 5; // '0\r\n\r\n' if (headers !== '') buflen += headers.length; if (trailers !== '') buflen += trailers.length; if (chunklen & 0xf0000000) octets += 7; else if (chunklen & 0xf000000) octets += 6; else if (chunklen & 0xf00000) octets += 5; else if (chunklen & 0xf0000) octets += 4; else if (chunklen & 0xf000) octets += 3; else if (chunklen & 0xf00) octets += 2; else if (chunklen & 0xf0) octets += 1; buflen += octets; var buf = new Buffer(buflen); if (headers !== '') { buf.write(headers, 0, headers.length, 'ascii'); offset = headers.length; } // Write chunk length in hex to buffer. This effectively limits us // to 4 GB chunks but that's okay because buffers are max 1 GB anyway. switch (octets) { case 8: buf[offset++] = hex((chunklen >>> 28) & 15); case 7: buf[offset++] = hex((chunklen >>> 24) & 15); case 6: buf[offset++] = hex((chunklen >>> 20) & 15); case 5: buf[offset++] = hex((chunklen >>> 16) & 15); case 4: buf[offset++] = hex((chunklen >>> 12) & 15); case 3: buf[offset++] = hex((chunklen >>> 8) & 15); case 2: buf[offset++] = hex((chunklen >>> 4) & 15); } buf[offset++] = hex(chunklen & 15); // Add '\r\n'. buf[offset++] = 13; buf[offset++] = 10; // Copy buffer. chunk.copy(buf, offset); offset += chunklen; // Add trailing '\r\n'. buf[offset++] = 13; buf[offset++] = 10; if (last === true) { // Add trailing '0\r\n\r\n'. buf[offset++] = 48; buf[offset++] = 13; buf[offset++] = 10; buf[offset++] = 13; buf[offset++] = 10; } if (trailers !== '') { buf.write(trailers, offset, trailers.length, 'ascii'); } return buf; } OutgoingMessage.prototype.write = function(chunk, encoding) { if (!this._header) { this._implicitHeader(); } if (!this._hasBody) { debug('This type of response MUST NOT have a body. ' + 'Ignoring write() calls.'); return true; } if (typeof chunk !== 'string' && !Buffer.isBuffer(chunk)) { throw new TypeError('first argument must be a string or Buffer'); } // If we get an empty string or buffer, then just do nothing, and // signal the user to keep writing. if (chunk.length === 0) return true; var len, ret; if (this.chunkedEncoding) { if (typeof(chunk) === 'string' && encoding !== 'hex' && encoding !== 'base64') { len = Buffer.byteLength(chunk, encoding); chunk = len.toString(16) + CRLF + chunk + CRLF; ret = this._send(chunk, encoding); } else if (Buffer.isBuffer(chunk)) { var buf = chunkify(chunk, '', '', false); ret = this._send(buf, encoding); } else { // Non-toString-friendly encoding. if (typeof chunk === 'string') len = Buffer.byteLength(chunk, encoding); else len = chunk.length; this._send(len.toString(16) + CRLF, 'ascii'); this._send(chunk, encoding); ret = this._send(CRLF); } } else { ret = this._send(chunk, encoding); } debug('write ret = ' + ret); return ret; }; OutgoingMessage.prototype.addTrailers = function(headers) { this._trailer = ''; var keys = Object.keys(headers); var isArray = (Array.isArray(headers)); var field, value; for (var i = 0, l = keys.length; i < l; i++) { var key = keys[i]; if (isArray) { field = headers[key][0]; value = headers[key][1]; } else { field = key; value = headers[key]; } this._trailer += field + ': ' + value + CRLF; } }; var zero_chunk_buf = new Buffer('\r\n0\r\n'); var crlf_buf = new Buffer('\r\n'); OutgoingMessage.prototype.end = function(data, encoding) { if (this.finished) { return false; } if (!this._header) { this._implicitHeader(); } if (data && !this._hasBody) { debug('This type of response MUST NOT have a body. ' + 'Ignoring data passed to end().'); data = false; } var ret; var hot = this._headerSent === false && (data && data.length > 0) && this.output.length === 0 && this.connection && this.connection.writable && this.connection._httpMessage === this; // The benefits of the hot-path optimization below start to fall // off when the buffer size gets up near 128KB, because the cost // of the copy is more than the cost of the extra write() call. // Switch to the write/end method at that point. Heuristics and // magic numbers are awful, but slow http responses are worse. if (hot && Buffer.isBuffer(data) && data.length > 120 * 1024) hot = false; // Can't concatenate safely with hex or base64 encodings. if (encoding === 'hex' || encoding === 'base64') hot = false; if (hot) { // Hot path. They're doing // res.writeHead(); // res.end(blah); // HACKY. if (typeof data === 'string') { if (this.chunkedEncoding) { var l = Buffer.byteLength(data, encoding).toString(16); ret = this.connection.write(this._header + l + CRLF + data + '\r\n0\r\n' + this._trailer + '\r\n', encoding); } else { ret = this.connection.write(this._header + data, encoding); } } else if (Buffer.isBuffer(data)) { if (this.chunkedEncoding) { var buf = chunkify(data, this._header, this._trailer, true); ret = this.connection.write(buf); } else { var header_len = this._header.length; var buf = new Buffer(header_len + data.length); buf.write(this._header, 0, header_len, 'ascii'); data.copy(buf, header_len); ret = this.connection.write(buf); } } else { throw new TypeError('first argument must be a string or Buffer'); } this._headerSent = true; } else if (data) { // Normal body write. ret = this.write(data, encoding); } if (!hot) { if (this.chunkedEncoding) { ret = this._send('0\r\n' + this._trailer + '\r\n', 'ascii'); } else { // Force a flush, HACK. ret = this._send(''); } } this.finished = true; // There is the first message on the outgoing queue, and we've sent // everything to the socket. debug('outgoing message end.'); if (this.output.length === 0 && this.connection._httpMessage === this) { this._finish(); } return ret; }; OutgoingMessage.prototype._finish = function() { assert(this.connection); if (this instanceof ServerResponse) { DTRACE_HTTP_SERVER_RESPONSE(this.connection); COUNTER_HTTP_SERVER_RESPONSE(); } else { assert(this instanceof ClientRequest); DTRACE_HTTP_CLIENT_REQUEST(this, this.connection); COUNTER_HTTP_CLIENT_REQUEST(); } this.emit('finish'); }; OutgoingMessage.prototype._flush = function() { // This logic is probably a bit confusing. Let me explain a bit: // // In both HTTP servers and clients it is possible to queue up several // outgoing messages. This is easiest to imagine in the case of a client. // Take the following situation: // // req1 = client.request('GET', '/'); // req2 = client.request('POST', '/'); // // When the user does // // req2.write('hello world\n'); // // it's possible that the first request has not been completely flushed to // the socket yet. Thus the outgoing messages need to be prepared to queue // up data internally before sending it on further to the socket's queue. // // This function, outgoingFlush(), is called by both the Server and Client // to attempt to flush any pending messages out to the socket. if (!this.socket) return; var ret; while (this.output.length) { if (!this.socket.writable) return; // XXX Necessary? var data = this.output.shift(); var encoding = this.outputEncodings.shift(); ret = this.socket.write(data, encoding); } if (this.finished) { // This is a queue to the server or client to bring in the next this. this._finish(); } else if (ret) { // This is necessary to prevent https from breaking this.emit('drain'); } }; function ServerResponse(req) { OutgoingMessage.call(this); if (req.method === 'HEAD') this._hasBody = false; this.sendDate = true; if (req.httpVersionMajor < 1 || req.httpVersionMinor < 1) { this.useChunkedEncodingByDefault = chunkExpression.test(req.headers.te); this.shouldKeepAlive = false; } } util.inherits(ServerResponse, OutgoingMessage); exports.ServerResponse = ServerResponse; ServerResponse.prototype.statusCode = 200; function onServerResponseClose() { // EventEmitter.emit makes a copy of the 'close' listeners array before // calling the listeners. detachSocket() unregisters onServerResponseClose // but if detachSocket() is called, directly or indirectly, by a 'close' // listener, onServerResponseClose is still in that copy of the listeners // array. That is, in the example below, b still gets called even though // it's been removed by a: // // var obj = new events.EventEmitter; // obj.on('event', a); // obj.on('event', b); // function a() { obj.removeListener('event', b) } // function b() { throw "BAM!" } // obj.emit('event'); // throws // // Ergo, we need to deal with stale 'close' events and handle the case // where the ServerResponse object has already been deconstructed. // Fortunately, that requires only a single if check. :-) if (this._httpMessage) this._httpMessage.emit('close'); } ServerResponse.prototype.assignSocket = function(socket) { assert(!socket._httpMessage); socket._httpMessage = this; socket.on('close', onServerResponseClose); this.socket = socket; this.connection = socket; this.emit('socket', socket); this._flush(); }; ServerResponse.prototype.detachSocket = function(socket) { assert(socket._httpMessage == this); socket.removeListener('close', onServerResponseClose); socket._httpMessage = null; this.socket = this.connection = null; }; ServerResponse.prototype.writeContinue = function() { this._writeRaw('HTTP/1.1 100 Continue' + CRLF + CRLF, 'ascii'); this._sent100 = true; }; ServerResponse.prototype._implicitHeader = function() { this.writeHead(this.statusCode); }; ServerResponse.prototype.writeHead = function(statusCode) { var reasonPhrase, headers, headerIndex; if (typeof arguments[1] == 'string') { reasonPhrase = arguments[1]; headerIndex = 2; } else { reasonPhrase = STATUS_CODES[statusCode] || 'unknown'; headerIndex = 1; } this.statusCode = statusCode; var obj = arguments[headerIndex]; if (obj && this._headers) { // Slow-case: when progressive API and header fields are passed. headers = this._renderHeaders(); if (Array.isArray(obj)) { // handle array case // TODO: remove when array is no longer accepted var field; for (var i = 0, len = obj.length; i < len; ++i) { field = obj[i][0]; if (headers[field] !== undefined) { obj.push([field, headers[field]]); } } headers = obj; } else { // handle object case var keys = Object.keys(obj); for (var i = 0; i < keys.length; i++) { var k = keys[i]; if (k) headers[k] = obj[k]; } } } else if (this._headers) { // only progressive api is used headers = this._renderHeaders(); } else { // only writeHead() called headers = obj; } var statusLine = 'HTTP/1.1 ' + statusCode.toString() + ' ' + reasonPhrase + CRLF; if (statusCode === 204 || statusCode === 304 || (100 <= statusCode && statusCode <= 199)) { // RFC 2616, 10.2.5: // The 204 response MUST NOT include a message-body, and thus is always // terminated by the first empty line after the header fields. // RFC 2616, 10.3.5: // The 304 response MUST NOT contain a message-body, and thus is always // terminated by the first empty line after the header fields. // RFC 2616, 10.1 Informational 1xx: // This class of status code indicates a provisional response, // consisting only of the Status-Line and optional headers, and is // terminated by an empty line. this._hasBody = false; } // don't keep alive connections where the client expects 100 Continue // but we sent a final status; they may put extra bytes on the wire. if (this._expect_continue && !this._sent100) { this.shouldKeepAlive = false; } this._storeHeader(statusLine, headers); }; ServerResponse.prototype.writeHeader = function() { this.writeHead.apply(this, arguments); }; // New Agent code. // The largest departure from the previous implementation is that // an Agent instance holds connections for a variable number of host:ports. // Surprisingly, this is still API compatible as far as third parties are // concerned. The only code that really notices the difference is the // request object. // Another departure is that all code related to HTTP parsing is in // ClientRequest.onSocket(). The Agent is now *strictly* // concerned with managing a connection pool. function Agent(options) { EventEmitter.call(this); var self = this; self.options = options || {}; self.requests = {}; self.sockets = {}; self.maxSockets = self.options.maxSockets || Agent.defaultMaxSockets; self.on('free', function(socket, host, port, localAddress) { var name = host + ':' + port; if (localAddress) { name += ':' + localAddress; } if (!socket.destroyed && self.requests[name] && self.requests[name].length) { self.requests[name].shift().onSocket(socket); if (self.requests[name].length === 0) { // don't leak delete self.requests[name]; } } else { // If there are no pending requests just destroy the // socket and it will get removed from the pool. This // gets us out of timeout issues and allows us to // default to Connection:keep-alive. socket.destroy(); } }); self.createConnection = net.createConnection; } util.inherits(Agent, EventEmitter); exports.Agent = Agent; Agent.defaultMaxSockets = 5; Agent.prototype.defaultPort = 80; Agent.prototype.addRequest = function(req, host, port, localAddress) { var name = host + ':' + port; if (localAddress) { name += ':' + localAddress; } if (!this.sockets[name]) { this.sockets[name] = []; } if (this.sockets[name].length < this.maxSockets) { // If we are under maxSockets create a new one. req.onSocket(this.createSocket(name, host, port, localAddress, req)); } else { // We are over limit so we'll add it to the queue. if (!this.requests[name]) { this.requests[name] = []; } this.requests[name].push(req); } }; Agent.prototype.createSocket = function(name, host, port, localAddress, req) { var self = this; var options = util._extend({}, self.options); options.port = port; options.host = host; options.localAddress = localAddress; options.servername = host; if (req) { var hostHeader = req.getHeader('host'); if (hostHeader) { options.servername = hostHeader.replace(/:.*$/, ''); } } var s = self.createConnection(options); if (!self.sockets[name]) { self.sockets[name] = []; } this.sockets[name].push(s); var onFree = function() { self.emit('free', s, host, port, localAddress); } s.on('free', onFree); var onClose = function(err) { // This is the only place where sockets get removed from the Agent. // If you want to remove a socket from the pool, just close it. // All socket errors end in a close event anyway. self.removeSocket(s, name, host, port, localAddress); } s.on('close', onClose); var onRemove = function() { // We need this function for cases like HTTP 'upgrade' // (defined by WebSockets) where we need to remove a socket from the pool // because it'll be locked up indefinitely self.removeSocket(s, name, host, port, localAddress); s.removeListener('close', onClose); s.removeListener('free', onFree); s.removeListener('agentRemove', onRemove); } s.on('agentRemove', onRemove); return s; }; Agent.prototype.removeSocket = function(s, name, host, port, localAddress) { if (this.sockets[name]) { var index = this.sockets[name].indexOf(s); if (index !== -1) { this.sockets[name].splice(index, 1); if (this.sockets[name].length === 0) { // don't leak delete this.sockets[name]; } } } if (this.requests[name] && this.requests[name].length) { var req = this.requests[name][0]; // If we have pending requests and a socket gets closed a new one this.createSocket(name, host, port, localAddress, req).emit('free'); } }; var globalAgent = new Agent(); exports.globalAgent = globalAgent; function ClientRequest(options, cb) { var self = this; OutgoingMessage.call(self); self.agent = options.agent === undefined ? globalAgent : options.agent; var defaultPort = options.defaultPort || 80; var port = options.port || defaultPort; var host = options.hostname || options.host || 'localhost'; if (options.setHost === undefined) { var setHost = true; } self.socketPath = options.socketPath; var method = self.method = (options.method || 'GET').toUpperCase(); self.path = options.path || '/'; if (cb) { self.once('response', cb); } if (!Array.isArray(options.headers)) { if (options.headers) { var keys = Object.keys(options.headers); for (var i = 0, l = keys.length; i < l; i++) { var key = keys[i]; self.setHeader(key, options.headers[key]); } } if (host && !this.getHeader('host') && setHost) { var hostHeader = host; if (port && +port !== defaultPort) { hostHeader += ':' + port; } this.setHeader('Host', hostHeader); } } if (options.auth && !this.getHeader('Authorization')) { //basic auth this.setHeader('Authorization', 'Basic ' + new Buffer(options.auth).toString('base64')); } if (method === 'GET' || method === 'HEAD' || method === 'CONNECT') { self.useChunkedEncodingByDefault = false; } else { self.useChunkedEncodingByDefault = true; } if (Array.isArray(options.headers)) { self._storeHeader(self.method + ' ' + self.path + ' HTTP/1.1\r\n', options.headers); } else if (self.getHeader('expect')) { self._storeHeader(self.method + ' ' + self.path + ' HTTP/1.1\r\n', self._renderHeaders()); } if (self.socketPath) { self._last = true; self.shouldKeepAlive = false; if (options.createConnection) { self.onSocket(options.createConnection(self.socketPath)); } else { self.onSocket(net.createConnection(self.socketPath)); } } else if (self.agent) { // If there is an agent we should default to Connection:keep-alive. self._last = false; self.shouldKeepAlive = true; self.agent.addRequest(self, host, port, options.localAddress); } else { // No agent, default to Connection:close. self._last = true; self.shouldKeepAlive = false; if (options.createConnection) { options.port = port; options.host = host; var conn = options.createConnection(options); } else { var conn = net.createConnection({ port: port, host: host, localAddress: options.localAddress }); } self.onSocket(conn); } self._deferToConnect(null, null, function() { self._flush(); self = null; }); } util.inherits(ClientRequest, OutgoingMessage); exports.ClientRequest = ClientRequest; ClientRequest.prototype._implicitHeader = function() { this._storeHeader(this.method + ' ' + this.path + ' HTTP/1.1\r\n', this._renderHeaders()); }; ClientRequest.prototype.abort = function() { // If we're aborting, we don't care about any more response data. if (this.res) this.res._dump(); else this.once('response', function(res) { res._dump(); }); if (this.socket) { // in-progress this.socket.destroy(); } else { // haven't been assigned a socket yet. // this could be more efficient, it could // remove itself from the pending requests this._deferToConnect('destroy', []); } }; function createHangUpError() { var error = new Error('socket hang up'); error.code = 'ECONNRESET'; return error; } // Free the parser and also break any links that it // might have to any other things. // TODO: All parser data should be attached to a // single object, so that it can be easily cleaned // up by doing `parser.data = {}`, which should // be done in FreeList.free. `parsers.free(parser)` // should be all that is needed. function freeParser(parser, req) { if (parser) { parser._headers = []; parser.onIncoming = null; if (parser.socket) { parser.socket.onend = null; parser.socket.ondata = null; parser.socket.parser = null; } parser.socket = null; parser.incoming = null; parsers.free(parser); parser = null; } if (req) { req.parser = null; } } function socketCloseListener() { var socket = this; var parser = socket.parser; var req = socket._httpMessage; debug('HTTP socket close'); req.emit('close'); if (req.res && req.res.readable) { // Socket closed before we emitted 'end' below. req.res.emit('aborted'); var res = req.res; res.on('end', function() { res.emit('close'); }); res.push(null); } else if (!req.res && !req._hadError) { // This socket error fired before we started to // receive a response. The error needs to // fire on the request. req.emit('error', createHangUpError()); req._hadError = true; } // Too bad. That output wasn't getting written. // This is pretty terrible that it doesn't raise an error. // Fixed better in v0.10 if (req.output) req.output.length = 0; if (req.outputEncodings) req.outputEncodings.length = 0; if (parser) { parser.finish(); freeParser(parser, req); } } function socketErrorListener(err) { var socket = this; var parser = socket.parser; var req = socket._httpMessage; debug('HTTP SOCKET ERROR: ' + err.message + '\n' + err.stack); if (req) { req.emit('error', err); // For Safety. Some additional errors might fire later on // and we need to make sure we don't double-fire the error event. req._hadError = true; } if (parser) { parser.finish(); freeParser(parser, req); } socket.destroy(); } function socketOnEnd() { var socket = this; var req = this._httpMessage; var parser = this.parser; if (!req.res) { // If we don't have a response then we know that the socket // ended prematurely and we need to emit an error on the request. req.emit('error', createHangUpError()); req._hadError = true; } if (parser) { parser.finish(); freeParser(parser, req); } socket.destroy(); } function socketOnData(d, start, end) { var socket = this; var req = this._httpMessage; var parser = this.parser; var ret = parser.execute(d, start, end - start); if (ret instanceof Error) { debug('parse error'); freeParser(parser, req); socket.destroy(); req.emit('error', ret); req._hadError = true; } else if (parser.incoming && parser.incoming.upgrade) { // Upgrade or CONNECT var bytesParsed = ret; var res = parser.incoming; req.res = res; socket.ondata = null; socket.onend = null; parser.finish(); // This is start + byteParsed var bodyHead = d.slice(start + bytesParsed, end); var eventName = req.method === 'CONNECT' ? 'connect' : 'upgrade'; if (EventEmitter.listenerCount(req, eventName) > 0) { req.upgradeOrConnect = true; // detach the socket socket.emit('agentRemove'); socket.removeListener('close', socketCloseListener); socket.removeListener('error', socketErrorListener); req.emit(eventName, res, socket, bodyHead); req.emit('close'); } else { // Got Upgrade header or CONNECT method, but have no handler. socket.destroy(); } freeParser(parser, req); } else if (parser.incoming && parser.incoming.complete && // When the status code is 100 (Continue), the server will // send a final response after this client sends a request // body. So, we must not free the parser. parser.incoming.statusCode !== 100) { freeParser(parser, req); } } // client function parserOnIncomingClient(res, shouldKeepAlive) { var parser = this; var socket = this.socket; var req = socket._httpMessage; // propogate "domain" setting... if (req.domain && !res.domain) { debug('setting "res.domain"'); res.domain = req.domain; } debug('AGENT incoming response!'); if (req.res) { // We already have a response object, this means the server // sent a double response. socket.destroy(); return; } req.res = res; // Responses to CONNECT request is handled as Upgrade. if (req.method === 'CONNECT') { res.upgrade = true; return true; // skip body } // Responses to HEAD requests are crazy. // HEAD responses aren't allowed to have an entity-body // but *can* have a content-length which actually corresponds // to the content-length of the entity-body had the request // been a GET. var isHeadResponse = req.method == 'HEAD'; debug('AGENT isHeadResponse ' + isHeadResponse); if (res.statusCode == 100) { // restart the parser, as this is a continue message. delete req.res; // Clear res so that we don't hit double-responses. req.emit('continue'); return true; } if (req.shouldKeepAlive && !shouldKeepAlive && !req.upgradeOrConnect) { // Server MUST respond with Connection:keep-alive for us to enable it. // If we've been upgraded (via WebSockets) we also shouldn't try to // keep the connection open. req.shouldKeepAlive = false; } DTRACE_HTTP_CLIENT_RESPONSE(socket, req); COUNTER_HTTP_CLIENT_RESPONSE(); req.res = res; res.req = req; // add our listener first, so that we guarantee socket cleanup res.on('end', responseOnEnd); var handled = req.emit('response', res); // If the user did not listen for the 'response' event, then they // can't possibly read the data, so we ._dump() it into the void // so that the socket doesn't hang there in a paused state. if (!handled) res._dump(); return isHeadResponse; } // client function responseOnEnd() { var res = this; var req = res.req; var socket = req.socket; if (!req.shouldKeepAlive) { if (socket.writable) { debug('AGENT socket.destroySoon()'); socket.destroySoon(); } assert(!socket.writable); } else { debug('AGENT socket keep-alive'); if (req.timeoutCb) { socket.setTimeout(0, req.timeoutCb); req.timeoutCb = null; } socket.removeListener('close', socketCloseListener); socket.removeListener('error', socketErrorListener); // Mark this socket as available, AFTER user-added end // handlers have a chance to run. process.nextTick(function() { socket.emit('free'); }); } } ClientRequest.prototype.onSocket = function(socket) { var req = this; process.nextTick(function() { var parser = parsers.alloc(); req.socket = socket; req.connection = socket; parser.reinitialize(HTTPParser.RESPONSE); parser.socket = socket; parser.incoming = null; req.parser = parser; socket.parser = parser; socket._httpMessage = req; // Setup "drain" propogation. httpSocketSetup(socket); // Propagate headers limit from request object to parser if (typeof req.maxHeadersCount === 'number') { parser.maxHeaderPairs = req.maxHeadersCount << 1; } else { // Set default value because parser may be reused from FreeList parser.maxHeaderPairs = 2000; } socket.on('error', socketErrorListener); socket.ondata = socketOnData; socket.onend = socketOnEnd; socket.on('close', socketCloseListener); parser.onIncoming = parserOnIncomingClient; req.emit('socket', socket); }); }; ClientRequest.prototype._deferToConnect = function(method, arguments_, cb) { // This function is for calls that need to happen once the socket is // connected and writable. It's an important promisy thing for all the socket // calls that happen either now (when a socket is assigned) or // in the future (when a socket gets assigned out of the pool and is // eventually writable). var self = this; var onSocket = function() { if (self.socket.writable) { if (method) { self.socket[method].apply(self.socket, arguments_); } if (cb) { cb(); } } else { self.socket.once('connect', function() { if (method) { self.socket[method].apply(self.socket, arguments_); } if (cb) { cb(); } }); } } if (!self.socket) { self.once('socket', onSocket); } else { onSocket(); } }; ClientRequest.prototype.setTimeout = function(msecs, callback) { if (callback) this.once('timeout', callback); var self = this; function emitTimeout() { self.emit('timeout'); } if (this.socket && this.socket.writable) { if (this.timeoutCb) this.socket.setTimeout(0, this.timeoutCb); this.timeoutCb = emitTimeout; this.socket.setTimeout(msecs, emitTimeout); return; } // Set timeoutCb so that it'll get cleaned up on request end this.timeoutCb = emitTimeout; if (this.socket) { var sock = this.socket; this.socket.once('connect', function() { sock.setTimeout(msecs, emitTimeout); }); return; } this.once('socket', function(sock) { sock.setTimeout(msecs, emitTimeout); }); }; ClientRequest.prototype.setNoDelay = function() { this._deferToConnect('setNoDelay', arguments); }; ClientRequest.prototype.setSocketKeepAlive = function() { this._deferToConnect('setKeepAlive', arguments); }; ClientRequest.prototype.clearTimeout = function(cb) { this.setTimeout(0, cb); }; exports.request = function(options, cb) { if (typeof options === 'string') { options = url.parse(options); } if (options.protocol && options.protocol !== 'http:') { throw new Error('Protocol:' + options.protocol + ' not supported.'); } return new ClientRequest(options, cb); }; exports.get = function(options, cb) { var req = exports.request(options, cb); req.end(); return req; }; function ondrain() { if (this._httpMessage) this._httpMessage.emit('drain'); } function httpSocketSetup(socket) { socket.removeListener('drain', ondrain); socket.on('drain', ondrain); } function Server(requestListener) { if (!(this instanceof Server)) return new Server(requestListener); net.Server.call(this, { allowHalfOpen: true }); if (requestListener) { this.addListener('request', requestListener); } // Similar option to this. Too lazy to write my own docs. // http://www.squid-cache.org/Doc/config/half_closed_clients/ // http://wiki.squid-cache.org/SquidFaq/InnerWorkings#What_is_a_half-closed_filedescriptor.3F this.httpAllowHalfOpen = false; this.addListener('connection', connectionListener); this.addListener('clientError', function(err, conn) { conn.destroy(err); }); this.timeout = 2 * 60 * 1000; } util.inherits(Server, net.Server); Server.prototype.setTimeout = function(msecs, callback) { this.timeout = msecs; if (callback) this.on('timeout', callback); }; exports.Server = Server; exports.createServer = function(requestListener) { return new Server(requestListener); }; function connectionListener(socket) { var self = this; var outgoing = []; var incoming = []; function abortIncoming() { while (incoming.length) { var req = incoming.shift(); req.emit('aborted'); req.emit('close'); } // abort socket._httpMessage ? } function serverSocketCloseListener() { debug('server socket close'); // mark this parser as reusable if (this.parser) freeParser(this.parser); abortIncoming(); } debug('SERVER new http connection'); httpSocketSetup(socket); // If the user has added a listener to the server, // request, or response, then it's their responsibility. // otherwise, destroy on timeout by default if (self.timeout) socket.setTimeout(self.timeout); socket.on('timeout', function() { var req = socket.parser && socket.parser.incoming; var reqTimeout = req && !req.complete && req.emit('timeout', socket); var res = socket._httpMessage; var resTimeout = res && res.emit('timeout', socket); var serverTimeout = self.emit('timeout', socket); if (!reqTimeout && !resTimeout && !serverTimeout) socket.destroy(); }); var parser = parsers.alloc(); parser.reinitialize(HTTPParser.REQUEST); parser.socket = socket; socket.parser = parser; parser.incoming = null; // Propagate headers limit from server instance to parser if (typeof this.maxHeadersCount === 'number') { parser.maxHeaderPairs = this.maxHeadersCount << 1; } else { // Set default value because parser may be reused from FreeList parser.maxHeaderPairs = 2000; } socket.addListener('error', function(e) { self.emit('clientError', e, this); }); socket.ondata = function(d, start, end) { assert(!socket._paused); var ret = parser.execute(d, start, end - start); if (ret instanceof Error) { debug('parse error'); socket.destroy(ret); } else if (parser.incoming && parser.incoming.upgrade) { // Upgrade or CONNECT var bytesParsed = ret; var req = parser.incoming; socket.ondata = null; socket.onend = null; socket.removeListener('close', serverSocketCloseListener); parser.finish(); freeParser(parser, req); // This is start + byteParsed var bodyHead = d.slice(start + bytesParsed, end); var eventName = req.method === 'CONNECT' ? 'connect' : 'upgrade'; if (EventEmitter.listenerCount(self, eventName) > 0) { self.emit(eventName, req, req.socket, bodyHead); } else { // Got upgrade header or CONNECT method, but have no handler. socket.destroy(); } } if (socket._paused) { // onIncoming paused the socket, we should pause the parser as well debug('pause parser'); socket.parser.pause(); } }; socket.onend = function() { var ret = parser.finish(); if (ret instanceof Error) { debug('parse error'); socket.destroy(ret); return; } if (!self.httpAllowHalfOpen) { abortIncoming(); if (socket.writable) socket.end(); } else if (outgoing.length) { outgoing[outgoing.length - 1]._last = true; } else if (socket._httpMessage) { socket._httpMessage._last = true; } else { if (socket.writable) socket.end(); } }; socket.addListener('close', serverSocketCloseListener); // The following callback is issued after the headers have been read on a // new message. In this callback we setup the response object and pass it // to the user. socket._paused = false; function socketOnDrain() { // If we previously paused, then start reading again. if (socket._paused) { socket._paused = false; socket.parser.resume(); readStart(socket); } } socket.on('drain', socketOnDrain); parser.onIncoming = function(req, shouldKeepAlive) { incoming.push(req); // If the writable end isn't consuming, then stop reading // so that we don't become overwhelmed by a flood of // pipelined requests that may never be resolved. if (!socket._paused) { var needPause = socket._writableState.needDrain; if (needPause) { socket._paused = true; // We also need to pause the parser, but don't do that until after // the call to execute, because we may still be processing the last // chunk. readStop(socket); } } var res = new ServerResponse(req); res.shouldKeepAlive = shouldKeepAlive; DTRACE_HTTP_SERVER_REQUEST(req, socket); COUNTER_HTTP_SERVER_REQUEST(); if (socket._httpMessage) { // There are already pending outgoing res, append. outgoing.push(res); } else { res.assignSocket(socket); } // When we're finished writing the response, check if this is the last // respose, if so destroy the socket. res.on('finish', function() { // Usually the first incoming element should be our request. it may // be that in the case abortIncoming() was called that the incoming // array will be empty. assert(incoming.length == 0 || incoming[0] === req); incoming.shift(); // if the user never called req.read(), and didn't pipe() or // .resume() or .on('data'), then we call req._dump() so that the // bytes will be pulled off the wire. if (!req._consuming) req._dump(); res.detachSocket(socket); if (res._last) { socket.destroySoon(); } else { // start sending the next message var m = outgoing.shift(); if (m) { m.assignSocket(socket); } } }); if (req.headers.expect !== undefined && (req.httpVersionMajor == 1 && req.httpVersionMinor == 1) && continueExpression.test(req.headers['expect'])) { res._expect_continue = true; if (EventEmitter.listenerCount(self, 'checkContinue') > 0) { self.emit('checkContinue', req, res); } else { res.writeContinue(); self.emit('request', req, res); } } else { self.emit('request', req, res); } return false; // Not a HEAD response. (Not even a response!) }; } exports._connectionListener = connectionListener; // Legacy Interface function Client(port, host) { if (!(this instanceof Client)) return new Client(port, host); EventEmitter.call(this); host = host || 'localhost'; port = port || 80; this.host = host; this.port = port; this.agent = new Agent({ host: host, port: port, maxSockets: 1 }); } util.inherits(Client, EventEmitter); Client.prototype.request = function(method, path, headers) { var self = this; var options = {}; options.host = self.host; options.port = self.port; if (method[0] === '/') { headers = path; path = method; method = 'GET'; } options.method = method; options.path = path; options.headers = headers; options.agent = self.agent; var c = new ClientRequest(options); c.on('error', function(e) { self.emit('error', e); }); // The old Client interface emitted 'end' on socket end. // This doesn't map to how we want things to operate in the future // but it will get removed when we remove this legacy interface. c.on('socket', function(s) { s.on('end', function() { if (self._decoder) { var ret = self._decoder.end(); if (ret) self.emit('data', ret); } self.emit('end'); }); }); return c; }; exports.Client = util.deprecate(Client, 'http.Client will be removed soon. Do not use it.'); exports.createClient = util.deprecate(function(port, host) { return new Client(port, host); }, 'http.createClient is deprecated. Use `http.request` instead.'); node-v0.10.25~dfsg2/lib/child_process.js0000644000000000000000000006504012270121457016547 0ustar rootroot// Copyright Joyent, Inc. and other Node contributors. // // Permission is hereby granted, free of charge, to any person obtaining a // copy of this software and associated documentation files (the // "Software"), to deal in the Software without restriction, including // without limitation the rights to use, copy, modify, merge, publish, // distribute, sublicense, and/or sell copies of the Software, and to permit // persons to whom the Software is furnished to do so, subject to the // following conditions: // // The above copyright notice and this permission notice shall be included // in all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS // OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF // MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN // NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, // DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR // OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE // USE OR OTHER DEALINGS IN THE SOFTWARE. var StringDecoder = require('string_decoder').StringDecoder; var EventEmitter = require('events').EventEmitter; var net = require('net'); var dgram = require('dgram'); var Process = process.binding('process_wrap').Process; var assert = require('assert'); var util = require('util'); var constants; // if (!constants) constants = process.binding('constants'); var handleWraps = {}; function handleWrapGetter(name, callback) { var cons; Object.defineProperty(handleWraps, name, { get: function() { if (cons !== undefined) return cons; return cons = callback(); } }); } handleWrapGetter('Pipe', function() { return process.binding('pipe_wrap').Pipe; }); handleWrapGetter('TTY', function() { return process.binding('tty_wrap').TTY; }); handleWrapGetter('TCP', function() { return process.binding('tcp_wrap').TCP; }); handleWrapGetter('UDP', function() { return process.binding('udp_wrap').UDP; }); // constructors for lazy loading function createPipe(ipc) { return new handleWraps.Pipe(ipc); } function createSocket(pipe, readable) { var s = new net.Socket({ handle: pipe }); if (readable) { s.writable = false; s.readable = true; } else { s.writable = true; s.readable = false; } return s; } // this object contain function to convert TCP objects to native handle objects // and back again. var handleConversion = { 'net.Native': { simultaneousAccepts: true, send: function(message, handle) { return handle; }, got: function(message, handle, emit) { emit(handle); } }, 'net.Server': { simultaneousAccepts: true, send: function(message, server) { return server._handle; }, got: function(message, handle, emit) { var self = this; var server = new net.Server(); server.listen(handle, function() { emit(server); }); } }, 'net.Socket': { send: function(message, socket) { // if the socket was created by net.Server if (socket.server) { // the slave should keep track of the socket message.key = socket.server._connectionKey; var firstTime = !this._channel.sockets.send[message.key]; var socketList = getSocketList('send', this, message.key); // the server should no longer expose a .connection property // and when asked to close it should query the socket status from // the slaves if (firstTime) socket.server._setupSlave(socketList); // Act like socket is detached socket.server._connections--; } // remove handle from socket object, it will be closed when the socket // will be sent var handle = socket._handle; handle.onread = function() {}; socket._handle = null; return handle; }, postSend: function(handle) { // Close the Socket handle after sending it handle.close(); }, got: function(message, handle, emit) { var socket = new net.Socket({handle: handle}); socket.readable = socket.writable = true; // if the socket was created by net.Server we will track the socket if (message.key) { // add socket to connections list var socketList = getSocketList('got', this, message.key); socketList.add({ socket: socket }); } emit(socket); } }, 'dgram.Native': { simultaneousAccepts: false, send: function(message, handle) { return handle; }, got: function(message, handle, emit) { emit(handle); } }, 'dgram.Socket': { simultaneousAccepts: false, send: function(message, socket) { message.dgramType = socket.type; return socket._handle; }, got: function(message, handle, emit) { var socket = new dgram.Socket(message.dgramType); socket.bind(handle, function() { emit(socket); }); } } }; // This object keep track of the socket there are sended function SocketListSend(slave, key) { EventEmitter.call(this); var self = this; this.key = key; this.slave = slave; } util.inherits(SocketListSend, EventEmitter); SocketListSend.prototype._request = function(msg, cmd, callback) { var self = this; if (!this.slave.connected) return onclose(); this.slave.send(msg); function onclose() { self.slave.removeListener('internalMessage', onreply); callback(new Error('Slave closed before reply')); }; function onreply(msg) { if (!(msg.cmd === cmd && msg.key === self.key)) return; self.slave.removeListener('disconnect', onclose); self.slave.removeListener('internalMessage', onreply); callback(null, msg); }; this.slave.once('disconnect', onclose); this.slave.on('internalMessage', onreply); }; SocketListSend.prototype.close = function close(callback) { this._request({ cmd: 'NODE_SOCKET_NOTIFY_CLOSE', key: this.key }, 'NODE_SOCKET_ALL_CLOSED', callback); }; SocketListSend.prototype.getConnections = function getConnections(callback) { this._request({ cmd: 'NODE_SOCKET_GET_COUNT', key: this.key }, 'NODE_SOCKET_COUNT', function(err, msg) { if (err) return callback(err); callback(null, msg.count); }); }; // This object keep track of the socket there are received function SocketListReceive(slave, key) { EventEmitter.call(this); var self = this; this.connections = 0; this.key = key; this.slave = slave; function onempty() { if (!self.slave.connected) return; self.slave.send({ cmd: 'NODE_SOCKET_ALL_CLOSED', key: self.key }); } this.slave.on('internalMessage', function(msg) { if (msg.key !== self.key) return; if (msg.cmd === 'NODE_SOCKET_NOTIFY_CLOSE') { // Already empty if (self.connections === 0) return onempty(); // Wait for sockets to get closed self.once('empty', onempty); } else if (msg.cmd === 'NODE_SOCKET_GET_COUNT') { if (!self.slave.connected) return; self.slave.send({ cmd: 'NODE_SOCKET_COUNT', key: self.key, count: self.connections }); } }); } util.inherits(SocketListReceive, EventEmitter); SocketListReceive.prototype.add = function(obj) { var self = this; this.connections++; // Notify previous owner of socket about its state change obj.socket.once('close', function() { self.connections--; if (self.connections === 0) self.emit('empty'); }); }; function getSocketList(type, slave, key) { var sockets = slave._channel.sockets[type]; var socketList = sockets[key]; if (!socketList) { var Construct = type === 'send' ? SocketListSend : SocketListReceive; socketList = sockets[key] = new Construct(slave, key); } return socketList; } var INTERNAL_PREFIX = 'NODE_'; function handleMessage(target, message, handle) { var eventName = 'message'; if (message !== null && typeof message === 'object' && typeof message.cmd === 'string' && message.cmd.length > INTERNAL_PREFIX.length && message.cmd.slice(0, INTERNAL_PREFIX.length) === INTERNAL_PREFIX) { eventName = 'internalMessage'; } target.emit(eventName, message, handle); } function setupChannel(target, channel) { target._channel = channel; target._handleQueue = null; var decoder = new StringDecoder('utf8'); var jsonBuffer = ''; channel.buffering = false; channel.onread = function(pool, offset, length, recvHandle) { if (pool) { jsonBuffer += decoder.write(pool.slice(offset, offset + length)); var i, start = 0; //Linebreak is used as a message end sign while ((i = jsonBuffer.indexOf('\n', start)) >= 0) { var json = jsonBuffer.slice(start, i); var message = JSON.parse(json); // There will be at most one NODE_HANDLE message in every chunk we // read because SCM_RIGHTS messages don't get coalesced. Make sure // that we deliver the handle with the right message however. if (message && message.cmd === 'NODE_HANDLE') handleMessage(target, message, recvHandle); else handleMessage(target, message, undefined); start = i + 1; } jsonBuffer = jsonBuffer.slice(start); this.buffering = jsonBuffer.length !== 0; } else { this.buffering = false; target.disconnect(); channel.onread = nop; channel.close(); maybeClose(target); } }; // object where socket lists will live channel.sockets = { got: {}, send: {} }; // handlers will go through this target.on('internalMessage', function(message, handle) { // Once acknowledged - continue sending handles. if (message.cmd === 'NODE_HANDLE_ACK') { assert(Array.isArray(target._handleQueue)); var queue = target._handleQueue; target._handleQueue = null; queue.forEach(function(args) { target.send(args.message, args.handle); }); return; } if (message.cmd !== 'NODE_HANDLE') return; // Acknowledge handle receival. target.send({ cmd: 'NODE_HANDLE_ACK' }); var obj = handleConversion[message.type]; // Update simultaneous accepts on Windows if (process.platform === 'win32') { handle._simultaneousAccepts = false; net._setSimultaneousAccepts(handle); } // Convert handle object obj.got.call(this, message, handle, function(handle) { handleMessage(target, message.msg, handle); }); }); target.send = function(message, handle) { if (typeof message === 'undefined') { throw new TypeError('message cannot be undefined'); } if (!this.connected) { this.emit('error', new Error('channel closed')); return; } // package messages with a handle object if (handle) { // this message will be handled by an internalMessage event handler message = { cmd: 'NODE_HANDLE', type: null, msg: message }; if (handle instanceof net.Socket) { message.type = 'net.Socket'; } else if (handle instanceof net.Server) { message.type = 'net.Server'; } else if (handle instanceof process.binding('tcp_wrap').TCP || handle instanceof process.binding('pipe_wrap').Pipe) { message.type = 'net.Native'; } else if (handle instanceof dgram.Socket) { message.type = 'dgram.Socket'; } else if (handle instanceof process.binding('udp_wrap').UDP) { message.type = 'dgram.Native'; } else { throw new TypeError("This handle type can't be sent"); } // Queue-up message and handle if we haven't received ACK yet. if (this._handleQueue) { this._handleQueue.push({ message: message.msg, handle: handle }); return; } var obj = handleConversion[message.type]; // convert TCP object to native handle object handle = handleConversion[message.type].send.apply(target, arguments); // Update simultaneous accepts on Windows if (obj.simultaneousAccepts) { net._setSimultaneousAccepts(handle); } } else if (this._handleQueue) { // Queue request anyway to avoid out-of-order messages. this._handleQueue.push({ message: message, handle: null }); return; } var string = JSON.stringify(message) + '\n'; var writeReq = channel.writeUtf8String(string, handle); if (!writeReq) { var er = errnoException(process._errno, 'write', 'cannot write to IPC channel.'); this.emit('error', er); } else if (handle && !this._handleQueue) { this._handleQueue = []; } if (obj && obj.postSend) { writeReq.oncomplete = obj.postSend.bind(null, handle); } else { writeReq.oncomplete = nop; } /* If the master is > 2 read() calls behind, please stop sending. */ return channel.writeQueueSize < (65536 * 2); }; target.connected = true; target.disconnect = function() { if (!this.connected) { this.emit('error', new Error('IPC channel is already disconnected')); return; } // do not allow messages to be written this.connected = false; this._channel = null; var fired = false; function finish() { if (fired) return; fired = true; channel.close(); target.emit('disconnect'); } // If a message is being read, then wait for it to complete. if (channel.buffering) { this.once('message', finish); this.once('internalMessage', finish); return; } finish(); }; channel.readStart(); } function nop() { } exports.fork = function(modulePath /*, args, options*/) { // Get options and args arguments. var options, args, execArgv; if (Array.isArray(arguments[1])) { args = arguments[1]; options = util._extend({}, arguments[2]); } else { args = []; options = util._extend({}, arguments[1]); } // Prepare arguments for fork: execArgv = options.execArgv || process.execArgv; args = execArgv.concat([modulePath], args); // Leave stdin open for the IPC channel. stdout and stderr should be the // same as the parent's if silent isn't set. options.stdio = options.silent ? ['pipe', 'pipe', 'pipe', 'ipc'] : [0, 1, 2, 'ipc']; options.execPath = options.execPath || process.execPath; return spawn(options.execPath, args, options); }; exports._forkChild = function(fd) { // set process.send() var p = createPipe(true); p.open(fd); p.unref(); setupChannel(process, p); var refs = 0; process.on('newListener', function(name) { if (name !== 'message' && name !== 'disconnect') return; if (++refs === 1) p.ref(); }); process.on('removeListener', function(name) { if (name !== 'message' && name !== 'disconnect') return; if (--refs === 0) p.unref(); }); }; exports.exec = function(command /*, options, callback */) { var file, args, options, callback; if (typeof arguments[1] === 'function') { options = undefined; callback = arguments[1]; } else { options = arguments[1]; callback = arguments[2]; } if (process.platform === 'win32') { file = 'cmd.exe'; args = ['/s', '/c', '"' + command + '"']; // Make a shallow copy before patching so we don't clobber the user's // options object. options = util._extend({}, options); options.windowsVerbatimArguments = true; } else { file = '/bin/sh'; args = ['-c', command]; } return exports.execFile(file, args, options, callback); }; exports.execFile = function(file /* args, options, callback */) { var args, optionArg, callback; var options = { encoding: 'utf8', timeout: 0, maxBuffer: 200 * 1024, killSignal: 'SIGTERM', cwd: null, env: null }; // Parse the parameters. if (typeof arguments[arguments.length - 1] === 'function') { callback = arguments[arguments.length - 1]; } if (Array.isArray(arguments[1])) { args = arguments[1]; options = util._extend(options, arguments[2]); } else { args = []; options = util._extend(options, arguments[1]); } var child = spawn(file, args, { cwd: options.cwd, env: options.env, windowsVerbatimArguments: !!options.windowsVerbatimArguments }); var stdout = ''; var stderr = ''; var killed = false; var exited = false; var timeoutId; var err; function exithandler(code, signal) { if (exited) return; exited = true; if (timeoutId) { clearTimeout(timeoutId); timeoutId = null; } if (!callback) return; if (err) { callback(err, stdout, stderr); } else if (code === 0 && signal === null) { callback(null, stdout, stderr); } else { var e = new Error('Command failed: ' + stderr); e.killed = child.killed || killed; e.code = code; e.signal = signal; callback(e, stdout, stderr); } } function errorhandler(e) { err = e; child.stdout.destroy(); child.stderr.destroy(); exithandler(); } function kill() { child.stdout.destroy(); child.stderr.destroy(); killed = true; try { child.kill(options.killSignal); } catch (e) { err = e; exithandler(); } } if (options.timeout > 0) { timeoutId = setTimeout(function() { kill(); timeoutId = null; }, options.timeout); } child.stdout.setEncoding(options.encoding); child.stderr.setEncoding(options.encoding); child.stdout.addListener('data', function(chunk) { stdout += chunk; if (stdout.length > options.maxBuffer) { err = new Error('stdout maxBuffer exceeded.'); kill(); } }); child.stderr.addListener('data', function(chunk) { stderr += chunk; if (stderr.length > options.maxBuffer) { err = new Error('stderr maxBuffer exceeded.'); kill(); } }); child.addListener('close', exithandler); child.addListener('error', errorhandler); return child; }; var spawn = exports.spawn = function(file /*, args, options*/) { var args, options; if (Array.isArray(arguments[1])) { args = arguments[1].slice(0); options = arguments[2]; } else { args = []; options = arguments[1]; } args.unshift(file); var env = (options ? options.env : null) || process.env; var envPairs = []; for (var key in env) { envPairs.push(key + '=' + env[key]); } var child = new ChildProcess(); if (options && options.customFds && !options.stdio) { options.stdio = options.customFds.map(function(fd) { return fd === -1 ? 'pipe' : fd; }); } child.spawn({ file: file, args: args, cwd: options ? options.cwd : null, windowsVerbatimArguments: !!(options && options.windowsVerbatimArguments), detached: !!(options && options.detached), envPairs: envPairs, stdio: options ? options.stdio : null, uid: options ? options.uid : null, gid: options ? options.gid : null }); return child; }; function maybeClose(subprocess) { subprocess._closesGot++; if (subprocess._closesGot == subprocess._closesNeeded) { subprocess.emit('close', subprocess.exitCode, subprocess.signalCode); } } function ChildProcess() { EventEmitter.call(this); // Initialize TCPWrap and PipeWrap process.binding('tcp_wrap'); process.binding('pipe_wrap'); var self = this; this._closesNeeded = 1; this._closesGot = 0; this.connected = false; this.signalCode = null; this.exitCode = null; this.killed = false; this._handle = new Process(); this._handle.owner = this; this._handle.onexit = function(exitCode, signalCode) { // // follow 0.4.x behaviour: // // - normally terminated processes don't touch this.signalCode // - signaled processes don't touch this.exitCode // // new in 0.9.x: // // - spawn failures are reported with exitCode == -1 // var err = (exitCode == -1) ? errnoException(process._errno, 'spawn') : null; if (signalCode) { self.signalCode = signalCode; } else { self.exitCode = exitCode; } if (self.stdin) { self.stdin.destroy(); } self._handle.close(); self._handle = null; if (exitCode == -1) { self.emit('error', err); } else { self.emit('exit', self.exitCode, self.signalCode); } // if any of the stdio streams have not been touched, // then pull all the data through so that it can get the // eof and emit a 'close' event. // Do it on nextTick so that the user has one last chance // to consume the output, if for example they only want to // start reading the data once the process exits. process.nextTick(function() { flushStdio(self); }); maybeClose(self); }; } util.inherits(ChildProcess, EventEmitter); function flushStdio(subprocess) { subprocess.stdio.forEach(function(stream, fd, stdio) { if (!stream || !stream.readable || stream._consuming || stream._readableState.flowing) return; stream.resume(); }); } function getHandleWrapType(stream) { if (stream instanceof handleWraps.Pipe) return 'pipe'; if (stream instanceof handleWraps.TTY) return 'tty'; if (stream instanceof handleWraps.TCP) return 'tcp'; if (stream instanceof handleWraps.UDP) return 'udp'; return false; } ChildProcess.prototype.spawn = function(options) { var self = this, ipc, ipcFd, // If no `stdio` option was given - use default stdio = options.stdio || 'pipe'; // Replace shortcut with an array if (typeof stdio === 'string') { switch (stdio) { case 'ignore': stdio = ['ignore', 'ignore', 'ignore']; break; case 'pipe': stdio = ['pipe', 'pipe', 'pipe']; break; case 'inherit': stdio = [0, 1, 2]; break; default: throw new TypeError('Incorrect value of stdio option: ' + stdio); } } else if (!Array.isArray(stdio)) { throw new TypeError('Incorrect value of stdio option: ' + stdio); } // At least 3 stdio will be created // Don't concat() a new Array() because it would be sparse, and // stdio.reduce() would skip the sparse elements of stdio. // See http://stackoverflow.com/a/5501711/3561 while (stdio.length < 3) stdio.push(undefined); // Translate stdio into C++-readable form // (i.e. PipeWraps or fds) stdio = stdio.reduce(function(acc, stdio, i) { function cleanup() { acc.filter(function(stdio) { return stdio.type === 'pipe' || stdio.type === 'ipc'; }).forEach(function(stdio) { stdio.handle.close(); }); } // Defaults if (stdio === undefined || stdio === null) { stdio = i < 3 ? 'pipe' : 'ignore'; } if (stdio === 'ignore') { acc.push({type: 'ignore'}); } else if (stdio === 'pipe' || typeof stdio === 'number' && stdio < 0) { acc.push({type: 'pipe', handle: createPipe()}); } else if (stdio === 'ipc') { if (ipc !== undefined) { // Cleanup previously created pipes cleanup(); throw Error('Child process can have only one IPC pipe'); } ipc = createPipe(true); ipcFd = i; acc.push({ type: 'pipe', handle: ipc, ipc: true }); } else if (typeof stdio === 'number' || typeof stdio.fd === 'number') { acc.push({ type: 'fd', fd: stdio.fd || stdio }); } else if (getHandleWrapType(stdio) || getHandleWrapType(stdio.handle) || getHandleWrapType(stdio._handle)) { var handle = getHandleWrapType(stdio) ? stdio : getHandleWrapType(stdio.handle) ? stdio.handle : stdio._handle; acc.push({ type: 'wrap', wrapType: getHandleWrapType(handle), handle: handle }); } else { // Cleanup cleanup(); throw new TypeError('Incorrect value for stdio stream: ' + stdio); } return acc; }, []); options.stdio = stdio; if (ipc !== undefined) { // Let child process know about opened IPC channel options.envPairs = options.envPairs || []; options.envPairs.push('NODE_CHANNEL_FD=' + ipcFd); } var r = this._handle.spawn(options); if (r) { // Close all opened fds on error stdio.forEach(function(stdio) { if (stdio.type === 'pipe') { stdio.handle.close(); } }); this._handle.close(); this._handle = null; throw errnoException(process._errno, 'spawn'); } this.pid = this._handle.pid; stdio.forEach(function(stdio, i) { if (stdio.type === 'ignore') return; if (stdio.ipc) { self._closesNeeded++; return; } if (stdio.handle) { // when i === 0 - we're dealing with stdin // (which is the only one writable pipe) stdio.socket = createSocket(self.pid !== 0 ? stdio.handle : null, i > 0); if (i > 0 && self.pid !== 0) { self._closesNeeded++; stdio.socket.on('close', function() { maybeClose(self); }); } } }); this.stdin = stdio.length >= 1 && stdio[0].socket !== undefined ? stdio[0].socket : null; this.stdout = stdio.length >= 2 && stdio[1].socket !== undefined ? stdio[1].socket : null; this.stderr = stdio.length >= 3 && stdio[2].socket !== undefined ? stdio[2].socket : null; this.stdio = stdio.map(function(stdio) { return stdio.socket === undefined ? null : stdio.socket; }); // Add .send() method and start listening for IPC data if (ipc !== undefined) setupChannel(this, ipc); return r; }; function errnoException(errorno, syscall, errmsg) { // TODO make this more compatible with ErrnoException from src/node.cc // Once all of Node is using this function the ErrnoException from // src/node.cc should be removed. var message = syscall + ' ' + errorno; if (errmsg) { message += ' - ' + errmsg; } var e = new Error(message); e.errno = e.code = errorno; e.syscall = syscall; return e; } ChildProcess.prototype.kill = function(sig) { var signal; if (!constants) { constants = process.binding('constants'); } if (sig === 0) { signal = 0; } else if (!sig) { signal = constants['SIGTERM']; } else { signal = constants[sig]; } if (signal === undefined) { throw new Error('Unknown signal: ' + sig); } if (this._handle) { var r = this._handle.kill(signal); if (r == 0) { /* Success. */ this.killed = true; return true; } else if (process._errno == 'ESRCH') { /* Already dead. */ } else if (process._errno == 'EINVAL' || process._errno == 'ENOSYS') { /* The underlying platform doesn't support this signal. */ throw errnoException(process._errno, 'kill'); } else { /* Other error, almost certainly EPERM. */ this.emit('error', errnoException(process._errno, 'kill')); } } /* Kill didn't succeed. */ return false; }; ChildProcess.prototype.ref = function() { if (this._handle) this._handle.ref(); }; ChildProcess.prototype.unref = function() { if (this._handle) this._handle.unref(); }; node-v0.10.25~dfsg2/lib/fs.js0000644000000000000000000013034012270121457014332 0ustar rootroot// Copyright Joyent, Inc. and other Node contributors. // // Permission is hereby granted, free of charge, to any person obtaining a // copy of this software and associated documentation files (the // "Software"), to deal in the Software without restriction, including // without limitation the rights to use, copy, modify, merge, publish, // distribute, sublicense, and/or sell copies of the Software, and to permit // persons to whom the Software is furnished to do so, subject to the // following conditions: // // The above copyright notice and this permission notice shall be included // in all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS // OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF // MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN // NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, // DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR // OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE // USE OR OTHER DEALINGS IN THE SOFTWARE. // Maintainers, keep in mind that octal literals are not allowed // in strict mode. Use the decimal value and add a comment with // the octal value. Example: // // var mode = 438; /* mode=0666 */ var util = require('util'); var pathModule = require('path'); var binding = process.binding('fs'); var constants = process.binding('constants'); var fs = exports; var Stream = require('stream').Stream; var EventEmitter = require('events').EventEmitter; var Readable = Stream.Readable; var Writable = Stream.Writable; var kMinPoolSpace = 128; var O_APPEND = constants.O_APPEND || 0; var O_CREAT = constants.O_CREAT || 0; var O_DIRECTORY = constants.O_DIRECTORY || 0; var O_EXCL = constants.O_EXCL || 0; var O_NOCTTY = constants.O_NOCTTY || 0; var O_NOFOLLOW = constants.O_NOFOLLOW || 0; var O_RDONLY = constants.O_RDONLY || 0; var O_RDWR = constants.O_RDWR || 0; var O_SYMLINK = constants.O_SYMLINK || 0; var O_SYNC = constants.O_SYNC || 0; var O_TRUNC = constants.O_TRUNC || 0; var O_WRONLY = constants.O_WRONLY || 0; var isWindows = process.platform === 'win32'; var DEBUG = process.env.NODE_DEBUG && /fs/.test(process.env.NODE_DEBUG); function rethrow() { // Only enable in debug mode. A backtrace uses ~1000 bytes of heap space and // is fairly slow to generate. var callback; if (DEBUG) { var backtrace = new Error; callback = debugCallback; } else callback = missingCallback; return callback; function debugCallback(err) { if (err) { backtrace.message = err.message; err = backtrace; missingCallback(err); } } function missingCallback(err) { if (err) { if (process.throwDeprecation) throw err; // Forgot a callback but don't know where? Use NODE_DEBUG=fs else if (!process.noDeprecation) { var msg = 'fs: missing callback ' + (err.stack || err.message); if (process.traceDeprecation) console.trace(msg); else console.error(msg); } } } } function maybeCallback(cb) { return typeof cb === 'function' ? cb : rethrow(); } // Ensure that callbacks run in the global context. Only use this function // for callbacks that are passed to the binding layer, callbacks that are // invoked from JS already run in the proper scope. function makeCallback(cb) { if (typeof cb !== 'function') { return rethrow(); } return function() { return cb.apply(null, arguments); }; } function assertEncoding(encoding) { if (encoding && !Buffer.isEncoding(encoding)) { throw new Error('Unknown encoding: ' + encoding); } } function nullCheck(path, callback) { if (('' + path).indexOf('\u0000') !== -1) { var er = new Error('Path must be a string without null bytes.'); if (!callback) throw er; process.nextTick(function() { callback(er); }); return false; } return true; } fs.Stats = binding.Stats; fs.Stats.prototype._checkModeProperty = function(property) { return ((this.mode & constants.S_IFMT) === property); }; fs.Stats.prototype.isDirectory = function() { return this._checkModeProperty(constants.S_IFDIR); }; fs.Stats.prototype.isFile = function() { return this._checkModeProperty(constants.S_IFREG); }; fs.Stats.prototype.isBlockDevice = function() { return this._checkModeProperty(constants.S_IFBLK); }; fs.Stats.prototype.isCharacterDevice = function() { return this._checkModeProperty(constants.S_IFCHR); }; fs.Stats.prototype.isSymbolicLink = function() { return this._checkModeProperty(constants.S_IFLNK); }; fs.Stats.prototype.isFIFO = function() { return this._checkModeProperty(constants.S_IFIFO); }; fs.Stats.prototype.isSocket = function() { return this._checkModeProperty(constants.S_IFSOCK); }; fs.exists = function(path, callback) { if (!nullCheck(path, cb)) return; binding.stat(pathModule._makeLong(path), cb); function cb(err, stats) { if (callback) callback(err ? false : true); } }; fs.existsSync = function(path) { try { nullCheck(path); binding.stat(pathModule._makeLong(path)); return true; } catch (e) { return false; } }; fs.readFile = function(path, options, callback_) { var callback = maybeCallback(arguments[arguments.length - 1]); if (typeof options === 'function' || !options) { options = { encoding: null, flag: 'r' }; } else if (typeof options === 'string') { options = { encoding: options, flag: 'r' }; } else if (!options) { options = { encoding: null, flag: 'r' }; } else if (typeof options !== 'object') { throw new TypeError('Bad arguments'); } var encoding = options.encoding; assertEncoding(encoding); // first, stat the file, so we know the size. var size; var buffer; // single buffer with file data var buffers; // list for when size is unknown var pos = 0; var fd; var flag = options.flag || 'r'; fs.open(path, flag, 438 /*=0666*/, function(er, fd_) { if (er) return callback(er); fd = fd_; fs.fstat(fd, function(er, st) { if (er) return callback(er); size = st.size; if (size === 0) { // the kernel lies about many files. // Go ahead and try to read some bytes. buffers = []; return read(); } buffer = new Buffer(size); read(); }); }); function read() { if (size === 0) { buffer = new Buffer(8192); fs.read(fd, buffer, 0, 8192, -1, afterRead); } else { fs.read(fd, buffer, pos, size - pos, -1, afterRead); } } function afterRead(er, bytesRead) { if (er) { return fs.close(fd, function(er2) { return callback(er); }); } if (bytesRead === 0) { return close(); } pos += bytesRead; if (size !== 0) { if (pos === size) close(); else read(); } else { // unknown size, just read until we don't get bytes. buffers.push(buffer.slice(0, bytesRead)); read(); } } function close() { fs.close(fd, function(er) { if (size === 0) { // collected the data into the buffers list. buffer = Buffer.concat(buffers, pos); } else if (pos < size) { buffer = buffer.slice(0, pos); } if (encoding) buffer = buffer.toString(encoding); return callback(er, buffer); }); } }; fs.readFileSync = function(path, options) { if (!options) { options = { encoding: null, flag: 'r' }; } else if (typeof options === 'string') { options = { encoding: options, flag: 'r' }; } else if (typeof options !== 'object') { throw new TypeError('Bad arguments'); } var encoding = options.encoding; assertEncoding(encoding); var flag = options.flag || 'r'; var fd = fs.openSync(path, flag, 438 /*=0666*/); var size; var threw = true; try { size = fs.fstatSync(fd).size; threw = false; } finally { if (threw) fs.closeSync(fd); } var pos = 0; var buffer; // single buffer with file data var buffers; // list for when size is unknown if (size === 0) { buffers = []; } else { buffer = new Buffer(size); } var done = false; while (!done) { var threw = true; try { if (size !== 0) { var bytesRead = fs.readSync(fd, buffer, pos, size - pos); } else { // the kernel lies about many files. // Go ahead and try to read some bytes. buffer = new Buffer(8192); var bytesRead = fs.readSync(fd, buffer, 0, 8192); if (bytesRead) { buffers.push(buffer.slice(0, bytesRead)); } } threw = false; } finally { if (threw) fs.closeSync(fd); } pos += bytesRead; done = (bytesRead === 0) || (size !== 0 && pos >= size); } fs.closeSync(fd); if (size === 0) { // data was collected into the buffers list. buffer = Buffer.concat(buffers, pos); } else if (pos < size) { buffer = buffer.slice(0, pos); } if (encoding) buffer = buffer.toString(encoding); return buffer; }; // Used by binding.open and friends function stringToFlags(flag) { // Only mess with strings if (typeof flag !== 'string') { return flag; } // O_EXCL is mandated by POSIX, Windows supports it too. // Let's add a check anyway, just in case. if (!O_EXCL && ~flag.indexOf('x')) { throw errnoException('ENOSYS', 'fs.open(O_EXCL)'); } switch (flag) { case 'r' : return O_RDONLY; case 'rs' : return O_RDONLY | O_SYNC; case 'r+' : return O_RDWR; case 'rs+' : return O_RDWR | O_SYNC; case 'w' : return O_TRUNC | O_CREAT | O_WRONLY; case 'wx' : // fall through case 'xw' : return O_TRUNC | O_CREAT | O_WRONLY | O_EXCL; case 'w+' : return O_TRUNC | O_CREAT | O_RDWR; case 'wx+': // fall through case 'xw+': return O_TRUNC | O_CREAT | O_RDWR | O_EXCL; case 'a' : return O_APPEND | O_CREAT | O_WRONLY; case 'ax' : // fall through case 'xa' : return O_APPEND | O_CREAT | O_WRONLY | O_EXCL; case 'a+' : return O_APPEND | O_CREAT | O_RDWR; case 'ax+': // fall through case 'xa+': return O_APPEND | O_CREAT | O_RDWR | O_EXCL; } throw new Error('Unknown file open flag: ' + flag); } // exported but hidden, only used by test/simple/test-fs-open-flags.js Object.defineProperty(exports, '_stringToFlags', { enumerable: false, value: stringToFlags }); // Yes, the follow could be easily DRYed up but I provide the explicit // list to make the arguments clear. fs.close = function(fd, callback) { binding.close(fd, makeCallback(callback)); }; fs.closeSync = function(fd) { return binding.close(fd); }; function modeNum(m, def) { switch (typeof m) { case 'number': return m; case 'string': return parseInt(m, 8); default: if (def) { return modeNum(def); } else { return undefined; } } } fs.open = function(path, flags, mode, callback) { callback = makeCallback(arguments[arguments.length - 1]); mode = modeNum(mode, 438 /*=0666*/); if (!nullCheck(path, callback)) return; binding.open(pathModule._makeLong(path), stringToFlags(flags), mode, callback); }; fs.openSync = function(path, flags, mode) { mode = modeNum(mode, 438 /*=0666*/); nullCheck(path); return binding.open(pathModule._makeLong(path), stringToFlags(flags), mode); }; fs.read = function(fd, buffer, offset, length, position, callback) { if (!Buffer.isBuffer(buffer)) { // legacy string interface (fd, length, position, encoding, callback) var cb = arguments[4], encoding = arguments[3]; assertEncoding(encoding); position = arguments[2]; length = arguments[1]; buffer = new Buffer(length); offset = 0; callback = function(err, bytesRead) { if (!cb) return; var str = (bytesRead > 0) ? buffer.toString(encoding, 0, bytesRead) : ''; (cb)(err, str, bytesRead); }; } function wrapper(err, bytesRead) { // Retain a reference to buffer so that it can't be GC'ed too soon. callback && callback(err, bytesRead || 0, buffer); } binding.read(fd, buffer, offset, length, position, wrapper); }; fs.readSync = function(fd, buffer, offset, length, position) { var legacy = false; if (!Buffer.isBuffer(buffer)) { // legacy string interface (fd, length, position, encoding, callback) legacy = true; var encoding = arguments[3]; assertEncoding(encoding); position = arguments[2]; length = arguments[1]; buffer = new Buffer(length); offset = 0; } var r = binding.read(fd, buffer, offset, length, position); if (!legacy) { return r; } var str = (r > 0) ? buffer.toString(encoding, 0, r) : ''; return [str, r]; }; fs.write = function(fd, buffer, offset, length, position, callback) { if (!Buffer.isBuffer(buffer)) { // legacy string interface (fd, data, position, encoding, callback) callback = arguments[4]; position = arguments[2]; assertEncoding(arguments[3]); buffer = new Buffer('' + arguments[1], arguments[3]); offset = 0; length = buffer.length; } if (!length) { if (typeof callback == 'function') { process.nextTick(function() { callback(undefined, 0); }); } return; } callback = maybeCallback(callback); function wrapper(err, written) { // Retain a reference to buffer so that it can't be GC'ed too soon. callback(err, written || 0, buffer); } binding.write(fd, buffer, offset, length, position, wrapper); }; fs.writeSync = function(fd, buffer, offset, length, position) { if (!Buffer.isBuffer(buffer)) { // legacy string interface (fd, data, position, encoding) position = arguments[2]; assertEncoding(arguments[3]); buffer = new Buffer('' + arguments[1], arguments[3]); offset = 0; length = buffer.length; } if (!length) return 0; return binding.write(fd, buffer, offset, length, position); }; fs.rename = function(oldPath, newPath, callback) { callback = makeCallback(callback); if (!nullCheck(oldPath, callback)) return; if (!nullCheck(newPath, callback)) return; binding.rename(pathModule._makeLong(oldPath), pathModule._makeLong(newPath), callback); }; fs.renameSync = function(oldPath, newPath) { nullCheck(oldPath); nullCheck(newPath); return binding.rename(pathModule._makeLong(oldPath), pathModule._makeLong(newPath)); }; fs.truncate = function(path, len, callback) { if (typeof path === 'number') { // legacy return fs.ftruncate(path, len, callback); } if (typeof len === 'function') { callback = len; len = 0; } else if (typeof len === 'undefined') { len = 0; } callback = maybeCallback(callback); fs.open(path, 'r+', function(er, fd) { if (er) return callback(er); binding.ftruncate(fd, len, function(er) { fs.close(fd, function(er2) { callback(er || er2); }); }); }); }; fs.truncateSync = function(path, len) { if (typeof path === 'number') { // legacy return fs.ftruncateSync(path, len); } if (typeof len === 'undefined') { len = 0; } // allow error to be thrown, but still close fd. var fd = fs.openSync(path, 'r+'); try { var ret = fs.ftruncateSync(fd, len); } finally { fs.closeSync(fd); } return ret; }; fs.ftruncate = function(fd, len, callback) { if (typeof len === 'function') { callback = len; len = 0; } else if (typeof len === 'undefined') { len = 0; } binding.ftruncate(fd, len, makeCallback(callback)); }; fs.ftruncateSync = function(fd, len) { if (typeof len === 'undefined') { len = 0; } return binding.ftruncate(fd, len); }; fs.rmdir = function(path, callback) { callback = makeCallback(callback); if (!nullCheck(path, callback)) return; binding.rmdir(pathModule._makeLong(path), callback); }; fs.rmdirSync = function(path) { nullCheck(path); return binding.rmdir(pathModule._makeLong(path)); }; fs.fdatasync = function(fd, callback) { binding.fdatasync(fd, makeCallback(callback)); }; fs.fdatasyncSync = function(fd) { return binding.fdatasync(fd); }; fs.fsync = function(fd, callback) { binding.fsync(fd, makeCallback(callback)); }; fs.fsyncSync = function(fd) { return binding.fsync(fd); }; fs.mkdir = function(path, mode, callback) { if (typeof mode === 'function') callback = mode; callback = makeCallback(callback); if (!nullCheck(path, callback)) return; binding.mkdir(pathModule._makeLong(path), modeNum(mode, 511 /*=0777*/), callback); }; fs.mkdirSync = function(path, mode) { nullCheck(path); return binding.mkdir(pathModule._makeLong(path), modeNum(mode, 511 /*=0777*/)); }; fs.readdir = function(path, callback) { callback = makeCallback(callback); if (!nullCheck(path, callback)) return; binding.readdir(pathModule._makeLong(path), callback); }; fs.readdirSync = function(path) { nullCheck(path); return binding.readdir(pathModule._makeLong(path)); }; fs.fstat = function(fd, callback) { binding.fstat(fd, makeCallback(callback)); }; fs.lstat = function(path, callback) { callback = makeCallback(callback); if (!nullCheck(path, callback)) return; binding.lstat(pathModule._makeLong(path), callback); }; fs.stat = function(path, callback) { callback = makeCallback(callback); if (!nullCheck(path, callback)) return; binding.stat(pathModule._makeLong(path), callback); }; fs.fstatSync = function(fd) { return binding.fstat(fd); }; fs.lstatSync = function(path) { nullCheck(path); return binding.lstat(pathModule._makeLong(path)); }; fs.statSync = function(path) { nullCheck(path); return binding.stat(pathModule._makeLong(path)); }; fs.readlink = function(path, callback) { callback = makeCallback(callback); if (!nullCheck(path, callback)) return; binding.readlink(pathModule._makeLong(path), callback); }; fs.readlinkSync = function(path) { nullCheck(path); return binding.readlink(pathModule._makeLong(path)); }; function preprocessSymlinkDestination(path, type) { if (!isWindows) { // No preprocessing is needed on Unix. return path; } else if (type === 'junction') { // Junctions paths need to be absolute and \\?\-prefixed. return pathModule._makeLong(path); } else { // Windows symlinks don't tolerate forward slashes. return ('' + path).replace(/\//g, '\\'); } } fs.symlink = function(destination, path, type_, callback) { var type = (typeof type_ === 'string' ? type_ : null); var callback = makeCallback(arguments[arguments.length - 1]); if (!nullCheck(destination, callback)) return; if (!nullCheck(path, callback)) return; binding.symlink(preprocessSymlinkDestination(destination, type), pathModule._makeLong(path), type, callback); }; fs.symlinkSync = function(destination, path, type) { type = (typeof type === 'string' ? type : null); nullCheck(destination); nullCheck(path); return binding.symlink(preprocessSymlinkDestination(destination, type), pathModule._makeLong(path), type); }; fs.link = function(srcpath, dstpath, callback) { callback = makeCallback(callback); if (!nullCheck(srcpath, callback)) return; if (!nullCheck(dstpath, callback)) return; binding.link(pathModule._makeLong(srcpath), pathModule._makeLong(dstpath), callback); }; fs.linkSync = function(srcpath, dstpath) { nullCheck(srcpath); nullCheck(dstpath); return binding.link(pathModule._makeLong(srcpath), pathModule._makeLong(dstpath)); }; fs.unlink = function(path, callback) { callback = makeCallback(callback); if (!nullCheck(path, callback)) return; binding.unlink(pathModule._makeLong(path), callback); }; fs.unlinkSync = function(path) { nullCheck(path); return binding.unlink(pathModule._makeLong(path)); }; fs.fchmod = function(fd, mode, callback) { binding.fchmod(fd, modeNum(mode), makeCallback(callback)); }; fs.fchmodSync = function(fd, mode) { return binding.fchmod(fd, modeNum(mode)); }; if (constants.hasOwnProperty('O_SYMLINK')) { fs.lchmod = function(path, mode, callback) { callback = maybeCallback(callback); fs.open(path, constants.O_WRONLY | constants.O_SYMLINK, function(err, fd) { if (err) { callback(err); return; } // prefer to return the chmod error, if one occurs, // but still try to close, and report closing errors if they occur. fs.fchmod(fd, mode, function(err) { fs.close(fd, function(err2) { callback(err || err2); }); }); }); }; fs.lchmodSync = function(path, mode) { var fd = fs.openSync(path, constants.O_WRONLY | constants.O_SYMLINK); // prefer to return the chmod error, if one occurs, // but still try to close, and report closing errors if they occur. var err, err2; try { var ret = fs.fchmodSync(fd, mode); } catch (er) { err = er; } try { fs.closeSync(fd); } catch (er) { err2 = er; } if (err || err2) throw (err || err2); return ret; }; } fs.chmod = function(path, mode, callback) { callback = makeCallback(callback); if (!nullCheck(path, callback)) return; binding.chmod(pathModule._makeLong(path), modeNum(mode), callback); }; fs.chmodSync = function(path, mode) { nullCheck(path); return binding.chmod(pathModule._makeLong(path), modeNum(mode)); }; if (constants.hasOwnProperty('O_SYMLINK')) { fs.lchown = function(path, uid, gid, callback) { callback = maybeCallback(callback); fs.open(path, constants.O_WRONLY | constants.O_SYMLINK, function(err, fd) { if (err) { callback(err); return; } fs.fchown(fd, uid, gid, callback); }); }; fs.lchownSync = function(path, uid, gid) { var fd = fs.openSync(path, constants.O_WRONLY | constants.O_SYMLINK); return fs.fchownSync(fd, uid, gid); }; } fs.fchown = function(fd, uid, gid, callback) { binding.fchown(fd, uid, gid, makeCallback(callback)); }; fs.fchownSync = function(fd, uid, gid) { return binding.fchown(fd, uid, gid); }; fs.chown = function(path, uid, gid, callback) { callback = makeCallback(callback); if (!nullCheck(path, callback)) return; binding.chown(pathModule._makeLong(path), uid, gid, callback); }; fs.chownSync = function(path, uid, gid) { nullCheck(path); return binding.chown(pathModule._makeLong(path), uid, gid); }; // converts Date or number to a fractional UNIX timestamp function toUnixTimestamp(time) { if (typeof time == 'number') { return time; } if (time instanceof Date) { // convert to 123.456 UNIX timestamp return time.getTime() / 1000; } throw new Error('Cannot parse time: ' + time); } // exported for unit tests, not for public consumption fs._toUnixTimestamp = toUnixTimestamp; fs.utimes = function(path, atime, mtime, callback) { callback = makeCallback(callback); if (!nullCheck(path, callback)) return; binding.utimes(pathModule._makeLong(path), toUnixTimestamp(atime), toUnixTimestamp(mtime), callback); }; fs.utimesSync = function(path, atime, mtime) { nullCheck(path); atime = toUnixTimestamp(atime); mtime = toUnixTimestamp(mtime); binding.utimes(pathModule._makeLong(path), atime, mtime); }; fs.futimes = function(fd, atime, mtime, callback) { atime = toUnixTimestamp(atime); mtime = toUnixTimestamp(mtime); binding.futimes(fd, atime, mtime, makeCallback(callback)); }; fs.futimesSync = function(fd, atime, mtime) { atime = toUnixTimestamp(atime); mtime = toUnixTimestamp(mtime); binding.futimes(fd, atime, mtime); }; function writeAll(fd, buffer, offset, length, position, callback) { callback = maybeCallback(arguments[arguments.length - 1]); // write(fd, buffer, offset, length, position, callback) fs.write(fd, buffer, offset, length, position, function(writeErr, written) { if (writeErr) { fs.close(fd, function() { if (callback) callback(writeErr); }); } else { if (written === length) { fs.close(fd, callback); } else { offset += written; length -= written; position += written; writeAll(fd, buffer, offset, length, position, callback); } } }); } fs.writeFile = function(path, data, options, callback) { var callback = maybeCallback(arguments[arguments.length - 1]); if (typeof options === 'function' || !options) { options = { encoding: 'utf8', mode: 438 /*=0666*/, flag: 'w' }; } else if (typeof options === 'string') { options = { encoding: options, mode: 438, flag: 'w' }; } else if (!options) { options = { encoding: 'utf8', mode: 438 /*=0666*/, flag: 'w' }; } else if (typeof options !== 'object') { throw new TypeError('Bad arguments'); } assertEncoding(options.encoding); var flag = options.flag || 'w'; fs.open(path, options.flag || 'w', options.mode, function(openErr, fd) { if (openErr) { if (callback) callback(openErr); } else { var buffer = Buffer.isBuffer(data) ? data : new Buffer('' + data, options.encoding || 'utf8'); var position = /a/.test(flag) ? null : 0; writeAll(fd, buffer, 0, buffer.length, position, callback); } }); }; fs.writeFileSync = function(path, data, options) { if (!options) { options = { encoding: 'utf8', mode: 438 /*=0666*/, flag: 'w' }; } else if (typeof options === 'string') { options = { encoding: options, mode: 438, flag: 'w' }; } else if (typeof options !== 'object') { throw new TypeError('Bad arguments'); } assertEncoding(options.encoding); var flag = options.flag || 'w'; var fd = fs.openSync(path, flag, options.mode); if (!Buffer.isBuffer(data)) { data = new Buffer('' + data, options.encoding || 'utf8'); } var written = 0; var length = data.length; var position = /a/.test(flag) ? null : 0; try { while (written < length) { written += fs.writeSync(fd, data, written, length - written, position); position += written; } } finally { fs.closeSync(fd); } }; fs.appendFile = function(path, data, options, callback_) { var callback = maybeCallback(arguments[arguments.length - 1]); if (typeof options === 'function' || !options) { options = { encoding: 'utf8', mode: 438 /*=0666*/, flag: 'a' }; } else if (typeof options === 'string') { options = { encoding: options, mode: 438, flag: 'a' }; } else if (!options) { options = { encoding: 'utf8', mode: 438 /*=0666*/, flag: 'a' }; } else if (typeof options !== 'object') { throw new TypeError('Bad arguments'); } if (!options.flag) options = util._extend({ flag: 'a' }, options); fs.writeFile(path, data, options, callback); }; fs.appendFileSync = function(path, data, options) { if (!options) { options = { encoding: 'utf8', mode: 438 /*=0666*/, flag: 'a' }; } else if (typeof options === 'string') { options = { encoding: options, mode: 438, flag: 'a' }; } else if (typeof options !== 'object') { throw new TypeError('Bad arguments'); } if (!options.flag) options = util._extend({ flag: 'a' }, options); fs.writeFileSync(path, data, options); }; function errnoException(errorno, syscall) { // TODO make this more compatible with ErrnoException from src/node.cc // Once all of Node is using this function the ErrnoException from // src/node.cc should be removed. var e = new Error(syscall + ' ' + errorno); e.errno = e.code = errorno; e.syscall = syscall; return e; } function FSWatcher() { EventEmitter.call(this); var self = this; var FSEvent = process.binding('fs_event_wrap').FSEvent; this._handle = new FSEvent(); this._handle.owner = this; this._handle.onchange = function(status, event, filename) { if (status) { self._handle.close(); self.emit('error', errnoException(process._errno, 'watch')); } else { self.emit('change', event, filename); } }; } util.inherits(FSWatcher, EventEmitter); FSWatcher.prototype.start = function(filename, persistent) { nullCheck(filename); var r = this._handle.start(pathModule._makeLong(filename), persistent); if (r) { this._handle.close(); throw errnoException(process._errno, 'watch'); } }; FSWatcher.prototype.close = function() { this._handle.close(); }; fs.watch = function(filename) { nullCheck(filename); var watcher; var options; var listener; if ('object' == typeof arguments[1]) { options = arguments[1]; listener = arguments[2]; } else { options = {}; listener = arguments[1]; } if (options.persistent === undefined) options.persistent = true; watcher = new FSWatcher(); watcher.start(filename, options.persistent); if (listener) { watcher.addListener('change', listener); } return watcher; }; // Stat Change Watchers function StatWatcher() { EventEmitter.call(this); var self = this; this._handle = new binding.StatWatcher(); // uv_fs_poll is a little more powerful than ev_stat but we curb it for // the sake of backwards compatibility var oldStatus = -1; this._handle.onchange = function(current, previous, newStatus) { if (oldStatus === -1 && newStatus === -1 && current.nlink === previous.nlink) return; oldStatus = newStatus; self.emit('change', current, previous); }; this._handle.onstop = function() { self.emit('stop'); }; } util.inherits(StatWatcher, EventEmitter); StatWatcher.prototype.start = function(filename, persistent, interval) { nullCheck(filename); this._handle.start(pathModule._makeLong(filename), persistent, interval); }; StatWatcher.prototype.stop = function() { this._handle.stop(); }; var statWatchers = {}; function inStatWatchers(filename) { return Object.prototype.hasOwnProperty.call(statWatchers, filename) && statWatchers[filename]; } fs.watchFile = function(filename) { nullCheck(filename); var stat; var listener; var options = { // Poll interval in milliseconds. 5007 is what libev used to use. It's // a little on the slow side but let's stick with it for now to keep // behavioral changes to a minimum. interval: 5007, persistent: true }; if ('object' == typeof arguments[1]) { options = util._extend(options, arguments[1]); listener = arguments[2]; } else { listener = arguments[1]; } if (!listener) { throw new Error('watchFile requires a listener function'); } if (inStatWatchers(filename)) { stat = statWatchers[filename]; } else { stat = statWatchers[filename] = new StatWatcher(); stat.start(filename, options.persistent, options.interval); } stat.addListener('change', listener); return stat; }; fs.unwatchFile = function(filename, listener) { nullCheck(filename); if (!inStatWatchers(filename)) return; var stat = statWatchers[filename]; if (typeof listener === 'function') { stat.removeListener('change', listener); } else { stat.removeAllListeners('change'); } if (EventEmitter.listenerCount(stat, 'change') === 0) { stat.stop(); statWatchers[filename] = undefined; } }; // Realpath // Not using realpath(2) because it's bad. // See: http://insanecoding.blogspot.com/2007/11/pathmax-simply-isnt.html var normalize = pathModule.normalize; // Regexp that finds the next partion of a (partial) path // result is [base_with_slash, base], e.g. ['somedir/', 'somedir'] if (isWindows) { var nextPartRe = /(.*?)(?:[\/\\]+|$)/g; } else { var nextPartRe = /(.*?)(?:[\/]+|$)/g; } // Regex to find the device root, including trailing slash. E.g. 'c:\\'. if (isWindows) { var splitRootRe = /^(?:[a-zA-Z]:|[\\\/]{2}[^\\\/]+[\\\/][^\\\/]+)?[\\\/]*/; } else { var splitRootRe = /^[\/]*/; } fs.realpathSync = function realpathSync(p, cache) { // make p is absolute p = pathModule.resolve(p); if (cache && Object.prototype.hasOwnProperty.call(cache, p)) { return cache[p]; } var original = p, seenLinks = {}, knownHard = {}; // current character position in p var pos; // the partial path so far, including a trailing slash if any var current; // the partial path without a trailing slash (except when pointing at a root) var base; // the partial path scanned in the previous round, with slash var previous; start(); function start() { // Skip over roots var m = splitRootRe.exec(p); pos = m[0].length; current = m[0]; base = m[0]; previous = ''; // On windows, check that the root exists. On unix there is no need. if (isWindows && !knownHard[base]) { fs.lstatSync(base); knownHard[base] = true; } } // walk down the path, swapping out linked pathparts for their real // values // NB: p.length changes. while (pos < p.length) { // find the next part nextPartRe.lastIndex = pos; var result = nextPartRe.exec(p); previous = current; current += result[0]; base = previous + result[1]; pos = nextPartRe.lastIndex; // continue if not a symlink if (knownHard[base] || (cache && cache[base] === base)) { continue; } var resolvedLink; if (cache && Object.prototype.hasOwnProperty.call(cache, base)) { // some known symbolic link. no need to stat again. resolvedLink = cache[base]; } else { var stat = fs.lstatSync(base); if (!stat.isSymbolicLink()) { knownHard[base] = true; if (cache) cache[base] = base; continue; } // read the link if it wasn't read before // dev/ino always return 0 on windows, so skip the check. var linkTarget = null; if (!isWindows) { var id = stat.dev.toString(32) + ':' + stat.ino.toString(32); if (seenLinks.hasOwnProperty(id)) { linkTarget = seenLinks[id]; } } if (linkTarget === null) { fs.statSync(base); linkTarget = fs.readlinkSync(base); } resolvedLink = pathModule.resolve(previous, linkTarget); // track this, if given a cache. if (cache) cache[base] = resolvedLink; if (!isWindows) seenLinks[id] = linkTarget; } // resolve the link, then start over p = pathModule.resolve(resolvedLink, p.slice(pos)); start(); } if (cache) cache[original] = p; return p; }; fs.realpath = function realpath(p, cache, cb) { if (typeof cb !== 'function') { cb = maybeCallback(cache); cache = null; } // make p is absolute p = pathModule.resolve(p); if (cache && Object.prototype.hasOwnProperty.call(cache, p)) { return process.nextTick(cb.bind(null, null, cache[p])); } var original = p, seenLinks = {}, knownHard = {}; // current character position in p var pos; // the partial path so far, including a trailing slash if any var current; // the partial path without a trailing slash (except when pointing at a root) var base; // the partial path scanned in the previous round, with slash var previous; start(); function start() { // Skip over roots var m = splitRootRe.exec(p); pos = m[0].length; current = m[0]; base = m[0]; previous = ''; // On windows, check that the root exists. On unix there is no need. if (isWindows && !knownHard[base]) { fs.lstat(base, function(err) { if (err) return cb(err); knownHard[base] = true; LOOP(); }); } else { process.nextTick(LOOP); } } // walk down the path, swapping out linked pathparts for their real // values function LOOP() { // stop if scanned past end of path if (pos >= p.length) { if (cache) cache[original] = p; return cb(null, p); } // find the next part nextPartRe.lastIndex = pos; var result = nextPartRe.exec(p); previous = current; current += result[0]; base = previous + result[1]; pos = nextPartRe.lastIndex; // continue if not a symlink if (knownHard[base] || (cache && cache[base] === base)) { return process.nextTick(LOOP); } if (cache && Object.prototype.hasOwnProperty.call(cache, base)) { // known symbolic link. no need to stat again. return gotResolvedLink(cache[base]); } return fs.lstat(base, gotStat); } function gotStat(err, stat) { if (err) return cb(err); // if not a symlink, skip to the next path part if (!stat.isSymbolicLink()) { knownHard[base] = true; if (cache) cache[base] = base; return process.nextTick(LOOP); } // stat & read the link if not read before // call gotTarget as soon as the link target is known // dev/ino always return 0 on windows, so skip the check. if (!isWindows) { var id = stat.dev.toString(32) + ':' + stat.ino.toString(32); if (seenLinks.hasOwnProperty(id)) { return gotTarget(null, seenLinks[id], base); } } fs.stat(base, function(err) { if (err) return cb(err); fs.readlink(base, function(err, target) { if (!isWindows) seenLinks[id] = target; gotTarget(err, target); }); }); } function gotTarget(err, target, base) { if (err) return cb(err); var resolvedLink = pathModule.resolve(previous, target); if (cache) cache[base] = resolvedLink; gotResolvedLink(resolvedLink); } function gotResolvedLink(resolvedLink) { // resolve the link, then start over p = pathModule.resolve(resolvedLink, p.slice(pos)); start(); } }; var pool; function allocNewPool(poolSize) { pool = new Buffer(poolSize); pool.used = 0; } fs.createReadStream = function(path, options) { return new ReadStream(path, options); }; util.inherits(ReadStream, Readable); fs.ReadStream = ReadStream; function ReadStream(path, options) { if (!(this instanceof ReadStream)) return new ReadStream(path, options); // a little bit bigger buffer and water marks by default options = util._extend({ highWaterMark: 64 * 1024 }, options || {}); Readable.call(this, options); this.path = path; this.fd = options.hasOwnProperty('fd') ? options.fd : null; this.flags = options.hasOwnProperty('flags') ? options.flags : 'r'; this.mode = options.hasOwnProperty('mode') ? options.mode : 438; /*=0666*/ this.start = options.hasOwnProperty('start') ? options.start : undefined; this.end = options.hasOwnProperty('end') ? options.end : undefined; this.autoClose = options.hasOwnProperty('autoClose') ? options.autoClose : true; this.pos = undefined; if (this.start !== undefined) { if ('number' !== typeof this.start) { throw TypeError('start must be a Number'); } if (this.end === undefined) { this.end = Infinity; } else if ('number' !== typeof this.end) { throw TypeError('end must be a Number'); } if (this.start > this.end) { throw new Error('start must be <= end'); } this.pos = this.start; } if (typeof this.fd !== 'number') this.open(); this.on('end', function() { if (this.autoClose) { this.destroy(); } }); } fs.FileReadStream = fs.ReadStream; // support the legacy name ReadStream.prototype.open = function() { var self = this; fs.open(this.path, this.flags, this.mode, function(er, fd) { if (er) { if (self.autoClose) { self.destroy(); } self.emit('error', er); return; } self.fd = fd; self.emit('open', fd); // start the flow of data. self.read(); }); }; ReadStream.prototype._read = function(n) { if (typeof this.fd !== 'number') return this.once('open', function() { this._read(n); }); if (this.destroyed) return; if (!pool || pool.length - pool.used < kMinPoolSpace) { // discard the old pool. pool = null; allocNewPool(this._readableState.highWaterMark); } // Grab another reference to the pool in the case that while we're // in the thread pool another read() finishes up the pool, and // allocates a new one. var thisPool = pool; var toRead = Math.min(pool.length - pool.used, n); var start = pool.used; if (this.pos !== undefined) toRead = Math.min(this.end - this.pos + 1, toRead); // already read everything we were supposed to read! // treat as EOF. if (toRead <= 0) return this.push(null); // the actual read. var self = this; fs.read(this.fd, pool, pool.used, toRead, this.pos, onread); // move the pool positions, and internal position for reading. if (this.pos !== undefined) this.pos += toRead; pool.used += toRead; function onread(er, bytesRead) { if (er) { if (self.autoClose) { self.destroy(); } self.emit('error', er); } else { var b = null; if (bytesRead > 0) b = thisPool.slice(start, start + bytesRead); self.push(b); } } }; ReadStream.prototype.destroy = function() { if (this.destroyed) return; this.destroyed = true; if ('number' === typeof this.fd) this.close(); }; ReadStream.prototype.close = function(cb) { var self = this; if (cb) this.once('close', cb); if (this.closed || 'number' !== typeof this.fd) { if ('number' !== typeof this.fd) { this.once('open', close); return; } return process.nextTick(this.emit.bind(this, 'close')); } this.closed = true; close(); function close(fd) { fs.close(fd || self.fd, function(er) { if (er) self.emit('error', er); else self.emit('close'); }); self.fd = null; } }; fs.createWriteStream = function(path, options) { return new WriteStream(path, options); }; util.inherits(WriteStream, Writable); fs.WriteStream = WriteStream; function WriteStream(path, options) { if (!(this instanceof WriteStream)) return new WriteStream(path, options); options = options || {}; Writable.call(this, options); this.path = path; this.fd = null; this.fd = options.hasOwnProperty('fd') ? options.fd : null; this.flags = options.hasOwnProperty('flags') ? options.flags : 'w'; this.mode = options.hasOwnProperty('mode') ? options.mode : 438; /*=0666*/ this.start = options.hasOwnProperty('start') ? options.start : undefined; this.pos = undefined; this.bytesWritten = 0; if (this.start !== undefined) { if ('number' !== typeof this.start) { throw TypeError('start must be a Number'); } if (this.start < 0) { throw new Error('start must be >= zero'); } this.pos = this.start; } if ('number' !== typeof this.fd) this.open(); // dispose on finish. this.once('finish', this.close); } fs.FileWriteStream = fs.WriteStream; // support the legacy name WriteStream.prototype.open = function() { fs.open(this.path, this.flags, this.mode, function(er, fd) { if (er) { this.destroy(); this.emit('error', er); return; } this.fd = fd; this.emit('open', fd); }.bind(this)); }; WriteStream.prototype._write = function(data, encoding, cb) { if (!Buffer.isBuffer(data)) return this.emit('error', new Error('Invalid data')); if (typeof this.fd !== 'number') return this.once('open', function() { this._write(data, encoding, cb); }); var self = this; fs.write(this.fd, data, 0, data.length, this.pos, function(er, bytes) { if (er) { self.destroy(); return cb(er); } self.bytesWritten += bytes; cb(); }); if (this.pos !== undefined) this.pos += data.length; }; WriteStream.prototype.destroy = ReadStream.prototype.destroy; WriteStream.prototype.close = ReadStream.prototype.close; // There is no shutdown() for files. WriteStream.prototype.destroySoon = WriteStream.prototype.end; // SyncWriteStream is internal. DO NOT USE. // Temporary hack for process.stdout and process.stderr when piped to files. function SyncWriteStream(fd) { Stream.call(this); this.fd = fd; this.writable = true; this.readable = false; } util.inherits(SyncWriteStream, Stream); // Export fs.SyncWriteStream = SyncWriteStream; SyncWriteStream.prototype.write = function(data, arg1, arg2) { var encoding, cb; // parse arguments if (arg1) { if (typeof arg1 === 'string') { encoding = arg1; cb = arg2; } else if (typeof arg1 === 'function') { cb = arg1; } else { throw new Error('bad arg'); } } assertEncoding(encoding); // Change strings to buffers. SLOW if (typeof data == 'string') { data = new Buffer(data, encoding); } fs.writeSync(this.fd, data, 0, data.length); if (cb) { process.nextTick(cb); } return true; }; SyncWriteStream.prototype.end = function(data, arg1, arg2) { if (data) { this.write(data, arg1, arg2); } this.destroy(); }; SyncWriteStream.prototype.destroy = function() { fs.closeSync(this.fd); this.fd = null; this.emit('close'); return true; }; SyncWriteStream.prototype.destroySoon = SyncWriteStream.prototype.destroy; node-v0.10.25~dfsg2/lib/console.js0000644000000000000000000000624512270121457015372 0ustar rootroot// Copyright Joyent, Inc. and other Node contributors. // // Permission is hereby granted, free of charge, to any person obtaining a // copy of this software and associated documentation files (the // "Software"), to deal in the Software without restriction, including // without limitation the rights to use, copy, modify, merge, publish, // distribute, sublicense, and/or sell copies of the Software, and to permit // persons to whom the Software is furnished to do so, subject to the // following conditions: // // The above copyright notice and this permission notice shall be included // in all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS // OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF // MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN // NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, // DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR // OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE // USE OR OTHER DEALINGS IN THE SOFTWARE. var util = require('util'); function Console(stdout, stderr) { if (!(this instanceof Console)) { return new Console(stdout, stderr); } if (!stdout || typeof stdout.write !== 'function') { throw new TypeError('Console expects a writable stream instance'); } if (!stderr) { stderr = stdout; } var prop = { writable: true, enumerable: false, configurable: true }; prop.value = stdout; Object.defineProperty(this, '_stdout', prop); prop.value = stderr; Object.defineProperty(this, '_stderr', prop); prop.value = {}; Object.defineProperty(this, '_times', prop); // bind the prototype functions to this Console instance Object.keys(Console.prototype).forEach(function(k) { this[k] = this[k].bind(this); }, this); } Console.prototype.log = function() { this._stdout.write(util.format.apply(this, arguments) + '\n'); }; Console.prototype.info = Console.prototype.log; Console.prototype.warn = function() { this._stderr.write(util.format.apply(this, arguments) + '\n'); }; Console.prototype.error = Console.prototype.warn; Console.prototype.dir = function(object) { this._stdout.write(util.inspect(object) + '\n'); }; Console.prototype.time = function(label) { this._times[label] = Date.now(); }; Console.prototype.timeEnd = function(label) { var time = this._times[label]; if (!time) { throw new Error('No such label: ' + label); } var duration = Date.now() - time; this.log('%s: %dms', label, duration); }; Console.prototype.trace = function() { // TODO probably can to do this better with V8's debug object once that is // exposed. var err = new Error; err.name = 'Trace'; err.message = util.format.apply(this, arguments); Error.captureStackTrace(err, arguments.callee); this.error(err.stack); }; Console.prototype.assert = function(expression) { if (!expression) { var arr = Array.prototype.slice.call(arguments, 1); require('assert').ok(false, util.format.apply(this, arr)); } }; module.exports = new Console(process.stdout, process.stderr); module.exports.Console = Console; node-v0.10.25~dfsg2/lib/tty.js0000644000000000000000000000732312270121457014546 0ustar rootroot// Copyright Joyent, Inc. and other Node contributors. // // Permission is hereby granted, free of charge, to any person obtaining a // copy of this software and associated documentation files (the // "Software"), to deal in the Software without restriction, including // without limitation the rights to use, copy, modify, merge, publish, // distribute, sublicense, and/or sell copies of the Software, and to permit // persons to whom the Software is furnished to do so, subject to the // following conditions: // // The above copyright notice and this permission notice shall be included // in all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS // OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF // MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN // NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, // DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR // OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE // USE OR OTHER DEALINGS IN THE SOFTWARE. var assert = require('assert'); var inherits = require('util').inherits; var net = require('net'); var TTY = process.binding('tty_wrap').TTY; var isTTY = process.binding('tty_wrap').isTTY; var util = require('util'); exports.isatty = function(fd) { return isTTY(fd); }; // backwards-compat exports.setRawMode = util.deprecate(function(flag) { if (!process.stdin.isTTY) { throw new Error('can\'t set raw mode on non-tty'); } process.stdin.setRawMode(flag); }, 'tty.setRawMode: Use `process.stdin.setRawMode()` instead.'); function ReadStream(fd, options) { if (!(this instanceof ReadStream)) return new ReadStream(fd, options); options = util._extend({ highWaterMark: 0, readable: true, writable: false, handle: new TTY(fd, true) }, options); net.Socket.call(this, options); this.isRaw = false; this.isTTY = true; } inherits(ReadStream, net.Socket); exports.ReadStream = ReadStream; ReadStream.prototype.setRawMode = function(flag) { flag = !!flag; this._handle.setRawMode(flag); this.isRaw = flag; }; function WriteStream(fd) { if (!(this instanceof WriteStream)) return new WriteStream(fd); net.Socket.call(this, { handle: new TTY(fd, false), readable: false, writable: true }); var winSize = this._handle.getWindowSize(); if (winSize) { this.columns = winSize[0]; this.rows = winSize[1]; } } inherits(WriteStream, net.Socket); exports.WriteStream = WriteStream; WriteStream.prototype.isTTY = true; WriteStream.prototype._refreshSize = function() { var oldCols = this.columns; var oldRows = this.rows; var winSize = this._handle.getWindowSize(); if (!winSize) { this.emit('error', errnoException(process._errno, 'getWindowSize')); return; } var newCols = winSize[0]; var newRows = winSize[1]; if (oldCols !== newCols || oldRows !== newRows) { this.columns = newCols; this.rows = newRows; this.emit('resize'); } }; // backwards-compat WriteStream.prototype.cursorTo = function(x, y) { require('readline').cursorTo(this, x, y); }; WriteStream.prototype.moveCursor = function(dx, dy) { require('readline').moveCursor(this, dx, dy); }; WriteStream.prototype.clearLine = function(dir) { require('readline').clearLine(this, dir); }; WriteStream.prototype.clearScreenDown = function() { require('readline').clearScreenDown(this); }; WriteStream.prototype.getWindowSize = function() { return [this.columns, this.rows]; }; // TODO share with net_uv and others function errnoException(errorno, syscall) { var e = new Error(syscall + ' ' + errorno); e.errno = e.code = errorno; e.syscall = syscall; return e; } node-v0.10.25~dfsg2/lib/tls.js0000644000000000000000000012004112270121457014521 0ustar rootroot// Copyright Joyent, Inc. and other Node contributors. // // Permission is hereby granted, free of charge, to any person obtaining a // copy of this software and associated documentation files (the // "Software"), to deal in the Software without restriction, including // without limitation the rights to use, copy, modify, merge, publish, // distribute, sublicense, and/or sell copies of the Software, and to permit // persons to whom the Software is furnished to do so, subject to the // following conditions: // // The above copyright notice and this permission notice shall be included // in all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS // OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF // MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN // NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, // DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR // OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE // USE OR OTHER DEALINGS IN THE SOFTWARE. var crypto = require('crypto'); var util = require('util'); var net = require('net'); var url = require('url'); var events = require('events'); var stream = require('stream'); var assert = require('assert').ok; var constants = require('constants'); var DEFAULT_CIPHERS = 'ECDHE-RSA-AES128-SHA256:AES128-GCM-SHA256:' + // TLS 1.2 'RC4:HIGH:!MD5:!aNULL:!EDH'; // TLS 1.0 // Allow {CLIENT_RENEG_LIMIT} client-initiated session renegotiations // every {CLIENT_RENEG_WINDOW} seconds. An error event is emitted if more // renegotations are seen. The settings are applied to all remote client // connections. exports.CLIENT_RENEG_LIMIT = 3; exports.CLIENT_RENEG_WINDOW = 600; exports.SLAB_BUFFER_SIZE = 10 * 1024 * 1024; exports.getCiphers = function() { var names = process.binding('crypto').getSSLCiphers(); // Drop all-caps names in favor of their lowercase aliases, var ctx = {}; names.forEach(function(name) { if (/^[0-9A-Z\-]+$/.test(name)) name = name.toLowerCase(); ctx[name] = true; }); return Object.getOwnPropertyNames(ctx).sort(); }; var debug; if (process.env.NODE_DEBUG && /tls/.test(process.env.NODE_DEBUG)) { debug = function(a) { console.error('TLS:', a); }; } else { debug = function() { }; } var Connection = null; try { Connection = process.binding('crypto').Connection; } catch (e) { throw new Error('node.js not compiled with openssl crypto support.'); } // Convert protocols array into valid OpenSSL protocols list // ("\x06spdy/2\x08http/1.1\x08http/1.0") function convertNPNProtocols(NPNProtocols, out) { // If NPNProtocols is Array - translate it into buffer if (Array.isArray(NPNProtocols)) { var buff = new Buffer(NPNProtocols.reduce(function(p, c) { return p + 1 + Buffer.byteLength(c); }, 0)); NPNProtocols.reduce(function(offset, c) { var clen = Buffer.byteLength(c); buff[offset] = clen; buff.write(c, offset + 1); return offset + 1 + clen; }, 0); NPNProtocols = buff; } // If it's already a Buffer - store it if (Buffer.isBuffer(NPNProtocols)) { out.NPNProtocols = NPNProtocols; } } function checkServerIdentity(host, cert) { // Create regexp to much hostnames function regexpify(host, wildcards) { // Add trailing dot (make hostnames uniform) if (!/\.$/.test(host)) host += '.'; // The same applies to hostname with more than one wildcard, // if hostname has wildcard when wildcards are not allowed, // or if there are less than two dots after wildcard (i.e. *.com or *d.com) // // also // // "The client SHOULD NOT attempt to match a presented identifier in // which the wildcard character comprises a label other than the // left-most label (e.g., do not match bar.*.example.net)." // RFC6125 if (!wildcards && /\*/.test(host) || /[\.\*].*\*/.test(host) || /\*/.test(host) && !/\*.*\..+\..+/.test(host)) { return /$./; } // Replace wildcard chars with regexp's wildcard and // escape all characters that have special meaning in regexps // (i.e. '.', '[', '{', '*', and others) var re = host.replace( /\*([a-z0-9\\-_\.])|[\.,\-\\\^\$+?*\[\]\(\):!\|{}]/g, function(all, sub) { if (sub) return '[a-z0-9\\-_]*' + (sub === '-' ? '\\-' : sub); return '\\' + all; }); return new RegExp('^' + re + '$', 'i'); } var dnsNames = [], uriNames = [], ips = [], matchCN = true, valid = false; // There're several names to perform check against: // CN and altnames in certificate extension // (DNS names, IP addresses, and URIs) // // Walk through altnames and generate lists of those names if (cert.subjectaltname) { cert.subjectaltname.split(/, /g).forEach(function(altname) { if (/^DNS:/.test(altname)) { dnsNames.push(altname.slice(4)); } else if (/^IP Address:/.test(altname)) { ips.push(altname.slice(11)); } else if (/^URI:/.test(altname)) { var uri = url.parse(altname.slice(4)); if (uri) uriNames.push(uri.hostname); } }); } // If hostname is an IP address, it should be present in the list of IP // addresses. if (net.isIP(host)) { valid = ips.some(function(ip) { return ip === host; }); } else { // Transform hostname to canonical form if (!/\.$/.test(host)) host += '.'; // Otherwise check all DNS/URI records from certificate // (with allowed wildcards) dnsNames = dnsNames.map(function(name) { return regexpify(name, true); }); // Wildcards ain't allowed in URI names uriNames = uriNames.map(function(name) { return regexpify(name, false); }); dnsNames = dnsNames.concat(uriNames); if (dnsNames.length > 0) matchCN = false; // Match against Common Name (CN) only if no supported identifiers are // present. // // "As noted, a client MUST NOT seek a match for a reference identifier // of CN-ID if the presented identifiers include a DNS-ID, SRV-ID, // URI-ID, or any application-specific identifier types supported by the // client." // RFC6125 if (matchCN) { var commonNames = cert.subject.CN; if (Array.isArray(commonNames)) { for (var i = 0, k = commonNames.length; i < k; ++i) { dnsNames.push(regexpify(commonNames[i], true)); } } else { dnsNames.push(regexpify(commonNames, true)); } } valid = dnsNames.some(function(re) { return re.test(host); }); } return valid; } exports.checkServerIdentity = checkServerIdentity; function SlabBuffer() { this.create(); } SlabBuffer.prototype.create = function create() { this.isFull = false; this.pool = new Buffer(exports.SLAB_BUFFER_SIZE); this.offset = 0; this.remaining = this.pool.length; }; SlabBuffer.prototype.use = function use(context, fn, size) { if (this.remaining === 0) { this.isFull = true; return 0; } var actualSize = this.remaining; if (size !== null) actualSize = Math.min(size, actualSize); var bytes = fn.call(context, this.pool, this.offset, actualSize); if (bytes > 0) { this.offset += bytes; this.remaining -= bytes; } assert(this.remaining >= 0); return bytes; }; var slabBuffer = null; // Base class of both CleartextStream and EncryptedStream function CryptoStream(pair, options) { stream.Duplex.call(this, options); this.pair = pair; this._pending = null; this._pendingEncoding = ''; this._pendingCallback = null; this._doneFlag = false; this._retryAfterPartial = false; this._halfRead = false; this._sslOutCb = null; this._resumingSession = false; this._reading = true; this._destroyed = false; this._ended = false; this._finished = false; this._opposite = null; if (slabBuffer === null) slabBuffer = new SlabBuffer(); this._buffer = slabBuffer; this.once('finish', onCryptoStreamFinish); // net.Socket calls .onend too this.once('end', onCryptoStreamEnd); } util.inherits(CryptoStream, stream.Duplex); function onCryptoStreamFinish() { this._finished = true; if (this === this.pair.cleartext) { debug('cleartext.onfinish'); if (this.pair.ssl) { // Generate close notify // NOTE: first call checks if client has sent us shutdown, // second call enqueues shutdown into the BIO. if (this.pair.ssl.shutdown() !== 1) { if (this.pair.ssl && this.pair.ssl.error) return this.pair.error(); this.pair.ssl.shutdown(); } if (this.pair.ssl && this.pair.ssl.error) return this.pair.error(); } } else { debug('encrypted.onfinish'); } // Try to read just to get sure that we won't miss EOF if (this._opposite.readable) this._opposite.read(0); if (this._opposite._ended) { this._done(); // No half-close, sorry if (this === this.pair.cleartext) this._opposite._done(); } } function onCryptoStreamEnd() { this._ended = true; if (this === this.pair.cleartext) { debug('cleartext.onend'); } else { debug('encrypted.onend'); } if (this.onend) this.onend(); } // NOTE: Called once `this._opposite` is set. CryptoStream.prototype.init = function init() { var self = this; this._opposite.on('sslOutEnd', function() { if (self._sslOutCb) { var cb = self._sslOutCb; self._sslOutCb = null; cb(null); } }); }; CryptoStream.prototype._write = function write(data, encoding, cb) { assert(this._pending === null); // Black-hole data if (!this.pair.ssl) return cb(null); // When resuming session don't accept any new data. // And do not put too much data into openssl, before writing it from encrypted // side. // // TODO(indutny): Remove magic number, use watermark based limits if (!this._resumingSession && this._opposite._internallyPendingBytes() < 128 * 1024) { // Write current buffer now var written; if (this === this.pair.cleartext) { debug('cleartext.write called with ' + data.length + ' bytes'); written = this.pair.ssl.clearIn(data, 0, data.length); } else { debug('encrypted.write called with ' + data.length + ' bytes'); written = this.pair.ssl.encIn(data, 0, data.length); } // Handle and report errors if (this.pair.ssl && this.pair.ssl.error) { return cb(this.pair.error(true)); } // Force SSL_read call to cycle some states/data inside OpenSSL this.pair.cleartext.read(0); // Cycle encrypted data if (this.pair.encrypted._internallyPendingBytes()) this.pair.encrypted.read(0); // Get NPN and Server name when ready this.pair.maybeInitFinished(); // Whole buffer was written if (written === data.length) { if (this === this.pair.cleartext) { debug('cleartext.write succeed with ' + written + ' bytes'); } else { debug('encrypted.write succeed with ' + written + ' bytes'); } // Invoke callback only when all data read from opposite stream if (this._opposite._halfRead) { assert(this._sslOutCb === null); this._sslOutCb = cb; } else { cb(null); } return; } else if (written !== 0 && written !== -1) { assert(!this._retryAfterPartial); this._retryAfterPartial = true; this._write(data.slice(written), encoding, cb); this._retryAfterPartial = false; return; } } else { debug('cleartext.write queue is full'); // Force SSL_read call to cycle some states/data inside OpenSSL this.pair.cleartext.read(0); } // No write has happened this._pending = data; this._pendingEncoding = encoding; this._pendingCallback = cb; if (this === this.pair.cleartext) { debug('cleartext.write queued with ' + data.length + ' bytes'); } else { debug('encrypted.write queued with ' + data.length + ' bytes'); } }; CryptoStream.prototype._writePending = function writePending() { var data = this._pending, encoding = this._pendingEncoding, cb = this._pendingCallback; this._pending = null; this._pendingEncoding = ''; this._pendingCallback = null; this._write(data, encoding, cb); }; CryptoStream.prototype._read = function read(size) { // XXX: EOF?! if (!this.pair.ssl) return this.push(null); // Wait for session to be resumed // Mark that we're done reading, but don't provide data or EOF if (this._resumingSession || !this._reading) return this.push(''); var out; if (this === this.pair.cleartext) { debug('cleartext.read called with ' + size + ' bytes'); out = this.pair.ssl.clearOut; } else { debug('encrypted.read called with ' + size + ' bytes'); out = this.pair.ssl.encOut; } var bytesRead = 0, start = this._buffer.offset, last = start; do { assert(last === this._buffer.offset); var read = this._buffer.use(this.pair.ssl, out, size - bytesRead); if (read > 0) { bytesRead += read; } last = this._buffer.offset; // Handle and report errors if (this.pair.ssl && this.pair.ssl.error) { this.pair.error(); break; } } while (read > 0 && !this._buffer.isFull && bytesRead < size && this.pair.ssl !== null); // Get NPN and Server name when ready this.pair.maybeInitFinished(); // Create new buffer if previous was filled up var pool = this._buffer.pool; if (this._buffer.isFull) this._buffer.create(); assert(bytesRead >= 0); if (this === this.pair.cleartext) { debug('cleartext.read succeed with ' + bytesRead + ' bytes'); } else { debug('encrypted.read succeed with ' + bytesRead + ' bytes'); } // Try writing pending data if (this._pending !== null) this._writePending(); if (this._opposite._pending !== null) this._opposite._writePending(); if (bytesRead === 0) { // EOF when cleartext has finished and we have nothing to read if (this._opposite._finished && this._internallyPendingBytes() === 0 || this.pair.ssl && this.pair.ssl.receivedShutdown) { // Perform graceful shutdown this._done(); // No half-open, sorry! if (this === this.pair.cleartext) { this._opposite._done(); // EOF this.push(null); } else if (!this.pair.ssl || !this.pair.ssl.receivedShutdown) { // EOF this.push(null); } } else { // Bail out this.push(''); } } else { // Give them requested data if (this.ondata) { this.ondata(pool, start, start + bytesRead); // Deceive streams2 var self = this; setImmediate(function() { // Force state.reading to set to false self.push(''); // Try reading more, we most likely have some data self.read(0); }); } else { this.push(pool.slice(start, start + bytesRead)); } } // Let users know that we've some internal data to read var halfRead = this._internallyPendingBytes() !== 0; // Smart check to avoid invoking 'sslOutEnd' in the most of the cases if (this._halfRead !== halfRead) { this._halfRead = halfRead; // Notify listeners about internal data end if (!halfRead) { if (this === this.pair.cleartext) { debug('cleartext.sslOutEnd'); } else { debug('encrypted.sslOutEnd'); } this.emit('sslOutEnd'); } } }; CryptoStream.prototype.setTimeout = function(timeout, callback) { if (this.socket) this.socket.setTimeout(timeout, callback); }; CryptoStream.prototype.setNoDelay = function(noDelay) { if (this.socket) this.socket.setNoDelay(noDelay); }; CryptoStream.prototype.setKeepAlive = function(enable, initialDelay) { if (this.socket) this.socket.setKeepAlive(enable, initialDelay); }; CryptoStream.prototype.__defineGetter__('bytesWritten', function() { return this.socket ? this.socket.bytesWritten : 0; }); // Example: // C=US\nST=CA\nL=SF\nO=Joyent\nOU=Node.js\nCN=ca1\nemailAddress=ry@clouds.org function parseCertString(s) { var out = {}; var parts = s.split('\n'); for (var i = 0, len = parts.length; i < len; i++) { var sepIndex = parts[i].indexOf('='); if (sepIndex > 0) { var key = parts[i].slice(0, sepIndex); var value = parts[i].slice(sepIndex + 1); if (key in out) { if (!Array.isArray(out[key])) { out[key] = [out[key]]; } out[key].push(value); } else { out[key] = value; } } } return out; } CryptoStream.prototype.getPeerCertificate = function() { if (this.pair.ssl) { var c = this.pair.ssl.getPeerCertificate(); if (c) { if (c.issuer) c.issuer = parseCertString(c.issuer); if (c.subject) c.subject = parseCertString(c.subject); return c; } } return null; }; CryptoStream.prototype.getSession = function() { if (this.pair.ssl) { return this.pair.ssl.getSession(); } return null; }; CryptoStream.prototype.isSessionReused = function() { if (this.pair.ssl) { return this.pair.ssl.isSessionReused(); } return null; }; CryptoStream.prototype.getCipher = function(err) { if (this.pair.ssl) { return this.pair.ssl.getCurrentCipher(); } else { return null; } }; CryptoStream.prototype.end = function(chunk, encoding) { if (this === this.pair.cleartext) { debug('cleartext.end'); } else { debug('encrypted.end'); } // Write pending data first if (this._pending !== null) this._writePending(); this.writable = false; stream.Duplex.prototype.end.call(this, chunk, encoding); }; CryptoStream.prototype.destroySoon = function(err) { if (this === this.pair.cleartext) { debug('cleartext.destroySoon'); } else { debug('encrypted.destroySoon'); } if (this.writable) this.end(); if (this._writableState.finished && this._opposite._ended) { this.destroy(); } else { // Wait for both `finish` and `end` events to ensure that all data that // was written on this side was read from the other side. var self = this; var waiting = 1; this._opposite.once('end', finish); if (!this._finished) { this.once('finish', finish); ++waiting; } } function finish() { if (--waiting === 0) self.destroy(); } }; CryptoStream.prototype.destroy = function(err) { if (this._destroyed) return; this._destroyed = true; this.readable = this.writable = false; // Destroy both ends if (this === this.pair.cleartext) { debug('cleartext.destroy'); } else { debug('encrypted.destroy'); } this._opposite.destroy(); var self = this; process.nextTick(function() { // Force EOF self.push(null); // Emit 'close' event self.emit('close', err ? true : false); }); }; CryptoStream.prototype._done = function() { this._doneFlag = true; if (this === this.pair.encrypted && !this.pair._secureEstablished) return this.pair.error(); if (this.pair.cleartext._doneFlag && this.pair.encrypted._doneFlag && !this.pair._doneFlag) { // If both streams are done: this.pair.destroy(); } }; // readyState is deprecated. Don't use it. Object.defineProperty(CryptoStream.prototype, 'readyState', { get: function() { if (this._connecting) { return 'opening'; } else if (this.readable && this.writable) { return 'open'; } else if (this.readable && !this.writable) { return 'readOnly'; } else if (!this.readable && this.writable) { return 'writeOnly'; } else { return 'closed'; } } }); function CleartextStream(pair, options) { CryptoStream.call(this, pair, options); // This is a fake kludge to support how the http impl sits // on top of net Sockets var self = this; this._handle = { readStop: function() { self._reading = false; }, readStart: function() { if (self._reading && self._readableState.length > 0) return; self._reading = true; self.read(0); if (self._opposite.readable) self._opposite.read(0); } }; } util.inherits(CleartextStream, CryptoStream); CleartextStream.prototype._internallyPendingBytes = function() { if (this.pair.ssl) { return this.pair.ssl.clearPending(); } else { return 0; } }; CleartextStream.prototype.address = function() { return this.socket && this.socket.address(); }; CleartextStream.prototype.__defineGetter__('remoteAddress', function() { return this.socket && this.socket.remoteAddress; }); CleartextStream.prototype.__defineGetter__('remotePort', function() { return this.socket && this.socket.remotePort; }); function EncryptedStream(pair, options) { CryptoStream.call(this, pair, options); } util.inherits(EncryptedStream, CryptoStream); EncryptedStream.prototype._internallyPendingBytes = function() { if (this.pair.ssl) { return this.pair.ssl.encPending(); } else { return 0; } }; function onhandshakestart() { debug('onhandshakestart'); var self = this; var ssl = self.ssl; var now = Date.now(); assert(now >= ssl.lastHandshakeTime); if ((now - ssl.lastHandshakeTime) >= exports.CLIENT_RENEG_WINDOW * 1000) { ssl.handshakes = 0; } var first = (ssl.lastHandshakeTime === 0); ssl.lastHandshakeTime = now; if (first) return; if (++ssl.handshakes > exports.CLIENT_RENEG_LIMIT) { // Defer the error event to the next tick. We're being called from OpenSSL's // state machine and OpenSSL is not re-entrant. We cannot allow the user's // callback to destroy the connection right now, it would crash and burn. setImmediate(function() { var err = new Error('TLS session renegotiation attack detected.'); if (self.cleartext) self.cleartext.emit('error', err); }); } } function onhandshakedone() { // for future use debug('onhandshakedone'); } function onclienthello(hello) { var self = this, once = false; this._resumingSession = true; function callback(err, session) { if (once) return; once = true; if (err) return self.socket.destroy(err); self.ssl.loadSession(session); // Cycle data self._resumingSession = false; self.cleartext.read(0); self.encrypted.read(0); } if (hello.sessionId.length <= 0 || !this.server || !this.server.emit('resumeSession', hello.sessionId, callback)) { callback(null, null); } } function onnewsession(key, session) { if (!this.server) return; this.server.emit('newSession', key, session); } /** * Provides a pair of streams to do encrypted communication. */ function SecurePair(credentials, isServer, requestCert, rejectUnauthorized, options) { if (!(this instanceof SecurePair)) { return new SecurePair(credentials, isServer, requestCert, rejectUnauthorized, options); } var self = this; options || (options = {}); events.EventEmitter.call(this); this.server = options.server; this._secureEstablished = false; this._isServer = isServer ? true : false; this._encWriteState = true; this._clearWriteState = true; this._doneFlag = false; this._destroying = false; if (!credentials) { this.credentials = crypto.createCredentials(); } else { this.credentials = credentials; } if (!this._isServer) { // For clients, we will always have either a given ca list or be using // default one requestCert = true; } this._rejectUnauthorized = rejectUnauthorized ? true : false; this._requestCert = requestCert ? true : false; this.ssl = new Connection(this.credentials.context, this._isServer ? true : false, this._isServer ? this._requestCert : options.servername, this._rejectUnauthorized); if (this._isServer) { this.ssl.onhandshakestart = onhandshakestart.bind(this); this.ssl.onhandshakedone = onhandshakedone.bind(this); this.ssl.onclienthello = onclienthello.bind(this); this.ssl.onnewsession = onnewsession.bind(this); this.ssl.lastHandshakeTime = 0; this.ssl.handshakes = 0; } if (process.features.tls_sni) { if (this._isServer && options.SNICallback) { this.ssl.setSNICallback(options.SNICallback); } this.servername = null; } if (process.features.tls_npn && options.NPNProtocols) { this.ssl.setNPNProtocols(options.NPNProtocols); this.npnProtocol = null; } /* Acts as a r/w stream to the cleartext side of the stream. */ this.cleartext = new CleartextStream(this, options.cleartext); /* Acts as a r/w stream to the encrypted side of the stream. */ this.encrypted = new EncryptedStream(this, options.encrypted); /* Let streams know about each other */ this.cleartext._opposite = this.encrypted; this.encrypted._opposite = this.cleartext; this.cleartext.init(); this.encrypted.init(); process.nextTick(function() { /* The Connection may be destroyed by an abort call */ if (self.ssl) { self.ssl.start(); /* In case of cipher suite failures - SSL_accept/SSL_connect may fail */ if (self.ssl && self.ssl.error) self.error(); } }); } util.inherits(SecurePair, events.EventEmitter); exports.createSecurePair = function(credentials, isServer, requestCert, rejectUnauthorized) { var pair = new SecurePair(credentials, isServer, requestCert, rejectUnauthorized); return pair; }; SecurePair.prototype.maybeInitFinished = function() { if (this.ssl && !this._secureEstablished && this.ssl.isInitFinished()) { if (process.features.tls_npn) { this.npnProtocol = this.ssl.getNegotiatedProtocol(); } if (process.features.tls_sni) { this.servername = this.ssl.getServername(); } this._secureEstablished = true; debug('secure established'); this.emit('secure'); } }; SecurePair.prototype.destroy = function() { if (this._destroying) return; if (!this._doneFlag) { debug('SecurePair.destroy'); this._destroying = true; // SecurePair should be destroyed only after it's streams this.cleartext.destroy(); this.encrypted.destroy(); this._doneFlag = true; this.ssl.error = null; this.ssl.close(); this.ssl = null; } }; SecurePair.prototype.error = function(returnOnly) { var err = this.ssl.error; this.ssl.error = null; if (!this._secureEstablished) { // Emit ECONNRESET instead of zero return if (!err || err.message === 'ZERO_RETURN') { var connReset = new Error('socket hang up'); connReset.code = 'ECONNRESET'; connReset.sslError = err && err.message; err = connReset; } this.destroy(); if (!returnOnly) this.emit('error', err); } else if (this._isServer && this._rejectUnauthorized && /peer did not return a certificate/.test(err.message)) { // Not really an error. this.destroy(); } else { if (!returnOnly) this.cleartext.emit('error', err); } return err; }; // TODO: support anonymous (nocert) and PSK // AUTHENTICATION MODES // // There are several levels of authentication that TLS/SSL supports. // Read more about this in "man SSL_set_verify". // // 1. The server sends a certificate to the client but does not request a // cert from the client. This is common for most HTTPS servers. The browser // can verify the identity of the server, but the server does not know who // the client is. Authenticating the client is usually done over HTTP using // login boxes and cookies and stuff. // // 2. The server sends a cert to the client and requests that the client // also send it a cert. The client knows who the server is and the server is // requesting the client also identify themselves. There are several // outcomes: // // A) verifyError returns null meaning the client's certificate is signed // by one of the server's CAs. The server know's the client idenity now // and the client is authorized. // // B) For some reason the client's certificate is not acceptable - // verifyError returns a string indicating the problem. The server can // either (i) reject the client or (ii) allow the client to connect as an // unauthorized connection. // // The mode is controlled by two boolean variables. // // requestCert // If true the server requests a certificate from client connections. For // the common HTTPS case, users will want this to be false, which is what // it defaults to. // // rejectUnauthorized // If true clients whose certificates are invalid for any reason will not // be allowed to make connections. If false, they will simply be marked as // unauthorized but secure communication will continue. By default this is // true. // // // // Options: // - requestCert. Send verify request. Default to false. // - rejectUnauthorized. Boolean, default to true. // - key. string. // - cert: string. // - ca: string or array of strings. // // emit 'secureConnection' // function (cleartextStream, encryptedStream) { } // // 'cleartextStream' has the boolean property 'authorized' to determine if // it was verified by the CA. If 'authorized' is false, a property // 'authorizationError' is set on cleartextStream and has the possible // values: // // "UNABLE_TO_GET_ISSUER_CERT", "UNABLE_TO_GET_CRL", // "UNABLE_TO_DECRYPT_CERT_SIGNATURE", "UNABLE_TO_DECRYPT_CRL_SIGNATURE", // "UNABLE_TO_DECODE_ISSUER_PUBLIC_KEY", "CERT_SIGNATURE_FAILURE", // "CRL_SIGNATURE_FAILURE", "CERT_NOT_YET_VALID" "CERT_HAS_EXPIRED", // "CRL_NOT_YET_VALID", "CRL_HAS_EXPIRED" "ERROR_IN_CERT_NOT_BEFORE_FIELD", // "ERROR_IN_CERT_NOT_AFTER_FIELD", "ERROR_IN_CRL_LAST_UPDATE_FIELD", // "ERROR_IN_CRL_NEXT_UPDATE_FIELD", "OUT_OF_MEM", // "DEPTH_ZERO_SELF_SIGNED_CERT", "SELF_SIGNED_CERT_IN_CHAIN", // "UNABLE_TO_GET_ISSUER_CERT_LOCALLY", "UNABLE_TO_VERIFY_LEAF_SIGNATURE", // "CERT_CHAIN_TOO_LONG", "CERT_REVOKED" "INVALID_CA", // "PATH_LENGTH_EXCEEDED", "INVALID_PURPOSE" "CERT_UNTRUSTED", // "CERT_REJECTED" // // // TODO: // cleartext.credentials (by mirroring from pair object) // cleartext.getCertificate() (by mirroring from pair.credentials.context) function Server(/* [options], listener */) { var options, listener; if (typeof arguments[0] == 'object') { options = arguments[0]; listener = arguments[1]; } else if (typeof arguments[0] == 'function') { options = {}; listener = arguments[0]; } if (!(this instanceof Server)) return new Server(options, listener); this._contexts = []; var self = this; // Handle option defaults: this.setOptions(options); if (!self.pfx && (!self.cert || !self.key)) { throw new Error('Missing PFX or certificate + private key.'); } var sharedCreds = crypto.createCredentials({ pfx: self.pfx, key: self.key, passphrase: self.passphrase, cert: self.cert, ca: self.ca, ciphers: self.ciphers || DEFAULT_CIPHERS, secureProtocol: self.secureProtocol, secureOptions: self.secureOptions, crl: self.crl, sessionIdContext: self.sessionIdContext }); var timeout = options.handshakeTimeout || (120 * 1000); if (typeof timeout !== 'number') { throw new TypeError('handshakeTimeout must be a number'); } // constructor call net.Server.call(this, function(socket) { var creds = crypto.createCredentials(null, sharedCreds.context); var pair = new SecurePair(creds, true, self.requestCert, self.rejectUnauthorized, { server: self, NPNProtocols: self.NPNProtocols, SNICallback: self.SNICallback, // Stream options cleartext: self._cleartext, encrypted: self._encrypted }); var cleartext = pipe(pair, socket); cleartext._controlReleased = false; function listener() { pair.emit('error', new Error('TLS handshake timeout')); } if (timeout > 0) { socket.setTimeout(timeout, listener); } pair.once('secure', function() { socket.setTimeout(0, listener); pair.cleartext.authorized = false; pair.cleartext.npnProtocol = pair.npnProtocol; pair.cleartext.servername = pair.servername; if (!self.requestCert) { cleartext._controlReleased = true; self.emit('secureConnection', pair.cleartext, pair.encrypted); } else { var verifyError = pair.ssl.verifyError(); if (verifyError) { pair.cleartext.authorizationError = verifyError.message; if (self.rejectUnauthorized) { socket.destroy(); pair.destroy(); } else { cleartext._controlReleased = true; self.emit('secureConnection', pair.cleartext, pair.encrypted); } } else { pair.cleartext.authorized = true; cleartext._controlReleased = true; self.emit('secureConnection', pair.cleartext, pair.encrypted); } } }); pair.on('error', function(err) { self.emit('clientError', err, this); }); }); if (listener) { this.on('secureConnection', listener); } } util.inherits(Server, net.Server); exports.Server = Server; exports.createServer = function(options, listener) { return new Server(options, listener); }; Server.prototype.setOptions = function(options) { if (typeof options.requestCert == 'boolean') { this.requestCert = options.requestCert; } else { this.requestCert = false; } if (typeof options.rejectUnauthorized == 'boolean') { this.rejectUnauthorized = options.rejectUnauthorized; } else { this.rejectUnauthorized = false; } if (options.pfx) this.pfx = options.pfx; if (options.key) this.key = options.key; if (options.passphrase) this.passphrase = options.passphrase; if (options.cert) this.cert = options.cert; if (options.ca) this.ca = options.ca; if (options.secureProtocol) this.secureProtocol = options.secureProtocol; if (options.crl) this.crl = options.crl; if (options.ciphers) this.ciphers = options.ciphers; var secureOptions = options.secureOptions || 0; if (options.honorCipherOrder) { secureOptions |= constants.SSL_OP_CIPHER_SERVER_PREFERENCE; } if (secureOptions) this.secureOptions = secureOptions; if (options.NPNProtocols) convertNPNProtocols(options.NPNProtocols, this); if (options.SNICallback) { this.SNICallback = options.SNICallback; } else { this.SNICallback = this.SNICallback.bind(this); } if (options.sessionIdContext) { this.sessionIdContext = options.sessionIdContext; } else if (this.requestCert) { this.sessionIdContext = crypto.createHash('md5') .update(process.argv.join(' ')) .digest('hex'); } if (options.cleartext) this.cleartext = options.cleartext; if (options.encrypted) this.encrypted = options.encrypted; }; // SNI Contexts High-Level API Server.prototype.addContext = function(servername, credentials) { if (!servername) { throw 'Servername is required parameter for Server.addContext'; } var re = new RegExp('^' + servername.replace(/([\.^$+?\-\\[\]{}])/g, '\\$1') .replace(/\*/g, '.*') + '$'); this._contexts.push([re, crypto.createCredentials(credentials).context]); }; Server.prototype.SNICallback = function(servername) { var ctx; this._contexts.some(function(elem) { if (servername.match(elem[0]) !== null) { ctx = elem[1]; return true; } }); return ctx; }; // Target API: // // var s = tls.connect({port: 8000, host: "google.com"}, function() { // if (!s.authorized) { // s.destroy(); // return; // } // // // s.socket; // // s.end("hello world\n"); // }); // // function normalizeConnectArgs(listArgs) { var args = net._normalizeConnectArgs(listArgs); var options = args[0]; var cb = args[1]; if (typeof listArgs[1] === 'object') { options = util._extend(options, listArgs[1]); } else if (typeof listArgs[2] === 'object') { options = util._extend(options, listArgs[2]); } return (cb) ? [options, cb] : [options]; } exports.connect = function(/* [port, host], options, cb */) { var args = normalizeConnectArgs(arguments); var options = args[0]; var cb = args[1]; var defaults = { rejectUnauthorized: '0' !== process.env.NODE_TLS_REJECT_UNAUTHORIZED }; options = util._extend(defaults, options || {}); var socket = options.socket ? options.socket : new net.Stream(); var sslcontext = crypto.createCredentials(options); var NPN = {}; convertNPNProtocols(options.NPNProtocols, NPN); var hostname = options.servername || options.host || 'localhost', pair = new SecurePair(sslcontext, false, true, options.rejectUnauthorized === true ? true : false, { NPNProtocols: NPN.NPNProtocols, servername: hostname, cleartext: options.cleartext, encrypted: options.encrypted }); if (options.session) { var session = options.session; if (typeof session === 'string') session = new Buffer(session, 'binary'); pair.ssl.setSession(session); } var cleartext = pipe(pair, socket); if (cb) { cleartext.once('secureConnect', cb); } if (!options.socket) { var connect_opt = (options.path && !options.port) ? {path: options.path} : { port: options.port, host: options.host, localAddress: options.localAddress }; socket.connect(connect_opt); } pair.on('secure', function() { var verifyError = pair.ssl.verifyError(); cleartext.npnProtocol = pair.npnProtocol; // Verify that server's identity matches it's certificate's names if (!verifyError) { var validCert = checkServerIdentity(hostname, pair.cleartext.getPeerCertificate()); if (!validCert) { verifyError = new Error('Hostname/IP doesn\'t match certificate\'s ' + 'altnames'); } } if (verifyError) { cleartext.authorized = false; cleartext.authorizationError = verifyError.message; if (pair._rejectUnauthorized) { cleartext.emit('error', verifyError); pair.destroy(); } else { cleartext.emit('secureConnect'); } } else { cleartext.authorized = true; cleartext.emit('secureConnect'); } }); pair.on('error', function(err) { cleartext.emit('error', err); }); cleartext._controlReleased = true; return cleartext; }; function pipe(pair, socket) { pair.encrypted.pipe(socket); socket.pipe(pair.encrypted); pair.encrypted.on('close', function() { process.nextTick(function() { // Encrypted should be unpiped from socket to prevent possible // write after destroy. pair.encrypted.unpipe(socket); socket.destroySoon(); }); }); pair.fd = socket.fd; var cleartext = pair.cleartext; cleartext.socket = socket; cleartext.encrypted = pair.encrypted; cleartext.authorized = false; // cycle the data whenever the socket drains, so that // we can pull some more into it. normally this would // be handled by the fact that pipe() triggers read() calls // on writable.drain, but CryptoStreams are a bit more // complicated. Since the encrypted side actually gets // its data from the cleartext side, we have to give it a // light kick to get in motion again. socket.on('drain', function() { if (pair.encrypted._pending) pair.encrypted._writePending(); if (pair.cleartext._pending) pair.cleartext._writePending(); pair.encrypted.read(0); pair.cleartext.read(0); }); function onerror(e) { if (cleartext._controlReleased) { cleartext.emit('error', e); } } function onclose() { socket.removeListener('error', onerror); socket.removeListener('timeout', ontimeout); } function ontimeout() { cleartext.emit('timeout'); } socket.on('error', onerror); socket.on('close', onclose); socket.on('timeout', ontimeout); return cleartext; } node-v0.10.25~dfsg2/lib/_stream_readable.js0000755000000000000000000006172012270121457017203 0ustar rootroot// Copyright Joyent, Inc. and other Node contributors. // // Permission is hereby granted, free of charge, to any person obtaining a // copy of this software and associated documentation files (the // "Software"), to deal in the Software without restriction, including // without limitation the rights to use, copy, modify, merge, publish, // distribute, sublicense, and/or sell copies of the Software, and to permit // persons to whom the Software is furnished to do so, subject to the // following conditions: // // The above copyright notice and this permission notice shall be included // in all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS // OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF // MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN // NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, // DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR // OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE // USE OR OTHER DEALINGS IN THE SOFTWARE. module.exports = Readable; Readable.ReadableState = ReadableState; var EE = require('events').EventEmitter; var Stream = require('stream'); var util = require('util'); var StringDecoder; util.inherits(Readable, Stream); function ReadableState(options, stream) { options = options || {}; // the point at which it stops calling _read() to fill the buffer // Note: 0 is a valid value, means "don't call _read preemptively ever" var hwm = options.highWaterMark; this.highWaterMark = (hwm || hwm === 0) ? hwm : 16 * 1024; // cast to ints. this.highWaterMark = ~~this.highWaterMark; this.buffer = []; this.length = 0; this.pipes = null; this.pipesCount = 0; this.flowing = false; this.ended = false; this.endEmitted = false; this.reading = false; // In streams that never have any data, and do push(null) right away, // the consumer can miss the 'end' event if they do some I/O before // consuming the stream. So, we don't emit('end') until some reading // happens. this.calledRead = false; // a flag to be able to tell if the onwrite cb is called immediately, // or on a later tick. We set this to true at first, becuase any // actions that shouldn't happen until "later" should generally also // not happen before the first write call. this.sync = true; // whenever we return null, then we set a flag to say // that we're awaiting a 'readable' event emission. this.needReadable = false; this.emittedReadable = false; this.readableListening = false; // object stream flag. Used to make read(n) ignore n and to // make all the buffer merging and length checks go away this.objectMode = !!options.objectMode; // Crypto is kind of old and crusty. Historically, its default string // encoding is 'binary' so we have to make this configurable. // Everything else in the universe uses 'utf8', though. this.defaultEncoding = options.defaultEncoding || 'utf8'; // when piping, we only care about 'readable' events that happen // after read()ing all the bytes and not getting any pushback. this.ranOut = false; // the number of writers that are awaiting a drain event in .pipe()s this.awaitDrain = 0; // if true, a maybeReadMore has been scheduled this.readingMore = false; this.decoder = null; this.encoding = null; if (options.encoding) { if (!StringDecoder) StringDecoder = require('string_decoder').StringDecoder; this.decoder = new StringDecoder(options.encoding); this.encoding = options.encoding; } } function Readable(options) { if (!(this instanceof Readable)) return new Readable(options); this._readableState = new ReadableState(options, this); // legacy this.readable = true; Stream.call(this); } // Manually shove something into the read() buffer. // This returns true if the highWaterMark has not been hit yet, // similar to how Writable.write() returns true if you should // write() some more. Readable.prototype.push = function(chunk, encoding) { var state = this._readableState; if (typeof chunk === 'string' && !state.objectMode) { encoding = encoding || state.defaultEncoding; if (encoding !== state.encoding) { chunk = new Buffer(chunk, encoding); encoding = ''; } } return readableAddChunk(this, state, chunk, encoding, false); }; // Unshift should *always* be something directly out of read() Readable.prototype.unshift = function(chunk) { var state = this._readableState; return readableAddChunk(this, state, chunk, '', true); }; function readableAddChunk(stream, state, chunk, encoding, addToFront) { var er = chunkInvalid(state, chunk); if (er) { stream.emit('error', er); } else if (chunk === null || chunk === undefined) { state.reading = false; if (!state.ended) onEofChunk(stream, state); } else if (state.objectMode || chunk && chunk.length > 0) { if (state.ended && !addToFront) { var e = new Error('stream.push() after EOF'); stream.emit('error', e); } else if (state.endEmitted && addToFront) { var e = new Error('stream.unshift() after end event'); stream.emit('error', e); } else { if (state.decoder && !addToFront && !encoding) chunk = state.decoder.write(chunk); // update the buffer info. state.length += state.objectMode ? 1 : chunk.length; if (addToFront) { state.buffer.unshift(chunk); } else { state.reading = false; state.buffer.push(chunk); } if (state.needReadable) emitReadable(stream); maybeReadMore(stream, state); } } else if (!addToFront) { state.reading = false; } return needMoreData(state); } // if it's past the high water mark, we can push in some more. // Also, if we have no data yet, we can stand some // more bytes. This is to work around cases where hwm=0, // such as the repl. Also, if the push() triggered a // readable event, and the user called read(largeNumber) such that // needReadable was set, then we ought to push more, so that another // 'readable' event will be triggered. function needMoreData(state) { return !state.ended && (state.needReadable || state.length < state.highWaterMark || state.length === 0); } // backwards compatibility. Readable.prototype.setEncoding = function(enc) { if (!StringDecoder) StringDecoder = require('string_decoder').StringDecoder; this._readableState.decoder = new StringDecoder(enc); this._readableState.encoding = enc; }; // Don't raise the hwm > 128MB var MAX_HWM = 0x800000; function roundUpToNextPowerOf2(n) { if (n >= MAX_HWM) { n = MAX_HWM; } else { // Get the next highest power of 2 n--; for (var p = 1; p < 32; p <<= 1) n |= n >> p; n++; } return n; } function howMuchToRead(n, state) { if (state.length === 0 && state.ended) return 0; if (state.objectMode) return n === 0 ? 0 : 1; if (isNaN(n) || n === null) { // only flow one buffer at a time if (state.flowing && state.buffer.length) return state.buffer[0].length; else return state.length; } if (n <= 0) return 0; // If we're asking for more than the target buffer level, // then raise the water mark. Bump up to the next highest // power of 2, to prevent increasing it excessively in tiny // amounts. if (n > state.highWaterMark) state.highWaterMark = roundUpToNextPowerOf2(n); // don't have that much. return null, unless we've ended. if (n > state.length) { if (!state.ended) { state.needReadable = true; return 0; } else return state.length; } return n; } // you can override either this method, or the async _read(n) below. Readable.prototype.read = function(n) { var state = this._readableState; state.calledRead = true; var nOrig = n; if (typeof n !== 'number' || n > 0) state.emittedReadable = false; // if we're doing read(0) to trigger a readable event, but we // already have a bunch of data in the buffer, then just trigger // the 'readable' event and move on. if (n === 0 && state.needReadable && (state.length >= state.highWaterMark || state.ended)) { emitReadable(this); return null; } n = howMuchToRead(n, state); // if we've ended, and we're now clear, then finish it up. if (n === 0 && state.ended) { if (state.length === 0) endReadable(this); return null; } // All the actual chunk generation logic needs to be // *below* the call to _read. The reason is that in certain // synthetic stream cases, such as passthrough streams, _read // may be a completely synchronous operation which may change // the state of the read buffer, providing enough data when // before there was *not* enough. // // So, the steps are: // 1. Figure out what the state of things will be after we do // a read from the buffer. // // 2. If that resulting state will trigger a _read, then call _read. // Note that this may be asynchronous, or synchronous. Yes, it is // deeply ugly to write APIs this way, but that still doesn't mean // that the Readable class should behave improperly, as streams are // designed to be sync/async agnostic. // Take note if the _read call is sync or async (ie, if the read call // has returned yet), so that we know whether or not it's safe to emit // 'readable' etc. // // 3. Actually pull the requested chunks out of the buffer and return. // if we need a readable event, then we need to do some reading. var doRead = state.needReadable; // if we currently have less than the highWaterMark, then also read some if (state.length - n <= state.highWaterMark) doRead = true; // however, if we've ended, then there's no point, and if we're already // reading, then it's unnecessary. if (state.ended || state.reading) doRead = false; if (doRead) { state.reading = true; state.sync = true; // if the length is currently zero, then we *need* a readable event. if (state.length === 0) state.needReadable = true; // call internal read method this._read(state.highWaterMark); state.sync = false; } // If _read called its callback synchronously, then `reading` // will be false, and we need to re-evaluate how much data we // can return to the user. if (doRead && !state.reading) n = howMuchToRead(nOrig, state); var ret; if (n > 0) ret = fromList(n, state); else ret = null; if (ret === null) { state.needReadable = true; n = 0; } state.length -= n; // If we have nothing in the buffer, then we want to know // as soon as we *do* get something into the buffer. if (state.length === 0 && !state.ended) state.needReadable = true; // If we happened to read() exactly the remaining amount in the // buffer, and the EOF has been seen at this point, then make sure // that we emit 'end' on the very next tick. if (state.ended && !state.endEmitted && state.length === 0) endReadable(this); return ret; }; function chunkInvalid(state, chunk) { var er = null; if (!Buffer.isBuffer(chunk) && 'string' !== typeof chunk && chunk !== null && chunk !== undefined && !state.objectMode && !er) { er = new TypeError('Invalid non-string/buffer chunk'); } return er; } function onEofChunk(stream, state) { if (state.decoder && !state.ended) { var chunk = state.decoder.end(); if (chunk && chunk.length) { state.buffer.push(chunk); state.length += state.objectMode ? 1 : chunk.length; } } state.ended = true; // if we've ended and we have some data left, then emit // 'readable' now to make sure it gets picked up. if (state.length > 0) emitReadable(stream); else endReadable(stream); } // Don't emit readable right away in sync mode, because this can trigger // another read() call => stack overflow. This way, it might trigger // a nextTick recursion warning, but that's not so bad. function emitReadable(stream) { var state = stream._readableState; state.needReadable = false; if (state.emittedReadable) return; state.emittedReadable = true; if (state.sync) process.nextTick(function() { emitReadable_(stream); }); else emitReadable_(stream); } function emitReadable_(stream) { stream.emit('readable'); } // at this point, the user has presumably seen the 'readable' event, // and called read() to consume some data. that may have triggered // in turn another _read(n) call, in which case reading = true if // it's in progress. // However, if we're not ended, or reading, and the length < hwm, // then go ahead and try to read some more preemptively. function maybeReadMore(stream, state) { if (!state.readingMore) { state.readingMore = true; process.nextTick(function() { maybeReadMore_(stream, state); }); } } function maybeReadMore_(stream, state) { var len = state.length; while (!state.reading && !state.flowing && !state.ended && state.length < state.highWaterMark) { stream.read(0); if (len === state.length) // didn't get any data, stop spinning. break; else len = state.length; } state.readingMore = false; } // abstract method. to be overridden in specific implementation classes. // call cb(er, data) where data is <= n in length. // for virtual (non-string, non-buffer) streams, "length" is somewhat // arbitrary, and perhaps not very meaningful. Readable.prototype._read = function(n) { this.emit('error', new Error('not implemented')); }; Readable.prototype.pipe = function(dest, pipeOpts) { var src = this; var state = this._readableState; switch (state.pipesCount) { case 0: state.pipes = dest; break; case 1: state.pipes = [state.pipes, dest]; break; default: state.pipes.push(dest); break; } state.pipesCount += 1; var doEnd = (!pipeOpts || pipeOpts.end !== false) && dest !== process.stdout && dest !== process.stderr; var endFn = doEnd ? onend : cleanup; if (state.endEmitted) process.nextTick(endFn); else src.once('end', endFn); dest.on('unpipe', onunpipe); function onunpipe(readable) { if (readable !== src) return; cleanup(); } function onend() { dest.end(); } // when the dest drains, it reduces the awaitDrain counter // on the source. This would be more elegant with a .once() // handler in flow(), but adding and removing repeatedly is // too slow. var ondrain = pipeOnDrain(src); dest.on('drain', ondrain); function cleanup() { // cleanup event handlers once the pipe is broken dest.removeListener('close', onclose); dest.removeListener('finish', onfinish); dest.removeListener('drain', ondrain); dest.removeListener('error', onerror); dest.removeListener('unpipe', onunpipe); src.removeListener('end', onend); src.removeListener('end', cleanup); // if the reader is waiting for a drain event from this // specific writer, then it would cause it to never start // flowing again. // So, if this is awaiting a drain, then we just call it now. // If we don't know, then assume that we are waiting for one. if (!dest._writableState || dest._writableState.needDrain) ondrain(); } // if the dest has an error, then stop piping into it. // however, don't suppress the throwing behavior for this. function onerror(er) { unpipe(); dest.removeListener('error', onerror); if (EE.listenerCount(dest, 'error') === 0) dest.emit('error', er); } // This is a brutally ugly hack to make sure that our error handler // is attached before any userland ones. NEVER DO THIS. if (!dest._events || !dest._events.error) dest.on('error', onerror); else if (Array.isArray(dest._events.error)) dest._events.error.unshift(onerror); else dest._events.error = [onerror, dest._events.error]; // Both close and finish should trigger unpipe, but only once. function onclose() { dest.removeListener('finish', onfinish); unpipe(); } dest.once('close', onclose); function onfinish() { dest.removeListener('close', onclose); unpipe(); } dest.once('finish', onfinish); function unpipe() { src.unpipe(dest); } // tell the dest that it's being piped to dest.emit('pipe', src); // start the flow if it hasn't been started already. if (!state.flowing) { // the handler that waits for readable events after all // the data gets sucked out in flow. // This would be easier to follow with a .once() handler // in flow(), but that is too slow. this.on('readable', pipeOnReadable); state.flowing = true; process.nextTick(function() { flow(src); }); } return dest; }; function pipeOnDrain(src) { return function() { var dest = this; var state = src._readableState; state.awaitDrain--; if (state.awaitDrain === 0) flow(src); }; } function flow(src) { var state = src._readableState; var chunk; state.awaitDrain = 0; function write(dest, i, list) { var written = dest.write(chunk); if (false === written) { state.awaitDrain++; } } while (state.pipesCount && null !== (chunk = src.read())) { if (state.pipesCount === 1) write(state.pipes, 0, null); else state.pipes.forEach(write); src.emit('data', chunk); // if anyone needs a drain, then we have to wait for that. if (state.awaitDrain > 0) return; } // if every destination was unpiped, either before entering this // function, or in the while loop, then stop flowing. // // NB: This is a pretty rare edge case. if (state.pipesCount === 0) { state.flowing = false; // if there were data event listeners added, then switch to old mode. if (EE.listenerCount(src, 'data') > 0) emitDataEvents(src); return; } // at this point, no one needed a drain, so we just ran out of data // on the next readable event, start it over again. state.ranOut = true; } function pipeOnReadable() { if (this._readableState.ranOut) { this._readableState.ranOut = false; flow(this); } } Readable.prototype.unpipe = function(dest) { var state = this._readableState; // if we're not piping anywhere, then do nothing. if (state.pipesCount === 0) return this; // just one destination. most common case. if (state.pipesCount === 1) { // passed in one, but it's not the right one. if (dest && dest !== state.pipes) return this; if (!dest) dest = state.pipes; // got a match. state.pipes = null; state.pipesCount = 0; this.removeListener('readable', pipeOnReadable); state.flowing = false; if (dest) dest.emit('unpipe', this); return this; } // slow case. multiple pipe destinations. if (!dest) { // remove all. var dests = state.pipes; var len = state.pipesCount; state.pipes = null; state.pipesCount = 0; this.removeListener('readable', pipeOnReadable); state.flowing = false; for (var i = 0; i < len; i++) dests[i].emit('unpipe', this); return this; } // try to find the right one. var i = state.pipes.indexOf(dest); if (i === -1) return this; state.pipes.splice(i, 1); state.pipesCount -= 1; if (state.pipesCount === 1) state.pipes = state.pipes[0]; dest.emit('unpipe', this); return this; }; // set up data events if they are asked for // Ensure readable listeners eventually get something Readable.prototype.on = function(ev, fn) { var res = Stream.prototype.on.call(this, ev, fn); if (ev === 'data' && !this._readableState.flowing) emitDataEvents(this); if (ev === 'readable' && this.readable) { var state = this._readableState; if (!state.readableListening) { state.readableListening = true; state.emittedReadable = false; state.needReadable = true; if (!state.reading) { this.read(0); } else if (state.length) { emitReadable(this, state); } } } return res; }; Readable.prototype.addListener = Readable.prototype.on; // pause() and resume() are remnants of the legacy readable stream API // If the user uses them, then switch into old mode. Readable.prototype.resume = function() { emitDataEvents(this); this.read(0); this.emit('resume'); }; Readable.prototype.pause = function() { emitDataEvents(this, true); this.emit('pause'); }; function emitDataEvents(stream, startPaused) { var state = stream._readableState; if (state.flowing) { // https://github.com/isaacs/readable-stream/issues/16 throw new Error('Cannot switch to old mode now.'); } var paused = startPaused || false; var readable = false; // convert to an old-style stream. stream.readable = true; stream.pipe = Stream.prototype.pipe; stream.on = stream.addListener = Stream.prototype.on; stream.on('readable', function() { readable = true; var c; while (!paused && (null !== (c = stream.read()))) stream.emit('data', c); if (c === null) { readable = false; stream._readableState.needReadable = true; } }); stream.pause = function() { paused = true; this.emit('pause'); }; stream.resume = function() { paused = false; if (readable) process.nextTick(function() { stream.emit('readable'); }); else this.read(0); this.emit('resume'); }; // now make it start, just in case it hadn't already. stream.emit('readable'); } // wrap an old-style stream as the async data source. // This is *not* part of the readable stream interface. // It is an ugly unfortunate mess of history. Readable.prototype.wrap = function(stream) { var state = this._readableState; var paused = false; var self = this; stream.on('end', function() { if (state.decoder && !state.ended) { var chunk = state.decoder.end(); if (chunk && chunk.length) self.push(chunk); } self.push(null); }); stream.on('data', function(chunk) { if (state.decoder) chunk = state.decoder.write(chunk); if (!chunk || !state.objectMode && !chunk.length) return; var ret = self.push(chunk); if (!ret) { paused = true; stream.pause(); } }); // proxy all the other methods. // important when wrapping filters and duplexes. for (var i in stream) { if (typeof stream[i] === 'function' && typeof this[i] === 'undefined') { this[i] = function(method) { return function() { return stream[method].apply(stream, arguments); }}(i); } } // proxy certain important events. var events = ['error', 'close', 'destroy', 'pause', 'resume']; events.forEach(function(ev) { stream.on(ev, self.emit.bind(self, ev)); }); // when we try to consume some more bytes, simply unpause the // underlying stream. self._read = function(n) { if (paused) { paused = false; stream.resume(); } }; return self; }; // exposed for testing purposes only. Readable._fromList = fromList; // Pluck off n bytes from an array of buffers. // Length is the combined lengths of all the buffers in the list. function fromList(n, state) { var list = state.buffer; var length = state.length; var stringMode = !!state.decoder; var objectMode = !!state.objectMode; var ret; // nothing in the list, definitely empty. if (list.length === 0) return null; if (length === 0) ret = null; else if (objectMode) ret = list.shift(); else if (!n || n >= length) { // read it all, truncate the array. if (stringMode) ret = list.join(''); else ret = Buffer.concat(list, length); list.length = 0; } else { // read just some of it. if (n < list[0].length) { // just take a part of the first list item. // slice is the same for buffers and strings. var buf = list[0]; ret = buf.slice(0, n); list[0] = buf.slice(n); } else if (n === list[0].length) { // first list is a perfect match ret = list.shift(); } else { // complex case. // we have enough to cover it, but it spans past the first buffer. if (stringMode) ret = ''; else ret = new Buffer(n); var c = 0; for (var i = 0, l = list.length; i < l && c < n; i++) { var buf = list[0]; var cpy = Math.min(n - c, buf.length); if (stringMode) ret += buf.slice(0, cpy); else buf.copy(ret, c, 0, cpy); if (cpy < buf.length) list[0] = buf.slice(cpy); else list.shift(); c += cpy; } } } return ret; } function endReadable(stream) { var state = stream._readableState; // If we get here before consuming all the bytes, then that is a // bug in node. Should never happen. if (state.length > 0) throw new Error('endReadable called on non-empty stream'); if (!state.endEmitted && state.calledRead) { state.ended = true; process.nextTick(function() { // Check that we didn't get one last unshift. if (!state.endEmitted && state.length === 0) { state.endEmitted = true; stream.readable = false; stream.emit('end'); } }); } } node-v0.10.25~dfsg2/lib/_stream_passthrough.js0000644000000000000000000000315112270121457020002 0ustar rootroot// Copyright Joyent, Inc. and other Node contributors. // // Permission is hereby granted, free of charge, to any person obtaining a // copy of this software and associated documentation files (the // "Software"), to deal in the Software without restriction, including // without limitation the rights to use, copy, modify, merge, publish, // distribute, sublicense, and/or sell copies of the Software, and to permit // persons to whom the Software is furnished to do so, subject to the // following conditions: // // The above copyright notice and this permission notice shall be included // in all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS // OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF // MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN // NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, // DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR // OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE // USE OR OTHER DEALINGS IN THE SOFTWARE. // a passthrough stream. // basically just the most minimal sort of Transform stream. // Every written chunk gets output as-is. module.exports = PassThrough; var Transform = require('_stream_transform'); var util = require('util'); util.inherits(PassThrough, Transform); function PassThrough(options) { if (!(this instanceof PassThrough)) return new PassThrough(options); Transform.call(this, options); } PassThrough.prototype._transform = function(chunk, encoding, cb) { cb(null, chunk); }; node-v0.10.25~dfsg2/lib/cluster.js0000644000000000000000000004057412270121457015414 0ustar rootroot// Copyright Joyent, Inc. and other Node contributors. // // Permission is hereby granted, free of charge, to any person obtaining a // copy of this software and associated documentation files (the // "Software"), to deal in the Software without restriction, including // without limitation the rights to use, copy, modify, merge, publish, // distribute, sublicense, and/or sell copies of the Software, and to permit // persons to whom the Software is furnished to do so, subject to the // following conditions: // // The above copyright notice and this permission notice shall be included // in all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS // OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF // MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN // NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, // DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR // OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE // USE OR OTHER DEALINGS IN THE SOFTWARE. var assert = require('assert'); var fork = require('child_process').fork; var net = require('net'); var EventEmitter = require('events').EventEmitter; var util = require('util'); function isObject(o) { return (typeof o === 'object' && o !== null); } var debug; if (process.env.NODE_DEBUG && /cluster/.test(process.env.NODE_DEBUG)) { debug = function(x) { var prefix = process.pid + ',' + (process.env.NODE_UNIQUE_ID ? 'Worker' : 'Master'); console.error(prefix, x); }; } else { debug = function() { }; } // cluster object: function Cluster() { EventEmitter.call(this); } util.inherits(Cluster, EventEmitter); var cluster = module.exports = new Cluster(); // Used in the master: var masterStarted = false; var ids = 0; var serverHandlers = {}; // Used in the worker: var serverListeners = {}; var queryIds = 0; var queryCallbacks = {}; // Define isWorker and isMaster cluster.isWorker = 'NODE_UNIQUE_ID' in process.env; cluster.isMaster = ! cluster.isWorker; // The worker object is only used in a worker cluster.worker = cluster.isWorker ? {} : null; // The workers array is only used in the master cluster.workers = cluster.isMaster ? {} : null; // Settings object var settings = cluster.settings = {}; // Simple function to call a function on each worker function eachWorker(cb) { // Go through all workers for (var id in cluster.workers) { if (cluster.workers.hasOwnProperty(id)) { cb(cluster.workers[id]); } } } // Extremely simple progress tracker function ProgressTracker(missing, callback) { this.missing = missing; this.callback = callback; } ProgressTracker.prototype.done = function() { this.missing -= 1; this.check(); }; ProgressTracker.prototype.check = function() { if (this.missing === 0) this.callback(); }; cluster.setupMaster = function(options) { // This can only be called from the master. assert(cluster.isMaster); // Don't allow this function to run more than once if (masterStarted) return; masterStarted = true; // Get filename and arguments options = options || {}; // By default, V8 writes the profile data of all processes to a single // v8.log. // // Running that log file through a tick processor produces bogus numbers // because many events won't match up with the recorded memory mappings // and you end up with graphs where 80+% of ticks is unaccounted for. // // Fixing the tick processor to deal with multi-process output is not very // useful because the processes may be running wildly disparate workloads. // // That's why we fix up the command line arguments to include // a "--logfile=v8-%p.log" argument (where %p is expanded to the PID) // unless it already contains a --logfile argument. var execArgv = options.execArgv || process.execArgv; if (execArgv.some(function(s) { return /^--prof/.test(s); }) && !execArgv.some(function(s) { return /^--logfile=/.test(s); })) { execArgv = execArgv.slice(); execArgv.push('--logfile=v8-%p.log'); } // Set settings object settings = cluster.settings = { exec: options.exec || process.argv[1], execArgv: execArgv, args: options.args || process.argv.slice(2), silent: options.silent || false }; // emit setup event cluster.emit('setup'); }; // Check if a message is internal only var INTERNAL_PREFIX = 'NODE_CLUSTER_'; function isInternalMessage(message) { return isObject(message) && typeof message.cmd === 'string' && message.cmd.length > INTERNAL_PREFIX.length && message.cmd.slice(0, INTERNAL_PREFIX.length) === INTERNAL_PREFIX; } // Modify message object to be internal function internalMessage(inMessage) { var outMessage = util._extend({}, inMessage); // Add internal prefix to cmd outMessage.cmd = INTERNAL_PREFIX + (outMessage.cmd || ''); return outMessage; } // Handle callback messages function handleResponse(outMessage, outHandle, inMessage, inHandle, worker) { // The message there will be sent var message = internalMessage(outMessage); // callback id - will be undefined if not set message._queryEcho = inMessage._requestEcho; // Call callback if a query echo is received if (inMessage._queryEcho) { queryCallbacks[inMessage._queryEcho](inMessage.content, inHandle); delete queryCallbacks[inMessage._queryEcho]; } // Send if outWrap contains something useful if (!(outMessage === undefined && message._queryEcho === undefined)) { sendInternalMessage(worker, message, outHandle); } } // Handle messages from both master and workers var messageHandler = {}; function handleMessage(worker, inMessage, inHandle) { // Remove internal prefix var message = util._extend({}, inMessage); message.cmd = inMessage.cmd.substr(INTERNAL_PREFIX.length); var respondUsed = false; function respond(outMessage, outHandler) { respondUsed = true; handleResponse(outMessage, outHandler, inMessage, inHandle, worker); } // Run handler if it exists if (messageHandler[message.cmd]) { messageHandler[message.cmd](message, worker, respond); } // Send respond if it hasn't been called yet if (respondUsed === false) { respond(); } } // Messages to the master will be handled using these methods if (cluster.isMaster) { // Handle online messages from workers messageHandler.online = function(message, worker) { worker.state = 'online'; debug('Worker ' + worker.process.pid + ' online'); worker.emit('online'); cluster.emit('online', worker); }; // Handle queryServer messages from workers messageHandler.queryServer = function(message, worker, send) { // This sequence of information is unique to the connection // but not to the worker var args = [message.address, message.port, message.addressType, message.fd]; var key = args.join(':'); var handler; if (serverHandlers.hasOwnProperty(key)) { handler = serverHandlers[key]; } else { if (message.addressType === 'udp4' || message.addressType === 'udp6') { var dgram = require('dgram'); handler = dgram._createSocketHandle.apply(net, args); } else { handler = net._createServerHandle.apply(net, args); } if (!handler) { send({ content: { error: process._errno } }, null); return; } serverHandlers[key] = handler; } // echo callback with the fd handler associated with it send({}, handler); }; // Handle listening messages from workers messageHandler.listening = function(message, worker) { worker.state = 'listening'; // Emit listening, now that we know the worker is listening worker.emit('listening', { address: message.address, port: message.port, addressType: message.addressType, fd: message.fd }); cluster.emit('listening', worker, { address: message.address, port: message.port, addressType: message.addressType, fd: message.fd }); }; // Handle suicide messages from workers messageHandler.suicide = function(message, worker) { worker.suicide = true; }; } // Messages to a worker will be handled using these methods else if (cluster.isWorker) { // Handle worker.disconnect from master messageHandler.disconnect = function(message, worker) { worker.disconnect(); }; } function toDecInt(value) { value = parseInt(value, 10); return isNaN(value) ? null : value; } // Create a worker object, that works both for master and worker function Worker(customEnv) { if (!(this instanceof Worker)) return new Worker(); EventEmitter.call(this); var self = this; var env = process.env; // Assign a unique id, default null this.id = cluster.isMaster ? ++ids : toDecInt(env.NODE_UNIQUE_ID); // XXX: Legacy. Remove in 0.9 this.workerID = this.uniqueID = this.id; // Assign state this.state = 'none'; // Create or get process if (cluster.isMaster) { // Create env object // first: copy and add id property var envCopy = util._extend({}, env); envCopy['NODE_UNIQUE_ID'] = this.id; // second: extend envCopy with the env argument if (isObject(customEnv)) { envCopy = util._extend(envCopy, customEnv); } // fork worker this.process = fork(settings.exec, settings.args, { 'env': envCopy, 'silent': settings.silent, 'execArgv': settings.execArgv }); } else { this.process = process; } if (cluster.isMaster) { // Save worker in the cluster.workers array cluster.workers[this.id] = this; // Emit a fork event, on next tick // There is no worker.fork event since this has no real purpose process.nextTick(function() { cluster.emit('fork', self); }); } // handle internalMessage, exit and disconnect event this.process.on('internalMessage', handleMessage.bind(null, this)); this.process.once('exit', function(exitCode, signalCode) { prepareExit(self, 'dead'); self.emit('exit', exitCode, signalCode); cluster.emit('exit', self, exitCode, signalCode); }); this.process.once('disconnect', function() { prepareExit(self, 'disconnected'); self.emit('disconnect'); cluster.emit('disconnect', self); }); // relay message and error this.process.on('message', this.emit.bind(this, 'message')); this.process.on('error', this.emit.bind(this, 'error')); } util.inherits(Worker, EventEmitter); cluster.Worker = Worker; function prepareExit(worker, state) { // set state to disconnect worker.state = state; // Make suicide a boolean worker.suicide = !!worker.suicide; // Remove from workers in the master if (cluster.isMaster) { delete cluster.workers[worker.id]; } } // Send internal message function sendInternalMessage(worker, message/*, handler, callback*/) { // Exist callback var callback = arguments[arguments.length - 1]; if (typeof callback !== 'function') { callback = undefined; } // exist handler var handler = arguments[2] !== callback ? arguments[2] : undefined; if (!isInternalMessage(message)) { message = internalMessage(message); } // Store callback for later if (callback) { message._requestEcho = worker.id + ':' + (++queryIds); queryCallbacks[message._requestEcho] = callback; } worker.send(message, handler); } // Send message to worker or master Worker.prototype.send = function() { // You could also just use process.send in a worker this.process.send.apply(this.process, arguments); }; // Kill the worker without restarting Worker.prototype.kill = Worker.prototype.destroy = function(signal) { if (!signal) signal = 'SIGTERM'; var self = this; this.suicide = true; if (cluster.isMaster) { // Disconnect IPC channel // this way the worker won't need to propagate suicide state to master if (self.process.connected) { self.process.once('disconnect', function() { self.process.kill(signal); }); self.process.disconnect(); } else { self.process.kill(signal); } } else { // Channel is open if (this.process.connected) { // Inform master to suicide and then kill sendInternalMessage(this, {cmd: 'suicide'}, function() { process.exit(0); }); // When channel is closed, terminate the process this.process.once('disconnect', function() { process.exit(0); }); } else { process.exit(0); } } }; // The .disconnect function will close all servers // and then disconnect the IPC channel. if (cluster.isMaster) { // Used in master Worker.prototype.disconnect = function() { this.suicide = true; sendInternalMessage(this, {cmd: 'disconnect'}); }; } else { // Used in workers Worker.prototype.disconnect = function() { var self = this; this.suicide = true; // keep track of open servers var servers = Object.keys(serverListeners).length; var progress = new ProgressTracker(servers, function() { // There are no more servers open so we will close the IPC channel. // Closing the IPC channel will emit a disconnect event // in both master and worker on the process object. // This event will be handled by prepareExit. self.process.disconnect(); }); // depending on where this function was called from (master or worker) // The suicide state has already been set, // but it doesn't really matter if we set it again. sendInternalMessage(this, {cmd: 'suicide'}, function() { // in case there are no servers progress.check(); // closing all servers gracefully var server; for (var key in serverListeners) { server = serverListeners[key]; // in case the server is closed we won't close it again if (server._handle === null) { progress.done(); continue; } server.on('close', progress.done.bind(progress)); server.close(); } }); }; } // Fork a new worker cluster.fork = function(env) { // This can only be called from the master. assert(cluster.isMaster); // Make sure that the master has been initialized cluster.setupMaster(); return (new cluster.Worker(env)); }; // execute .disconnect on all workers and close handlers when done cluster.disconnect = function(callback) { // This can only be called from the master. assert(cluster.isMaster); // Close all TCP handlers when all workers are disconnected var workers = Object.keys(cluster.workers).length; var progress = new ProgressTracker(workers, function() { for (var key in serverHandlers) { serverHandlers[key].close(); delete serverHandlers[key]; } // call callback when done if (callback) callback(); }); // begin disconnecting all workers eachWorker(function(worker) { worker.once('disconnect', progress.done.bind(progress)); worker.disconnect(); }); // in case there weren't any workers progress.check(); }; // Internal function. Called from src/node.js when worker process starts. cluster._setupWorker = function() { // Get worker class var worker = cluster.worker = new Worker(); // we will terminate the worker // when the worker is disconnected from the parent accidentally process.once('disconnect', function() { if (worker.suicide !== true) { process.exit(0); } }); // Tell master that the worker is online worker.state = 'online'; sendInternalMessage(worker, { cmd: 'online' }); }; // Internal function. Called by net.js and dgram.js when attempting to bind a // TCP server or UDP socket. cluster._getServer = function(tcpSelf, address, port, addressType, fd, cb) { // This can only be called from a worker. assert(cluster.isWorker); // Store tcp instance for later use var key = [address, port, addressType, fd].join(':'); serverListeners[key] = tcpSelf; // Send a listening message to the master tcpSelf.once('listening', function() { cluster.worker.state = 'listening'; sendInternalMessage(cluster.worker, { cmd: 'listening', address: address, port: tcpSelf.address().port || port, addressType: addressType, fd: fd }); }); // Request the fd handler from the master process var message = { cmd: 'queryServer', address: address, port: port, addressType: addressType, fd: fd }; // The callback will be stored until the master has responded sendInternalMessage(cluster.worker, message, function(msg, handle) { cb(handle, msg && msg.error); }); }; node-v0.10.25~dfsg2/lib/querystring.js0000644000000000000000000001307412270121457016322 0ustar rootroot// Copyright Joyent, Inc. and other Node contributors. // // Permission is hereby granted, free of charge, to any person obtaining a // copy of this software and associated documentation files (the // "Software"), to deal in the Software without restriction, including // without limitation the rights to use, copy, modify, merge, publish, // distribute, sublicense, and/or sell copies of the Software, and to permit // persons to whom the Software is furnished to do so, subject to the // following conditions: // // The above copyright notice and this permission notice shall be included // in all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS // OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF // MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN // NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, // DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR // OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE // USE OR OTHER DEALINGS IN THE SOFTWARE. // Query String Utilities var QueryString = exports; // If obj.hasOwnProperty has been overridden, then calling // obj.hasOwnProperty(prop) will break. // See: https://github.com/joyent/node/issues/1707 function hasOwnProperty(obj, prop) { return Object.prototype.hasOwnProperty.call(obj, prop); } function charCode(c) { return c.charCodeAt(0); } // a safe fast alternative to decodeURIComponent QueryString.unescapeBuffer = function(s, decodeSpaces) { var out = new Buffer(s.length); var state = 'CHAR'; // states: CHAR, HEX0, HEX1 var n, m, hexchar; for (var inIndex = 0, outIndex = 0; inIndex <= s.length; inIndex++) { var c = s.charCodeAt(inIndex); switch (state) { case 'CHAR': switch (c) { case charCode('%'): n = 0; m = 0; state = 'HEX0'; break; case charCode('+'): if (decodeSpaces) c = charCode(' '); // pass thru default: out[outIndex++] = c; break; } break; case 'HEX0': state = 'HEX1'; hexchar = c; if (charCode('0') <= c && c <= charCode('9')) { n = c - charCode('0'); } else if (charCode('a') <= c && c <= charCode('f')) { n = c - charCode('a') + 10; } else if (charCode('A') <= c && c <= charCode('F')) { n = c - charCode('A') + 10; } else { out[outIndex++] = charCode('%'); out[outIndex++] = c; state = 'CHAR'; break; } break; case 'HEX1': state = 'CHAR'; if (charCode('0') <= c && c <= charCode('9')) { m = c - charCode('0'); } else if (charCode('a') <= c && c <= charCode('f')) { m = c - charCode('a') + 10; } else if (charCode('A') <= c && c <= charCode('F')) { m = c - charCode('A') + 10; } else { out[outIndex++] = charCode('%'); out[outIndex++] = hexchar; out[outIndex++] = c; break; } out[outIndex++] = 16 * n + m; break; } } // TODO support returning arbitrary buffers. return out.slice(0, outIndex - 1); }; QueryString.unescape = function(s, decodeSpaces) { return QueryString.unescapeBuffer(s, decodeSpaces).toString(); }; QueryString.escape = function(str) { return encodeURIComponent(str); }; var stringifyPrimitive = function(v) { switch (typeof v) { case 'string': return v; case 'boolean': return v ? 'true' : 'false'; case 'number': return isFinite(v) ? v : ''; default: return ''; } }; QueryString.stringify = QueryString.encode = function(obj, sep, eq, name) { sep = sep || '&'; eq = eq || '='; if (obj === null) { obj = undefined; } if (typeof obj === 'object') { return Object.keys(obj).map(function(k) { var ks = QueryString.escape(stringifyPrimitive(k)) + eq; if (Array.isArray(obj[k])) { return obj[k].map(function(v) { return ks + QueryString.escape(stringifyPrimitive(v)); }).join(sep); } else { return ks + QueryString.escape(stringifyPrimitive(obj[k])); } }).join(sep); } if (!name) return ''; return QueryString.escape(stringifyPrimitive(name)) + eq + QueryString.escape(stringifyPrimitive(obj)); }; // Parse a key=val string. QueryString.parse = QueryString.decode = function(qs, sep, eq, options) { sep = sep || '&'; eq = eq || '='; var obj = {}; if (typeof qs !== 'string' || qs.length === 0) { return obj; } var regexp = /\+/g; qs = qs.split(sep); var maxKeys = 1000; if (options && typeof options.maxKeys === 'number') { maxKeys = options.maxKeys; } var len = qs.length; // maxKeys <= 0 means that we should not limit keys count if (maxKeys > 0 && len > maxKeys) { len = maxKeys; } for (var i = 0; i < len; ++i) { var x = qs[i].replace(regexp, '%20'), idx = x.indexOf(eq), kstr, vstr, k, v; if (idx >= 0) { kstr = x.substr(0, idx); vstr = x.substr(idx + 1); } else { kstr = x; vstr = ''; } try { k = decodeURIComponent(kstr); v = decodeURIComponent(vstr); } catch (e) { k = QueryString.unescape(kstr, true); v = QueryString.unescape(vstr, true); } if (!hasOwnProperty(obj, k)) { obj[k] = v; } else if (Array.isArray(obj[k])) { obj[k].push(v); } else { obj[k] = [obj[k], v]; } } return obj; }; node-v0.10.25~dfsg2/lib/buffer.js0000644000000000000000000006225112270121457015200 0ustar rootroot// Copyright Joyent, Inc. and other Node contributors. // // Permission is hereby granted, free of charge, to any person obtaining a // copy of this software and associated documentation files (the // "Software"), to deal in the Software without restriction, including // without limitation the rights to use, copy, modify, merge, publish, // distribute, sublicense, and/or sell copies of the Software, and to permit // persons to whom the Software is furnished to do so, subject to the // following conditions: // // The above copyright notice and this permission notice shall be included // in all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS // OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF // MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN // NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, // DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR // OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE // USE OR OTHER DEALINGS IN THE SOFTWARE. var SlowBuffer = process.binding('buffer').SlowBuffer; var assert = require('assert'); exports.INSPECT_MAX_BYTES = 50; // Make SlowBuffer inherit from Buffer. // This is an exception to the rule that __proto__ is not allowed in core. SlowBuffer.prototype.__proto__ = Buffer.prototype; function clamp(index, len, defaultValue) { if (typeof index !== 'number') return defaultValue; index = ~~index; // Coerce to integer. if (index >= len) return len; if (index >= 0) return index; index += len; if (index >= 0) return index; return 0; } function toHex(n) { if (n < 16) return '0' + n.toString(16); return n.toString(16); } SlowBuffer.prototype.toString = function(encoding, start, end) { encoding = String(encoding || 'utf8').toLowerCase(); start = +start || 0; if (typeof end !== 'number') end = this.length; // Fastpath empty strings if (+end == start) { return ''; } switch (encoding) { case 'hex': return this.hexSlice(start, end); case 'utf8': case 'utf-8': return this.utf8Slice(start, end); case 'ascii': return this.asciiSlice(start, end); case 'binary': return this.binarySlice(start, end); case 'base64': return this.base64Slice(start, end); case 'ucs2': case 'ucs-2': case 'utf16le': case 'utf-16le': return this.ucs2Slice(start, end); default: throw new TypeError('Unknown encoding: ' + encoding); } }; SlowBuffer.prototype.write = function(string, offset, length, encoding) { // Support both (string, offset, length, encoding) // and the legacy (string, encoding, offset, length) if (isFinite(offset)) { if (!isFinite(length)) { encoding = length; length = undefined; } } else { // legacy var swap = encoding; encoding = offset; offset = length; length = swap; } offset = +offset || 0; var remaining = this.length - offset; if (!length) { length = remaining; } else { length = +length; if (length > remaining) { length = remaining; } } encoding = String(encoding || 'utf8').toLowerCase(); switch (encoding) { case 'hex': return this.hexWrite(string, offset, length); case 'utf8': case 'utf-8': return this.utf8Write(string, offset, length); case 'ascii': return this.asciiWrite(string, offset, length); case 'binary': return this.binaryWrite(string, offset, length); case 'base64': return this.base64Write(string, offset, length); case 'ucs2': case 'ucs-2': case 'utf16le': case 'utf-16le': return this.ucs2Write(string, offset, length); default: throw new TypeError('Unknown encoding: ' + encoding); } }; // slice(start, end) SlowBuffer.prototype.slice = function(start, end) { var len = this.length; start = clamp(start, len, 0); end = clamp(end, len, len); return new Buffer(this, end - start, start); }; var zeroBuffer = new SlowBuffer(0); // Buffer function Buffer(subject, encoding, offset) { if (!(this instanceof Buffer)) { return new Buffer(subject, encoding, offset); } var type; // Are we slicing? if (typeof offset === 'number') { if (!Buffer.isBuffer(subject)) { throw new TypeError('First argument must be a Buffer when slicing'); } this.length = +encoding > 0 ? Math.ceil(encoding) : 0; this.parent = subject.parent ? subject.parent : subject; this.offset = offset; } else { // Find the length switch (type = typeof subject) { case 'number': this.length = +subject > 0 ? Math.ceil(subject) : 0; break; case 'string': this.length = Buffer.byteLength(subject, encoding); break; case 'object': // Assume object is array-ish this.length = +subject.length > 0 ? Math.ceil(subject.length) : 0; break; default: throw new TypeError('First argument needs to be a number, ' + 'array or string.'); } if (this.length > Buffer.poolSize) { // Big buffer, just alloc one. this.parent = new SlowBuffer(this.length); this.offset = 0; } else if (this.length > 0) { // Small buffer. if (!pool || pool.length - pool.used < this.length) allocPool(); this.parent = pool; this.offset = pool.used; // Align on 8 byte boundary to avoid alignment issues on ARM. pool.used = (pool.used + this.length + 7) & ~7; } else { // Zero-length buffer this.parent = zeroBuffer; this.offset = 0; } // optimize by branching logic for new allocations if (typeof subject !== 'number') { if (type === 'string') { // We are a string this.length = this.write(subject, 0, encoding); // if subject is buffer then use built-in copy method } else if (Buffer.isBuffer(subject)) { if (subject.parent) subject.parent.copy(this.parent, this.offset, subject.offset, this.length + subject.offset); else subject.copy(this.parent, this.offset, 0, this.length); } else if (isArrayIsh(subject)) { for (var i = 0; i < this.length; i++) this.parent[i + this.offset] = subject[i]; } } } SlowBuffer.makeFastBuffer(this.parent, this, this.offset, this.length); } function isArrayIsh(subject) { return Array.isArray(subject) || subject && typeof subject === 'object' && typeof subject.length === 'number'; } exports.SlowBuffer = SlowBuffer; exports.Buffer = Buffer; Buffer.isEncoding = function(encoding) { switch (encoding && encoding.toLowerCase()) { case 'hex': case 'utf8': case 'utf-8': case 'ascii': case 'binary': case 'base64': case 'ucs2': case 'ucs-2': case 'utf16le': case 'utf-16le': case 'raw': return true; default: return false; } }; Buffer.poolSize = 8 * 1024; var pool; function allocPool() { pool = new SlowBuffer(Buffer.poolSize); pool.used = 0; } // Static methods Buffer.isBuffer = function isBuffer(b) { return b instanceof Buffer; }; // Inspect Buffer.prototype.inspect = function inspect() { var out = [], len = this.length, name = this.constructor.name; for (var i = 0; i < len; i++) { out[i] = toHex(this[i]); if (i == exports.INSPECT_MAX_BYTES) { out[i + 1] = '...'; break; } } return '<' + name + ' ' + out.join(' ') + '>'; }; Buffer.prototype.get = function get(offset) { if (offset < 0 || offset >= this.length) throw new RangeError('offset is out of bounds'); return this.parent[this.offset + offset]; }; Buffer.prototype.set = function set(offset, v) { if (offset < 0 || offset >= this.length) throw new RangeError('offset is out of bounds'); return this.parent[this.offset + offset] = v; }; // write(string, offset = 0, length = buffer.length-offset, encoding = 'utf8') Buffer.prototype.write = function(string, offset, length, encoding) { // Support both (string, offset, length, encoding) // and the legacy (string, encoding, offset, length) if (isFinite(offset)) { if (!isFinite(length)) { encoding = length; length = undefined; } } else { // legacy var swap = encoding; encoding = offset; offset = length; length = swap; } offset = +offset || 0; var remaining = this.length - offset; if (!length) { length = remaining; } else { length = +length; if (length > remaining) { length = remaining; } } encoding = String(encoding || 'utf8').toLowerCase(); if (string.length > 0 && (length < 0 || offset < 0)) throw new RangeError('attempt to write beyond buffer bounds'); var ret; switch (encoding) { case 'hex': ret = this.parent.hexWrite(string, this.offset + offset, length); break; case 'utf8': case 'utf-8': ret = this.parent.utf8Write(string, this.offset + offset, length); break; case 'ascii': ret = this.parent.asciiWrite(string, this.offset + offset, length); break; case 'binary': ret = this.parent.binaryWrite(string, this.offset + offset, length); break; case 'base64': // Warning: maxLength not taken into account in base64Write ret = this.parent.base64Write(string, this.offset + offset, length); break; case 'ucs2': case 'ucs-2': case 'utf16le': case 'utf-16le': ret = this.parent.ucs2Write(string, this.offset + offset, length); break; default: throw new TypeError('Unknown encoding: ' + encoding); } Buffer._charsWritten = SlowBuffer._charsWritten; return ret; }; Buffer.prototype.toJSON = function() { return Array.prototype.slice.call(this, 0); }; // toString(encoding, start=0, end=buffer.length) Buffer.prototype.toString = function(encoding, start, end) { encoding = String(encoding || 'utf8').toLowerCase(); if (typeof start !== 'number' || start < 0) { start = 0; } else if (start > this.length) { start = this.length; } if (typeof end !== 'number' || end > this.length) { end = this.length; } else if (end < 0) { end = 0; } start = start + this.offset; end = end + this.offset; switch (encoding) { case 'hex': return this.parent.hexSlice(start, end); case 'utf8': case 'utf-8': return this.parent.utf8Slice(start, end); case 'ascii': return this.parent.asciiSlice(start, end); case 'binary': return this.parent.binarySlice(start, end); case 'base64': return this.parent.base64Slice(start, end); case 'ucs2': case 'ucs-2': case 'utf16le': case 'utf-16le': return this.parent.ucs2Slice(start, end); default: throw new TypeError('Unknown encoding: ' + encoding); } }; // byteLength Buffer.byteLength = SlowBuffer.byteLength; // fill(value, start=0, end=buffer.length) Buffer.prototype.fill = function fill(value, start, end) { value || (value = 0); start || (start = 0); end || (end = this.length); if (typeof value === 'string') { value = value.charCodeAt(0); } if (typeof value !== 'number' || isNaN(value)) { throw new TypeError('value is not a number'); } if (end < start) throw new RangeError('end < start'); // Fill 0 bytes; we're done if (end === start) return 0; if (this.length == 0) return 0; if (start < 0 || start >= this.length) { throw new RangeError('start out of bounds'); } if (end < 0 || end > this.length) { throw new RangeError('end out of bounds'); } return this.parent.fill(value, start + this.offset, end + this.offset); }; Buffer.concat = function(list, length) { if (!Array.isArray(list)) { throw new TypeError('Usage: Buffer.concat(list, [length])'); } if (list.length === 0) { return new Buffer(0); } else if (list.length === 1) { return list[0]; } if (typeof length !== 'number') { length = 0; for (var i = 0; i < list.length; i++) { var buf = list[i]; length += buf.length; } } var buffer = new Buffer(length); var pos = 0; for (var i = 0; i < list.length; i++) { var buf = list[i]; buf.copy(buffer, pos); pos += buf.length; } return buffer; }; // copy(targetBuffer, targetStart=0, sourceStart=0, sourceEnd=buffer.length) Buffer.prototype.copy = function(target, target_start, start, end) { // set undefined/NaN or out of bounds values equal to their default if (!(target_start >= 0)) target_start = 0; if (!(start >= 0)) start = 0; if (!(end < this.length)) end = this.length; // Copy 0 bytes; we're done if (end === start || target.length === 0 || this.length === 0 || start > this.length) return 0; if (end < start) throw new RangeError('sourceEnd < sourceStart'); if (target_start >= target.length) throw new RangeError('targetStart out of bounds'); if (target.length - target_start < end - start) end = target.length - target_start + start; return this.parent.copy(target.parent || target, target_start + (target.offset || 0), start + this.offset, end + this.offset); }; // slice(start, end) Buffer.prototype.slice = function(start, end) { var len = this.length; start = clamp(start, len, 0); end = clamp(end, len, len); return new Buffer(this.parent, end - start, start + this.offset); }; // Legacy methods for backwards compatibility. Buffer.prototype.utf8Slice = function(start, end) { return this.toString('utf8', start, end); }; Buffer.prototype.binarySlice = function(start, end) { return this.toString('binary', start, end); }; Buffer.prototype.asciiSlice = function(start, end) { return this.toString('ascii', start, end); }; Buffer.prototype.utf8Write = function(string, offset) { return this.write(string, offset, 'utf8'); }; Buffer.prototype.binaryWrite = function(string, offset) { return this.write(string, offset, 'binary'); }; Buffer.prototype.asciiWrite = function(string, offset) { return this.write(string, offset, 'ascii'); }; /* * Need to make sure that buffer isn't trying to write out of bounds. * This check is far too slow internally for fast buffers. */ function checkOffset(offset, ext, length) { if ((offset % 1) !== 0 || offset < 0) throw new RangeError('offset is not uint'); if (offset + ext > length) throw new RangeError('Trying to access beyond buffer length'); } Buffer.prototype.readUInt8 = function(offset, noAssert) { if (!noAssert) checkOffset(offset, 1, this.length); return this[offset]; }; function readUInt16(buffer, offset, isBigEndian) { var val = 0; if (isBigEndian) { val = buffer[offset] << 8; val |= buffer[offset + 1]; } else { val = buffer[offset]; val |= buffer[offset + 1] << 8; } return val; } Buffer.prototype.readUInt16LE = function(offset, noAssert) { if (!noAssert) checkOffset(offset, 2, this.length); return readUInt16(this, offset, false, noAssert); }; Buffer.prototype.readUInt16BE = function(offset, noAssert) { if (!noAssert) checkOffset(offset, 2, this.length); return readUInt16(this, offset, true, noAssert); }; function readUInt32(buffer, offset, isBigEndian, noAssert) { var val = 0; if (isBigEndian) { val = buffer[offset + 1] << 16; val |= buffer[offset + 2] << 8; val |= buffer[offset + 3]; val = val + (buffer[offset] << 24 >>> 0); } else { val = buffer[offset + 2] << 16; val |= buffer[offset + 1] << 8; val |= buffer[offset]; val = val + (buffer[offset + 3] << 24 >>> 0); } return val; } Buffer.prototype.readUInt32LE = function(offset, noAssert) { if (!noAssert) checkOffset(offset, 4, this.length); return readUInt32(this, offset, false, noAssert); }; Buffer.prototype.readUInt32BE = function(offset, noAssert) { if (!noAssert) checkOffset(offset, 4, this.length); return readUInt32(this, offset, true, noAssert); }; /* * Signed integer types, yay team! A reminder on how two's complement actually * works. The first bit is the signed bit, i.e. tells us whether or not the * number should be positive or negative. If the two's complement value is * positive, then we're done, as it's equivalent to the unsigned representation. * * Now if the number is positive, you're pretty much done, you can just leverage * the unsigned translations and return those. Unfortunately, negative numbers * aren't quite that straightforward. * * At first glance, one might be inclined to use the traditional formula to * translate binary numbers between the positive and negative values in two's * complement. (Though it doesn't quite work for the most negative value) * Mainly: * - invert all the bits * - add one to the result * * Of course, this doesn't quite work in Javascript. Take for example the value * of -128. This could be represented in 16 bits (big-endian) as 0xff80. But of * course, Javascript will do the following: * * > ~0xff80 * -65409 * * Whoh there, Javascript, that's not quite right. But wait, according to * Javascript that's perfectly correct. When Javascript ends up seeing the * constant 0xff80, it has no notion that it is actually a signed number. It * assumes that we've input the unsigned value 0xff80. Thus, when it does the * binary negation, it casts it into a signed value, (positive 0xff80). Then * when you perform binary negation on that, it turns it into a negative number. * * Instead, we're going to have to use the following general formula, that works * in a rather Javascript friendly way. I'm glad we don't support this kind of * weird numbering scheme in the kernel. * * (BIT-MAX - (unsigned)val + 1) * -1 * * The astute observer, may think that this doesn't make sense for 8-bit numbers * (really it isn't necessary for them). However, when you get 16-bit numbers, * you do. Let's go back to our prior example and see how this will look: * * (0xffff - 0xff80 + 1) * -1 * (0x007f + 1) * -1 * (0x0080) * -1 */ Buffer.prototype.readInt8 = function(offset, noAssert) { if (!noAssert) checkOffset(offset, 1, this.length); if (!(this[offset] & 0x80)) return (this[offset]); return ((0xff - this[offset] + 1) * -1); }; function readInt16(buffer, offset, isBigEndian) { var val = readUInt16(buffer, offset, isBigEndian); if (!(val & 0x8000)) return val; return (0xffff - val + 1) * -1; } Buffer.prototype.readInt16LE = function(offset, noAssert) { if (!noAssert) checkOffset(offset, 2, this.length); return readInt16(this, offset, false); }; Buffer.prototype.readInt16BE = function(offset, noAssert) { if (!noAssert) checkOffset(offset, 2, this.length); return readInt16(this, offset, true); }; function readInt32(buffer, offset, isBigEndian) { var val = readUInt32(buffer, offset, isBigEndian); if (!(val & 0x80000000)) return (val); return (0xffffffff - val + 1) * -1; } Buffer.prototype.readInt32LE = function(offset, noAssert) { if (!noAssert) checkOffset(offset, 4, this.length); return readInt32(this, offset, false); }; Buffer.prototype.readInt32BE = function(offset, noAssert) { if (!noAssert) checkOffset(offset, 4, this.length); return readInt32(this, offset, true); }; Buffer.prototype.readFloatLE = function(offset, noAssert) { if (!noAssert) checkOffset(offset, 4, this.length); return this.parent.readFloatLE(this.offset + offset, !!noAssert); }; Buffer.prototype.readFloatBE = function(offset, noAssert) { if (!noAssert) checkOffset(offset, 4, this.length); return this.parent.readFloatBE(this.offset + offset, !!noAssert); }; Buffer.prototype.readDoubleLE = function(offset, noAssert) { if (!noAssert) checkOffset(offset, 8, this.length); return this.parent.readDoubleLE(this.offset + offset, !!noAssert); }; Buffer.prototype.readDoubleBE = function(offset, noAssert) { if (!noAssert) checkOffset(offset, 8, this.length); return this.parent.readDoubleBE(this.offset + offset, !!noAssert); }; function checkInt(buffer, value, offset, ext, max, min) { if ((value % 1) !== 0 || value > max || value < min) throw TypeError('value is out of bounds'); if ((offset % 1) !== 0 || offset < 0) throw TypeError('offset is not uint'); if (offset + ext > buffer.length || buffer.length + offset < 0) throw RangeError('Trying to write outside buffer length'); } Buffer.prototype.writeUInt8 = function(value, offset, noAssert) { if (!noAssert) checkInt(this, value, offset, 1, 0xff, 0); this[offset] = value; }; function writeUInt16(buffer, value, offset, isBigEndian) { if (isBigEndian) { buffer[offset] = (value & 0xff00) >>> 8; buffer[offset + 1] = value & 0x00ff; } else { buffer[offset + 1] = (value & 0xff00) >>> 8; buffer[offset] = value & 0x00ff; } } Buffer.prototype.writeUInt16LE = function(value, offset, noAssert) { if (!noAssert) checkInt(this, value, offset, 2, 0xffff, 0); writeUInt16(this, value, offset, false); }; Buffer.prototype.writeUInt16BE = function(value, offset, noAssert) { if (!noAssert) checkInt(this, value, offset, 2, 0xffff, 0); writeUInt16(this, value, offset, true); }; function writeUInt32(buffer, value, offset, isBigEndian) { if (isBigEndian) { buffer[offset] = (value >>> 24) & 0xff; buffer[offset + 1] = (value >>> 16) & 0xff; buffer[offset + 2] = (value >>> 8) & 0xff; buffer[offset + 3] = value & 0xff; } else { buffer[offset + 3] = (value >>> 24) & 0xff; buffer[offset + 2] = (value >>> 16) & 0xff; buffer[offset + 1] = (value >>> 8) & 0xff; buffer[offset] = value & 0xff; } } Buffer.prototype.writeUInt32LE = function(value, offset, noAssert) { if (!noAssert) checkInt(this, value, offset, 4, 0xffffffff, 0); writeUInt32(this, value, offset, false); }; Buffer.prototype.writeUInt32BE = function(value, offset, noAssert) { if (!noAssert) checkInt(this, value, offset, 4, 0xffffffff, 0); writeUInt32(this, value, offset, true); }; /* * We now move onto our friends in the signed number category. Unlike unsigned * numbers, we're going to have to worry a bit more about how we put values into * arrays. Since we are only worrying about signed 32-bit values, we're in * slightly better shape. Unfortunately, we really can't do our favorite binary * & in this system. It really seems to do the wrong thing. For example: * * > -32 & 0xff * 224 * * What's happening above is really: 0xe0 & 0xff = 0xe0. However, the results of * this aren't treated as a signed number. Ultimately a bad thing. * * What we're going to want to do is basically create the unsigned equivalent of * our representation and pass that off to the wuint* functions. To do that * we're going to do the following: * * - if the value is positive * we can pass it directly off to the equivalent wuint * - if the value is negative * we do the following computation: * mb + val + 1, where * mb is the maximum unsigned value in that byte size * val is the Javascript negative integer * * * As a concrete value, take -128. In signed 16 bits this would be 0xff80. If * you do out the computations: * * 0xffff - 128 + 1 * 0xffff - 127 * 0xff80 * * You can then encode this value as the signed version. This is really rather * hacky, but it should work and get the job done which is our goal here. */ Buffer.prototype.writeInt8 = function(value, offset, noAssert) { if (!noAssert) checkInt(this, value, offset, 1, 0x7f, -0x80); if (value < 0) value = 0xff + value + 1; this[offset] = value; }; Buffer.prototype.writeInt16LE = function(value, offset, noAssert) { if (!noAssert) checkInt(this, value, offset, 2, 0x7fff, -0x8000); if (value < 0) value = 0xffff + value + 1; writeUInt16(this, value, offset, false); }; Buffer.prototype.writeInt16BE = function(value, offset, noAssert) { if (!noAssert) checkInt(this, value, offset, 2, 0x7fff, -0x8000); if (value < 0) value = 0xffff + value + 1; writeUInt16(this, value, offset, true); }; Buffer.prototype.writeInt32LE = function(value, offset, noAssert) { if (!noAssert) checkInt(this, value, offset, 4, 0x7fffffff, -0x80000000); if (value < 0) value = 0xffffffff + value + 1; writeUInt32(this, value, offset, false); }; Buffer.prototype.writeInt32BE = function(value, offset, noAssert) { if (!noAssert) checkInt(this, value, offset, 4, 0x7fffffff, -0x80000000); if (value < 0) value = 0xffffffff + value + 1; writeUInt32(this, value, offset, true); }; Buffer.prototype.writeFloatLE = function(value, offset, noAssert) { if (!noAssert) checkOffset(offset, 4, this.length); this.parent.writeFloatLE(value, this.offset + offset, !!noAssert); }; Buffer.prototype.writeFloatBE = function(value, offset, noAssert) { if (!noAssert) checkOffset(offset, 4, this.length); this.parent.writeFloatBE(value, this.offset + offset, !!noAssert); }; Buffer.prototype.writeDoubleLE = function(value, offset, noAssert) { if (!noAssert) checkOffset(offset, 8, this.length); this.parent.writeDoubleLE(value, this.offset + offset, !!noAssert); }; Buffer.prototype.writeDoubleBE = function(value, offset, noAssert) { if (!noAssert) checkOffset(offset, 8, this.length); this.parent.writeDoubleBE(value, this.offset + offset, !!noAssert); }; node-v0.10.25~dfsg2/lib/url.js0000644000000000000000000005312712270121457014533 0ustar rootroot// Copyright Joyent, Inc. and other Node contributors. // // Permission is hereby granted, free of charge, to any person obtaining a // copy of this software and associated documentation files (the // "Software"), to deal in the Software without restriction, including // without limitation the rights to use, copy, modify, merge, publish, // distribute, sublicense, and/or sell copies of the Software, and to permit // persons to whom the Software is furnished to do so, subject to the // following conditions: // // The above copyright notice and this permission notice shall be included // in all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS // OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF // MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN // NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, // DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR // OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE // USE OR OTHER DEALINGS IN THE SOFTWARE. var punycode = require('punycode'); exports.parse = urlParse; exports.resolve = urlResolve; exports.resolveObject = urlResolveObject; exports.format = urlFormat; exports.Url = Url; function Url() { this.protocol = null; this.slashes = null; this.auth = null; this.host = null; this.port = null; this.hostname = null; this.hash = null; this.search = null; this.query = null; this.pathname = null; this.path = null; this.href = null; } // Reference: RFC 3986, RFC 1808, RFC 2396 // define these here so at least they only have to be // compiled once on the first module load. var protocolPattern = /^([a-z0-9.+-]+:)/i, portPattern = /:[0-9]*$/, // RFC 2396: characters reserved for delimiting URLs. // We actually just auto-escape these. delims = ['<', '>', '"', '`', ' ', '\r', '\n', '\t'], // RFC 2396: characters not allowed for various reasons. unwise = ['{', '}', '|', '\\', '^', '~', '`'].concat(delims), // Allowed by RFCs, but cause of XSS attacks. Always escape these. autoEscape = ['\''].concat(delims), // Characters that are never ever allowed in a hostname. // Note that any invalid chars are also handled, but these // are the ones that are *expected* to be seen, so we fast-path // them. nonHostChars = ['%', '/', '?', ';', '#'] .concat(unwise).concat(autoEscape), hostEndingChars = ['/', '?', '#'], hostnameMaxLen = 255, hostnamePartPattern = /^[a-z0-9A-Z_-]{0,63}$/, hostnamePartStart = /^([a-z0-9A-Z_-]{0,63})(.*)$/, // protocols that can allow "unsafe" and "unwise" chars. unsafeProtocol = { 'javascript': true, 'javascript:': true }, // protocols that never have a hostname. hostlessProtocol = { 'javascript': true, 'javascript:': true }, // protocols that always contain a // bit. slashedProtocol = { 'http': true, 'https': true, 'ftp': true, 'gopher': true, 'file': true, 'http:': true, 'https:': true, 'ftp:': true, 'gopher:': true, 'file:': true }, querystring = require('querystring'); function urlParse(url, parseQueryString, slashesDenoteHost) { if (url && typeof(url) === 'object' && url instanceof Url) return url; var u = new Url; u.parse(url, parseQueryString, slashesDenoteHost); return u; } Url.prototype.parse = function(url, parseQueryString, slashesDenoteHost) { if (typeof url !== 'string') { throw new TypeError("Parameter 'url' must be a string, not " + typeof url); } var rest = url; // trim before proceeding. // This is to support parse stuff like " http://foo.com \n" rest = rest.trim(); var proto = protocolPattern.exec(rest); if (proto) { proto = proto[0]; var lowerProto = proto.toLowerCase(); this.protocol = lowerProto; rest = rest.substr(proto.length); } // figure out if it's got a host // user@server is *always* interpreted as a hostname, and url // resolution will treat //foo/bar as host=foo,path=bar because that's // how the browser resolves relative URLs. if (slashesDenoteHost || proto || rest.match(/^\/\/[^@\/]+@[^@\/]+/)) { var slashes = rest.substr(0, 2) === '//'; if (slashes && !(proto && hostlessProtocol[proto])) { rest = rest.substr(2); this.slashes = true; } } if (!hostlessProtocol[proto] && (slashes || (proto && !slashedProtocol[proto]))) { // there's a hostname. // the first instance of /, ?, ;, or # ends the host. // // If there is an @ in the hostname, then non-host chars *are* allowed // to the left of the last @ sign, unless some host-ending character // comes *before* the @-sign. // URLs are obnoxious. // // ex: // http://a@b@c/ => user:a@b host:c // http://a@b?@c => user:a host:c path:/?@c // v0.12 TODO(isaacs): This is not quite how Chrome does things. // Review our test case against browsers more comprehensively. // find the first instance of any hostEndingChars var hostEnd = -1; for (var i = 0; i < hostEndingChars.length; i++) { var hec = rest.indexOf(hostEndingChars[i]); if (hec !== -1 && (hostEnd === -1 || hec < hostEnd)) hostEnd = hec; } // at this point, either we have an explicit point where the // auth portion cannot go past, or the last @ char is the decider. var auth, atSign; if (hostEnd === -1) { // atSign can be anywhere. atSign = rest.lastIndexOf('@'); } else { // atSign must be in auth portion. // http://a@b/c@d => host:b auth:a path:/c@d atSign = rest.lastIndexOf('@', hostEnd); } // Now we have a portion which is definitely the auth. // Pull that off. if (atSign !== -1) { auth = rest.slice(0, atSign); rest = rest.slice(atSign + 1); this.auth = decodeURIComponent(auth); } // the host is the remaining to the left of the first non-host char hostEnd = -1; for (var i = 0; i < nonHostChars.length; i++) { var hec = rest.indexOf(nonHostChars[i]); if (hec !== -1 && (hostEnd === -1 || hec < hostEnd)) hostEnd = hec; } // if we still have not hit it, then the entire thing is a host. if (hostEnd === -1) hostEnd = rest.length; this.host = rest.slice(0, hostEnd); rest = rest.slice(hostEnd); // pull out port. this.parseHost(); // we've indicated that there is a hostname, // so even if it's empty, it has to be present. this.hostname = this.hostname || ''; // if hostname begins with [ and ends with ] // assume that it's an IPv6 address. var ipv6Hostname = this.hostname[0] === '[' && this.hostname[this.hostname.length - 1] === ']'; // validate a little. if (!ipv6Hostname) { var hostparts = this.hostname.split(/\./); for (var i = 0, l = hostparts.length; i < l; i++) { var part = hostparts[i]; if (!part) continue; if (!part.match(hostnamePartPattern)) { var newpart = ''; for (var j = 0, k = part.length; j < k; j++) { if (part.charCodeAt(j) > 127) { // we replace non-ASCII char with a temporary placeholder // we need this to make sure size of hostname is not // broken by replacing non-ASCII by nothing newpart += 'x'; } else { newpart += part[j]; } } // we test again with ASCII char only if (!newpart.match(hostnamePartPattern)) { var validParts = hostparts.slice(0, i); var notHost = hostparts.slice(i + 1); var bit = part.match(hostnamePartStart); if (bit) { validParts.push(bit[1]); notHost.unshift(bit[2]); } if (notHost.length) { rest = '/' + notHost.join('.') + rest; } this.hostname = validParts.join('.'); break; } } } } if (this.hostname.length > hostnameMaxLen) { this.hostname = ''; } else { // hostnames are always lower case. this.hostname = this.hostname.toLowerCase(); } if (!ipv6Hostname) { // IDNA Support: Returns a puny coded representation of "domain". // It only converts the part of the domain name that // has non ASCII characters. I.e. it dosent matter if // you call it with a domain that already is in ASCII. var domainArray = this.hostname.split('.'); var newOut = []; for (var i = 0; i < domainArray.length; ++i) { var s = domainArray[i]; newOut.push(s.match(/[^A-Za-z0-9_-]/) ? 'xn--' + punycode.encode(s) : s); } this.hostname = newOut.join('.'); } var p = this.port ? ':' + this.port : ''; var h = this.hostname || ''; this.host = h + p; this.href += this.host; // strip [ and ] from the hostname // the host field still retains them, though if (ipv6Hostname) { this.hostname = this.hostname.substr(1, this.hostname.length - 2); if (rest[0] !== '/') { rest = '/' + rest; } } } // now rest is set to the post-host stuff. // chop off any delim chars. if (!unsafeProtocol[lowerProto]) { // First, make 100% sure that any "autoEscape" chars get // escaped, even if encodeURIComponent doesn't think they // need to be. for (var i = 0, l = autoEscape.length; i < l; i++) { var ae = autoEscape[i]; var esc = encodeURIComponent(ae); if (esc === ae) { esc = escape(ae); } rest = rest.split(ae).join(esc); } } // chop off from the tail first. var hash = rest.indexOf('#'); if (hash !== -1) { // got a fragment string. this.hash = rest.substr(hash); rest = rest.slice(0, hash); } var qm = rest.indexOf('?'); if (qm !== -1) { this.search = rest.substr(qm); this.query = rest.substr(qm + 1); if (parseQueryString) { this.query = querystring.parse(this.query); } rest = rest.slice(0, qm); } else if (parseQueryString) { // no query string, but parseQueryString still requested this.search = ''; this.query = {}; } if (rest) this.pathname = rest; if (slashedProtocol[lowerProto] && this.hostname && !this.pathname) { this.pathname = '/'; } //to support http.request if (this.pathname || this.search) { var p = this.pathname || ''; var s = this.search || ''; this.path = p + s; } // finally, reconstruct the href based on what has been validated. this.href = this.format(); return this; }; // format a parsed object into a url string function urlFormat(obj) { // ensure it's an object, and not a string url. // If it's an obj, this is a no-op. // this way, you can call url_format() on strings // to clean up potentially wonky urls. if (typeof(obj) === 'string') obj = urlParse(obj); if (!(obj instanceof Url)) return Url.prototype.format.call(obj); return obj.format(); } Url.prototype.format = function() { var auth = this.auth || ''; if (auth) { auth = encodeURIComponent(auth); auth = auth.replace(/%3A/i, ':'); auth += '@'; } var protocol = this.protocol || '', pathname = this.pathname || '', hash = this.hash || '', host = false, query = ''; if (this.host) { host = auth + this.host; } else if (this.hostname) { host = auth + (this.hostname.indexOf(':') === -1 ? this.hostname : '[' + this.hostname + ']'); if (this.port) { host += ':' + this.port; } } if (this.query && typeof this.query === 'object' && Object.keys(this.query).length) { query = querystring.stringify(this.query); } var search = this.search || (query && ('?' + query)) || ''; if (protocol && protocol.substr(-1) !== ':') protocol += ':'; // only the slashedProtocols get the //. Not mailto:, xmpp:, etc. // unless they had them to begin with. if (this.slashes || (!protocol || slashedProtocol[protocol]) && host !== false) { host = '//' + (host || ''); if (pathname && pathname.charAt(0) !== '/') pathname = '/' + pathname; } else if (!host) { host = ''; } if (hash && hash.charAt(0) !== '#') hash = '#' + hash; if (search && search.charAt(0) !== '?') search = '?' + search; pathname = pathname.replace(/[?#]/g, function(match) { return encodeURIComponent(match); }); search = search.replace('#', '%23'); return protocol + host + pathname + search + hash; }; function urlResolve(source, relative) { return urlParse(source, false, true).resolve(relative); } Url.prototype.resolve = function(relative) { return this.resolveObject(urlParse(relative, false, true)).format(); }; function urlResolveObject(source, relative) { if (!source) return relative; return urlParse(source, false, true).resolveObject(relative); } Url.prototype.resolveObject = function(relative) { if (typeof relative === 'string') { var rel = new Url(); rel.parse(relative, false, true); relative = rel; } var result = new Url(); Object.keys(this).forEach(function(k) { result[k] = this[k]; }, this); // hash is always overridden, no matter what. // even href="" will remove it. result.hash = relative.hash; // if the relative url is empty, then there's nothing left to do here. if (relative.href === '') { result.href = result.format(); return result; } // hrefs like //foo/bar always cut to the protocol. if (relative.slashes && !relative.protocol) { // take everything except the protocol from relative Object.keys(relative).forEach(function(k) { if (k !== 'protocol') result[k] = relative[k]; }); //urlParse appends trailing / to urls like http://www.example.com if (slashedProtocol[result.protocol] && result.hostname && !result.pathname) { result.path = result.pathname = '/'; } result.href = result.format(); return result; } if (relative.protocol && relative.protocol !== result.protocol) { // if it's a known url protocol, then changing // the protocol does weird things // first, if it's not file:, then we MUST have a host, // and if there was a path // to begin with, then we MUST have a path. // if it is file:, then the host is dropped, // because that's known to be hostless. // anything else is assumed to be absolute. if (!slashedProtocol[relative.protocol]) { Object.keys(relative).forEach(function(k) { result[k] = relative[k]; }); result.href = result.format(); return result; } result.protocol = relative.protocol; if (!relative.host && !hostlessProtocol[relative.protocol]) { var relPath = (relative.pathname || '').split('/'); while (relPath.length && !(relative.host = relPath.shift())); if (!relative.host) relative.host = ''; if (!relative.hostname) relative.hostname = ''; if (relPath[0] !== '') relPath.unshift(''); if (relPath.length < 2) relPath.unshift(''); result.pathname = relPath.join('/'); } else { result.pathname = relative.pathname; } result.search = relative.search; result.query = relative.query; result.host = relative.host || ''; result.auth = relative.auth; result.hostname = relative.hostname || relative.host; result.port = relative.port; // to support http.request if (result.pathname || result.search) { var p = result.pathname || ''; var s = result.search || ''; result.path = p + s; } result.slashes = result.slashes || relative.slashes; result.href = result.format(); return result; } var isSourceAbs = (result.pathname && result.pathname.charAt(0) === '/'), isRelAbs = ( relative.host || relative.pathname && relative.pathname.charAt(0) === '/' ), mustEndAbs = (isRelAbs || isSourceAbs || (result.host && relative.pathname)), removeAllDots = mustEndAbs, srcPath = result.pathname && result.pathname.split('/') || [], relPath = relative.pathname && relative.pathname.split('/') || [], psychotic = result.protocol && !slashedProtocol[result.protocol]; // if the url is a non-slashed url, then relative // links like ../.. should be able // to crawl up to the hostname, as well. This is strange. // result.protocol has already been set by now. // Later on, put the first path part into the host field. if (psychotic) { result.hostname = ''; result.port = null; if (result.host) { if (srcPath[0] === '') srcPath[0] = result.host; else srcPath.unshift(result.host); } result.host = ''; if (relative.protocol) { relative.hostname = null; relative.port = null; if (relative.host) { if (relPath[0] === '') relPath[0] = relative.host; else relPath.unshift(relative.host); } relative.host = null; } mustEndAbs = mustEndAbs && (relPath[0] === '' || srcPath[0] === ''); } if (isRelAbs) { // it's absolute. result.host = (relative.host || relative.host === '') ? relative.host : result.host; result.hostname = (relative.hostname || relative.hostname === '') ? relative.hostname : result.hostname; result.search = relative.search; result.query = relative.query; srcPath = relPath; // fall through to the dot-handling below. } else if (relPath.length) { // it's relative // throw away the existing file, and take the new path instead. if (!srcPath) srcPath = []; srcPath.pop(); srcPath = srcPath.concat(relPath); result.search = relative.search; result.query = relative.query; } else if (relative.search !== null && relative.search !== undefined) { // just pull out the search. // like href='?foo'. // Put this after the other two cases because it simplifies the booleans if (psychotic) { result.hostname = result.host = srcPath.shift(); //occationaly the auth can get stuck only in host //this especialy happens in cases like //url.resolveObject('mailto:local1@domain1', 'local2@domain2') var authInHost = result.host && result.host.indexOf('@') > 0 ? result.host.split('@') : false; if (authInHost) { result.auth = authInHost.shift(); result.host = result.hostname = authInHost.shift(); } } result.search = relative.search; result.query = relative.query; //to support http.request if (result.pathname !== null || result.search !== null) { result.path = (result.pathname ? result.pathname : '') + (result.search ? result.search : ''); } result.href = result.format(); return result; } if (!srcPath.length) { // no path at all. easy. // we've already handled the other stuff above. result.pathname = null; //to support http.request if (result.search) { result.path = '/' + result.search; } else { result.path = null; } result.href = result.format(); return result; } // if a url ENDs in . or .., then it must get a trailing slash. // however, if it ends in anything else non-slashy, // then it must NOT get a trailing slash. var last = srcPath.slice(-1)[0]; var hasTrailingSlash = ( (result.host || relative.host) && (last === '.' || last === '..') || last === ''); // strip single dots, resolve double dots to parent dir // if the path tries to go above the root, `up` ends up > 0 var up = 0; for (var i = srcPath.length; i >= 0; i--) { last = srcPath[i]; if (last == '.') { srcPath.splice(i, 1); } else if (last === '..') { srcPath.splice(i, 1); up++; } else if (up) { srcPath.splice(i, 1); up--; } } // if the path is allowed to go above the root, restore leading ..s if (!mustEndAbs && !removeAllDots) { for (; up--; up) { srcPath.unshift('..'); } } if (mustEndAbs && srcPath[0] !== '' && (!srcPath[0] || srcPath[0].charAt(0) !== '/')) { srcPath.unshift(''); } if (hasTrailingSlash && (srcPath.join('/').substr(-1) !== '/')) { srcPath.push(''); } var isAbsolute = srcPath[0] === '' || (srcPath[0] && srcPath[0].charAt(0) === '/'); // put the host back if (psychotic) { result.hostname = result.host = isAbsolute ? '' : srcPath.length ? srcPath.shift() : ''; //occationaly the auth can get stuck only in host //this especialy happens in cases like //url.resolveObject('mailto:local1@domain1', 'local2@domain2') var authInHost = result.host && result.host.indexOf('@') > 0 ? result.host.split('@') : false; if (authInHost) { result.auth = authInHost.shift(); result.host = result.hostname = authInHost.shift(); } } mustEndAbs = mustEndAbs || (result.host && srcPath.length); if (mustEndAbs && !isAbsolute) { srcPath.unshift(''); } if (!srcPath.length) { result.pathname = null; result.path = null; } else { result.pathname = srcPath.join('/'); } //to support request.http if (result.pathname !== null || result.search !== null) { result.path = (result.pathname ? result.pathname : '') + (result.search ? result.search : ''); } result.auth = relative.auth || result.auth; result.slashes = result.slashes || relative.slashes; result.href = result.format(); return result; }; Url.prototype.parseHost = function() { var host = this.host; var port = portPattern.exec(host); if (port) { port = port[0]; if (port !== ':') { this.port = port.substr(1); } host = host.substr(0, host.length - port.length); } if (host) this.hostname = host; }; node-v0.10.25~dfsg2/lib/events.js0000644000000000000000000002045312270121457015231 0ustar rootroot// Copyright Joyent, Inc. and other Node contributors. // // Permission is hereby granted, free of charge, to any person obtaining a // copy of this software and associated documentation files (the // "Software"), to deal in the Software without restriction, including // without limitation the rights to use, copy, modify, merge, publish, // distribute, sublicense, and/or sell copies of the Software, and to permit // persons to whom the Software is furnished to do so, subject to the // following conditions: // // The above copyright notice and this permission notice shall be included // in all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS // OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF // MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN // NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, // DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR // OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE // USE OR OTHER DEALINGS IN THE SOFTWARE. var domain; exports.usingDomains = false; function EventEmitter() { this.domain = null; if (exports.usingDomains) { // if there is an active domain, then attach to it. domain = domain || require('domain'); if (domain.active && !(this instanceof domain.Domain)) { this.domain = domain.active; } } this._events = this._events || {}; this._maxListeners = this._maxListeners || defaultMaxListeners; } exports.EventEmitter = EventEmitter; // By default EventEmitters will print a warning if more than // 10 listeners are added to it. This is a useful default which // helps finding memory leaks. // // Obviously not all Emitters should be limited to 10. This function allows // that to be increased. Set to zero for unlimited. var defaultMaxListeners = 10; EventEmitter.prototype.setMaxListeners = function(n) { if (typeof n !== 'number' || n < 0 || isNaN(n)) throw TypeError('n must be a positive number'); this._maxListeners = n; }; EventEmitter.prototype.emit = function(type) { var er, handler, len, args, i, listeners; if (!this._events) this._events = {}; // If there is no 'error' event listener then throw. if (type === 'error') { if (!this._events.error || (typeof this._events.error === 'object' && !this._events.error.length)) { er = arguments[1]; if (this.domain) { if (!er) er = new TypeError('Uncaught, unspecified "error" event.'); er.domainEmitter = this; er.domain = this.domain; er.domainThrown = false; this.domain.emit('error', er); } else if (er instanceof Error) { throw er; // Unhandled 'error' event } else { throw TypeError('Uncaught, unspecified "error" event.'); } return false; } } handler = this._events[type]; if (typeof handler === 'undefined') return false; if (this.domain && this !== process) this.domain.enter(); if (typeof handler === 'function') { switch (arguments.length) { // fast cases case 1: handler.call(this); break; case 2: handler.call(this, arguments[1]); break; case 3: handler.call(this, arguments[1], arguments[2]); break; // slower default: len = arguments.length; args = new Array(len - 1); for (i = 1; i < len; i++) args[i - 1] = arguments[i]; handler.apply(this, args); } } else if (typeof handler === 'object') { len = arguments.length; args = new Array(len - 1); for (i = 1; i < len; i++) args[i - 1] = arguments[i]; listeners = handler.slice(); len = listeners.length; for (i = 0; i < len; i++) listeners[i].apply(this, args); } if (this.domain && this !== process) this.domain.exit(); return true; }; EventEmitter.prototype.addListener = function(type, listener) { var m; if (typeof listener !== 'function') throw TypeError('listener must be a function'); if (!this._events) this._events = {}; // To avoid recursion in the case that type === "newListener"! Before // adding it to the listeners, first emit "newListener". if (this._events.newListener) this.emit('newListener', type, typeof listener.listener === 'function' ? listener.listener : listener); if (!this._events[type]) // Optimize the case of one listener. Don't need the extra array object. this._events[type] = listener; else if (typeof this._events[type] === 'object') // If we've already got an array, just append. this._events[type].push(listener); else // Adding the second element, need to change to array. this._events[type] = [this._events[type], listener]; // Check for listener leak if (typeof this._events[type] === 'object' && !this._events[type].warned) { m = this._maxListeners; if (m && m > 0 && this._events[type].length > m) { this._events[type].warned = true; console.error('(node) warning: possible EventEmitter memory ' + 'leak detected. %d listeners added. ' + 'Use emitter.setMaxListeners() to increase limit.', this._events[type].length); console.trace(); } } return this; }; EventEmitter.prototype.on = EventEmitter.prototype.addListener; EventEmitter.prototype.once = function(type, listener) { if (typeof listener !== 'function') throw TypeError('listener must be a function'); var fired = false; function g() { this.removeListener(type, g); if (!fired) { fired = true; listener.apply(this, arguments); } } g.listener = listener; this.on(type, g); return this; }; // emits a 'removeListener' event iff the listener was removed EventEmitter.prototype.removeListener = function(type, listener) { var list, position, length, i; if (typeof listener !== 'function') throw TypeError('listener must be a function'); if (!this._events || !this._events[type]) return this; list = this._events[type]; length = list.length; position = -1; if (list === listener || (typeof list.listener === 'function' && list.listener === listener)) { delete this._events[type]; if (this._events.removeListener) this.emit('removeListener', type, listener); } else if (typeof list === 'object') { for (i = length; i-- > 0;) { if (list[i] === listener || (list[i].listener && list[i].listener === listener)) { position = i; break; } } if (position < 0) return this; if (list.length === 1) { list.length = 0; delete this._events[type]; } else { list.splice(position, 1); } if (this._events.removeListener) this.emit('removeListener', type, listener); } return this; }; EventEmitter.prototype.removeAllListeners = function(type) { var key, listeners; if (!this._events) return this; // not listening for removeListener, no need to emit if (!this._events.removeListener) { if (arguments.length === 0) this._events = {}; else if (this._events[type]) delete this._events[type]; return this; } // emit removeListener for all listeners on all events if (arguments.length === 0) { for (key in this._events) { if (key === 'removeListener') continue; this.removeAllListeners(key); } this.removeAllListeners('removeListener'); this._events = {}; return this; } listeners = this._events[type]; if (typeof listeners === 'function') { this.removeListener(type, listeners); } else if (Array.isArray(listeners)) { // LIFO order while (listeners.length) this.removeListener(type, listeners[listeners.length - 1]); } delete this._events[type]; return this; }; EventEmitter.prototype.listeners = function(type) { var ret; if (!this._events || !this._events[type]) ret = []; else if (typeof this._events[type] === 'function') ret = [this._events[type]]; else ret = this._events[type].slice(); return ret; }; EventEmitter.listenerCount = function(emitter, type) { var ret; if (!emitter._events || !emitter._events[type]) ret = 0; else if (typeof emitter._events[type] === 'function') ret = 1; else ret = emitter._events[type].length; return ret; }; node-v0.10.25~dfsg2/lib/vm.js0000644000000000000000000000410412270121457014342 0ustar rootroot// Copyright Joyent, Inc. and other Node contributors. // // Permission is hereby granted, free of charge, to any person obtaining a // copy of this software and associated documentation files (the // "Software"), to deal in the Software without restriction, including // without limitation the rights to use, copy, modify, merge, publish, // distribute, sublicense, and/or sell copies of the Software, and to permit // persons to whom the Software is furnished to do so, subject to the // following conditions: // // The above copyright notice and this permission notice shall be included // in all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS // OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF // MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN // NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, // DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR // OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE // USE OR OTHER DEALINGS IN THE SOFTWARE. var binding = process.binding('evals'); module.exports = Script; Script.Script = Script; function Script(code, ctx, filename) { if (!(this instanceof Script)) { return new Script(code, ctx, filename); } var ns = new binding.NodeScript(code, ctx, filename); // bind all methods to this Script object Object.keys(binding.NodeScript.prototype).forEach(function(f) { if (typeof binding.NodeScript.prototype[f] === 'function') { this[f] = function() { if (!(this instanceof Script)) { throw new TypeError('invalid call to ' + f); } return ns[f].apply(ns, arguments); }; } }, this); } Script.createScript = function(code, ctx, name) { return new Script(code, ctx, name); }; Script.createContext = binding.NodeScript.createContext; Script.runInContext = binding.NodeScript.runInContext; Script.runInThisContext = binding.NodeScript.runInThisContext; Script.runInNewContext = binding.NodeScript.runInNewContext; node-v0.10.25~dfsg2/lib/dgram.js0000644000000000000000000002677212270121457015031 0ustar rootroot// Copyright Joyent, Inc. and other Node contributors. // // Permission is hereby granted, free of charge, to any person obtaining a // copy of this software and associated documentation files (the // "Software"), to deal in the Software without restriction, including // without limitation the rights to use, copy, modify, merge, publish, // distribute, sublicense, and/or sell copies of the Software, and to permit // persons to whom the Software is furnished to do so, subject to the // following conditions: // // The above copyright notice and this permission notice shall be included // in all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS // OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF // MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN // NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, // DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR // OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE // USE OR OTHER DEALINGS IN THE SOFTWARE. var assert = require('assert'); var util = require('util'); var events = require('events'); var UDP = process.binding('udp_wrap').UDP; var BIND_STATE_UNBOUND = 0; var BIND_STATE_BINDING = 1; var BIND_STATE_BOUND = 2; // lazily loaded var cluster = null; var dns = null; var net = null; // no-op callback function noop() { } function isIP(address) { if (!net) net = require('net'); return net.isIP(address); } function lookup(address, family, callback) { if (!dns) dns = require('dns'); return dns.lookup(address, family, callback); } function lookup4(address, callback) { return lookup(address || '0.0.0.0', 4, callback); } function lookup6(address, callback) { return lookup(address || '::0', 6, callback); } function newHandle(type) { if (type == 'udp4') { var handle = new UDP; handle.lookup = lookup4; return handle; } if (type == 'udp6') { var handle = new UDP; handle.lookup = lookup6; handle.bind = handle.bind6; handle.send = handle.send6; return handle; } if (type == 'unix_dgram') throw new Error('unix_dgram sockets are not supported any more.'); throw new Error('Bad socket type specified. Valid types are: udp4, udp6'); } exports._createSocketHandle = function(address, port, addressType, fd) { // Opening an existing fd is not supported for UDP handles. assert(typeof fd !== 'number' || fd < 0); var handle = newHandle(addressType); if (port || address) { var r = handle.bind(address, port || 0, 0); if (r == -1) { handle.close(); handle = null; } } return handle; }; function Socket(type, listener) { events.EventEmitter.call(this); var handle = newHandle(type); handle.owner = this; this._handle = handle; this._receiving = false; this._bindState = BIND_STATE_UNBOUND; this.type = type; this.fd = null; // compatibility hack if (typeof listener === 'function') this.on('message', listener); } util.inherits(Socket, events.EventEmitter); exports.Socket = Socket; exports.createSocket = function(type, listener) { return new Socket(type, listener); }; function startListening(socket) { socket._handle.onmessage = onMessage; // Todo: handle errors socket._handle.recvStart(); socket._receiving = true; socket._bindState = BIND_STATE_BOUND; socket.fd = -42; // compatibility hack socket.emit('listening'); } function replaceHandle(self, newHandle) { // Set up the handle that we got from master. newHandle.lookup = self._handle.lookup; newHandle.bind = self._handle.bind; newHandle.send = self._handle.send; newHandle.owner = self; // Replace the existing handle by the handle we got from master. self._handle.close(); self._handle = newHandle; } Socket.prototype.bind = function(/*port, address, callback*/) { var self = this; self._healthCheck(); if (this._bindState != BIND_STATE_UNBOUND) throw new Error('Socket is already bound'); this._bindState = BIND_STATE_BINDING; if (typeof arguments[arguments.length - 1] === 'function') self.once('listening', arguments[arguments.length - 1]); var UDP = process.binding('udp_wrap').UDP; if (arguments[0] instanceof UDP) { replaceHandle(self, arguments[0]); startListening(self); return; } var port = arguments[0]; var address = arguments[1]; if (typeof address === 'function') address = ''; // a.k.a. "any address" // resolve address first self._handle.lookup(address, function(err, ip) { if (err) { self._bindState = BIND_STATE_UNBOUND; self.emit('error', err); return; } if (!cluster) cluster = require('cluster'); if (cluster.isWorker) { cluster._getServer(self, ip, port, self.type, -1, function(handle, err) { if (err) return self.emit('error', errnoException(err, 'bind')); if (!self._handle) // handle has been closed in the mean time. return handle.close(); replaceHandle(self, handle); startListening(self); }); } else { if (!self._handle) return; // handle has been closed in the mean time if (self._handle.bind(ip, port || 0, /*flags=*/ 0)) { self.emit('error', errnoException(process._errno, 'bind')); self._bindState = BIND_STATE_UNBOUND; // Todo: close? return; } startListening(self); } }); }; // thin wrapper around `send`, here for compatibility with dgram_legacy.js Socket.prototype.sendto = function(buffer, offset, length, port, address, callback) { if (typeof offset !== 'number' || typeof length !== 'number') throw new Error('send takes offset and length as args 2 and 3'); if (typeof address !== 'string') throw new Error(this.type + ' sockets must send to port, address'); this.send(buffer, offset, length, port, address, callback); }; Socket.prototype.send = function(buffer, offset, length, port, address, callback) { var self = this; if (!Buffer.isBuffer(buffer)) throw new TypeError('First argument must be a buffer object.'); offset = offset | 0; if (offset < 0) throw new RangeError('Offset should be >= 0'); if (offset >= buffer.length) throw new RangeError('Offset into buffer too large'); // Sending a zero-length datagram is kind of pointless but it _is_ // allowed, hence check that length >= 0 rather than > 0. length = length | 0; if (length < 0) throw new RangeError('Length should be >= 0'); if (offset + length > buffer.length) throw new RangeError('Offset + length beyond buffer length'); port = port | 0; if (port <= 0 || port > 65535) throw new RangeError('Port should be > 0 and < 65536'); callback = callback || noop; self._healthCheck(); if (self._bindState == BIND_STATE_UNBOUND) self.bind(0, null); // If the socket hasn't been bound yet, push the outbound packet onto the // send queue and send after binding is complete. if (self._bindState != BIND_STATE_BOUND) { // If the send queue hasn't been initialized yet, do it, and install an // event handler that flushes the send queue after binding is done. if (!self._sendQueue) { self._sendQueue = []; self.once('listening', function() { // Flush the send queue. for (var i = 0; i < self._sendQueue.length; i++) self.send.apply(self, self._sendQueue[i]); self._sendQueue = undefined; }); } self._sendQueue.push([buffer, offset, length, port, address, callback]); return; } self._handle.lookup(address, function(err, ip) { if (err) { if (callback) callback(err); self.emit('error', err); } else if (self._handle) { var req = self._handle.send(buffer, offset, length, port, ip); if (req) { req.oncomplete = afterSend; req.cb = callback; } else { // don't emit as error, dgram_legacy.js compatibility var err = errnoException(process._errno, 'send'); process.nextTick(function() { callback(err); }); } } }); }; function afterSend(status, handle, req, buffer) { var self = handle.owner; if (req.cb) req.cb(null, buffer.length); // compatibility with dgram_legacy.js } Socket.prototype.close = function() { this._healthCheck(); this._stopReceiving(); this._handle.close(); this._handle = null; this.emit('close'); }; Socket.prototype.address = function() { this._healthCheck(); var address = this._handle.getsockname(); if (!address) throw errnoException(process._errno, 'getsockname'); return address; }; Socket.prototype.setBroadcast = function(arg) { if (this._handle.setBroadcast((arg) ? 1 : 0)) { throw errnoException(process._errno, 'setBroadcast'); } }; Socket.prototype.setTTL = function(arg) { if (typeof arg !== 'number') { throw new TypeError('Argument must be a number'); } if (this._handle.setTTL(arg)) { throw errnoException(process._errno, 'setTTL'); } return arg; }; Socket.prototype.setMulticastTTL = function(arg) { if (typeof arg !== 'number') { throw new TypeError('Argument must be a number'); } if (this._handle.setMulticastTTL(arg)) { throw errnoException(process._errno, 'setMulticastTTL'); } return arg; }; Socket.prototype.setMulticastLoopback = function(arg) { arg = arg ? 1 : 0; if (this._handle.setMulticastLoopback(arg)) { throw errnoException(process._errno, 'setMulticastLoopback'); } return arg; // 0.4 compatibility }; Socket.prototype.addMembership = function(multicastAddress, interfaceAddress) { this._healthCheck(); if (!multicastAddress) { throw new Error('multicast address must be specified'); } if (this._handle.addMembership(multicastAddress, interfaceAddress)) { throw new errnoException(process._errno, 'addMembership'); } }; Socket.prototype.dropMembership = function(multicastAddress, interfaceAddress) { this._healthCheck(); if (!multicastAddress) { throw new Error('multicast address must be specified'); } if (this._handle.dropMembership(multicastAddress, interfaceAddress)) { throw new errnoException(process._errno, 'dropMembership'); } }; Socket.prototype._healthCheck = function() { if (!this._handle) throw new Error('Not running'); // error message from dgram_legacy.js }; Socket.prototype._stopReceiving = function() { if (!this._receiving) return; this._handle.recvStop(); this._receiving = false; this.fd = null; // compatibility hack }; function onMessage(handle, slab, start, len, rinfo) { var self = handle.owner; if (!slab) { return self.emit('error', errnoException(process._errno, 'recvmsg')); } rinfo.size = len; // compatibility self.emit('message', slab.slice(start, start + len), rinfo); } Socket.prototype.ref = function() { if (this._handle) this._handle.ref(); }; Socket.prototype.unref = function() { if (this._handle) this._handle.unref(); }; // TODO share with net_uv and others function errnoException(errorno, syscall) { var e = new Error(syscall + ' ' + errorno); e.errno = e.code = errorno; e.syscall = syscall; return e; } node-v0.10.25~dfsg2/lib/domain.js0000644000000000000000000001473712270121457015204 0ustar rootroot// Copyright Joyent, Inc. and other Node contributors. // // Permission is hereby granted, free of charge, to any person obtaining a // copy of this software and associated documentation files (the // "Software"), to deal in the Software without restriction, including // without limitation the rights to use, copy, modify, merge, publish, // distribute, sublicense, and/or sell copies of the Software, and to permit // persons to whom the Software is furnished to do so, subject to the // following conditions: // // The above copyright notice and this permission notice shall be included // in all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS // OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF // MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN // NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, // DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR // OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE // USE OR OTHER DEALINGS IN THE SOFTWARE. var util = require('util'); var events = require('events'); var EventEmitter = events.EventEmitter; var inherits = util.inherits; // methods that are called when trying to shut down expliclitly bound EEs var endMethods = ['end', 'abort', 'destroy', 'destroySoon']; // communicate with events module, but don't require that // module to have to load this one, since this module has // a few side effects. events.usingDomains = true; // let the process know we're using domains process._usingDomains(); exports.Domain = Domain; exports.create = exports.createDomain = function(cb) { return new Domain(cb); }; // it's possible to enter one domain while already inside // another one. the stack is each entered domain. var stack = []; exports._stack = stack; // the active domain is always the one that we're currently in. exports.active = null; inherits(Domain, EventEmitter); function Domain() { EventEmitter.call(this); this.members = []; } Domain.prototype.enter = function() { if (this._disposed) return; // note that this might be a no-op, but we still need // to push it onto the stack so that we can pop it later. exports.active = process.domain = this; stack.push(this); }; Domain.prototype.exit = function() { // skip disposed domains, as usual, but also don't do anything if this // domain is not on the stack. var index = stack.lastIndexOf(this); if (this._disposed || index === -1) return; // exit all domains until this one. stack.splice(index); exports.active = stack[stack.length - 1]; process.domain = exports.active; }; // note: this works for timers as well. Domain.prototype.add = function(ee) { // disposed domains can't be used for new things. if (this._disposed) return; // already added to this domain. if (ee.domain === this) return; // has a domain already - remove it first. if (ee.domain) { ee.domain.remove(ee); } // check for circular Domain->Domain links. // This causes bad insanity! // // For example: // var d = domain.create(); // var e = domain.create(); // d.add(e); // e.add(d); // e.emit('error', er); // RangeError, stack overflow! if (this.domain && (ee instanceof Domain)) { for (var d = this.domain; d; d = d.domain) { if (ee === d) return; } } ee.domain = this; this.members.push(ee); }; Domain.prototype.remove = function(ee) { ee.domain = null; var index = this.members.indexOf(ee); if (index !== -1) { this.members.splice(index, 1); } }; Domain.prototype.run = function(fn) { return this.bind(fn)(); }; Domain.prototype.intercept = function(cb) { return this.bind(cb, true); }; Domain.prototype.bind = function(cb, interceptError) { // if cb throws, catch it here. var self = this; var b = function() { // disposing turns functions into no-ops if (self._disposed) return; if (this instanceof Domain) { return cb.apply(this, arguments); } // only intercept first-arg errors if explicitly requested. if (interceptError && arguments[0] && (arguments[0] instanceof Error)) { var er = arguments[0]; util._extend(er, { domainBound: cb, domainThrown: false, domain: self }); self.emit('error', er); return; } // remove first-arg if intercept as assumed to be the error-arg if (interceptError) { var len = arguments.length; var args; switch (len) { case 0: case 1: // no args that we care about. args = []; break; case 2: // optimization for most common case: cb(er, data) args = [arguments[1]]; break; default: // slower for less common case: cb(er, foo, bar, baz, ...) args = new Array(len - 1); for (var i = 1; i < len; i++) { args[i - 1] = arguments[i]; } break; } self.enter(); var ret = cb.apply(this, args); self.exit(); return ret; } self.enter(); var ret = cb.apply(this, arguments); self.exit(); return ret; }; b.domain = this; return b; }; Domain.prototype.dispose = function() { if (this._disposed) return; // if we're the active domain, then get out now. this.exit(); this.emit('dispose'); // remove error handlers. this.removeAllListeners(); this.on('error', function() {}); // try to kill all the members. // XXX There should be more consistent ways // to shut down things! this.members.forEach(function(m) { // if it's a timeout or interval, cancel it. clearTimeout(m); // drop all event listeners. if (m instanceof EventEmitter) { m.removeAllListeners(); // swallow errors m.on('error', function() {}); } // Be careful! // By definition, we're likely in error-ridden territory here, // so it's quite possible that calling some of these methods // might cause additional exceptions to be thrown. endMethods.forEach(function(method) { if (typeof m[method] === 'function') { try { m[method](); } catch (er) {} } }); }); // remove from parent domain, if there is one. if (this.domain) this.domain.remove(this); // kill the references so that they can be properly gc'ed. this.members.length = 0; // finally, mark this domain as 'no longer relevant' // so that it can't be entered or activated. this._disposed = true; }; node-v0.10.25~dfsg2/lib/repl.js0000644000000000000000000006764312270121457014703 0ustar rootroot// Copyright Joyent, Inc. and other Node contributors. // // Permission is hereby granted, free of charge, to any person obtaining a // copy of this software and associated documentation files (the // "Software"), to deal in the Software without restriction, including // without limitation the rights to use, copy, modify, merge, publish, // distribute, sublicense, and/or sell copies of the Software, and to permit // persons to whom the Software is furnished to do so, subject to the // following conditions: // // The above copyright notice and this permission notice shall be included // in all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS // OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF // MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN // NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, // DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR // OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE // USE OR OTHER DEALINGS IN THE SOFTWARE. /* A repl library that you can include in your own code to get a runtime * interface to your program. * * var repl = require("repl"); * // start repl on stdin * repl.start("prompt> "); * * // listen for unix socket connections and start repl on them * net.createServer(function(socket) { * repl.start("node via Unix socket> ", socket); * }).listen("/tmp/node-repl-sock"); * * // listen for TCP socket connections and start repl on them * net.createServer(function(socket) { * repl.start("node via TCP socket> ", socket); * }).listen(5001); * * // expose foo to repl context * repl.start("node > ").context.foo = "stdin is fun"; */ var util = require('util'); var inherits = require('util').inherits; var Stream = require('stream'); var vm = require('vm'); var path = require('path'); var fs = require('fs'); var rl = require('readline'); var Console = require('console').Console; var EventEmitter = require('events').EventEmitter; // If obj.hasOwnProperty has been overridden, then calling // obj.hasOwnProperty(prop) will break. // See: https://github.com/joyent/node/issues/1707 function hasOwnProperty(obj, prop) { return Object.prototype.hasOwnProperty.call(obj, prop); } // hack for require.resolve("./relative") to work properly. module.filename = path.resolve('repl'); // hack for repl require to work properly with node_modules folders module.paths = require('module')._nodeModulePaths(module.filename); // Can overridden with custom print functions, such as `probe` or `eyes.js`. // This is the default "writer" value if none is passed in the REPL options. exports.writer = util.inspect; exports._builtinLibs = ['assert', 'buffer', 'child_process', 'cluster', 'crypto', 'dgram', 'dns', 'domain', 'events', 'fs', 'http', 'https', 'net', 'os', 'path', 'punycode', 'querystring', 'readline', 'stream', 'string_decoder', 'tls', 'tty', 'url', 'util', 'vm', 'zlib']; function REPLServer(prompt, stream, eval_, useGlobal, ignoreUndefined) { if (!(this instanceof REPLServer)) { return new REPLServer(prompt, stream, eval_, useGlobal, ignoreUndefined); } EventEmitter.call(this); var options, input, output; if (typeof prompt == 'object') { // an options object was given options = prompt; stream = options.stream || options.socket; input = options.input; output = options.output; eval_ = options.eval; useGlobal = options.useGlobal; ignoreUndefined = options.ignoreUndefined; prompt = options.prompt; } else if (typeof prompt != 'string') { throw new Error('An options Object, or a prompt String are required'); } else { options = {}; } var self = this; self.useGlobal = !!useGlobal; self.ignoreUndefined = !!ignoreUndefined; self.eval = eval_ || function(code, context, file, cb) { var err, result; try { if (self.useGlobal) { result = vm.runInThisContext(code, file); } else { result = vm.runInContext(code, context, file); } } catch (e) { err = e; } if (err && process.domain) { process.domain.emit('error', err); process.domain.exit(); } else { cb(err, result); } }; if (!input && !output) { // legacy API, passing a 'stream'/'socket' option if (!stream) { // use stdin and stdout as the default streams if none were given stream = process; } if (stream.stdin && stream.stdout) { // We're given custom object with 2 streams, or the `process` object input = stream.stdin; output = stream.stdout; } else { // We're given a duplex readable/writable Stream, like a `net.Socket` input = stream; output = stream; } } self.inputStream = input; self.outputStream = output; self.resetContext(); self.bufferedCommand = ''; self.prompt = (prompt != undefined ? prompt : '> '); function complete(text, callback) { self.complete(text, callback); } var rli = rl.createInterface({ input: self.inputStream, output: self.outputStream, completer: complete, terminal: options.terminal }); self.rli = rli; this.commands = {}; defineDefaultCommands(this); // figure out which "writer" function to use self.writer = options.writer || exports.writer; if (typeof options.useColors === 'undefined') { options.useColors = rli.terminal; } self.useColors = !!options.useColors; if (self.useColors && self.writer === util.inspect) { // Turn on ANSI coloring. self.writer = function(obj, showHidden, depth) { return util.inspect(obj, showHidden, depth, true); }; } rli.setPrompt(self.prompt); rli.on('close', function() { self.emit('exit'); }); var sawSIGINT = false; rli.on('SIGINT', function() { var empty = rli.line.length === 0; rli.clearLine(); if (!(self.bufferedCommand && self.bufferedCommand.length > 0) && empty) { if (sawSIGINT) { rli.close(); sawSIGINT = false; return; } rli.output.write('(^C again to quit)\n'); sawSIGINT = true; } else { sawSIGINT = false; } self.bufferedCommand = ''; self.displayPrompt(); }); rli.on('line', function(cmd) { sawSIGINT = false; var skipCatchall = false; cmd = trimWhitespace(cmd); // Check to see if a REPL keyword was used. If it returns true, // display next prompt and return. if (cmd && cmd.charAt(0) === '.' && isNaN(parseFloat(cmd))) { var matches = cmd.match(/^(\.[^\s]+)\s*(.*)$/); var keyword = matches && matches[1]; var rest = matches && matches[2]; if (self.parseREPLKeyword(keyword, rest) === true) { return; } else { self.outputStream.write('Invalid REPL keyword\n'); skipCatchall = true; } } if (!skipCatchall) { var evalCmd = self.bufferedCommand + cmd + '\n'; // This try is for determining if the command is complete, or should // continue onto the next line. // We try to evaluate both expressions e.g. // '{ a : 1 }' // and statements e.g. // 'for (var i = 0; i < 10; i++) console.log(i);' // First we attempt to eval as expression with parens. // This catches '{a : 1}' properly. self.eval('(' + evalCmd + ')', self.context, 'repl', function(e, ret) { if (e && !isSyntaxError(e)) return finish(e); if (typeof ret === 'function' && /^[\r\n\s]*function/.test(evalCmd) || e) { // Now as statement without parens. self.eval(evalCmd, self.context, 'repl', finish); } else { finish(null, ret); } }); } else { finish(null); } function finish(e, ret) { self.memory(cmd); // If error was SyntaxError and not JSON.parse error if (isSyntaxError(e)) { if (!self.bufferedCommand && cmd.trim().match(/^npm /)) { self.outputStream.write('npm should be run outside of the ' + 'node repl, in your normal shell.\n' + '(Press Control-D to exit.)\n'); self.bufferedCommand = ''; self.displayPrompt(); return; } // Start buffering data like that: // { // ... x: 1 // ... } self.bufferedCommand += cmd + '\n'; self.displayPrompt(); return; } else if (e) { self.outputStream.write((e.stack || e) + '\n'); } // Clear buffer if no SyntaxErrors self.bufferedCommand = ''; // If we got any output - print it (if no error) if (!e && (!self.ignoreUndefined || ret !== undefined)) { self.context._ = ret; self.outputStream.write(self.writer(ret) + '\n'); } // Display prompt again self.displayPrompt(); }; }); rli.on('SIGCONT', function() { self.displayPrompt(true); }); self.displayPrompt(); } inherits(REPLServer, EventEmitter); exports.REPLServer = REPLServer; // prompt is a string to print on each line for the prompt, // source is a stream to use for I/O, defaulting to stdin/stdout. exports.start = function(prompt, source, eval_, useGlobal, ignoreUndefined) { var repl = new REPLServer(prompt, source, eval_, useGlobal, ignoreUndefined); if (!exports.repl) exports.repl = repl; return repl; }; REPLServer.prototype.createContext = function() { var context; if (this.useGlobal) { context = global; } else { context = vm.createContext(); for (var i in global) context[i] = global[i]; context.console = new Console(this.outputStream); context.global = context; context.global.global = context; } context.module = module; context.require = require; this.lines = []; this.lines.level = []; // make built-in modules available directly // (loaded lazily) exports._builtinLibs.forEach(function(name) { Object.defineProperty(context, name, { get: function() { var lib = require(name); context._ = context[name] = lib; return lib; }, // allow the creation of other globals with this name set: function(val) { delete context[name]; context[name] = val; }, configurable: true }); }); return context; }; REPLServer.prototype.resetContext = function() { this.context = this.createContext(); }; REPLServer.prototype.displayPrompt = function(preserveCursor) { var prompt = this.prompt; if (this.bufferedCommand.length) { prompt = '...'; var levelInd = new Array(this.lines.level.length).join('..'); prompt += levelInd + ' '; } this.rli.setPrompt(prompt); this.rli.prompt(preserveCursor); }; // A stream to push an array into a REPL // used in REPLServer.complete function ArrayStream() { Stream.call(this); this.run = function(data) { var self = this; data.forEach(function(line) { self.emit('data', line + '\n'); }); } } util.inherits(ArrayStream, Stream); ArrayStream.prototype.readable = true; ArrayStream.prototype.writable = true; ArrayStream.prototype.resume = function() {}; ArrayStream.prototype.write = function() {}; var requireRE = /\brequire\s*\(['"](([\w\.\/-]+\/)?([\w\.\/-]*))/; var simpleExpressionRE = /(([a-zA-Z_$](?:\w|\$)*)\.)*([a-zA-Z_$](?:\w|\$)*)\.?$/; // Provide a list of completions for the given leading text. This is // given to the readline interface for handling tab completion. // // Example: // complete('var foo = util.') // -> [['util.print', 'util.debug', 'util.log', 'util.inspect', 'util.pump'], // 'util.' ] // // Warning: This eval's code like "foo.bar.baz", so it will run property // getter code. REPLServer.prototype.complete = function(line, callback) { // There may be local variables to evaluate, try a nested REPL if (this.bufferedCommand != undefined && this.bufferedCommand.length) { // Get a new array of inputed lines var tmp = this.lines.slice(); // Kill off all function declarations to push all local variables into // global scope this.lines.level.forEach(function(kill) { if (kill.isFunction) { tmp[kill.line] = ''; } }); var flat = new ArrayStream(); // make a new "input" stream var magic = new REPLServer('', flat); // make a nested REPL magic.context = magic.createContext(); flat.run(tmp); // eval the flattened code // all this is only profitable if the nested REPL // does not have a bufferedCommand if (!magic.bufferedCommand) { return magic.complete(line, callback); } } var completions; // list of completion lists, one for each inheritance "level" var completionGroups = []; var completeOn, match, filter, i, j, group, c; // REPL commands (e.g. ".break"). var match = null; match = line.match(/^\s*(\.\w*)$/); if (match) { completionGroups.push(Object.keys(this.commands)); completeOn = match[1]; if (match[1].length > 1) { filter = match[1]; } completionGroupsLoaded(); } else if (match = line.match(requireRE)) { // require('...') var exts = Object.keys(require.extensions); var indexRe = new RegExp('^index(' + exts.map(regexpEscape).join('|') + ')$'); completeOn = match[1]; var subdir = match[2] || ''; var filter = match[1]; var dir, files, f, name, base, ext, abs, subfiles, s; group = []; var paths = module.paths.concat(require('module').globalPaths); for (i = 0; i < paths.length; i++) { dir = path.resolve(paths[i], subdir); try { files = fs.readdirSync(dir); } catch (e) { continue; } for (f = 0; f < files.length; f++) { name = files[f]; ext = path.extname(name); base = name.slice(0, -ext.length); if (base.match(/-\d+\.\d+(\.\d+)?/) || name === '.npm') { // Exclude versioned names that 'npm' installs. continue; } if (exts.indexOf(ext) !== -1) { if (!subdir || base !== 'index') { group.push(subdir + base); } } else { abs = path.resolve(dir, name); try { if (fs.statSync(abs).isDirectory()) { group.push(subdir + name + '/'); subfiles = fs.readdirSync(abs); for (s = 0; s < subfiles.length; s++) { if (indexRe.test(subfiles[s])) { group.push(subdir + name); } } } } catch (e) {} } } } if (group.length) { completionGroups.push(group); } if (!subdir) { completionGroups.push(exports._builtinLibs); } completionGroupsLoaded(); // Handle variable member lookup. // We support simple chained expressions like the following (no function // calls, etc.). That is for simplicity and also because we *eval* that // leading expression so for safety (see WARNING above) don't want to // eval function calls. // // foo.bar<|> # completions for 'foo' with filter 'bar' // spam.eggs.<|> # completions for 'spam.eggs' with filter '' // foo<|> # all scope vars with filter 'foo' // foo.<|> # completions for 'foo' with filter '' } else if (line.length === 0 || line[line.length - 1].match(/\w|\.|\$/)) { match = simpleExpressionRE.exec(line); if (line.length === 0 || match) { var expr; completeOn = (match ? match[0] : ''); if (line.length === 0) { filter = ''; expr = ''; } else if (line[line.length - 1] === '.') { filter = ''; expr = match[0].slice(0, match[0].length - 1); } else { var bits = match[0].split('.'); filter = bits.pop(); expr = bits.join('.'); } // Resolve expr and get its completions. var obj, memberGroups = []; if (!expr) { // If context is instance of vm.ScriptContext // Get global vars synchronously if (this.useGlobal || this.context.constructor && this.context.constructor.name === 'Context') { var contextProto = this.context; while (contextProto = Object.getPrototypeOf(contextProto)) { completionGroups.push(Object.getOwnPropertyNames(contextProto)); } completionGroups.push(Object.getOwnPropertyNames(this.context)); addStandardGlobals(completionGroups, filter); completionGroupsLoaded(); } else { this.eval('.scope', this.context, 'repl', function(err, globals) { if (err || !globals) { addStandardGlobals(completionGroups, filter); } else if (Array.isArray(globals[0])) { // Add grouped globals globals.forEach(function(group) { completionGroups.push(group); }); } else { completionGroups.push(globals); addStandardGlobals(completionGroups, filter); } completionGroupsLoaded(); }); } } else { this.eval(expr, this.context, 'repl', function(e, obj) { // if (e) console.log(e); if (obj != null) { if (typeof obj === 'object' || typeof obj === 'function') { memberGroups.push(Object.getOwnPropertyNames(obj)); } // works for non-objects try { var sentinel = 5; var p; if (typeof obj === 'object' || typeof obj === 'function') { p = Object.getPrototypeOf(obj); } else { p = obj.constructor ? obj.constructor.prototype : null; } while (p !== null) { memberGroups.push(Object.getOwnPropertyNames(p)); p = Object.getPrototypeOf(p); // Circular refs possible? Let's guard against that. sentinel--; if (sentinel <= 0) { break; } } } catch (e) { //console.log("completion error walking prototype chain:" + e); } } if (memberGroups.length) { for (i = 0; i < memberGroups.length; i++) { completionGroups.push(memberGroups[i].map(function(member) { return expr + '.' + member; })); } if (filter) { filter = expr + '.' + filter; } } completionGroupsLoaded(); }); } } else { completionGroupsLoaded(); } } else { completionGroupsLoaded(); } // Will be called when all completionGroups are in place // Useful for async autocompletion function completionGroupsLoaded(err) { if (err) throw err; // Filter, sort (within each group), uniq and merge the completion groups. if (completionGroups.length && filter) { var newCompletionGroups = []; for (i = 0; i < completionGroups.length; i++) { group = completionGroups[i].filter(function(elem) { return elem.indexOf(filter) == 0; }); if (group.length) { newCompletionGroups.push(group); } } completionGroups = newCompletionGroups; } if (completionGroups.length) { var uniq = {}; // unique completions across all groups completions = []; // Completion group 0 is the "closest" // (least far up the inheritance chain) // so we put its completions last: to be closest in the REPL. for (i = completionGroups.length - 1; i >= 0; i--) { group = completionGroups[i]; group.sort(); for (var j = 0; j < group.length; j++) { c = group[j]; if (!hasOwnProperty(uniq, c)) { completions.push(c); uniq[c] = true; } } completions.push(''); // separator btwn groups } while (completions.length && completions[completions.length - 1] === '') { completions.pop(); } } callback(null, [completions || [], completeOn]); } }; /** * Used to parse and execute the Node REPL commands. * * @param {keyword} keyword The command entered to check. * @return {Boolean} If true it means don't continue parsing the command. */ REPLServer.prototype.parseREPLKeyword = function(keyword, rest) { var cmd = this.commands[keyword]; if (cmd) { cmd.action.call(this, rest); return true; } return false; }; REPLServer.prototype.defineCommand = function(keyword, cmd) { if (typeof cmd === 'function') { cmd = {action: cmd}; } else if (typeof cmd.action !== 'function') { throw new Error('bad argument, action must be a function'); } this.commands['.' + keyword] = cmd; }; REPLServer.prototype.memory = function memory(cmd) { var self = this; self.lines = self.lines || []; self.lines.level = self.lines.level || []; // save the line so I can do magic later if (cmd) { // TODO should I tab the level? self.lines.push(new Array(self.lines.level.length).join(' ') + cmd); } else { // I don't want to not change the format too much... self.lines.push(''); } // I need to know "depth." // Because I can not tell the difference between a } that // closes an object literal and a } that closes a function if (cmd) { // going down is { and ( e.g. function() { // going up is } and ) var dw = cmd.match(/{|\(/g); var up = cmd.match(/}|\)/g); up = up ? up.length : 0; dw = dw ? dw.length : 0; var depth = dw - up; if (depth) { (function workIt() { if (depth > 0) { // going... down. // push the line#, depth count, and if the line is a function. // Since JS only has functional scope I only need to remove // "function() {" lines, clearly this will not work for // "function() // {" but nothing should break, only tab completion for local // scope will not work for this function. self.lines.level.push({ line: self.lines.length - 1, depth: depth, isFunction: /\s*function\s*/.test(cmd) }); } else if (depth < 0) { // going... up. var curr = self.lines.level.pop(); if (curr) { var tmp = curr.depth + depth; if (tmp < 0) { //more to go, recurse depth += curr.depth; workIt(); } else if (tmp > 0) { //remove and push back curr.depth += depth; self.lines.level.push(curr); } } } }()); } // it is possible to determine a syntax error at this point. // if the REPL still has a bufferedCommand and // self.lines.level.length === 0 // TODO? keep a log of level so that any syntax breaking lines can // be cleared on .break and in the case of a syntax error? // TODO? if a log was kept, then I could clear the bufferedComand and // eval these lines and throw the syntax error } else { self.lines.level = []; } }; function addStandardGlobals(completionGroups, filter) { // Global object properties // (http://www.ecma-international.org/publications/standards/Ecma-262.htm) completionGroups.push(['NaN', 'Infinity', 'undefined', 'eval', 'parseInt', 'parseFloat', 'isNaN', 'isFinite', 'decodeURI', 'decodeURIComponent', 'encodeURI', 'encodeURIComponent', 'Object', 'Function', 'Array', 'String', 'Boolean', 'Number', 'Date', 'RegExp', 'Error', 'EvalError', 'RangeError', 'ReferenceError', 'SyntaxError', 'TypeError', 'URIError', 'Math', 'JSON']); // Common keywords. Exclude for completion on the empty string, b/c // they just get in the way. if (filter) { completionGroups.push(['break', 'case', 'catch', 'const', 'continue', 'debugger', 'default', 'delete', 'do', 'else', 'export', 'false', 'finally', 'for', 'function', 'if', 'import', 'in', 'instanceof', 'let', 'new', 'null', 'return', 'switch', 'this', 'throw', 'true', 'try', 'typeof', 'undefined', 'var', 'void', 'while', 'with', 'yield']); } } function defineDefaultCommands(repl) { // TODO remove me after 0.3.x repl.defineCommand('break', { help: 'Sometimes you get stuck, this gets you out', action: function() { this.bufferedCommand = ''; this.displayPrompt(); } }); var clearMessage; if (repl.useGlobal) { clearMessage = 'Alias for .break'; } else { clearMessage = 'Break, and also clear the local context'; } repl.defineCommand('clear', { help: clearMessage, action: function() { this.bufferedCommand = ''; if (!this.useGlobal) { this.outputStream.write('Clearing context...\n'); this.resetContext(); } this.displayPrompt(); } }); repl.defineCommand('exit', { help: 'Exit the repl', action: function() { this.rli.close(); } }); repl.defineCommand('help', { help: 'Show repl options', action: function() { var self = this; Object.keys(this.commands).sort().forEach(function(name) { var cmd = self.commands[name]; self.outputStream.write(name + '\t' + (cmd.help || '') + '\n'); }); this.displayPrompt(); } }); repl.defineCommand('save', { help: 'Save all evaluated commands in this REPL session to a file', action: function(file) { try { fs.writeFileSync(file, this.lines.join('\n') + '\n'); this.outputStream.write('Session saved to:' + file + '\n'); } catch (e) { this.outputStream.write('Failed to save:' + file + '\n'); } this.displayPrompt(); } }); repl.defineCommand('load', { help: 'Load JS from a file into the REPL session', action: function(file) { try { var stats = fs.statSync(file); if (stats && stats.isFile()) { var self = this; var data = fs.readFileSync(file, 'utf8'); var lines = data.split('\n'); this.displayPrompt(); lines.forEach(function(line) { if (line) { self.rli.write(line + '\n'); } }); } } catch (e) { this.outputStream.write('Failed to load:' + file + '\n'); } this.displayPrompt(); } }); } function trimWhitespace(cmd) { var trimmer = /^\s*(.+)\s*$/m, matches = trimmer.exec(cmd); if (matches && matches.length === 2) { return matches[1]; } return ''; } function regexpEscape(s) { return s.replace(/[-[\]{}()*+?.,\\^$|#\s]/g, '\\$&'); } /** * Converts commands that use var and function () to use the * local exports.context when evaled. This provides a local context * on the REPL. * * @param {String} cmd The cmd to convert. * @return {String} The converted command. */ REPLServer.prototype.convertToContext = function(cmd) { var self = this, matches, scopeVar = /^\s*var\s*([_\w\$]+)(.*)$/m, scopeFunc = /^\s*function\s*([_\w\$]+)/; // Replaces: var foo = "bar"; with: self.context.foo = bar; matches = scopeVar.exec(cmd); if (matches && matches.length === 3) { return 'self.context.' + matches[1] + matches[2]; } // Replaces: function foo() {}; with: foo = function foo() {}; matches = scopeFunc.exec(self.bufferedCommand); if (matches && matches.length === 2) { return matches[1] + ' = ' + self.bufferedCommand; } return cmd; }; /** * Returns `true` if "e" is a SyntaxError, `false` otherwise. * This function filters out false positives likes JSON.parse() errors and * RegExp syntax errors. */ function isSyntaxError(e) { // Convert error to string e = e && (e.stack || e.toString()); return e && e.match(/^SyntaxError/) && // RegExp syntax error !e.match(/^SyntaxError: Invalid regular expression/) && !e.match(/^SyntaxError: Invalid flags supplied to RegExp constructor/) && // "strict mode" syntax errors !e.match(/^SyntaxError: .*strict mode.*/i) && // JSON.parse() error !e.match(/\n {4}at Object.parse \(native\)\n/); } node-v0.10.25~dfsg2/lib/timers.js0000644000000000000000000002637212270121457015236 0ustar rootroot// Copyright Joyent, Inc. and other Node contributors. // // Permission is hereby granted, free of charge, to any person obtaining a // copy of this software and associated documentation files (the // "Software"), to deal in the Software without restriction, including // without limitation the rights to use, copy, modify, merge, publish, // distribute, sublicense, and/or sell copies of the Software, and to permit // persons to whom the Software is furnished to do so, subject to the // following conditions: // // The above copyright notice and this permission notice shall be included // in all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS // OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF // MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN // NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, // DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR // OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE // USE OR OTHER DEALINGS IN THE SOFTWARE. var Timer = process.binding('timer_wrap').Timer; var L = require('_linklist'); var assert = require('assert').ok; // Timeout values > TIMEOUT_MAX are set to 1. var TIMEOUT_MAX = 2147483647; // 2^31-1 var debug; if (process.env.NODE_DEBUG && /timer/.test(process.env.NODE_DEBUG)) { debug = function() { require('util').error.apply(this, arguments); }; } else { debug = function() { }; } // IDLE TIMEOUTS // // Because often many sockets will have the same idle timeout we will not // use one timeout watcher per item. It is too much overhead. Instead // we'll use a single watcher for all sockets with the same timeout value // and a linked list. This technique is described in the libev manual: // http://pod.tst.eu/http://cvs.schmorp.de/libev/ev.pod#Be_smart_about_timeouts // Object containing all lists, timers // key = time in milliseconds // value = list var lists = {}; // the main function - creates lists on demand and the watchers associated // with them. function insert(item, msecs) { item._idleStart = Date.now(); item._idleTimeout = msecs; if (msecs < 0) return; var list; if (lists[msecs]) { list = lists[msecs]; } else { list = new Timer(); list.start(msecs, 0); L.init(list); lists[msecs] = list; list.msecs = msecs; list.ontimeout = listOnTimeout; } L.append(list, item); assert(!L.isEmpty(list)); // list is not empty } function listOnTimeout() { var msecs = this.msecs; var list = this; debug('timeout callback ' + msecs); var now = Date.now(); debug('now: ' + now); var first; while (first = L.peek(list)) { var diff = now - first._idleStart; if (diff < msecs) { list.start(msecs - diff, 0); debug(msecs + ' list wait because diff is ' + diff); return; } else { L.remove(first); assert(first !== L.peek(list)); if (!first._onTimeout) continue; // v0.4 compatibility: if the timer callback throws and the // domain or uncaughtException handler ignore the exception, // other timers that expire on this tick should still run. // // https://github.com/joyent/node/issues/2631 var domain = first.domain; if (domain && domain._disposed) continue; try { if (domain) domain.enter(); var threw = true; first._onTimeout(); if (domain) domain.exit(); threw = false; } finally { if (threw) { process.nextTick(function() { list.ontimeout(); }); } } } } debug(msecs + ' list empty'); assert(L.isEmpty(list)); list.close(); delete lists[msecs]; } var unenroll = exports.unenroll = function(item) { L.remove(item); var list = lists[item._idleTimeout]; // if empty then stop the watcher debug('unenroll'); if (list && L.isEmpty(list)) { debug('unenroll: list empty'); list.close(); delete lists[item._idleTimeout]; } // if active is called later, then we want to make sure not to insert again item._idleTimeout = -1; }; // Does not start the time, just sets up the members needed. exports.enroll = function(item, msecs) { // if this item was already in a list somewhere // then we should unenroll it from that if (item._idleNext) unenroll(item); // Ensure that msecs fits into signed int32 if (msecs > 0x7fffffff) { msecs = 0x7fffffff; } item._idleTimeout = msecs; L.init(item); }; // call this whenever the item is active (not idle) // it will reset its timeout. exports.active = function(item) { var msecs = item._idleTimeout; if (msecs >= 0) { var list = lists[msecs]; if (!list || L.isEmpty(list)) { insert(item, msecs); } else { item._idleStart = Date.now(); L.append(list, item); } } }; /* * DOM-style timers */ exports.setTimeout = function(callback, after) { var timer; after *= 1; // coalesce to number or NaN if (!(after >= 1 && after <= TIMEOUT_MAX)) { after = 1; // schedule on next tick, follows browser behaviour } timer = new Timeout(after); if (arguments.length <= 2) { timer._onTimeout = callback; } else { /* * Sometimes setTimeout is called with arguments, EG * * setTimeout(callback, 2000, "hello", "world") * * If that's the case we need to call the callback with * those args. The overhead of an extra closure is not * desired in the normal case. */ var args = Array.prototype.slice.call(arguments, 2); timer._onTimeout = function() { callback.apply(timer, args); } } if (process.domain) timer.domain = process.domain; exports.active(timer); return timer; }; exports.clearTimeout = function(timer) { if (timer && (timer.ontimeout || timer._onTimeout)) { timer.ontimeout = timer._onTimeout = null; if (timer instanceof Timeout) { timer.close(); // for after === 0 } else { exports.unenroll(timer); } } }; exports.setInterval = function(callback, repeat) { repeat *= 1; // coalesce to number or NaN if (!(repeat >= 1 && repeat <= TIMEOUT_MAX)) { repeat = 1; // schedule on next tick, follows browser behaviour } var timer = new Timeout(repeat); var args = Array.prototype.slice.call(arguments, 2); timer._onTimeout = wrapper; timer._repeat = true; if (process.domain) timer.domain = process.domain; exports.active(timer); return timer; function wrapper() { callback.apply(this, args); // If callback called clearInterval(). if (timer._repeat === false) return; // If timer is unref'd (or was - it's permanently removed from the list.) if (this._handle) { this._handle.start(repeat, 0); } else { timer._idleTimeout = repeat; exports.active(timer); } } }; exports.clearInterval = function(timer) { if (timer && timer._repeat) { timer._repeat = false; clearTimeout(timer); } }; var Timeout = function(after) { this._idleTimeout = after; this._idlePrev = this; this._idleNext = this; this._idleStart = null; this._onTimeout = null; this._repeat = false; }; Timeout.prototype.unref = function() { if (!this._handle) { var now = Date.now(); if (!this._idleStart) this._idleStart = now; var delay = this._idleStart + this._idleTimeout - now; if (delay < 0) delay = 0; exports.unenroll(this); this._handle = new Timer(); this._handle.ontimeout = this._onTimeout; this._handle.start(delay, 0); this._handle.domain = this.domain; this._handle.unref(); } else { this._handle.unref(); } }; Timeout.prototype.ref = function() { if (this._handle) this._handle.ref(); }; Timeout.prototype.close = function() { this._onTimeout = null; if (this._handle) { this._handle.ontimeout = null; this._handle.close(); } else { exports.unenroll(this); } }; var immediateQueue = {}; L.init(immediateQueue); function processImmediate() { var immediate = L.shift(immediateQueue); if (L.isEmpty(immediateQueue)) { process._needImmediateCallback = false; } if (immediate._onImmediate) { if (immediate.domain) immediate.domain.enter(); immediate._onImmediate(); if (immediate.domain) immediate.domain.exit(); } } exports.setImmediate = function(callback) { var immediate = {}, args; L.init(immediate); immediate._onImmediate = callback; if (arguments.length > 1) { args = Array.prototype.slice.call(arguments, 1); immediate._onImmediate = function() { callback.apply(immediate, args); }; } if (!process._needImmediateCallback) { process._needImmediateCallback = true; process._immediateCallback = processImmediate; } if (process.domain) immediate.domain = process.domain; L.append(immediateQueue, immediate); return immediate; }; exports.clearImmediate = function(immediate) { if (!immediate) return; immediate._onImmediate = undefined; L.remove(immediate); if (L.isEmpty(immediateQueue)) { process._needImmediateCallback = false; } }; // Internal APIs that need timeouts should use timers._unrefActive isntead of // timers.active as internal timeouts shouldn't hold the loop open var unrefList, unrefTimer; function unrefTimeout() { var now = Date.now(); debug('unrefTimer fired'); var first; while (first = L.peek(unrefList)) { var diff = now - first._idleStart; if (diff < first._idleTimeout) { diff = first._idleTimeout - diff; unrefTimer.start(diff, 0); unrefTimer.when = now + diff; debug('unrefTimer rescheudling for later'); return; } L.remove(first); var domain = first.domain; if (!first._onTimeout) continue; if (domain && domain._disposed) continue; try { if (domain) domain.enter(); var threw = true; debug('unreftimer firing timeout'); first._onTimeout(); threw = false; if (domain) domain.exit(); } finally { if (threw) process.nextTick(unrefTimeout); } } debug('unrefList is empty'); unrefTimer.when = -1; } exports._unrefActive = function(item) { var msecs = item._idleTimeout; if (!msecs || msecs < 0) return; assert(msecs >= 0); L.remove(item); if (!unrefList) { debug('unrefList initialized'); unrefList = {}; L.init(unrefList); debug('unrefTimer initialized'); unrefTimer = new Timer(); unrefTimer.unref(); unrefTimer.when = -1; unrefTimer.ontimeout = unrefTimeout; } var now = Date.now(); item._idleStart = now; if (L.isEmpty(unrefList)) { debug('unrefList empty'); L.append(unrefList, item); unrefTimer.start(msecs, 0); unrefTimer.when = now + msecs; debug('unrefTimer scheduled'); return; } var when = now + msecs; debug('unrefList find where we can insert'); var cur, them; for (cur = unrefList._idlePrev; cur != unrefList; cur = cur._idlePrev) { them = cur._idleStart + cur._idleTimeout; if (when < them) { debug('unrefList inserting into middle of list'); L.append(cur, item); if (unrefTimer.when > when) { debug('unrefTimer is scheduled to fire too late, reschedule'); unrefTimer.start(msecs, 0); unrefTimer.when = when; } return; } } debug('unrefList append to end'); L.append(unrefList, item); }; node-v0.10.25~dfsg2/lib/_stream_duplex.js0000644000000000000000000000464012270121457016740 0ustar rootroot// Copyright Joyent, Inc. and other Node contributors. // // Permission is hereby granted, free of charge, to any person obtaining a // copy of this software and associated documentation files (the // "Software"), to deal in the Software without restriction, including // without limitation the rights to use, copy, modify, merge, publish, // distribute, sublicense, and/or sell copies of the Software, and to permit // persons to whom the Software is furnished to do so, subject to the // following conditions: // // The above copyright notice and this permission notice shall be included // in all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS // OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF // MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN // NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, // DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR // OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE // USE OR OTHER DEALINGS IN THE SOFTWARE. // a duplex stream is just a stream that is both readable and writable. // Since JS doesn't have multiple prototypal inheritance, this class // prototypally inherits from Readable, and then parasitically from // Writable. module.exports = Duplex; var util = require('util'); var Readable = require('_stream_readable'); var Writable = require('_stream_writable'); util.inherits(Duplex, Readable); Object.keys(Writable.prototype).forEach(function(method) { if (!Duplex.prototype[method]) Duplex.prototype[method] = Writable.prototype[method]; }); function Duplex(options) { if (!(this instanceof Duplex)) return new Duplex(options); Readable.call(this, options); Writable.call(this, options); if (options && options.readable === false) this.readable = false; if (options && options.writable === false) this.writable = false; this.allowHalfOpen = true; if (options && options.allowHalfOpen === false) this.allowHalfOpen = false; this.once('end', onend); } // the no-half-open enforcer function onend() { // if we allow half-open state, or if the writable side ended, // then we're ok. if (this.allowHalfOpen || this._writableState.ended) return; // no more data can be written. // But allow more writes to happen in this tick. process.nextTick(this.end.bind(this)); } node-v0.10.25~dfsg2/lib/constants.js0000644000000000000000000000223512270121457015737 0ustar rootroot// Copyright Joyent, Inc. and other Node contributors. // // Permission is hereby granted, free of charge, to any person obtaining a // copy of this software and associated documentation files (the // "Software"), to deal in the Software without restriction, including // without limitation the rights to use, copy, modify, merge, publish, // distribute, sublicense, and/or sell copies of the Software, and to permit // persons to whom the Software is furnished to do so, subject to the // following conditions: // // The above copyright notice and this permission notice shall be included // in all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS // OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF // MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN // NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, // DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR // OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE // USE OR OTHER DEALINGS IN THE SOFTWARE. module.exports = process.binding('constants'); node-v0.10.25~dfsg2/lib/sys.js0000644000000000000000000000235412270121457014543 0ustar rootroot// Copyright Joyent, Inc. and other Node contributors. // // Permission is hereby granted, free of charge, to any person obtaining a // copy of this software and associated documentation files (the // "Software"), to deal in the Software without restriction, including // without limitation the rights to use, copy, modify, merge, publish, // distribute, sublicense, and/or sell copies of the Software, and to permit // persons to whom the Software is furnished to do so, subject to the // following conditions: // // The above copyright notice and this permission notice shall be included // in all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS // OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF // MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN // NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, // DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR // OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE // USE OR OTHER DEALINGS IN THE SOFTWARE. // the sys module was renamed to 'util'. // this shim remains to keep old programs working. module.exports = require('util'); node-v0.10.25~dfsg2/lib/https.js0000644000000000000000000000711312270121457015065 0ustar rootroot// Copyright Joyent, Inc. and other Node contributors. // // Permission is hereby granted, free of charge, to any person obtaining a // copy of this software and associated documentation files (the // "Software"), to deal in the Software without restriction, including // without limitation the rights to use, copy, modify, merge, publish, // distribute, sublicense, and/or sell copies of the Software, and to permit // persons to whom the Software is furnished to do so, subject to the // following conditions: // // The above copyright notice and this permission notice shall be included // in all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS // OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF // MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN // NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, // DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR // OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE // USE OR OTHER DEALINGS IN THE SOFTWARE. var tls = require('tls'); var http = require('http'); var util = require('util'); var url = require('url'); var inherits = require('util').inherits; function Server(opts, requestListener) { if (!(this instanceof Server)) return new Server(opts, requestListener); if (process.features.tls_npn && !opts.NPNProtocols) { opts.NPNProtocols = ['http/1.1', 'http/1.0']; } tls.Server.call(this, opts, http._connectionListener); this.httpAllowHalfOpen = false; if (requestListener) { this.addListener('request', requestListener); } this.addListener('clientError', function(err, conn) { conn.destroy(err); }); } inherits(Server, tls.Server); exports.Server = Server; exports.createServer = function(opts, requestListener) { return new Server(opts, requestListener); }; // HTTPS agents. function createConnection(port, host, options) { if (typeof port === 'object') { options = port; } else if (typeof host === 'object') { options = host; } else if (typeof options === 'object') { options = options; } else { options = {}; } if (typeof port === 'number') { options.port = port; } if (typeof host === 'string') { options.host = host; } return tls.connect(options); } function Agent(options) { http.Agent.call(this, options); this.createConnection = createConnection; } inherits(Agent, http.Agent); Agent.prototype.defaultPort = 443; var globalAgent = new Agent(); exports.globalAgent = globalAgent; exports.Agent = Agent; exports.request = function(options, cb) { if (typeof options === 'string') { options = url.parse(options); } if (options.protocol && options.protocol !== 'https:') { throw new Error('Protocol:' + options.protocol + ' not supported.'); } options = util._extend({ createConnection: createConnection, defaultPort: 443 }, options); if (typeof options.agent === 'undefined') { if (typeof options.ca === 'undefined' && typeof options.cert === 'undefined' && typeof options.ciphers === 'undefined' && typeof options.key === 'undefined' && typeof options.passphrase === 'undefined' && typeof options.pfx === 'undefined' && typeof options.rejectUnauthorized === 'undefined') { options.agent = globalAgent; } else { options.agent = new Agent(options); } } return new http.ClientRequest(options, cb); }; exports.get = function(options, cb) { var req = exports.request(options, cb); req.end(); return req; }; node-v0.10.25~dfsg2/lib/net.js0000644000000000000000000010226412270121457014514 0ustar rootroot// Copyright Joyent, Inc. and other Node contributors. // // Permission is hereby granted, free of charge, to any person obtaining a // copy of this software and associated documentation files (the // "Software"), to deal in the Software without restriction, including // without limitation the rights to use, copy, modify, merge, publish, // distribute, sublicense, and/or sell copies of the Software, and to permit // persons to whom the Software is furnished to do so, subject to the // following conditions: // // The above copyright notice and this permission notice shall be included // in all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS // OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF // MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN // NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, // DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR // OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE // USE OR OTHER DEALINGS IN THE SOFTWARE. var events = require('events'); var stream = require('stream'); var timers = require('timers'); var util = require('util'); var assert = require('assert'); var cares = process.binding('cares_wrap'); var cluster; function noop() {} // constructor for lazy loading function createPipe() { var Pipe = process.binding('pipe_wrap').Pipe; return new Pipe(); } // constructor for lazy loading function createTCP() { var TCP = process.binding('tcp_wrap').TCP; return new TCP(); } function createHandle(fd) { var tty = process.binding('tty_wrap'); var type = tty.guessHandleType(fd); if (type === 'PIPE') return createPipe(); if (type === 'TCP') return createTCP(); throw new TypeError('Unsupported fd type: ' + type); } var debug; if (process.env.NODE_DEBUG && /net/.test(process.env.NODE_DEBUG)) { var pid = process.pid; debug = function(x) { // if console is not set up yet, then skip this. if (!console.error) return; console.error('NET: %d', pid, util.format.apply(util, arguments).slice(0, 500)); }; } else { debug = function() { }; } function isPipeName(s) { return typeof s === 'string' && toNumber(s) === false; } exports.createServer = function() { return new Server(arguments[0], arguments[1]); }; // Target API: // // var s = net.connect({port: 80, host: 'google.com'}, function() { // ... // }); // // There are various forms: // // connect(options, [cb]) // connect(port, [host], [cb]) // connect(path, [cb]); // exports.connect = exports.createConnection = function() { var args = normalizeConnectArgs(arguments); var s = new Socket(args[0]); return Socket.prototype.connect.apply(s, args); }; // Returns an array [options] or [options, cb] // It is the same as the argument of Socket.prototype.connect(). function normalizeConnectArgs(args) { var options = {}; if (typeof args[0] === 'object') { // connect(options, [cb]) options = args[0]; } else if (isPipeName(args[0])) { // connect(path, [cb]); options.path = args[0]; } else { // connect(port, [host], [cb]) options.port = args[0]; if (typeof args[1] === 'string') { options.host = args[1]; } } var cb = args[args.length - 1]; return (typeof cb === 'function') ? [options, cb] : [options]; } exports._normalizeConnectArgs = normalizeConnectArgs; // called when creating new Socket, or when re-using a closed Socket function initSocketHandle(self) { self.destroyed = false; self.errorEmitted = false; self.bytesRead = 0; self._bytesDispatched = 0; // Handle creation may be deferred to bind() or connect() time. if (self._handle) { self._handle.owner = self; self._handle.onread = onread; } } function Socket(options) { if (!(this instanceof Socket)) return new Socket(options); this._connecting = false; this._handle = null; switch (typeof options) { case 'number': options = { fd: options }; // Legacy interface. break; case 'undefined': options = {}; break; } stream.Duplex.call(this, options); if (options.handle) { this._handle = options.handle; // private } else if (typeof options.fd !== 'undefined') { this._handle = createHandle(options.fd); this._handle.open(options.fd); this.readable = options.readable !== false; this.writable = options.writable !== false; } else { // these will be set once there is a connection this.readable = this.writable = false; } this.onend = null; // shut down the socket when we're finished with it. this.on('finish', onSocketFinish); this.on('_socketEnd', onSocketEnd); initSocketHandle(this); this._pendingData = null; this._pendingEncoding = ''; // handle strings directly this._writableState.decodeStrings = false; // default to *not* allowing half open sockets this.allowHalfOpen = options && options.allowHalfOpen || false; // if we have a handle, then start the flow of data into the // buffer. if not, then this will happen when we connect if (this._handle && options.readable !== false) this.read(0); } util.inherits(Socket, stream.Duplex); // the user has called .end(), and all the bytes have been // sent out to the other side. // If allowHalfOpen is false, or if the readable side has // ended already, then destroy. // If allowHalfOpen is true, then we need to do a shutdown, // so that only the writable side will be cleaned up. function onSocketFinish() { // If still connecting - defer handling 'finish' until 'connect' will happen if (this._connecting) { debug('osF: not yet connected'); return this.once('connect', onSocketFinish); } debug('onSocketFinish'); if (!this.readable || this._readableState.ended) { debug('oSF: ended, destroy', this._readableState); return this.destroy(); } debug('oSF: not ended, call shutdown()'); // otherwise, just shutdown, or destroy() if not possible if (!this._handle || !this._handle.shutdown) return this.destroy(); var shutdownReq = this._handle.shutdown(); if (!shutdownReq) return this._destroy(errnoException(process._errno, 'shutdown')); shutdownReq.oncomplete = afterShutdown; } function afterShutdown(status, handle, req) { var self = handle.owner; debug('afterShutdown destroyed=%j', self.destroyed, self._readableState); // callback may come after call to destroy. if (self.destroyed) return; if (self._readableState.ended) { debug('readableState ended, destroying'); self.destroy(); } else { self.once('_socketEnd', self.destroy); } } // the EOF has been received, and no more bytes are coming. // if the writable side has ended already, then clean everything // up. function onSocketEnd() { // XXX Should not have to do as much crap in this function. // ended should already be true, since this is called *after* // the EOF errno and onread has eof'ed debug('onSocketEnd', this._readableState); this._readableState.ended = true; if (this._readableState.endEmitted) { this.readable = false; maybeDestroy(this); } else { this.once('end', function() { this.readable = false; maybeDestroy(this); }); this.read(0); } if (!this.allowHalfOpen) { this.write = writeAfterFIN; this.destroySoon(); } } // Provide a better error message when we call end() as a result // of the other side sending a FIN. The standard 'write after end' // is overly vague, and makes it seem like the user's code is to blame. function writeAfterFIN(chunk, encoding, cb) { if (typeof encoding === 'function') { cb = encoding; encoding = null; } var er = new Error('This socket has been ended by the other party'); er.code = 'EPIPE'; var self = this; // TODO: defer error events consistently everywhere, not just the cb self.emit('error', er); if (typeof cb === 'function') { process.nextTick(function() { cb(er); }); } } exports.Socket = Socket; exports.Stream = Socket; // Legacy naming. Socket.prototype.read = function(n) { if (n === 0) return stream.Readable.prototype.read.call(this, n); this.read = stream.Readable.prototype.read; this._consuming = true; return this.read(n); }; Socket.prototype.listen = function() { debug('socket.listen'); var self = this; self.on('connection', arguments[0]); listen(self, null, null, null); }; Socket.prototype.setTimeout = function(msecs, callback) { if (msecs > 0 && !isNaN(msecs) && isFinite(msecs)) { timers.enroll(this, msecs); timers._unrefActive(this); if (callback) { this.once('timeout', callback); } } else if (msecs === 0) { timers.unenroll(this); if (callback) { this.removeListener('timeout', callback); } } }; Socket.prototype._onTimeout = function() { debug('_onTimeout'); this.emit('timeout'); }; Socket.prototype.setNoDelay = function(enable) { // backwards compatibility: assume true when `enable` is omitted if (this._handle && this._handle.setNoDelay) this._handle.setNoDelay(typeof enable === 'undefined' ? true : !!enable); }; Socket.prototype.setKeepAlive = function(setting, msecs) { if (this._handle && this._handle.setKeepAlive) this._handle.setKeepAlive(setting, ~~(msecs / 1000)); }; Socket.prototype.address = function() { if (this._handle && this._handle.getsockname) { return this._handle.getsockname(); } return null; }; Object.defineProperty(Socket.prototype, 'readyState', { get: function() { if (this._connecting) { return 'opening'; } else if (this.readable && this.writable) { return 'open'; } else if (this.readable && !this.writable) { return 'readOnly'; } else if (!this.readable && this.writable) { return 'writeOnly'; } else { return 'closed'; } } }); Object.defineProperty(Socket.prototype, 'bufferSize', { get: function() { if (this._handle) { return this._handle.writeQueueSize + this._writableState.length; } } }); // Just call handle.readStart until we have enough in the buffer Socket.prototype._read = function(n) { debug('_read'); if (this._connecting || !this._handle) { debug('_read wait for connection'); this.once('connect', this._read.bind(this, n)); } else if (!this._handle.reading) { // not already reading, start the flow debug('Socket._read readStart'); this._handle.reading = true; var r = this._handle.readStart(); if (r) this._destroy(errnoException(process._errno, 'read')); } }; Socket.prototype.end = function(data, encoding) { stream.Duplex.prototype.end.call(this, data, encoding); this.writable = false; DTRACE_NET_STREAM_END(this); // just in case we're waiting for an EOF. if (this.readable && !this._readableState.endEmitted) this.read(0); else maybeDestroy(this); }; // Call whenever we set writable=false or readable=false function maybeDestroy(socket) { if (!socket.readable && !socket.writable && !socket.destroyed && !socket._connecting && !socket._writableState.length) { socket.destroy(); } } Socket.prototype.destroySoon = function() { if (this.writable) this.end(); if (this._writableState.finished) this.destroy(); else this.once('finish', this.destroy); }; Socket.prototype._destroy = function(exception, cb) { debug('destroy'); var self = this; function fireErrorCallbacks() { if (cb) cb(exception); if (exception && !self.errorEmitted) { process.nextTick(function() { self.emit('error', exception); }); self.errorEmitted = true; } }; if (this.destroyed) { debug('already destroyed, fire error callbacks'); fireErrorCallbacks(); return; } self._connecting = false; this.readable = this.writable = false; timers.unenroll(this); debug('close'); if (this._handle) { if (this !== process.stderr) debug('close handle'); var isException = exception ? true : false; this._handle.close(function() { debug('emit close'); self.emit('close', isException); }); this._handle.onread = noop; this._handle = null; } fireErrorCallbacks(); this.destroyed = true; if (this.server) { COUNTER_NET_SERVER_CONNECTION_CLOSE(this); debug('has server'); this.server._connections--; if (this.server._emitCloseIfDrained) { this.server._emitCloseIfDrained(); } } }; Socket.prototype.destroy = function(exception) { debug('destroy', exception); this._destroy(exception); }; // This function is called whenever the handle gets a // buffer, or when there's an error reading. function onread(buffer, offset, length) { var handle = this; var self = handle.owner; assert(handle === self._handle, 'handle != self._handle'); timers._unrefActive(self); var end = offset + length; debug('onread', process._errno, offset, length, end); if (buffer) { debug('got data'); // read success. // In theory (and in practice) calling readStop right now // will prevent this from being called again until _read() gets // called again. // if we didn't get any bytes, that doesn't necessarily mean EOF. // wait for the next one. if (offset === end) { debug('not any data, keep waiting'); return; } // if it's not enough data, we'll just call handle.readStart() // again right away. self.bytesRead += length; // Optimization: emit the original buffer with end points var ret = true; if (self.ondata) self.ondata(buffer, offset, end); else ret = self.push(buffer.slice(offset, end)); if (handle.reading && !ret) { handle.reading = false; debug('readStop'); var r = handle.readStop(); if (r) self._destroy(errnoException(process._errno, 'read')); } } else if (process._errno == 'EOF') { debug('EOF'); if (self._readableState.length === 0) { self.readable = false; maybeDestroy(self); } if (self.onend) self.once('end', self.onend); // push a null to signal the end of data. self.push(null); // internal end event so that we know that the actual socket // is no longer readable, and we can start the shutdown // procedure. No need to wait for all the data to be consumed. self.emit('_socketEnd'); } else { debug('error', process._errno); // Error self._destroy(errnoException(process._errno, 'read')); } } Socket.prototype._getpeername = function() { if (!this._handle || !this._handle.getpeername) { return {}; } if (!this._peername) { this._peername = this._handle.getpeername(); // getpeername() returns null on error if (this._peername === null) { return {}; } } return this._peername; }; Socket.prototype.__defineGetter__('remoteAddress', function() { return this._getpeername().address; }); Socket.prototype.__defineGetter__('remotePort', function() { return this._getpeername().port; }); Socket.prototype._getsockname = function() { if (!this._handle || !this._handle.getsockname) { return {}; } if (!this._sockname) { this._sockname = this._handle.getsockname(); if (this._sockname === null) { return {}; } } return this._sockname; }; Socket.prototype.__defineGetter__('localAddress', function() { return this._getsockname().address; }); Socket.prototype.__defineGetter__('localPort', function() { return this._getsockname().port; }); Socket.prototype.write = function(chunk, encoding, cb) { if (typeof chunk !== 'string' && !Buffer.isBuffer(chunk)) throw new TypeError('invalid data'); return stream.Duplex.prototype.write.apply(this, arguments); }; Socket.prototype._write = function(data, encoding, cb) { // If we are still connecting, then buffer this for later. // The Writable logic will buffer up any more writes while // waiting for this one to be done. if (this._connecting) { this._pendingData = data; this._pendingEncoding = encoding; this.once('connect', function() { this._write(data, encoding, cb); }); return; } this._pendingData = null; this._pendingEncoding = ''; timers._unrefActive(this); if (!this._handle) { this._destroy(new Error('This socket is closed.'), cb); return false; } var enc = Buffer.isBuffer(data) ? 'buffer' : encoding; var writeReq = createWriteReq(this._handle, data, enc); if (!writeReq || typeof writeReq !== 'object') return this._destroy(errnoException(process._errno, 'write'), cb); writeReq.oncomplete = afterWrite; this._bytesDispatched += writeReq.bytes; // If it was entirely flushed, we can write some more right now. // However, if more is left in the queue, then wait until that clears. if (this._handle.writeQueueSize === 0) cb(); else writeReq.cb = cb; }; function createWriteReq(handle, data, encoding) { switch (encoding) { case 'buffer': return handle.writeBuffer(data); case 'utf8': case 'utf-8': return handle.writeUtf8String(data); case 'ascii': return handle.writeAsciiString(data); case 'ucs2': case 'ucs-2': case 'utf16le': case 'utf-16le': return handle.writeUcs2String(data); default: return handle.writeBuffer(new Buffer(data, encoding)); } } Socket.prototype.__defineGetter__('bytesWritten', function() { var bytes = this._bytesDispatched, state = this._writableState, data = this._pendingData, encoding = this._pendingEncoding; state.buffer.forEach(function(el) { if (Buffer.isBuffer(el.chunk)) bytes += el.chunk.length; else bytes += Buffer.byteLength(el.chunk, el.encoding); }); if (data) { if (Buffer.isBuffer(data)) bytes += data.length; else bytes += Buffer.byteLength(data, encoding); } return bytes; }); function afterWrite(status, handle, req) { var self = handle.owner; var state = self._writableState; if (self !== process.stderr && self !== process.stdout) debug('afterWrite', status, req); // callback may come after call to destroy. if (self.destroyed) { debug('afterWrite destroyed'); return; } if (status) { debug('write failure', errnoException(process._errno, 'write')); self._destroy(errnoException(process._errno, 'write'), req.cb); return; } timers._unrefActive(self); if (self !== process.stderr && self !== process.stdout) debug('afterWrite call cb'); if (req.cb) req.cb.call(self); } function connect(self, address, port, addressType, localAddress) { // TODO return promise from Socket.prototype.connect which // wraps _connectReq. assert.ok(self._connecting); if (localAddress) { var r; if (addressType == 6) { r = self._handle.bind6(localAddress); } else { r = self._handle.bind(localAddress); } if (r) { self._destroy(errnoException(process._errno, 'bind')); return; } } var connectReq; if (addressType == 6) { connectReq = self._handle.connect6(address, port); } else if (addressType == 4) { connectReq = self._handle.connect(address, port); } else { connectReq = self._handle.connect(address, afterConnect); } if (connectReq !== null) { connectReq.oncomplete = afterConnect; } else { self._destroy(errnoException(process._errno, 'connect')); } } Socket.prototype.connect = function(options, cb) { if (this.write !== Socket.prototype.write) this.write = Socket.prototype.write; if (typeof options !== 'object') { // Old API: // connect(port, [host], [cb]) // connect(path, [cb]); var args = normalizeConnectArgs(arguments); return Socket.prototype.connect.apply(this, args); } if (this.destroyed) { this._readableState.reading = false; this._readableState.ended = false; this._writableState.ended = false; this._writableState.ending = false; this._writableState.finished = false; this.destroyed = false; this._handle = null; } var self = this; var pipe = !!options.path; if (!this._handle) { this._handle = pipe ? createPipe() : createTCP(); initSocketHandle(this); } if (typeof cb === 'function') { self.once('connect', cb); } timers._unrefActive(this); self._connecting = true; self.writable = true; if (pipe) { connect(self, options.path); } else if (!options.host) { debug('connect: missing host'); connect(self, '127.0.0.1', options.port, 4); } else { var host = options.host; debug('connect: find host ' + host); require('dns').lookup(host, function(err, ip, addressType) { // It's possible we were destroyed while looking this up. // XXX it would be great if we could cancel the promise returned by // the look up. if (!self._connecting) return; if (err) { // net.createConnection() creates a net.Socket object and // immediately calls net.Socket.connect() on it (that's us). // There are no event listeners registered yet so defer the // error event to the next tick. process.nextTick(function() { self.emit('error', err); self._destroy(); }); } else { timers._unrefActive(self); addressType = addressType || 4; // node_net.cc handles null host names graciously but user land // expects remoteAddress to have a meaningful value ip = ip || (addressType === 4 ? '127.0.0.1' : '0:0:0:0:0:0:0:1'); connect(self, ip, options.port, addressType, options.localAddress); } }); } return self; }; Socket.prototype.ref = function() { if (this._handle) this._handle.ref(); }; Socket.prototype.unref = function() { if (this._handle) this._handle.unref(); }; function afterConnect(status, handle, req, readable, writable) { var self = handle.owner; // callback may come after call to destroy if (self.destroyed) { return; } assert(handle === self._handle, 'handle != self._handle'); debug('afterConnect'); assert.ok(self._connecting); self._connecting = false; if (status == 0) { self.readable = readable; self.writable = writable; timers._unrefActive(self); self.emit('connect'); // start the first read, or get an immediate EOF. // this doesn't actually consume any bytes, because len=0. if (readable) self.read(0); } else { self._connecting = false; self._destroy(errnoException(process._errno, 'connect')); } } function errnoException(errorno, syscall) { // TODO make this more compatible with ErrnoException from src/node.cc // Once all of Node is using this function the ErrnoException from // src/node.cc should be removed. var e = new Error(syscall + ' ' + errorno); e.errno = e.code = errorno; e.syscall = syscall; return e; } function Server(/* [ options, ] listener */) { if (!(this instanceof Server)) return new Server(arguments[0], arguments[1]); events.EventEmitter.call(this); var self = this; var options; if (typeof arguments[0] == 'function') { options = {}; self.on('connection', arguments[0]); } else { options = arguments[0] || {}; if (typeof arguments[1] == 'function') { self.on('connection', arguments[1]); } } this._connections = 0; Object.defineProperty(this, 'connections', { get: util.deprecate(function() { if (self._usingSlaves) { return null; } return self._connections; }, 'connections property is deprecated. Use getConnections() method'), set: util.deprecate(function(val) { return (self._connections = val); }, 'connections property is deprecated. Use getConnections() method'), configurable: true, enumerable: true }); this._handle = null; this._usingSlaves = false; this._slaves = []; this.allowHalfOpen = options.allowHalfOpen || false; } util.inherits(Server, events.EventEmitter); exports.Server = Server; function toNumber(x) { return (x = Number(x)) >= 0 ? x : false; } var createServerHandle = exports._createServerHandle = function(address, port, addressType, fd) { var r = 0; // assign handle in listen, and clean up if bind or listen fails var handle; if (typeof fd === 'number' && fd >= 0) { try { handle = createHandle(fd); } catch (e) { // Not a fd we can listen on. This will trigger an error. debug('listen invalid fd=' + fd + ': ' + e.message); process._errno = 'EINVAL'; // hack, callers expect that errno is set return null; } handle.open(fd); handle.readable = true; handle.writable = true; return handle; } else if (port == -1 && addressType == -1) { handle = createPipe(); if (process.platform === 'win32') { var instances = parseInt(process.env.NODE_PENDING_PIPE_INSTANCES); if (!isNaN(instances)) { handle.setPendingInstances(instances); } } } else { handle = createTCP(); } if (address || port) { debug('bind to ' + address); if (addressType == 6) { r = handle.bind6(address, port); } else { r = handle.bind(address, port); } } if (r) { handle.close(); handle = null; } return handle; }; Server.prototype._listen2 = function(address, port, addressType, backlog, fd) { debug('listen2', address, port, addressType, backlog); var self = this; var r = 0; // If there is not yet a handle, we need to create one and bind. // In the case of a server sent via IPC, we don't need to do this. if (!self._handle) { debug('_listen2: create a handle'); self._handle = createServerHandle(address, port, addressType, fd); if (!self._handle) { var error = errnoException(process._errno, 'listen'); process.nextTick(function() { self.emit('error', error); }); return; } } else { debug('_listen2: have a handle already'); } self._handle.onconnection = onconnection; self._handle.owner = self; // Use a backlog of 512 entries. We pass 511 to the listen() call because // the kernel does: backlogsize = roundup_pow_of_two(backlogsize + 1); // which will thus give us a backlog of 512 entries. r = self._handle.listen(backlog || 511); if (r) { var ex = errnoException(process._errno, 'listen'); self._handle.close(); self._handle = null; process.nextTick(function() { self.emit('error', ex); }); return; } // generate connection key, this should be unique to the connection this._connectionKey = addressType + ':' + address + ':' + port; process.nextTick(function() { self.emit('listening'); }); }; function listen(self, address, port, addressType, backlog, fd) { if (!cluster) cluster = require('cluster'); if (cluster.isMaster) { self._listen2(address, port, addressType, backlog, fd); return; } cluster._getServer(self, address, port, addressType, fd, function(handle, err) { // EACCESS and friends if (err) { self.emit('error', errnoException(err, 'bind')); return; } // Some operating systems (notably OS X and Solaris) don't report // EADDRINUSE errors right away. libuv mimics that behavior for the // sake of platform consistency but that means we have have a socket on // our hands that is not actually bound. That's why we check if the // actual port matches what we requested and if not, raise an error. // The exception is when port == 0 because that means "any random // port". if (port && handle.getsockname && port != handle.getsockname().port) { self.emit('error', errnoException('EADDRINUSE', 'bind')); return; } self._handle = handle; self._listen2(address, port, addressType, backlog, fd); }); } Server.prototype.listen = function() { var self = this; var lastArg = arguments[arguments.length - 1]; if (typeof lastArg == 'function') { self.once('listening', lastArg); } var port = toNumber(arguments[0]); // The third optional argument is the backlog size. // When the ip is omitted it can be the second argument. var backlog = toNumber(arguments[1]) || toNumber(arguments[2]); var TCP = process.binding('tcp_wrap').TCP; if (arguments.length == 0 || typeof arguments[0] == 'function') { // Bind to a random port. listen(self, '0.0.0.0', 0, null, backlog); } else if (arguments[0] && typeof arguments[0] === 'object') { var h = arguments[0]; if (h._handle) { h = h._handle; } else if (h.handle) { h = h.handle; } if (h instanceof TCP) { self._handle = h; listen(self, null, -1, -1, backlog); } else if (typeof h.fd === 'number' && h.fd >= 0) { listen(self, null, null, null, backlog, h.fd); } else { throw new Error('Invalid listen argument: ' + h); } } else if (isPipeName(arguments[0])) { // UNIX socket or Windows pipe. var pipeName = self._pipeName = arguments[0]; listen(self, pipeName, -1, -1, backlog); } else if (typeof arguments[1] == 'undefined' || typeof arguments[1] == 'function' || typeof arguments[1] == 'number') { // The first argument is the port, no IP given. listen(self, '0.0.0.0', port, 4, backlog); } else { // The first argument is the port, the second an IP. require('dns').lookup(arguments[1], function(err, ip, addressType) { if (err) { self.emit('error', err); } else { listen(self, ip || '0.0.0.0', port, ip ? addressType : 4, backlog); } }); } return self; }; Server.prototype.address = function() { if (this._handle && this._handle.getsockname) { return this._handle.getsockname(); } else if (this._pipeName) { return this._pipeName; } else { return null; } }; function onconnection(clientHandle) { var handle = this; var self = handle.owner; debug('onconnection'); if (!clientHandle) { self.emit('error', errnoException(process._errno, 'accept')); return; } if (self.maxConnections && self._connections >= self.maxConnections) { clientHandle.close(); return; } var socket = new Socket({ handle: clientHandle, allowHalfOpen: self.allowHalfOpen }); socket.readable = socket.writable = true; self._connections++; socket.server = self; DTRACE_NET_SERVER_CONNECTION(socket); COUNTER_NET_SERVER_CONNECTION(socket); self.emit('connection', socket); } Server.prototype.getConnections = function(cb) { function end(err, connections) { process.nextTick(function() { cb(err, connections); }); } if (!this._usingSlaves) { return end(null, this._connections); } // Poll slaves var left = this._slaves.length, total = this._connections; function oncount(err, count) { if (err) { left = -1; return end(err); } total += count; if (--left === 0) return end(null, total); } this._slaves.forEach(function(slave) { slave.getConnections(oncount); }); }; Server.prototype.close = function(cb) { function onSlaveClose() { if (--left !== 0) return; self._connections = 0; self._emitCloseIfDrained(); } if (!this._handle) { // Throw error. Follows net_legacy behaviour. throw new Error('Not running'); } if (cb) { this.once('close', cb); } this._handle.close(); this._handle = null; if (this._usingSlaves) { var self = this, left = this._slaves.length; // Increment connections to be sure that, even if all sockets will be closed // during polling of slaves, `close` event will be emitted only once. this._connections++; // Poll slaves this._slaves.forEach(function(slave) { slave.close(onSlaveClose); }); } else { this._emitCloseIfDrained(); } return this; }; Server.prototype._emitCloseIfDrained = function() { debug('SERVER _emitCloseIfDrained'); var self = this; if (self._handle || self._connections) { debug('SERVER handle? %j connections? %d', !!self._handle, self._connections); return; } process.nextTick(function() { debug('SERVER: emit close'); self.emit('close'); }); }; Server.prototype.listenFD = util.deprecate(function(fd, type) { return this.listen({ fd: fd }); }, 'listenFD is deprecated. Use listen({fd: }).'); Server.prototype._setupSlave = function(socketList) { this._usingSlaves = true; this._slaves.push(socketList); }; Server.prototype.ref = function() { if (this._handle) this._handle.ref(); }; Server.prototype.unref = function() { if (this._handle) this._handle.unref(); }; // TODO: isIP should be moved to the DNS code. Putting it here now because // this is what the legacy system did. exports.isIP = cares.isIP; exports.isIPv4 = function(input) { return exports.isIP(input) === 4; }; exports.isIPv6 = function(input) { return exports.isIP(input) === 6; }; if (process.platform === 'win32') { var simultaneousAccepts; exports._setSimultaneousAccepts = function(handle) { if (typeof handle === 'undefined') { return; } if (typeof simultaneousAccepts === 'undefined') { simultaneousAccepts = (process.env.NODE_MANY_ACCEPTS && process.env.NODE_MANY_ACCEPTS !== '0'); } if (handle._simultaneousAccepts !== simultaneousAccepts) { handle.setSimultaneousAccepts(simultaneousAccepts); handle._simultaneousAccepts = simultaneousAccepts; } }; } else { exports._setSimultaneousAccepts = function(handle) {}; } node-v0.10.25~dfsg2/lib/util.js0000644000000000000000000003563012270121457014705 0ustar rootroot// Copyright Joyent, Inc. and other Node contributors. // // Permission is hereby granted, free of charge, to any person obtaining a // copy of this software and associated documentation files (the // "Software"), to deal in the Software without restriction, including // without limitation the rights to use, copy, modify, merge, publish, // distribute, sublicense, and/or sell copies of the Software, and to permit // persons to whom the Software is furnished to do so, subject to the // following conditions: // // The above copyright notice and this permission notice shall be included // in all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS // OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF // MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN // NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, // DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR // OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE // USE OR OTHER DEALINGS IN THE SOFTWARE. var formatRegExp = /%[sdj%]/g; exports.format = function(f) { if (typeof f !== 'string') { var objects = []; for (var i = 0; i < arguments.length; i++) { objects.push(inspect(arguments[i])); } return objects.join(' '); } var i = 1; var args = arguments; var len = args.length; var str = String(f).replace(formatRegExp, function(x) { if (x === '%%') return '%'; if (i >= len) return x; switch (x) { case '%s': return String(args[i++]); case '%d': return Number(args[i++]); case '%j': return JSON.stringify(args[i++]); default: return x; } }); for (var x = args[i]; i < len; x = args[++i]) { if (x === null || typeof x !== 'object') { str += ' ' + x; } else { str += ' ' + inspect(x); } } return str; }; // Mark that a method should not be used. // Returns a modified function which warns once by default. // If --no-deprecation is set, then it is a no-op. exports.deprecate = function(fn, msg) { if (process.noDeprecation === true) { return fn; } var warned = false; function deprecated() { if (!warned) { if (process.throwDeprecation) { throw new Error(msg); } else if (process.traceDeprecation) { console.trace(msg); } else { console.error(msg); } warned = true; } return fn.apply(this, arguments); } return deprecated; }; exports.print = function() { for (var i = 0, len = arguments.length; i < len; ++i) { process.stdout.write(String(arguments[i])); } }; exports.puts = function() { for (var i = 0, len = arguments.length; i < len; ++i) { process.stdout.write(arguments[i] + '\n'); } }; exports.debug = function(x) { process.stderr.write('DEBUG: ' + x + '\n'); }; var error = exports.error = function(x) { for (var i = 0, len = arguments.length; i < len; ++i) { process.stderr.write(arguments[i] + '\n'); } }; /** * Echos the value of a value. Trys to print the value out * in the best way possible given the different types. * * @param {Object} obj The object to print out. * @param {Object} opts Optional options object that alters the output. */ /* legacy: obj, showHidden, depth, colors*/ function inspect(obj, opts) { // default options var ctx = { seen: [], stylize: stylizeNoColor }; // legacy... if (arguments.length >= 3) ctx.depth = arguments[2]; if (arguments.length >= 4) ctx.colors = arguments[3]; if (typeof opts === 'boolean') { // legacy... ctx.showHidden = opts; } else if (opts) { // got an "options" object exports._extend(ctx, opts); } // set default options if (typeof ctx.showHidden === 'undefined') ctx.showHidden = false; if (typeof ctx.depth === 'undefined') ctx.depth = 2; if (typeof ctx.colors === 'undefined') ctx.colors = false; if (typeof ctx.customInspect === 'undefined') ctx.customInspect = true; if (ctx.colors) ctx.stylize = stylizeWithColor; return formatValue(ctx, obj, ctx.depth); } exports.inspect = inspect; // http://en.wikipedia.org/wiki/ANSI_escape_code#graphics inspect.colors = { 'bold' : [1, 22], 'italic' : [3, 23], 'underline' : [4, 24], 'inverse' : [7, 27], 'white' : [37, 39], 'grey' : [90, 39], 'black' : [30, 39], 'blue' : [34, 39], 'cyan' : [36, 39], 'green' : [32, 39], 'magenta' : [35, 39], 'red' : [31, 39], 'yellow' : [33, 39] }; // Don't use 'blue' not visible on cmd.exe inspect.styles = { 'special': 'cyan', 'number': 'yellow', 'boolean': 'yellow', 'undefined': 'grey', 'null': 'bold', 'string': 'green', 'date': 'magenta', // "name": intentionally not styling 'regexp': 'red' }; function stylizeWithColor(str, styleType) { var style = inspect.styles[styleType]; if (style) { return '\u001b[' + inspect.colors[style][0] + 'm' + str + '\u001b[' + inspect.colors[style][1] + 'm'; } else { return str; } } function stylizeNoColor(str, styleType) { return str; } function arrayToHash(array) { var hash = {}; array.forEach(function(val, idx) { hash[val] = true; }); return hash; } function formatValue(ctx, value, recurseTimes) { // Provide a hook for user-specified inspect functions. // Check that value is an object with an inspect function on it if (ctx.customInspect && value && typeof value.inspect === 'function' && // Filter out the util module, it's inspect function is special value.inspect !== exports.inspect && // Also filter out any prototype objects using the circular check. !(value.constructor && value.constructor.prototype === value)) { return String(value.inspect(recurseTimes)); } // Primitive types cannot have properties var primitive = formatPrimitive(ctx, value); if (primitive) { return primitive; } // Look up the keys of the object. var keys = Object.keys(value); var visibleKeys = arrayToHash(keys); if (ctx.showHidden) { keys = Object.getOwnPropertyNames(value); } // Some type of object without properties can be shortcutted. if (keys.length === 0) { if (typeof value === 'function') { var name = value.name ? ': ' + value.name : ''; return ctx.stylize('[Function' + name + ']', 'special'); } if (isRegExp(value)) { return ctx.stylize(RegExp.prototype.toString.call(value), 'regexp'); } if (isDate(value)) { return ctx.stylize(Date.prototype.toString.call(value), 'date'); } if (isError(value)) { return formatError(value); } } var base = '', array = false, braces = ['{', '}']; // Make Array say that they are Array if (isArray(value)) { array = true; braces = ['[', ']']; } // Make functions say that they are functions if (typeof value === 'function') { var n = value.name ? ': ' + value.name : ''; base = ' [Function' + n + ']'; } // Make RegExps say that they are RegExps if (isRegExp(value)) { base = ' ' + RegExp.prototype.toString.call(value); } // Make dates with properties first say the date if (isDate(value)) { base = ' ' + Date.prototype.toUTCString.call(value); } // Make error with message first say the error if (isError(value)) { base = ' ' + formatError(value); } if (keys.length === 0 && (!array || value.length == 0)) { return braces[0] + base + braces[1]; } if (recurseTimes < 0) { if (isRegExp(value)) { return ctx.stylize(RegExp.prototype.toString.call(value), 'regexp'); } else { return ctx.stylize('[Object]', 'special'); } } ctx.seen.push(value); var output; if (array) { output = formatArray(ctx, value, recurseTimes, visibleKeys, keys); } else { output = keys.map(function(key) { return formatProperty(ctx, value, recurseTimes, visibleKeys, key, array); }); } ctx.seen.pop(); return reduceToSingleString(output, base, braces); } function formatPrimitive(ctx, value) { switch (typeof value) { case 'undefined': return ctx.stylize('undefined', 'undefined'); case 'string': var simple = '\'' + JSON.stringify(value).replace(/^"|"$/g, '') .replace(/'/g, "\\'") .replace(/\\"/g, '"') + '\''; return ctx.stylize(simple, 'string'); case 'number': return ctx.stylize('' + value, 'number'); case 'boolean': return ctx.stylize('' + value, 'boolean'); } // For some reason typeof null is "object", so special case here. if (value === null) { return ctx.stylize('null', 'null'); } } function formatError(value) { return '[' + Error.prototype.toString.call(value) + ']'; } function formatArray(ctx, value, recurseTimes, visibleKeys, keys) { var output = []; for (var i = 0, l = value.length; i < l; ++i) { if (hasOwnProperty(value, String(i))) { output.push(formatProperty(ctx, value, recurseTimes, visibleKeys, String(i), true)); } else { output.push(''); } } keys.forEach(function(key) { if (!key.match(/^\d+$/)) { output.push(formatProperty(ctx, value, recurseTimes, visibleKeys, key, true)); } }); return output; } function formatProperty(ctx, value, recurseTimes, visibleKeys, key, array) { var name, str, desc; desc = Object.getOwnPropertyDescriptor(value, key) || { value: value[key] }; if (desc.get) { if (desc.set) { str = ctx.stylize('[Getter/Setter]', 'special'); } else { str = ctx.stylize('[Getter]', 'special'); } } else { if (desc.set) { str = ctx.stylize('[Setter]', 'special'); } } if (!hasOwnProperty(visibleKeys, key)) { name = '[' + key + ']'; } if (!str) { if (ctx.seen.indexOf(desc.value) < 0) { if (recurseTimes === null) { str = formatValue(ctx, desc.value, null); } else { str = formatValue(ctx, desc.value, recurseTimes - 1); } if (str.indexOf('\n') > -1) { if (array) { str = str.split('\n').map(function(line) { return ' ' + line; }).join('\n').substr(2); } else { str = '\n' + str.split('\n').map(function(line) { return ' ' + line; }).join('\n'); } } } else { str = ctx.stylize('[Circular]', 'special'); } } if (typeof name === 'undefined') { if (array && key.match(/^\d+$/)) { return str; } name = JSON.stringify('' + key); if (name.match(/^"([a-zA-Z_][a-zA-Z_0-9]*)"$/)) { name = name.substr(1, name.length - 2); name = ctx.stylize(name, 'name'); } else { name = name.replace(/'/g, "\\'") .replace(/\\"/g, '"') .replace(/(^"|"$)/g, "'"); name = ctx.stylize(name, 'string'); } } return name + ': ' + str; } function reduceToSingleString(output, base, braces) { var numLinesEst = 0; var length = output.reduce(function(prev, cur) { numLinesEst++; if (cur.indexOf('\n') >= 0) numLinesEst++; return prev + cur.length + 1; }, 0); if (length > 60) { return braces[0] + (base === '' ? '' : base + '\n ') + ' ' + output.join(',\n ') + ' ' + braces[1]; } return braces[0] + base + ' ' + output.join(', ') + ' ' + braces[1]; } // NOTE: These type checking functions intentionally don't use `instanceof` // because it is fragile and can be easily faked with `Object.create()`. function isArray(ar) { return Array.isArray(ar) || (typeof ar === 'object' && objectToString(ar) === '[object Array]'); } exports.isArray = isArray; function isRegExp(re) { return typeof re === 'object' && objectToString(re) === '[object RegExp]'; } exports.isRegExp = isRegExp; function isDate(d) { return typeof d === 'object' && objectToString(d) === '[object Date]'; } exports.isDate = isDate; function isError(e) { return typeof e === 'object' && objectToString(e) === '[object Error]'; } exports.isError = isError; function objectToString(o) { return Object.prototype.toString.call(o); } exports.p = exports.deprecate(function() { for (var i = 0, len = arguments.length; i < len; ++i) { error(exports.inspect(arguments[i])); } }, 'util.p: Use console.error() instead.'); function pad(n) { return n < 10 ? '0' + n.toString(10) : n.toString(10); } var months = ['Jan', 'Feb', 'Mar', 'Apr', 'May', 'Jun', 'Jul', 'Aug', 'Sep', 'Oct', 'Nov', 'Dec']; // 26 Feb 16:19:34 function timestamp() { var d = new Date(); var time = [pad(d.getHours()), pad(d.getMinutes()), pad(d.getSeconds())].join(':'); return [d.getDate(), months[d.getMonth()], time].join(' '); } exports.log = function(msg) { exports.puts(timestamp() + ' - ' + msg.toString()); }; exports.exec = exports.deprecate(function() { return require('child_process').exec.apply(this, arguments); }, 'util.exec is now called `child_process.exec`.'); function pump(readStream, writeStream, callback) { var callbackCalled = false; function call(a, b, c) { if (callback && !callbackCalled) { callback(a, b, c); callbackCalled = true; } } readStream.addListener('data', function(chunk) { if (writeStream.write(chunk) === false) readStream.pause(); }); writeStream.addListener('drain', function() { readStream.resume(); }); readStream.addListener('end', function() { writeStream.end(); }); readStream.addListener('close', function() { call(); }); readStream.addListener('error', function(err) { writeStream.end(); call(err); }); writeStream.addListener('error', function(err) { readStream.destroy(); call(err); }); } exports.pump = exports.deprecate(pump, 'util.pump() is deprecated. Use readableStream.pipe() instead.'); /** * Inherit the prototype methods from one constructor into another. * * The Function.prototype.inherits from lang.js rewritten as a standalone * function (not on Function.prototype). NOTE: If this file is to be loaded * during bootstrapping this function needs to be rewritten using some native * functions as prototype setup using normal JavaScript does not work as * expected during bootstrapping (see mirror.js in r114903). * * @param {function} ctor Constructor function which needs to inherit the * prototype. * @param {function} superCtor Constructor function to inherit prototype from. */ exports.inherits = function(ctor, superCtor) { ctor.super_ = superCtor; ctor.prototype = Object.create(superCtor.prototype, { constructor: { value: ctor, enumerable: false, writable: true, configurable: true } }); }; exports._extend = function(origin, add) { // Don't do anything if add isn't an object if (!add || typeof add !== 'object') return origin; var keys = Object.keys(add); var i = keys.length; while (i--) { origin[keys[i]] = add[keys[i]]; } return origin; }; function hasOwnProperty(obj, prop) { return Object.prototype.hasOwnProperty.call(obj, prop); } node-v0.10.25~dfsg2/lib/freelist.js0000644000000000000000000000333412270121457015541 0ustar rootroot// Copyright Joyent, Inc. and other Node contributors. // // Permission is hereby granted, free of charge, to any person obtaining a // copy of this software and associated documentation files (the // "Software"), to deal in the Software without restriction, including // without limitation the rights to use, copy, modify, merge, publish, // distribute, sublicense, and/or sell copies of the Software, and to permit // persons to whom the Software is furnished to do so, subject to the // following conditions: // // The above copyright notice and this permission notice shall be included // in all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS // OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF // MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN // NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, // DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR // OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE // USE OR OTHER DEALINGS IN THE SOFTWARE. // This is a free list to avoid creating so many of the same object. exports.FreeList = function(name, max, constructor) { this.name = name; this.constructor = constructor; this.max = max; this.list = []; }; exports.FreeList.prototype.alloc = function() { //debug("alloc " + this.name + " " + this.list.length); return this.list.length ? this.list.shift() : this.constructor.apply(this, arguments); }; exports.FreeList.prototype.free = function(obj) { //debug("free " + this.name + " " + this.list.length); if (this.list.length < this.max) { this.list.push(obj); } }; node-v0.10.25~dfsg2/lib/_stream_writable.js0000644000000000000000000002453112270121457017251 0ustar rootroot// Copyright Joyent, Inc. and other Node contributors. // // Permission is hereby granted, free of charge, to any person obtaining a // copy of this software and associated documentation files (the // "Software"), to deal in the Software without restriction, including // without limitation the rights to use, copy, modify, merge, publish, // distribute, sublicense, and/or sell copies of the Software, and to permit // persons to whom the Software is furnished to do so, subject to the // following conditions: // // The above copyright notice and this permission notice shall be included // in all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS // OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF // MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN // NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, // DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR // OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE // USE OR OTHER DEALINGS IN THE SOFTWARE. // A bit simpler than readable streams. // Implement an async ._write(chunk, cb), and it'll handle all // the drain event emission and buffering. module.exports = Writable; Writable.WritableState = WritableState; var util = require('util'); var assert = require('assert'); var Stream = require('stream'); util.inherits(Writable, Stream); function WriteReq(chunk, encoding, cb) { this.chunk = chunk; this.encoding = encoding; this.callback = cb; } function WritableState(options, stream) { options = options || {}; // the point at which write() starts returning false // Note: 0 is a valid value, means that we always return false if // the entire buffer is not flushed immediately on write() var hwm = options.highWaterMark; this.highWaterMark = (hwm || hwm === 0) ? hwm : 16 * 1024; // object stream flag to indicate whether or not this stream // contains buffers or objects. this.objectMode = !!options.objectMode; // cast to ints. this.highWaterMark = ~~this.highWaterMark; this.needDrain = false; // at the start of calling end() this.ending = false; // when end() has been called, and returned this.ended = false; // when 'finish' is emitted this.finished = false; // should we decode strings into buffers before passing to _write? // this is here so that some node-core streams can optimize string // handling at a lower level. var noDecode = options.decodeStrings === false; this.decodeStrings = !noDecode; // Crypto is kind of old and crusty. Historically, its default string // encoding is 'binary' so we have to make this configurable. // Everything else in the universe uses 'utf8', though. this.defaultEncoding = options.defaultEncoding || 'utf8'; // not an actual buffer we keep track of, but a measurement // of how much we're waiting to get pushed to some underlying // socket or file. this.length = 0; // a flag to see when we're in the middle of a write. this.writing = false; // a flag to be able to tell if the onwrite cb is called immediately, // or on a later tick. We set this to true at first, becuase any // actions that shouldn't happen until "later" should generally also // not happen before the first write call. this.sync = true; // a flag to know if we're processing previously buffered items, which // may call the _write() callback in the same tick, so that we don't // end up in an overlapped onwrite situation. this.bufferProcessing = false; // the callback that's passed to _write(chunk,cb) this.onwrite = function(er) { onwrite(stream, er); }; // the callback that the user supplies to write(chunk,encoding,cb) this.writecb = null; // the amount that is being written when _write is called. this.writelen = 0; this.buffer = []; } function Writable(options) { // Writable ctor is applied to Duplexes, though they're not // instanceof Writable, they're instanceof Readable. if (!(this instanceof Writable) && !(this instanceof Stream.Duplex)) return new Writable(options); this._writableState = new WritableState(options, this); // legacy. this.writable = true; Stream.call(this); } // Otherwise people can pipe Writable streams, which is just wrong. Writable.prototype.pipe = function() { this.emit('error', new Error('Cannot pipe. Not readable.')); }; function writeAfterEnd(stream, state, cb) { var er = new Error('write after end'); // TODO: defer error events consistently everywhere, not just the cb stream.emit('error', er); process.nextTick(function() { cb(er); }); } // If we get something that is not a buffer, string, null, or undefined, // and we're not in objectMode, then that's an error. // Otherwise stream chunks are all considered to be of length=1, and the // watermarks determine how many objects to keep in the buffer, rather than // how many bytes or characters. function validChunk(stream, state, chunk, cb) { var valid = true; if (!Buffer.isBuffer(chunk) && 'string' !== typeof chunk && chunk !== null && chunk !== undefined && !state.objectMode) { var er = new TypeError('Invalid non-string/buffer chunk'); stream.emit('error', er); process.nextTick(function() { cb(er); }); valid = false; } return valid; } Writable.prototype.write = function(chunk, encoding, cb) { var state = this._writableState; var ret = false; if (typeof encoding === 'function') { cb = encoding; encoding = null; } if (Buffer.isBuffer(chunk)) encoding = 'buffer'; else if (!encoding) encoding = state.defaultEncoding; if (typeof cb !== 'function') cb = function() {}; if (state.ended) writeAfterEnd(this, state, cb); else if (validChunk(this, state, chunk, cb)) ret = writeOrBuffer(this, state, chunk, encoding, cb); return ret; }; function decodeChunk(state, chunk, encoding) { if (!state.objectMode && state.decodeStrings !== false && typeof chunk === 'string') { chunk = new Buffer(chunk, encoding); } return chunk; } // if we're already writing something, then just put this // in the queue, and wait our turn. Otherwise, call _write // If we return false, then we need a drain event, so set that flag. function writeOrBuffer(stream, state, chunk, encoding, cb) { chunk = decodeChunk(state, chunk, encoding); if (Buffer.isBuffer(chunk)) encoding = 'buffer'; var len = state.objectMode ? 1 : chunk.length; state.length += len; var ret = state.length < state.highWaterMark; // we must ensure that previous needDrain will not be reset to false. if (!ret) state.needDrain = true; if (state.writing) state.buffer.push(new WriteReq(chunk, encoding, cb)); else doWrite(stream, state, len, chunk, encoding, cb); return ret; } function doWrite(stream, state, len, chunk, encoding, cb) { state.writelen = len; state.writecb = cb; state.writing = true; state.sync = true; stream._write(chunk, encoding, state.onwrite); state.sync = false; } function onwriteError(stream, state, sync, er, cb) { if (sync) process.nextTick(function() { cb(er); }); else cb(er); stream.emit('error', er); } function onwriteStateUpdate(state) { state.writing = false; state.writecb = null; state.length -= state.writelen; state.writelen = 0; } function onwrite(stream, er) { var state = stream._writableState; var sync = state.sync; var cb = state.writecb; onwriteStateUpdate(state); if (er) onwriteError(stream, state, sync, er, cb); else { // Check if we're actually ready to finish, but don't emit yet var finished = needFinish(stream, state); if (!finished && !state.bufferProcessing && state.buffer.length) clearBuffer(stream, state); if (sync) { process.nextTick(function() { afterWrite(stream, state, finished, cb); }); } else { afterWrite(stream, state, finished, cb); } } } function afterWrite(stream, state, finished, cb) { if (!finished) onwriteDrain(stream, state); cb(); if (finished) finishMaybe(stream, state); } // Must force callback to be called on nextTick, so that we don't // emit 'drain' before the write() consumer gets the 'false' return // value, and has a chance to attach a 'drain' listener. function onwriteDrain(stream, state) { if (state.length === 0 && state.needDrain) { state.needDrain = false; stream.emit('drain'); } } // if there's something in the buffer waiting, then process it function clearBuffer(stream, state) { state.bufferProcessing = true; for (var c = 0; c < state.buffer.length; c++) { var entry = state.buffer[c]; var chunk = entry.chunk; var encoding = entry.encoding; var cb = entry.callback; var len = state.objectMode ? 1 : chunk.length; doWrite(stream, state, len, chunk, encoding, cb); // if we didn't call the onwrite immediately, then // it means that we need to wait until it does. // also, that means that the chunk and cb are currently // being processed, so move the buffer counter past them. if (state.writing) { c++; break; } } state.bufferProcessing = false; if (c < state.buffer.length) state.buffer = state.buffer.slice(c); else state.buffer.length = 0; } Writable.prototype._write = function(chunk, encoding, cb) { cb(new Error('not implemented')); }; Writable.prototype.end = function(chunk, encoding, cb) { var state = this._writableState; if (typeof chunk === 'function') { cb = chunk; chunk = null; encoding = null; } else if (typeof encoding === 'function') { cb = encoding; encoding = null; } if (typeof chunk !== 'undefined' && chunk !== null) this.write(chunk, encoding); // ignore unnecessary end() calls. if (!state.ending && !state.finished) endWritable(this, state, cb); }; function needFinish(stream, state) { return (state.ending && state.length === 0 && !state.finished && !state.writing); } function finishMaybe(stream, state) { var need = needFinish(stream, state); if (need) { state.finished = true; stream.emit('finish'); } return need; } function endWritable(stream, state, cb) { state.ending = true; finishMaybe(stream, state); if (cb) { if (state.finished) process.nextTick(cb); else stream.once('finish', cb); } state.ended = true; } node-v0.10.25~dfsg2/AUTHORS0000644000000000000000000004312012270121457013665 0ustar rootroot# Authors ordered by first contribution. Ryan Dahl Urban Hafner Joshaven Potter Abe Fettig Kevin van Zonneveld Michael Carter Jeff Smick Jon Crosby Felix Geisendörfer Ray Morgan Jérémy Lal Isaac Z. Schlueter Brandon Beacher Tim Caswell Connor Dunn Johan Sørensen Friedemann Altrock Onne Gorter Rhys Jones Jan Lehnardt Simon Willison Chew Choon Keat Jered Schmidt Michaeljohn Clement Karl Guertin Xavier Shay Christopher Lenz TJ Holowaychuk Johan Dahlberg Simon Cornelius P. Umacob Ryan McGrath Rasmus Andersson Micheil Smith Jonas Pfenniger David Sklar Charles Lehner Elliott Cable Benjamin Thomas San-Tai Hsu Ben Williamson Joseph Pecoraro Erich Ocean Alexis Sellier Blaine Cook Stanislav Opichal Aaron Heckmann Mikeal Rogers Matt Brubeck Michael Stillwell Yuichiro MASUI Mark Hansen Zoran Tomicic Jeremy Ashkenas Scott González James Duncan Arlo Breault Kris Kowal Jacek Becela Rob Ellis Tim Smart Herbert Vojčík Krishna Rajendran Nicholas Kinsey Scott Taylor Carson McDonald Matt Ranney James Herdman Julian Lamb Brian Hammond Mathias Pettersson Trevor Blackwell Thomas Lee Daniel Berger Paulo Matias Peter Griess Jonathan Knezek Jonathan Rentzsch Ben Noordhuis Elijah Insua Andrew Johnston Brian White Aapo Laitinen Sam Hughes Orlando Vazquez Raffaele Sena Brian McKenna Paul Querna Ben Lowery Peter Dekkers David Siegel Marshall Culpepper Ruben Rodriguez Dmitry Baranovskiy Blake Mizerany Jerome Etienne Dmitriy Shalashov Adam Wiggins Rick Olson Sergey Kryzhanovsky Marco Rogers Benjamin Fritsch Jan Kassens Robert Keizer Sam Shull Chandra Sekar S Andrew Naylor Benjamin Kramer Danny Coates Nick Stenning Bert Belder Trent Mick Fedor Indutny Illarionov Oleg Aria Stewart Johan Euphrosine Russell Haering Bradley Meck Tobie Langel Tony Metzidis Mark Nottingham Sam Stephenson Jorge Chamorro Bieling Evan Larkin Sean Coates Tom Hughes-Croucher Joshua Peek Nathan Rajlich Peteris Krumins AJ ONeal Sami Samhuri Nikhil Marathe Vitali Lovich Stéphan Kochen Oleg Efimov Guillaume Tuton Tim Cooijmans Dan Søndergaard Silas Sewell Wade Simmons Daniel Gröber Travis Swicegood Oleg Slobodskoi Jeremy Martin Michael Wilber Sean Braithwaite Anders Conbere Devin Torres Theo Schlossnagle Kai Chen Daniel Chcouri <333222@gmail.com> Mihai Călin Bazon Ali Farhadi Daniel Ennis Carter Allen Greg Hughes David Trejo Joe Walnes Koichi Kobayashi Konstantin Käfer Richard Rodger Andreas Reich Tony Huang Dean McNamee Trevor Burnham Zachary Scott Arnout Kazemier George Stagas Ben Weaver Scott McWhirter Jakub Lekstan Nick Campbell Nebu Pookins Tim Baumann Robert Mustacchi George Miroshnykov Mark Cavage Håvard Stranden Marcel Laverdet Alexandre Marangone Ryan Petrello Fuji Goro Siddharth Mahendraker Dave Pacheco Mathias Buus Henry Rawas Yoshihiro KIKUCHI Brett Kiefer Mariano Iglesias Jörn Horstmann Joe Shaw Niklas Fiekas Adam Luikart Artem Zaytsev Alex Xu Jeremy Selier Igor Zinkovsky Kip Gebhardt Stefan Rusu Shigeki Ohtsu Wojciech Wnętrzak Devon Govett Steve Engledow Pierre-Alexandre St-Jean Reid Burke Vicente Jimenez Aguilar Tadashi SAWADA Jeroen Janssen Daniel Pihlström Stefan Bühler Alexander Uvarov Aku Kotkavuo Peter Bright Logan Smyth Christopher Wright Glen Low Thomas Shinnick Mickaël Delahaye Antranig Basman Maciej Małecki Evan Martin Peter Lyons Jann Horn Abimanyu Raja Niclas Hoyer Karl Skomski Michael Jackson Ashok Mudukutore Sean Cunningham Vitor Balocco Ben Leslie Eric Lovett Christian Tellnes Colton Baker Tyler Larson Tomasz Janczuk Ilya Dmitrichenko Simen Brekken Guglielmo Ferri <44gatti@gmail.com> Thomas Parslow Ryan Emery Jordan Sissel Matt Robenolt Jacob H.C. Kragh Benjamin Pasero Scott Anderson Yoji SHIDARA Mathias Bynens Łukasz Walukiewicz Artur Adib E. Azer Koçulu Paddy Byers Roman Shtylman Kyle Robinson Young Tim Oxley Eduard Burtescu Ingmar Runge Russ Bradberry Andreas Madsen Adam Malcontenti-Wilson Avi Flax Pedro Teixeira Johan Bergström James Hartig Shannen Saez Seong-Rak Choi Dave Irvine Ju-yeong Park Phil Sung Damon Oehlman Mikael Bourges-Sevenier Emerson Macedo Ryunosuke SATO Michael Bernstein Guillermo Rauch Dan Williams Brandon Benvie Nicolas LaCasse Dan VerWeire Matthew Fitzsimmons Philip Tellis Christopher Jeffrey Seth Fitzsimmons Einar Otto Stangvik Paul Vorbach Luke Gallagher Tomasz Buchert Myles Byrne T.C. Hollingsworth Cam Pedersen Roly Fentanes Ted Young Joshua Holbrook Blake Miner Vincent Ollivier Jimb Esser Sambasiva Suda Sadique Ali Dmitry Nizovtsev Alex Kocharin Ming Liu Shea Levy Nao Iizuka Christian Ress Rod Vagg Matt Ezell Charlie McConnell Farid Neshat Johannes Wüller Erik Lundin Bryan Cantrill Yosef Dinerstein Nathan Friedly Aaron Jacobs Mustansir Golawala Atsuo Fukaya Domenic Denicola Joshua S. Weinstein Dane Springmeyer Erik Dubbelboer Malte-Thorben Bruns Michael Thomas Garen Torikian EungJun Yi Vincent Voyer Takahiro ANDO Brian Schroeder J. Lee Coltrane Javier Hernández James Koval Kevin Gadd Ray Solomon Kevin Bowman Erwin van der Koogh Matt Gollob Simon Sturmer Joel Brandt Marc Harter Nuno Job Ben Kelly Felix Böhm George Shank Gabriel de Perthuis Vladimir Beloborodov Tim Macfarlane Jonas Westerlund Dominic Tarr Justin Plock Timothy J Fontaine Toshihiro Nakamura Ivan Torres Philipp Hagemeister Mike Morearty Pavel Lang Peter Rybin Joe Andaverde Eugen Dueck Gil Pedersen Tyler Neylon Josh Erickson Golo Roden Ron Korving Brandon Wilson Ian Babrou Bearice Ren Ankur Oberoi Atsuya Takagi Pooya Karimian Frédéric Germain Robin Lee Kazuyuki Yamada Adam Blackburn Willi Eggeling Paul Serby Andrew Paprocki Ricky Ng-Adam Aaditya Bhatia Max Ogden Igor Soarez Olivier Lalonde Francois Marier Trevor Norris Kai Sasaki Lewuathe Nicolas Chambrier Tim Bradshaw Johannes Ewald Chris Dent Dan Milon Brandon Philips Frederico Silva Jan Wynholds Girish Ramakrishnan Anthony Pesch Stephen Gallagher Sergey Kholodilov Tim Kuijsten Michael Axiak Chad Rhyner Ben Taber Luke Arduini Luke Bayes Nirk Niggler James Hight Mike Harsch Alexandr Emelin James Campos Dave Olszewski Tim Price Jake Verbaten Jacob Gable Rick Yakubowski Dan Kohn Andy Burke Sugendran Ganess Jim Schubert Victor Costan Arianit Uka Andrei Sedoi Eugene Girshov Evan Oxfeld Lars-Magnus Skog Raymond Feng Aaron Cannon Xidorn Quan Paolo Fragomeni Scott Blomquist Henry Chin Julian Gruber JeongHoon Byun Iskren Ivov Chernev Alexey Kupershtokh Benjamin Ruston Mitar Milutinovic Michael Hart Andrew Hart Rafael Garcia Tobias Müllerleile Stanislav Ochotnicky Ryan Graham Kelly Gerber Ryan Doenges Sean Silva Miroslav Bajtoš Sam Roberts Kevin Locke Daniel Moore Robert Kowalski Benoit Vallée Ryuichi Okumura Brandon Frohs Nathan Zadoks Rafael Henrique Moreira Daniel G. Taylor Kiyoshi Nomo Veres Lajos Yuan Chuan Peter Rust Shuan Wang Andrew Chilton Wyatt Preul Forrest L Norvell Eran Hammer Daniel Chatfield Eivind Uggedal Edward Hutchins Chris Wren Duan Yao Eric Schrock Zarko Stankovic Maxim Bogushevich Phillip Alexander Tim Wood Linus Unnebäck Nikolai Vavilov Michael Ridgway Yazhong Liu Gabriel Falkenberg Kai Groner Gabriel Farrell Nicolas Kaiser Lev Gimelfarb Dav Glass ayanamist Lorenz Leutgeb Brandon Cheng Alexis Campailla node-v0.10.25~dfsg2/README.md0000644000000000000000000000413312270121457014075 0ustar rootrootEvented I/O for V8 javascript. [![Build Status](https://secure.travis-ci.org/joyent/node.png)](http://travis-ci.org/joyent/node) === ### To build: Prerequisites (Unix only): * GCC 4.2 or newer * Python 2.6 or 2.7 * GNU Make 3.81 or newer * libexecinfo (FreeBSD and OpenBSD only) Unix/Macintosh: ./configure make make install If your python binary is in a non-standard location or has a non-standard name, run the following instead: export PYTHON=/path/to/python $PYTHON ./configure make make install Windows: vcbuild.bat You can download pre-built binaries for various operating systems from [http://nodejs.org/download/](http://nodejs.org/download/). The Windows and OS X installers will prompt you for the location to install to. The tarballs are self-contained; you can extract them to a local directory with: tar xzf /path/to/node---.tar.gz Or system-wide with: cd /usr/local && tar --strip-components 1 -xzf \ /path/to/node---.tar.gz ### To run the tests: Unix/Macintosh: make test Windows: vcbuild.bat test ### To build the documentation: make doc ### To read the documentation: man doc/node.1 Resources for Newcomers --- - [The Wiki](https://github.com/joyent/node/wiki) - [nodejs.org](http://nodejs.org/) - [how to install node.js and npm (node package manager)](http://www.joyent.com/blog/installing-node-and-npm/) - [list of modules](https://github.com/joyent/node/wiki/modules) - [searching the npm registry](http://npmjs.org/) - [list of companies and projects using node](https://github.com/joyent/node/wiki/Projects,-Applications,-and-Companies-Using-Node) - [node.js mailing list](http://groups.google.com/group/nodejs) - irc chatroom, [#node.js on freenode.net](http://webchat.freenode.net?channels=node.js&uio=d4) - [community](https://github.com/joyent/node/wiki/Community) - [contributing](https://github.com/joyent/node/wiki/Contributing) - [big list of all the helpful wiki pages](https://github.com/joyent/node/wiki/_pages) node-v0.10.25~dfsg2/BSDmakefile0000644000000000000000000000007512270121457014650 0ustar rootrootall: @echo "I need GNU make. Please run \`gmake\` instead." node-v0.10.25~dfsg2/ChangeLog0000644000000000000000000037420612270121457014403 0ustar rootroot2014.01.23, Version 0.10.25 (Stable) * uv: Upgrade to v0.10.23 * npm: Upgrade to v1.3.24 * v8: Fix enumeration for objects with lots of properties * child_process: fix spawn() optional arguments (Sam Roberts) * cluster: report more errors to workers (Fedor Indutny) * domains: exit() only affects active domains (Ryan Graham) * src: OnFatalError handler must abort() (Timothy J Fontaine) * stream: writes may return false but forget to emit drain (Yang Tianyang) 2013.12.18, Version 0.10.24 (Stable), b7fd6bc899ccb629d790c47aee06aba87e535c41 * uv: Upgrade to v0.10.21 * npm: upgrade to 1.3.21 * v8: backport fix for CVE-2013-{6639|6640} * build: unix install node and dep library headers (Timothy J Fontaine) * cluster, v8: fix --logfile=%p.log (Ben Noordhuis) * module: only cache package main (Wyatt Preul) 2013.12.12, Version 0.10.23 (Stable), 0462bc23564e7e950a70ae4577a840b04db6c7c6 * uv: Upgrade to v0.10.20 (Timothy J Fontaine) * npm: Upgrade to 1.3.17 (isaacs) * gyp: update to 78b26f7 (Timothy J Fontaine) * build: include postmortem symbols on linux (Timothy J Fontaine) * crypto: Make Decipher._flush() emit errors. (Kai Groner) * dgram: fix abort when getting `fd` of closed dgram (Fedor Indutny) * events: do not accept NaN in setMaxListeners (Fedor Indutny) * events: avoid calling `once` functions twice (Tim Wood) * events: fix TypeError in removeAllListeners (Jeremy Martin) * fs: report correct path when EEXIST (Fedor Indutny) * process: enforce allowed signals for kill (Sam Roberts) * tls: emit 'end' on .receivedShutdown (Fedor Indutny) * tls: fix potential data corruption (Fedor Indutny) * tls: handle `ssl.start()` errors appropriately (Fedor Indutny) * tls: reset NPN callbacks after SNI (Fedor Indutny) 2013.11.12, Version 0.10.22 (Stable), cbff8f091c22fb1df6b238c7a1b9145db950fa65 * npm: Upgrade to 1.3.14 * uv: Upgrade to v0.10.19 * child_process: don't assert on stale file descriptor events (Fedor Indutny) * darwin: Fix "Not Responding" in Mavericks activity monitor (Fedor Indutny) * debugger: Fix bug in sb() with unnamed script (Maxim Bogushevich) * repl: do not insert duplicates into completions (Maciej Małecki) * src: Fix memory leak on closed handles (Timothy J Fontaine) * tls: prevent stalls by using read(0) (Fedor Indutny) * v8: use correct timezone information on Solaris (Maciej Małecki) 2013.10.18, Version 0.10.21 (Stable), e2da042844a830fafb8031f6c477eb4f96195210 * uv: Upgrade to v0.10.18 * crypto: clear errors from verify failure (Timothy J Fontaine) * dtrace: interpret two byte strings (Dave Pacheco) * fs: fix fs.truncate() file content zeroing bug (Ben Noordhuis) * http: provide backpressure for pipeline flood (isaacs) * tls: fix premature connection termination (Ben Noordhuis) 2013.09.30, Version 0.10.20 (Stable), d7234c8d50a1af73f60d2d3c0cc7eed17429a481 * tls: fix sporadic hang and partial reads (Fedor Indutny) - fixes "npm ERR! cb() never called!" 2013.09.24, Version 0.10.19 (Stable), 6b5e6a5a3ec8d994c9aab3b800b9edbf1b287904 * uv: Upgrade to v0.10.17 * npm: upgrade to 1.3.11 * readline: handle input starting with control chars (Eric Schrock) * configure: add mips-float-abi (soft, hard) option (Andrei Sedoi) * stream: objectMode transforms allow falsey values (isaacs) * tls: prevent duplicate values returned from read (Nathan Rajlich) * tls: NPN protocols are now local to connections (Fedor Indutny) 2013.09.04, Version 0.10.18 (Stable), 67a1f0c52e0708e2596f3f2134b8386d6112561e * uv: Upgrade to v0.10.15 * stream: Don't crash on unset _events property (isaacs) * stream: Pass 'buffer' encoding with decoded writable chunks (isaacs) 2013.08.21, Version 0.10.17 (Stable), 469a4a5091a677df62be319675056b869c31b35c * uv: Upgrade v0.10.14 * http_parser: Do not accept PUN/GEM methods as PUT/GET (Chris Dickinson) * tls: fix assertion when ssl is destroyed at read (Fedor Indutny) * stream: Throw on 'error' if listeners removed (isaacs) * dgram: fix assertion on bad send() arguments (Ben Noordhuis) * readline: pause stdin before turning off terminal raw mode (Daniel Chatfield) 2013.08.16, Version 0.10.16 (Stable), 50b4c905a4425430ae54db4906f88982309e128d * v8: back-port fix for CVE-2013-2882 * npm: Upgrade to 1.3.8 * crypto: fix assert() on malformed hex input (Ben Noordhuis) * crypto: fix memory leak in randomBytes() error path (Ben Noordhuis) * events: fix memory leak, don't leak event names (Ben Noordhuis) * http: Handle hex/base64 encodings properly (isaacs) * http: improve chunked res.write(buf) performance (Ben Noordhuis) * stream: Fix double pipe error emit (Eran Hammer) 2013.07.25, Version 0.10.15 (Stable) * src: fix process.getuid() return value (Ben Noordhuis) 2013.07.25, Version 0.10.14 (Stable), fdf57f811f9683a4ec49a74dc7226517e32e6c9d * uv: Upgrade to v0.10.13 * npm: Upgrade to v1.3.5 * os: Don't report negative times in cpu info (Ben Noordhuis) * fs: Handle large UID and GID (Ben Noordhuis) * url: Fix edge-case when protocol is non-lowercase (Shuan Wang) * doc: Streams API Doc Rewrite (isaacs) * node: call MakeDomainCallback in all domain cases (Trevor Norris) * crypto: fix memory leak in LoadPKCS12 (Fedor Indutny) 2013.07.09, Version 0.10.13 (Stable), e32660a984427d46af6a144983cf7b8045b7299c * uv: Upgrade to v0.10.12 * npm: Upgrade to 1.3.2 * windows: get proper errno (Ben Noordhuis) * tls: only wait for finish if we haven't seen it (Timothy J Fontaine) * http: Dump response when request is aborted (isaacs) * http: use an unref'd timer to fix delay in exit (Peter Rust) * zlib: level can be negative (Brian White) * zlib: allow zero values for level and strategy (Brian White) * buffer: add comment explaining buffer alignment (Ben Noordhuis) * string_bytes: properly detect 64bit (Timothy J Fontaine) * src: fix memory leak in UsingDomains() (Ben Noordhuis) 2013.06.18, Version 0.10.12 (Stable), a088cf4f930d3928c97d239adf950ab43e7794aa * npm: Upgrade to 1.2.32 * readline: make `ctrl + L` clear the screen (Yuan Chuan) * v8: add setVariableValue debugger command (Ben Noordhuis) * net: Do not destroy socket mid-write (isaacs) * v8: fix build for mips32r2 architecture (Andrei Sedoi) * configure: fix cross-compilation host_arch_cc() (Andrei Sedoi) 2013.06.13, Version 0.10.11 (Stable), d9d5bc465450ae5d60da32e9ffcf71c2767f1fad * uv: upgrade to 0.10.11 * npm: Upgrade to 1.2.30 * openssl: add missing configuration pieces for MIPS (Andrei Sedoi) * Revert "http: remove bodyHead from 'upgrade' events" (isaacs) * v8: fix pointer arithmetic undefined behavior (Trevor Norris) * crypto: fix utf8/utf-8 encoding check (Ben Noordhuis) * net: Fix busy loop on POLLERR|POLLHUP on older linux kernels (Ben Noordhuis, isaacs) 2013.06.04, Version 0.10.10 (Stable), 25e51c396aa23018603baae2b1d9390f5d9db496 * uv: Upgrade to 0.10.10 * npm: Upgrade to 1.2.25 * url: Properly parse certain oddly formed urls (isaacs) * stream: unshift('') is a noop (isaacs) 2013.05.30, Version 0.10.9 (Stable), 878ffdbe6a8eac918ef3a7f13925681c3778060b * npm: Upgrade to 1.2.24 * uv: Upgrade to v0.10.9 * repl: fix JSON.parse error check (Brian White) * tls: proper .destroySoon (Fedor Indutny) * tls: invoke write cb only after opposite read end (Fedor Indutny) * tls: ignore .shutdown() syscall error (Fedor Indutny) 2013.05.24, Version 0.10.8 (Stable), 30d9e9fdd9d4c33d3d95a129d021cd8b5b91eddb * v8: update to 3.14.5.9 * uv: upgrade to 0.10.8 * npm: Upgrade to 1.2.23 * http: remove bodyHead from 'upgrade' events (Nathan Zadoks) * http: Return true on empty writes, not false (isaacs) * http: save roundtrips, convert buffers to strings (Ben Noordhuis) * configure: respect the --dest-os flag consistently (Nathan Rajlich) * buffer: throw when writing beyond buffer (Trevor Norris) * crypto: Clear error after DiffieHellman key errors (isaacs) * string_bytes: strip padding from base64 strings (Trevor Norris) 2013.05.17, Version 0.10.7 (Stable), d2fdae197ac542f686ee06835d1153dd43b862e5 * uv: upgrade to v0.10.7 * npm: Upgrade to 1.2.21 * crypto: Don't ignore verify encoding argument (isaacs) * buffer, crypto: fix default encoding regression (Ben Noordhuis) * timers: fix setInterval() assert (Ben Noordhuis) 2013.05.14, Version 0.10.6 (Stable), 5deb1672f2b5794f8be19498a425ea4dc0b0711f * module: Deprecate require.extensions (isaacs) * stream: make Readable.wrap support objectMode, empty streams (Daniel Moore) * child_process: fix handle delivery (Ben Noordhuis) * crypto: Fix performance regression (isaacs) * src: DRY string encoding/decoding (isaacs) 2013.04.23, Version 0.10.5 (Stable), deeaf8fab978e3cadb364e46fb32dafdebe5f095 * uv: Upgrade to 0.10.5 (isaacs) * build: added support for Visual Studio 2012 (Miroslav Bajtoš) * http: Don't try to destroy nonexistent sockets (isaacs) * crypto: LazyTransform on properties, not methods (isaacs) * assert: put info in err.message, not err.name (Ryan Doenges) * dgram: fix no address bind() (Ben Noordhuis) * handle_wrap: fix NULL pointer dereference (Ben Noordhuis) * os: fix unlikely buffer overflow in os.type() (Ben Noordhuis) * stream: Fix unshift() race conditions (isaacs) 2013.04.11, Version 0.10.4 (Stable), 9712aa9f76073c30850b20a188b1ed12ffb74d17 * uv: Upgrade to 0.10.4 * npm: Upgrade to 1.2.18 * v8: Avoid excessive memory growth in JSON.parse (Fedor Indutny) * child_process, cluster: fix O(n*m) scan of cmd string (Ben Noordhuis) * net: fix socket.bytesWritten Buffers support (Fedor Indutny) * buffer: fix offset checks (Łukasz Walukiewicz) * stream: call write cb before finish event (isaacs) * http: Support write(data, 'hex') (isaacs) * crypto: dh secret should be left-padded (Fedor Indutny) * process: expose NODE_MODULE_VERSION in process.versions (Rod Vagg) * crypto: fix constructor call in crypto streams (Andreas Madsen) * net: account for encoding in .byteLength (Fedor Indutny) * net: fix buffer iteration in bytesWritten (Fedor Indutny) * crypto: zero is not an error if writing 0 bytes (Fedor Indutny) * tls: Re-enable check of CN-ID in cert verification (Tobias Müllerleile) 2013.04.03, Version 0.10.3 (Stable), d4982f6f5e4a9a703127489a553b8d782997ea43 * npm: Upgrade to 1.2.17 * child_process: acknowledge sent handles (Fedor Indutny) * etw: update prototypes to match dtrace provider (Timothy J Fontaine) * dtrace: pass more arguments to probes (Dave Pacheco) * build: allow building with dtrace on osx (Dave Pacheco) * http: Remove legacy ECONNRESET workaround code (isaacs) * http: Ensure socket cleanup on client response end (isaacs) * tls: Destroy socket when encrypted side closes (isaacs) * repl: isSyntaxError() catches "strict mode" errors (Nathan Rajlich) * crypto: Pass options to ctor calls (isaacs) * src: tie process.versions.uv to uv_version_string() (Ben Noordhuis) 2013.03.28, Version 0.10.2 (Stable) * npm: Upgrade to 1.2.15 * uv: Upgrade to 0.10.3 * tls: handle SSL_ERROR_ZERO_RETURN (Fedor Indutny) * tls: handle errors before calling C++ methods (Fedor Indutny) * tls: remove harmful unnecessary bounds checking (Marcel Laverdet) * crypto: make getCiphers() return non-SSL ciphers (Ben Noordhuis) * crypto: check randomBytes() size argument (Ben Noordhuis) * timers: do not calculate Timeout._when property (Alexey Kupershtokh) * timers: fix off-by-one ms error (Alexey Kupershtokh) * timers: handle signed int32 overflow in enroll() (Fedor Indutny) * stream: Fix stall in Transform under very specific conditions (Gil Pedersen) * stream: Handle late 'readable' event listeners (isaacs) * stream: Fix early end in Writables on zero-length writes (isaacs) * domain: fix domain callback from MakeCallback (Trevor Norris) * child_process: don't emit same handle twice (Ben Noordhuis) * child_process: fix sending utf-8 to child process (Ben Noordhuis) 2013.03.21, Version 0.10.1 (Stable), c274d1643589bf104122674a8c3fd147527a667d * npm: upgrade to 1.2.15 * crypto: Improve performance of non-stream APIs (Fedor Indutny) * tls: always reset this.ssl.error after handling (Fedor Indutny) * tls: Prevent mid-stream hangs (Fedor Indutny, isaacs) * net: improve arbitrary tcp socket support (Ben Noordhuis) * net: handle 'finish' event only after 'connect' (Fedor Indutny) * http: Don't hot-path end() for large buffers (isaacs) * fs: Missing cb errors are deprecated, not a throw (isaacs) * fs: make write/appendFileSync correctly set file mode (Raymond Feng) * stream: Return self from readable.wrap (isaacs) * stream: Never call decoder.end() multiple times (Gil Pedersen) * windows: enable watching signals with process.on('SIGXYZ') (Bert Belder) * node: revert removal of MakeCallback (Trevor Norris) * node: Unwrap without aborting in handle fd getter (isaacs) 2013.03.11, Version 0.10.0 (Stable), 163ca274230fce536afe76c64676c332693ad7c1 * npm: Upgrade to 1.2.14 * core: Append filename properly in dlopen on windows (isaacs) * zlib: Manage flush flags appropriately (isaacs) * domains: Handle errors thrown in nested error handlers (isaacs) * buffer: Strip high bits when converting to ascii (Ben Noordhuis) * win/msi: Enable modify and repair (Bert Belder) * win/msi: Add feature selection for various node parts (Bert Belder) * win/msi: use consistent registry key paths (Bert Belder) * child_process: support sending dgram socket (Andreas Madsen) * fs: Raise EISDIR on Windows when calling fs.read/write on a dir (isaacs) * unix: fix strict aliasing warnings, macro-ify functions (Ben Noordhuis) * unix: honor UV_THREADPOOL_SIZE environment var (Ben Noordhuis) * win/tty: fix typo in color attributes enumeration (Bert Belder) * win/tty: don't touch insert mode or quick edit mode (Bert Belder) 2013.03.06, Version 0.9.12 (Unstable), 0debf5a82934da805592b6496756cdf27c993abc * stream: Allow strings in Readable.push/unshift (isaacs) * stream: Remove bufferSize option (isaacs) * stream: Increase highWaterMark on large reads (isaacs) * stream: _write: takes an encoding argument (isaacs) * stream: _transform: remove output() method, provide encoding (isaacs) * stream: Don't require read(0) to emit 'readable' event (isaacs) * node: Add --throw-deprecation (isaacs) * http: fix multiple timeout events (Eugene Girshov) * http: More useful setTimeout API on server (isaacs) * net: use close callback, not process.nextTick (Ben Noordhuis) * net: Provide better error when writing after FIN (isaacs) * dns: Support NAPTR queries (Pavel Lang) * dns: fix ReferenceError in resolve() error path (Xidorn Quan) * child_process: handle ENOENT correctly on Windows (Scott Blomquist) * cluster: Rename destroy() to kill(signal=SIGTERM) (isaacs) * build: define nightly tag external to build system (Timothy J Fontaine) * build: make msi build work when spaces are present in the path (Bert Belder) * build: fix msi build issue with WiX 3.7/3.8 (Raymond Feng) * repl: make compatible with domains (Dave Olszewski) * events: Code cleanup and performance improvements (Trevor Norris) 2013.03.01, Version 0.9.11 (Unstable), 83392403b7a9b7782b37c17688938c75010f81ba * V8: downgrade to 3.14.5 * openssl: update to 1.0.1e * darwin: Make process.title work properly (Ben Noordhuis) * fs: Support mode/flag options to read/append/writeFile (isaacs) * stream: _read() no longer takes a callback (isaacs) * stream: Add stream.unshift(chunk) (isaacs) * stream: remove lowWaterMark feature (isaacs) * net: omit superfluous 'connect' event (Ben Noordhuis) * build, windows: disable SEH (Ben Noordhuis) * core: remove errno global (Ben Noordhuis) * core: Remove the nextTick for running the main file (isaacs) * core: Mark exit() calls with status codes (isaacs) * core: Fix debug signal handler race condition lock (isaacs) * crypto: clear error stack (Ben Noordhuis) * test: optionally set common.PORT via env variable (Timothy J Fontaine) * path: Throw TypeError on non-string args to path.resolve/join (isaacs, Arianit Uka) * crypto: fix uninitialized memory access in openssl (Ben Noordhuis) 2013.02.19, Version 0.9.10 (Unstable) * V8: Upgrade to 3.15.11.15 * npm: Upgrade to 1.2.12 * fs: Change default WriteStream config, increase perf (isaacs) * process: streamlining tick callback logic (Trevor Norris) * stream_wrap, udp_wrap: add read-only fd property (Ben Noordhuis) * buffer: accept negative indices in Buffer#slice() (Ben Noordhuis) * tls: Cycle data when underlying socket drains (isaacs) * stream: read(0) should not always trigger _read(n,cb) (isaacs) * stream: Empty strings/buffers do not signal EOF any longer (isaacs) * crypto: improve cipher/decipher error messages (Ben Noordhuis) * net: Respect the 'readable' flag on sockets (isaacs) * net: don't suppress ECONNRESET (Ben Noordhuis) * typed arrays: copy Buffer in typed array constructor (Ben Noordhuis) * typed arrays: make DataView throw on non-ArrayBuffer (Ben Noordhuis) * windows: MSI installer enhancements (Scott Blomquist, Jim Schubert) 2013.02.07, Version 0.9.9 (Unstable), 4b9f0d190cd6b22853caeb0e07145a98ce1d1d7f * tls: port CryptoStream to streams2 (Fedor Indutny) * typed arrays: only share ArrayBuffer backing store (Ben Noordhuis) * stream: make Writable#end() accept a callback function (Nathan Rajlich) * buffer: optimize 'hex' handling (Ben Noordhuis) * dns, cares: don't filter NOTIMP, REFUSED, SERVFAIL (Ben Noordhuis) * readline: treat bare \r as a line ending (isaacs) * readline: make \r\n emit one 'line' event (Ben Noordhuis) * cluster: support datagram sockets (Bert Belder) * stream: Correct Transform class backpressure (isaacs) * addon: Pass module object to NODE_MODULE init function (isaacs, Rod Vagg) * buffer: slow buffer copy compatibility fix (Trevor Norris) * Add bytesWritten to tls.CryptoStream (Andy Burke) 2013.01.24, Version 0.9.8 (Unstable), 5f2f8400f665dc32c3e10e7d31d53d756ded9156 * npm: Upgrade to v1.2.3 * V8: Upgrade to 3.15.11.10 * streams: Support objects other than Buffers (Jake Verbaten) * buffer: remove float write range checks (Trevor Norris) * http: close connection on 304/204 responses with chunked encoding (Ben Noordhuis) * build: fix build with dtrace support on FreeBSD (Fedor Indutny) * console: Support formatting options in trace() (isaacs) * domain: empty stack on all exceptions (Dave Olszewski) * unix, windows: make uv_*_bind() error codes consistent (Andrius Bentkus) * linux: add futimes() fallback (Ben Noordhuis) 2013.01.18, Version 0.9.7 (Unstable), 9e7bebeb8305edd55735a95955a98fdbe47572e5 * V8: Upgrade to 3.15.11.7 * npm: Upgrade to 1.2.2 * punycode: Upgrade to 1.2.0 (Mathias Bynens) * repl: make built-in modules available by default (Felix Böhm) * windows: add support for '_Total' perf counters (Scott Blomquist) * cluster: make --prof work for workers (Ben Noordhuis) * child_process: do not keep list of sent sockets (Fedor Indutny) * tls: Follow RFC6125 more strictly (Fedor Indutny) * buffer: floating point read/write improvements (Trevor Norris) * TypedArrays: Improve dataview perf without endian param (Dean McNamee) * module: assert require() called with a non-empty string (Felix Böhm, James Campos) * stdio: Set readable/writable flags properly (isaacs) * stream: Properly handle large reads from push-streams (isaacs) 2013.01.11, Version 0.9.6 (Unstable), 9313fdc71ca8335d5e3a391c103230ee6219b3e2 * V8: update to 3.15.11.5 * node: remove ev-emul.h (Ben Noordhuis) * path: make basename and extname ignore trailing slashes (Bert Belder) * typed arrays: fix sunos signed/unsigned char issue (Ben Noordhuis) * child_process: Fix {stdio:'inherit'} regression (Ben Noordhuis) * child_process: Fix pipe() from child stdio streams (Maciej Małecki) * child_process: make fork() execPath configurable (Bradley Meck) * stream: Add readable.push(chunk) method (isaacs) * dtrace: x64 ustack helper (Fedor Indutny) * repl: fix floating point number parsing (Nirk Niggler) * repl: allow overriding builtins (Ben Noordhuis) * net: add localAddress and localPort to Socket (James Hight) * fs: make pool size coincide with ReadStream bufferSize (Shigeki Ohtsu) * typed arrays: implement load and store swizzling (Dean McNamee) * windows: fix perfctr crash on XP and 2003 (Scott Blomquist) * dgram: fix double implicit bind error (Ben Noordhuis) 2012.12.30, Version 0.9.5 (Unstable), 01994e8119c24f2284bac0779b32acb49c95bee7 * assert: improve support for new execution contexts (lukebayes) * domain: use camelCase instead of snake_case (isaacs) * domain: Do not use uncaughtException handler (isaacs) * fs: make 'end' work with ReadStream without 'start' (Ben Noordhuis) * https: optimize createConnection() (Ryunosuke SATO) * buffer: speed up base64 encoding by 20% (Ben Noordhuis) * doc: Colorize API stabilitity index headers in docs (Luke Arduini) * net: socket.readyState corrections (bentaber) * http: Performance enhancements for http under streams2 (isaacs) * stream: fix to emit end event on http.ClientResponse (Shigeki Ohtsu) * stream: fix event handler leak in readstream pipe and unpipe (Andreas Madsen) * build: Support ./configure --tag switch (Maciej Małecki) * repl: don't touch `require.cache` (Nathan Rajlich) * node: Emit 'exit' event when exiting for an uncaught exception (isaacs) 2012.12.21, Version 0.9.4 (Unstable), d86d83c75f6343b5368bb7bd328b4466a035e1d4 * streams: Update all streaming interfaces to use new classes (isaacs) * node: remove idle gc (Ben Noordhuis) * http: protect against response splitting attacks (Bert Belder) * fs: Raise error when null bytes detected in paths (isaacs) * fs: fix 'object is not a function' callback errors (Ben Noordhuis) * fs: add autoClose=true option to fs.createReadStream (Farid Neshat) * process: add getgroups(), setgroups(), initgroups() (Ben Noordhuis) * openssl: optimized asm code on x86 and x64 (Bert Belder) * crypto: fix leak in GetPeerCertificate (Fedor Indutny) * add systemtap support (Jan Wynholds) * windows: add ETW and PerfCounters support (Scott Blomquist) * windows: fix normalization of UNC paths (Bert Belder) * crypto: fix ssl error handling (Sergey Kholodilov) * node: remove eio-emul.h (Ben Noordhuis) * os: add os.endianness() function (Nathan Rajlich) * readline: don't emit "line" events with a trailing '\n' char (Nathan Rajlich) * build: add configure option to generate xcode build files (Timothy J Fontaine) * build: allow linking against system libuv, cares, http_parser (Stephen Gallagher) * typed arrays: add slice() support to ArrayBuffer (Anthony Pesch) * debugger: exit and kill child on SIGTERM or SIGHUP (Fedor Indutny) * url: url.format escapes delimiters in path and query (J. Lee Coltrane) 2012.10.24, Version 0.9.3 (Unstable), 1ed4c6776e4f52956918b70565502e0f8869829d * V8: Upgrade to 3.13.7.4 * crypto: Default to buffers instead of binary strings (isaacs, Fedor Indutny) * crypto: add getHashes() and getCiphers() (Ben Noordhuis) * unix: add custom thread pool, remove libeio (Ben Noordhuis) * util: make `inspect()` accept an "options" argument (Nathan Rajlich) * https: fix renegotation attack protection (Ben Noordhuis) * cluster: make 'listening' handler see actual port (Aaditya Bhatia) * windows: use USERPROFILE to get the user's home dir (Bert Belder) * path: add platform specific path delimiter (Paul Serby) * http: add response.headersSent property (Pavel Lang) * child_process: make .fork()'d child auto-exit (Ben Noordhuis) * events: add 'removeListener' event (Ben Noordhuis) * string_decoder: Add 'end' method, do base64 properly (isaacs) * buffer: include encoding value in exception when invalid (Ricky Ng-Adam) * http: make http.ServerResponse no longer emit 'end' (isaacs) * streams: fix pipe is destructed by 'end' from destination (koichik) 2012.09.17, Version 0.9.2 (Unstable), 6e2055889091a424fbb5c500bc3ab9c05d1c28b4 * http_parser: upgrade to ad3b631 * openssl: upgrade 1.0.1c * darwin: use FSEvents to watch directory changes (Fedor Indutny) * unix: support missing API on NetBSD (Shigeki Ohtsu) * unix: fix EMFILE busy loop (Ben Noordhuis) * windows: un-break writable tty handles (Bert Belder) * windows: map WSAESHUTDOWN to UV_EPIPE (Bert Belder) * windows: make spawn with custom environment work again (Bert Belder) * windows: map ERROR_DIRECTORY to UV_ENOENT (Bert Belder) * tls, https: validate server certificate by default (Ben Noordhuis) * tls, https: throw exception on missing key/cert (Ben Noordhuis) * tls: async session storage (Fedor Indutny) * installer: don't install header files (Ben Noordhuis) * buffer: implement Buffer.prototype.toJSON() (Nathan Rajlich) * buffer: added support for writing NaN and Infinity (koichik) * http: make http.ServerResponse emit 'end' (Ben Noordhuis) * build: ./configure --ninja (Ben Noordhuis, Timothy J Fontaine) * installer: fix --without-npm (Ben Noordhuis) * cli: make -p equivalent to -pe (Ben Noordhuis) * url: Go much faster by using Url class (isaacs) 2012.08.28, Version 0.9.1 (Unstable), e6ce259d2caf338fec991c2dd447de763ce99ab7 * buffer: Add Buffer.isEncoding(enc) to test for valid encoding values (isaacs) * Raise UV_ECANCELED on premature close. (Ben Noordhuis) * Remove c-ares from libuv, move to a top-level node dependency (Bert Belder) * ref/unref for all HandleWraps, timers, servers, and sockets (Timothy J Fontaine) * addon: remove node-waf, superseded by node-gyp (Ben Noordhuis) * child_process: emit error on exec failure (Ben Noordhuis) * cluster: do not use internal server API (Andreas Madsen) * constants: add O_DIRECT (Ian Babrou) * crypto: add sync interface to crypto.pbkdf2() (Ben Noordhuis) * darwin: emulate fdatasync() (Fedor Indutny) * dgram: make .bind() always asynchronous (Ben Noordhuis) * events: Make emitter.listeners() side-effect free (isaacs, Joe Andaverde) * fs: Throw early on invalid encoding args (isaacs) * fs: fix naming of truncate/ftruncate functions (isaacs) * http: bubble up parser errors to ClientRequest (Brian White) * linux: improve cpuinfo parser on ARM and MIPS (Ben Noordhuis) * net: add support for IPv6 addresses ending in :: (Josh Erickson) * net: support Server.listen(Pipe) (Andreas Madsen) * node: don't scan add-on for "init" symbol (Ben Noordhuis) * remove process.uvCounters() (Ben Noordhuis) * repl: console writes to repl rather than process stdio (Nathan Rajlich) * timers: implement setImmediate (Timothy J Fontaine) * tls: fix segfault in pummel/test-tls-ci-reneg-attack (Ben Noordhuis) * tools: Move gyp addon tools to node-gyp (Nathan Rajlich) * unix: preliminary signal handler support (Ben Noordhuis) * unix: remove dependency on ev_child (Ben Noordhuis) * unix: work around darwin bug, don't poll() on pipe (Fedor Indutny) * util: Formally deprecate util.pump() (Ben Noordhuis) * windows: make active and closing handle state independent (Bert Belder) * windows: report spawn errors to the exit callback (Bert Belder) * windows: signal handling support with uv_signal_t (Bert Belder) 2012.07.20, Version 0.9.0 (Unstable), f9b237f478c372fd55e4590d7399dcd8f25f3603 * punycode: update to v1.1.1 (Mathias Bynens) * c-ares: upgrade to 1.9.0 (Saúl Ibarra Corretgé) * dns: ignore rogue DNS servers reported by windows (Saúl Ibarra Corretgé) * unix: speed up uv_async_send() (Ben Noordhuis) * darwin: get cpu model correctly on mac (Xidorn Quan) * nextTick: Handle tick callbacks before any other I/O (isaacs) * Enable color customization of `util.inspect` (Pavel Lang) * tls: Speed and memory improvements (Fedor Indutny) * readline: Use one history item for reentered line (Vladimir Beloborodov) * Fix #3521 Make process.env more like a regular Object (isaacs) 2013.06.13, Version 0.8.25 (maintenance), 0b9bdb2bc7e1c872f0ea4713517fda22a4b0b202 * npm: Upgrade to 1.2.30 * child_process: fix handle delivery (Ben Noordhuis) 2013.06.04, Version 0.8.24 (maintenance), c1a1ab067721ea17ef7b05ec5c68b01321017f05 * npm: Upgrade to v1.2.24 * url: Properly parse certain oddly formed urls (isaacs) * http: Don't try to destroy nonexistent sockets (isaacs) * handle_wrap: fix NULL pointer dereference (Ben Noordhuis) 2013.04.09, Version 0.8.23 (maintenance), c67f8d0500fe15637a623eb759d2ad7eb9fb3b0b * npm: Upgrade to v1.2.18 * http: Avoid EE warning on ECONNREFUSED handling (isaacs) * tls: Re-enable check of CN-ID in cert verification (Tobias Müllerleile) * child_process: fix sending utf-8 to child process (Ben Noordhuis) * crypto: check key type in GetPeerCertificate() (Ben Noordhuis) * win/openssl: mark assembled object files as seh safe (Bert Belder) * windows/msi: fix msi build issue with WiX 3.7/3.8 (Raymond Feng) 2013.03.07, Version 0.8.22 (Stable), 67a4cb4fe8c2346e30ffb83f7178e205cc2dab33 * npm: Update to 1.2.14 * cluster: propagate bind errors (Ben Noordhuis) * crypto: don't assert when calling Cipher#final() twice (Ben Noordhuis) * build, windows: disable SEH (Ben Noordhuis) 2013.02.25, Version 0.8.21 (Stable), 530d8c05d4c546146f18e5ba811d7eb3b7b7c0c5 * http: Do not free the wrong parser on socket close (isaacs) * http: Handle hangup writes more gently (isaacs) * zlib: fix assert on bad input (Ben Noordhuis) * test: add TAP output to the test runner (Timothy J Fontaine) * unix: Handle EINPROGRESS from domain sockets (Ben Noordhuis) 2013.02.15, Version 0.8.20 (Stable), e10c75579b536581ddd7ae4e2c3bf8a9d550d343 * npm: Upgrade to v1.2.11 * http: Do not let Agent hand out destroyed sockets (isaacs) * http: Raise hangup error on destroyed socket write (isaacs) * http: protect against response splitting attacks (Bert Belder) 2013.02.06, Version 0.8.19 (Stable), 53978bdf420622ff0121c63c0338c9e7c2e60869 * npm: Upgrade to v1.2.10 * zlib: pass object size hint to V8 (Ben Noordhuis) * zlib: reduce memory consumption, release early (Ben Noordhuis) * buffer: slow buffer copy compatibility fix (Trevor Norris) * zlib: don't assert on malformed dictionary (Ben Noordhuis) * zlib: don't assert on missing dictionary (Ben Noordhuis) * windows: better ipv6 support (Bert Belder) * windows: add error mappings related to unsupported protocols (Bert Belder) * windows: map ERROR_DIRECTORY to UV_ENOENT (Bert Belder) 2013.01.18, Version 0.8.18 (Stable), 2c4eef0d972838c51999d32c0d251857a713dc18 * npm: Upgrade to v1.2.2 * dns: make error message match errno (Dan Milon) * tls: follow RFC6125 more stricly (Fedor Indutny) * buffer: reject negative SlowBuffer offsets (Ben Noordhuis) * install: add simplejson fallback (Chris Dent) * http: fix "Cannot call method 'emit' of null" (Ben Noordhuis) 2013.01.09, Version 0.8.17 (Stable), c50c33e9397d7a0a8717e8ce7530572907c054ad * npm: Upgrade to v1.2.0 - peerDependencies (Domenic Denicola) - node-gyp v0.8.2 (Nathan Rajlich) - Faster installs from github user/project shorthands (Nathan Zadoks) * typed arrays: fix 32 bit size/index overflow (Ben Noordhuis) * http: Improve performance of single-packet responses (Ben Noordhuis) * install: fix openbsd man page location (Ben Noordhuis) * http: bubble up parser errors to ClientRequest (Brian White) 2012.12.13, Version 0.8.16 (Stable), 1c9c6277d5cfcaaac8569c0c8f7daa64292048a9 * npm: Upgrade to 1.1.69 * fs: fix WriteStream/ReadStream fd leaks (Ben Noordhuis) * crypto: fix leak in GetPeerCertificate (Fedor Indutny) * buffer: Don't double-negate numeric buffer arg (Trevor Norris) * net: More accurate IP address validation and IPv6 dotted notation. (Joshua Erickson) 2012.11.26, Version 0.8.15 (Stable), fdf91afb494a7a2fff2913d817f589c191a2c88f * npm: Upgrade to 1.1.66 (isaacs) * linux: use /proc/cpuinfo for CPU frequency (Ben Noordhuis) * windows: map WSAESHUTDOWN to UV_EPIPE (Ben Noordhuis) * windows: map ERROR_GEN_FAILURE to UV_EIO (Bert Belder) * unix: do not set environ unless one is provided (Charlie McConnell) * domains: don't crash if domain is set to null (Bert Belder) * windows: fix the x64 debug build (Bert Belder) * net, tls: fix connect() resource leak (Ben Noordhuis) 2012.10.25, Version 0.8.14 (Stable), b00527fcf05c3d9f/b5d5d790f9472906a59fe218 * events: Don't clobber pre-existing _events obj in EE ctor (isaacs) 2012.10.25, Version 0.8.13 (Stable), ff4c974873f9a7cc6a5b042eb9b6389bb8dde6d6 * V8: Upgrade to 3.11.10.25 * npm: Upgrade to 1.1.65 * url: parse hostnames that start with - or _ (Ben Noordhuis) * repl: Fix Windows 8 terminal issue (Bert Belder) * typed arrays: use signed char for signed int8s (Aaron Jacobs) * crypto: fix bugs in DiffieHellman (Ben Noordhuis) * configure: turn on VFPv3 on ARMv7 (Ben Noordhuis) * Re-enable OpenSSL UI for entering passphrases via tty (Ben Noordhuis) * repl: ensure each REPL instance gets its own "context" (Nathan Rajlich) 2012.10.12, Version 0.8.12 (Stable), 38c72d4e29574dec5205bcf23c2a85efe65331a4 * npm: Upgrade to 1.1.63 * crypto: Reduce stability index to 2-Unstable (isaacs) * windows: fix handle leak in uv_fs_utime (Bert Belder) * windows: fix application crashed popup in debug version (Bert Belder) * buffer: report proper retained size in profiler (Ben Noordhuis) * buffer: fix byteLength with UTF-16LE (koichik) * repl: make "end of input" JSON.parse() errors throw in the REPL (Nathan Rajlich) * repl: make invalid RegExp modifiers throw in the REPL (Nathan Rajlich) * http: handle multiple Proxy-Authenticate values (Willi Eggeling) 2012.09.27, Version 0.8.11 (Stable), e1f39468fa580c1e4cb15fac621f87944ee625dc * fs: Fix stat() size reporting for large files (Ben Noordhuis) 2012.09.25, Version 0.8.10 (Stable), 0bc273da4fcaa79b209ed755ad249a3e7be626a6 * npm: Upgrade to 1.1.62 * repl: make invalid RegExps throw in the REPL (Nathan Rajlich) * v8: loosen artificial mmap constraint (Bryan Cantrill) * process: fix setuid() and setgid() error reporting (Ben Noordhuis) * domain: Properly exit() on domain disposal (isaacs) * fs: fix watchFile() missing deletion events (Ben Noordhuis) * fs: fix assert in fs.watch() (Ben Noordhuis) * fs: don't segfault on deeply recursive stat() (Ben Noordhuis) * http: Remove timeout handler when data arrives (Frédéric Germain) * http: make the client "res" object gets the same domain as "req" (Nathan Rajlich) * windows: don't blow up when an invalid FD is used (Bert Belder) * unix: map EDQUOT to UV_ENOSPC (Charlie McConnell) * linux: improve /proc/cpuinfo parser (Ben Noordhuis) * win/tty: reset background brightness when color is set to default (Bert Belder) * unix: put child process stdio fds in blocking mode (Ben Noordhuis) * unix: fix EMFILE busy loop (Ben Noordhuis) * sunos: don't set TCP_KEEPALIVE (Ben Noordhuis) * tls: Use slab allocator for memory management (Fedor Indutny) * openssl: Use optimized assembly code for x86 and x64 (Bert Belder) 2012.09.11, Version 0.8.9 (Stable), b88c3902b241cf934e75443b934f2033ad3915b1 * v8: upgrade to 3.11.10.22 * GYP: upgrade to r1477 * npm: Upgrade to 1.1.61 * npm: Don't create world-writable files (isaacs) * windows: fix single-accept mode for shared server sockets (Bert Belder) * windows: fix uninitialized memory access in uv_update_time() (Bert Belder) * windows: don't throw when a signal handler is attached (Bert Belder) * unix: fix memory leak in udp (Ben Noordhuis) * unix: map errno ESPIPE (Ben Noordhuis) * unix, windows: fix memory corruption in fs-poll.c (Ben Noordhuis) * sunos: fix os.cpus() on x86_64 (Ben Noordhuis) * child process: fix processes with IPC channel don't emit 'close' (Bert Belder) * build: add a "--dest-os" option to force a gyp "flavor" (Nathan Rajlich) * build: set `process.platform` to "sunos" on SunOS (Nathan Rajlich) * build: fix `make -j` fails after `make clean` (Bearice Ren) * build: fix openssl configuration for "arm" builds (Nathan Rajlich) * tls: support unix domain socket/named pipe in tls.connect (Shigeki Ohtsu) * https: make https.get() accept a URL (koichik) * http: respect HTTP/1.0 TE header (Ben Noordhuis) * crypto, tls: Domainify setSNICallback, pbkdf2, randomBytes (Ben Noordhuis) * stream.pipe: Don't call destroy() unless it's a function (isaacs) 2012.08.22, Version 0.8.8 (Stable), a299c97bbc701f4d460e91214d7bfe7a9589d361 * V8: upgrade to 3.11.10.19 * npm: upgrade to 1.1.59 * windows: fix uninitialized memory access in uv_update_time() (Bert Belder) * unix, windows: fix memory corruption in fs-poll.c (Ben Noordhuis) * unix: fix integer overflow in uv_hrtime (Tim Holy) * sunos: fix uv_cpu_info() on x86_64 (Ben Noordhuis) * tls: update default cipher list (Ben Noordhuis) * unix: Fix llvm and older gcc duplicate symbol warnings (Bert Belder) * fs: fix use after free in stat watcher (Ben Noordhuis) * build: Fix using manually compiled gcc on OS X (Nathan Rajlich) * windows: make junctions work again (Bert Belder) 2012.08.15, Version 0.8.7 (Stable), f640c5d35cba96634cd8176a525a1d876e361a61 * npm: Upgrade to 1.1.49 * website: download page (Golo Roden) * crypto: fix uninitialized memory access in openssl (Ben Noordhuis) * buffer, crypto: fix buffer decoding (Ben Noordhuis) * build: compile with -fno-tree-vrp when gcc >= 4.0 (Ben Noordhuis) * tls: handle multiple CN fields when verifying cert (Ben Noordhuis) * doc: remove unused util from child_process (Kyle Robinson Young) * build: rework -fvisibility=hidden detection (Ben Noordhuis) * windows: don't duplicate invalid stdio handles (Bert Belder) * windows: fix typos in process-stdio.c (Bert Belder) 2012.08.07, Version 0.8.6 (Stable), 0544a586ca6b6b900a42e164033dbf350765700a * npm: Upgrade to v1.1.48 * Add 'make binary' to build binary tarballs for all Unixes (Nathan Rajlich) * zlib: Emit 'close' on destroy(). (Dominic Tarr) * child_process: Fix stdout=null when stdio=['pipe'] (Tyler Neylon) * installer: prevent ETXTBSY errors (Ben Noordhuis) * installer: honor --without-npm, default install path (Ben Noordhuis) * net: make pause work with connecting sockets (Bert Belder) * installer: fix cross-compile installs (Ben Noordhuis) * net: fix .listen({fd:0}) (Ben Noordhuis) * windows: map WSANO_DATA to UV_ENOENT (Bert Belder) 2012.08.02, Version 0.8.5 (Stable), 9b86a4453f0c76f2707a75c0b2343aba33ec63bc * node: tag Encode and friends NODE_EXTERN (Ben Noordhuis) * fs: fix ReadStream / WriteStream missing callback (Gil Pedersen) * fs: fix readFileSync("/proc/cpuinfo") regression (Ben Noordhuis) * installer: don't assume bash is installed (Ben Noordhuis) * Report errors properly from --eval and stdin (isaacs) * assert: fix throws() throws an error without message property (koichik) * cluster: fix libuv assert in net.listen() (Ben Noordhuis) * build: always link sunos builds with libumem (Trent Mick) * build: improve armv7 / hard-float detection (Adam Malcontenti-Wilson) * https: Use host header as effective servername (isaacs) * sunos: work around OS bug to prevent fs.watch() from spinning (Bryan Cantrill) * linux: fix 'two watchers, one path' segfault (Ben Noordhuis) * windows: fix memory leaks in many fs functions (Bert Belder) * windows: don't allow directories to be opened for writing/appending (Bert Belder) * windows: make fork() work even when not all stdio handles are valid (Bert Belder) * windows: make unlink() not remove mount points, and improve performance (Bert Belder) * build: Sign pkg installer for OS X (isaacs) 2012.07.25, Version 0.8.4 (Stable), f98562fcd7d1cab573ca4dc1612157d6999befd4 * V8: Upgrade to 3.11.10.17 * npm: Upgrade to 1.1.45 * net: fix Socket({ fd: 42 }) api (Ben Noordhuis) * readline: Remove event listeners on close (isaacs) * windows: correctly prep long path for fs.exists(Sync) (Bert Belder) * debugger: wake up the event loop when a debugger command is dispatched (Peter Rybin) * tls: verify server's identity (Fedor Indutny) * net: ignore socket.setTimeout(Infinity or NaN) (Fedor Indutny) 2012.07.19, Version 0.8.3 (Stable), 60bf2d6cb33e4ce55604f73889ab840a9de8bdab * V8: upgrade to 3.11.10.15 * npm: Upgrade to 1.1.43 * net: fix net.Server.listen({fd:x}) error reporting (Ben Noordhuis) * net: fix bogus errno reporting (Ben Noordhuis) * build: Move npm shebang logic into an npm script (isaacs) * build: fix add-on loading on freebsd (Ben Noordhuis) * build: disable unsafe optimizations (Ben Noordhuis) * build: fix spurious mksnapshot crashes for good (Ben Noordhuis) * build: speed up genv8constants (Dave Pacheco) * fs: make unwatchFile() remove a specific listener (Ben Noordhuis) * domain: Remove first arg from intercepted fn (Toshihiro Nakamura) * domain: Fix memory leak on error (isaacs) * events: Fix memory leak from removeAllListeners (Nathan Rajlich) * zlib: Fix memory leak in Unzip class. (isaacs) * crypto: Fix memory leak in DecipherUpdate() (Ben Noordhuis) 2012.07.09, Version 0.8.2 (Stable), cc6084b9ac5cf1d4fe5e7165b71e8fc05d11be1f * npm: Upgrade to 1.1.36 * readline: don't use Function#call() (Nathan Rajlich) * Code cleanup to pass 'use strict' (Jonas Westerlund) * module: add filename to require() json errors (TJ Holowaychuk) * readline: fix for unicode prompts (Tim Macfarlane) * timers: fix handling of large timeouts (Ben Noordhuis) * repl: fix passing an empty line inserting "undefined" into the buffer (Nathan Rajlich) * repl: fix crashes when buffering command (Maciej Małecki) * build: rename strict_aliasing to node_no_strict_aliasing (Ben Noordhuis) * build: disable -fstrict-aliasing for any gcc < 4.6.0 (Ben Noordhuis) * build: detect cc version with -dumpversion (Ben Noordhuis) * build: handle output of localized gcc or clang (Ben Noordhuis) * unix: fix memory corruption in freebsd.c (Ben Noordhuis) * unix: fix 'zero handles, one request' busy loop (Ben Noordhuis) * unix: fix busy loop on unexpected tcp message (Ben Noordhuis) * unix: fix EINPROGRESS busy loop (Ben Noordhuis) 2012.06.29, Version 0.8.1 (stable), 2134aa3d5c622fc3c3b02ccb713fcde0e0df479a * V8: upgrade to v3.11.10.12 * npm: upgrade to v1.1.33 - Support for parallel use of the cache folder - Retry on registry timeouts or network failures (Trent Mick) - Reduce 'engines' failures to a warning - Use new zsh completion if aviailable (Jeremy Cantrell) * Fix #3577 Un-break require('sys') * util: speed up formatting of large arrays/objects (Ben Noordhuis) * windows: make fs.realpath(Sync) work with UNC paths (Bert Belder) * build: fix --shared-v8 option (Ben Noordhuis) * doc: `detached` is a boolean (Andreas Madsen) * build: use proper python interpreter (Ben Noordhuis) * build: expand ~ in `./configure --prefix=~/a/b/c` (Ben Noordhuis) * build: handle CC env var with spaces (Gabriel de Perthuis) * build: fix V8 build when compiling with gcc 4.5 (Ben Noordhuis) * build: fix --shared-v8 option (Ben Noordhuis) * windows msi: Fix icon issue which caused huge file size (Bert Belder) * unix: assume that dlopen() may clobber dlerror() (Ben Noordhuis) * sunos: fix memory corruption bugs (Ben Noordhuis) * windows: better (f)utimes and (f)stat (Bert Belder) 2012.06.25, Version 0.8.0 (stable), 8b8a7a7f9b41e74e1e810d0330738ad06fc302ec * V8: upgrade to v3.11.10.10 * npm: Upgrade to 1.1.32 * Deprecate iowatcher (Ben Noordhuis) * windows: update icon (Bert Belder) * http: Hush 'MUST NOT have a body' warnings to debug() (isaacs) * Move blog.nodejs.org content into repository (isaacs) * Fix #3503: stdin: resume() on pipe(dest) (isaacs) * crypto: fix error reporting in SetKey() (Fedor Indutny) * Add --no-deprecation and --trace-deprecation command-line flags (isaacs) * fs: fix fs.watchFile() (Ben Noordhuis) * fs: Fix fs.readfile() on pipes (isaacs) * Rename GYP variable node_use_system_openssl to be consistent (Ryan Dahl) 2012.06.19, Version 0.7.12 (unstable), a72120190a8ffdbcd3d6ad2a2e6ceecd2087111e * npm: Upgrade to 1.1.30 - Improved 'npm init' - Fix the 'cb never called' error from 'oudated' and 'update' - Add --save-bundle|-B config - Fix isaacs/npm#2465: Make npm script and windows shims cygwin-aware - Fix isaacs/npm#2452 Use --save(-dev|-optional) in npm rm - `logstream` option to replace removed `logfd` (Rod Vagg) - Read default descriptions from README.md files * Shims to support deprecated ev_* and eio_* methods (Ben Noordhuis) * #3118 net.Socket: Delay pause/resume until after connect (isaacs) * #3465 Add ./configure --no-ifaddrs flag (isaacs) * child_process: add .stdin stream to forks (Fedor Indutny) * build: fix `make install DESTDIR=/path` (Ben Noordhuis) * tls: fix off-by-one error in renegotiation check (Ben Noordhuis) * crypto: Fix diffie-hellman key generation UTF-8 errors (Fedor Indutny) * node: change the constructor name of process from EventEmitter to process (Andreas Madsen) * net: Prevent property access throws during close (Reid Burke) * querystring: improved speed and code cleanup (Felix Böhm) * sunos: fix assertion errors breaking fs.watch() (Fedor Indutny) * unix: stat: detect sub-second changes (Ben Noordhuis) * add stat() based file watcher (Ben Noordhuis) 2012.06.15, Version 0.7.11 (unstable), 5cfe0b86d5be266ef51bbba369c39e412ee51944 * V8: Upgrade to v3.11.10 * npm: Upgrade to 1.1.26 * doc: Improve cross-linking in API docs markdown (Ben Kelly) * Fix #3425: removeAllListeners should delete array (Reid Burke) * cluster: don't silently drop messages when the write queue gets big (Bert Belder) * Add Buffer.concat method (isaacs) * windows: make symlinks tolerant to forward slashes (Bert Belder) * build: Add node.d and node.1 to installer (isaacs) * cluster: rename worker.unqiueID to worker.id (Andreas Madsen) * Windows: Enable ETW events on Windows for existing DTrace probes. (Igor Zinkovsky) * test: bundle node-weak in test/gc so that it doesn't need to be downloaded (Nathan Rajlich) * Make many tests pass on Windows (Bert Belder) * Fix #3388 Support listening on file descriptors (isaacs) * Fix #3407 Add os.tmpDir() (isaacs) * Unbreak the snapshotted build on Windows (Bert Belder) * Clean up child_process.kill throws (Bert Belder) * crypto: make cipher/decipher accept buffer args (Ben Noordhuis) 2012.06.11, Version 0.7.10 (unstable), 12a32a48a30182621b3f8e9b9695d1946b53c131 * Roll V8 back to 3.9.24.31 * build: x64 target should always pass -m64 (Robert Mustacchi) * add NODE_EXTERN to node::Start (Joel Brandt) * repl: Warn about running npm commands (isaacs) * slab_allocator: fix crash in dtor if V8 is dead (Ben Noordhuis) * slab_allocator: fix leak of Persistent handles (Shigeki Ohtsu) * windows/msi: add node.js prompt to startmenu (Jeroen Janssen) * windows/msi: fix adding node to PATH (Jeroen Janssen) * windows/msi: add start menu links when installing (Jeroen Janssen) * windows: don't install x64 version into the 'program files (x86)' folder (Matt Gollob) * domain: Fix #3379 domain.intercept no longer passes error arg to cb (Marc Harter) * fs: make callbacks run in global context (Ben Noordhuis) * fs: enable fs.realpath on windows (isaacs) * child_process: expose UV_PROCESS_DETACHED as options.detached (Charlie McConnell) * child_process: new stdio API for .spawn() method (Fedor Indutny) * child_process: spawn().ref() and spawn().unref() (Fedor Indutny) * Upgrade npm to 1.1.25 - Enable npm link on windows - Properly remove sh-shim on Windows - Abstract out registry client and logger 2012.05.28, Version 0.7.9 (unstable), 782277f11a753ded831439ed826448c06fc0f356 * Upgrade V8 to 3.11.1 * Upgrade npm to 1.1.23 * uv: rework reference counting scheme (Ben Noordhuis) * uv: add interface for joining external event loops (Bert Belder) * repl, readline: Handle Ctrl+Z and SIGCONT better (Nathan Rajlich) * fs: 64bit offsets for fs calls (Igor Zinkovsky) * fs: add sync open flags 'rs' and 'rs+' (Kevin Bowman) * windows: enable creating directory junctions with fs.symlink (Igor Zinkovsky, Bert Belder) * windows: fix fs.lstat to properly detect symlinks. (Igor Zinkovsky) * Fix #3270 Escape url.parse delims (isaacs) * http: make http.get() accept a URL (Adam Malcontenti-Wilson) * Cleanup vm module memory leakage (Marcel Laverdet) * Optimize writing strings with Socket.write (Bert Belder) * add support for CESU-8 and UTF-16LE encodings (koichik) * path: add path.sep to get the path separator. (Yi, EungJun) * net, http: add backlog parameter to .listen() (Erik Dubbelboer) * debugger: support mirroring Date objects (Fedor Indutny) * addon: add AtExit() function (Ben Noordhuis) * net: signal localAddress bind failure in connect (Brian Schroeder) * util: handle non-string return value in .inspect() (Alex Kocharin) 2012.04.18, Version 0.7.8 (unstable), c2b47097c0b483552efc1947c6766fa1128600b6 * Upgrade V8 to 3.9.24.9 * Upgrade OpenSSL to 1.0.0f * Upgrade npm to 1.1.18 * Show licenses in Binary installers * Domains (isaacs) * readline: rename "end" to "close" (Nathan Rajlich) * tcp: make getsockname() return address family as string (Shigeki Ohtsu) * http, https: fix .setTimeout() (ssuda) * os: add cross platform EOL character (Mustansir Golawala) * typed arrays: unexport SizeOfArrayElementForType() (Aaron Jacobs) * net: honor 'enable' flag in .setNoDelay() (Ben Noordhuis) * child_process: emit error when .kill fails (Andreas Madsen) * gyp: fix 'argument list too long' build error (Ben Noordhuis) * fs.WriteStream: Handle modifications to fs.open (isaacs) * repl, readline: Handle newlines better (Nathan Rajlich, Nathan Friedly) * build: target OSX 10.5 when building on darwin (Nathan Rajlich) * Fix #3052 Handle errors properly in zlib (isaacs) * build: add support for DTrace and postmortem (Dave Pacheco) * core: add reusable Slab allocator (Ben Noordhuis) 2012.03.30, Version 0.7.7 (unstable), 5cda2542fdb086f9fe5de889bea435a65e377dea * Upgrade V8 to 3.9.24.7 * Upgrade npm to 1.1.15 * Handle Emoji characters properly (Erik Corry, Bert Belder) * readline: migrate ansi/vt100 logic from tty to readline (Nathan Rajlich) * readline: Fix multiline handling (Alex Kocharin) * add a -i/--interactive flag to force the REPL (Nathan Rajlich) * debugger: add breakOnException command (Fedor Indutny) * cluster: kill workers when master dies (Andreas Madsen) * cluster: add graceful disconnect support (Andreas Madsen) * child_process: Separate 'close' event from 'exit' (Charlie McConnell) * typed arrays: add Uint8ClampedArray (Mikael Bourges-Sevenier) * buffer: Fix byte alignment issues (Ben Noordhuis, Erik Lundin) * tls: fix CryptoStream.setKeepAlive() (Shigeki Ohtsu) * Expose http parse error codes (Felix Geisendörfer) * events: don't delete the listeners array (Ben Noordhuis, Nathan Rajlich) * process: add process.config to view node's ./configure settings (Nathan Rajlich) * process: process.execArgv to see node's arguments (Micheil Smith) * process: fix process.title setter (Ben Noordhuis) * timers: handle negative or non-numeric timeout values (Ben Noordhuis) 2012.03.13, Version 0.7.6 (unstable), f06abda6f58e517349d1b63a2cbf5a8d04a03505 * Upgrade v8 to 3.9.17 * Upgrade npm to 1.1.8 - Add support for os/cpu fields in package.json (Adam Blackburn) - Automatically node-gyp packages containing a binding.gyp - Fix failures unpacking in UNC shares - Never create un-listable directories - Handle cases where an optionalDependency fails to build * events: newListener emit correct fn when using 'once' (Roly Fentanes) * url: Ignore empty port component (Łukasz Walukiewicz) * module: replace 'children' array (isaacs) * tls: parse multiple values of a key in ssl certificate (Sambasiva Suda) * cluster: support passing of named pipes (Ben Noordhuis) * Windows: include syscall in fs errors (Bert Belder) * http: #2888 Emit end event only once (Igor Zinkovsky) * readline: add multiline support (Rlidwka) * process: add `process.hrtime()` (Nathan Rajlich) * net, http, https: add localAddress option (Dmitry Nizovtsev) * addon improvements (Nathan Rajlich) * build improvements (Ben Noordhuis, Sadique Ali, T.C. Hollingsworth, Nathan Rajlich) * add support for "SEARCH" request methods (Nathan Rajlich) * expose the zlib and http_parser version in process.versions (Nathan Rajlich) 2012.02.23, Version 0.7.5 (unstable), d384b8b0d2ab7f05465f0a3e15fe20b4e25b5f86 * startup speed improvements (Maciej Małecki) * crypto: add function getDiffieHellman() (Tomasz Buchert) * buffer: support decoding of URL-safe base64 (Ben Noordhuis) * Make QueryString.parse() even faster (Brian White) * url: decode url entities in auth section (Ben Noordhuis) * http: support PURGE request method (Ben Noordhuis) * http: Generate Date headers on responses (Mark Nottingham) * Fix #2762: Add callback to close function. (Mikeal Rogers) * dgram: fix out-of-bound memory read (Ben Noordhuis) * repl: add automatic loading of built-in libs (Brandon Benvie) * repl: remove double calls where possible (Fedor Indutny) * Readline improvements. Related: #2737 #2756 (Colton Baker) * build: disable -fomit-frame-pointer on solaris (Dave Pacheco) * build: arch detection improvements (Nathan Rajlich) * build: Make a fat binary for the OS X `make pkg`. (Nathan Rajlich) * jslint src/ and lib/ on 'make test' (isaacs) 2012.02.14, Version 0.7.4 (unstable), de21de920cf93ec40736ada3792a7f85f3eadeda * Upgrade V8 to 3.9.5 * Upgrade npm to 1.1.1 * build: Detect host_arch better (Karl Skomski) * debugger: export `debug_port` to `process` (Fedor Indutny) * api docs: CSS bug fixes (isaacs) * build: use -fPIC for native addons on UNIX (Nathan Rajlich) * Re-add top-level v8::Locker (Marcel Laverdet) * Move images out of the dist tarballs (isaacs) * libuv: Remove uv_export and uv_import (Ben Noordhuis) * build: Support x64 build on Windows (Igor Zinkovsky) 2012.02.07, Version 0.7.3 (unstable), 99059aad8d654acda4abcfaa68df182b50f2ec90 * Upgrade V8 to 3.9.2 * Revert support for isolates. (Ben Noordhuis) * cluster: Cleanup docs, event handling, and process.disconnect (Andreas Madsen) * gyp_addon: link with node.lib on Windows (Nathan Rajlich) * http: fix case where http-parser is freed twice (koichik) * Windows: disable RTTI and exceptions (Bert Belder) 2012.02.01, Version 0.7.2 (unstable), ec79acb3a6166e30f0bf271fbbfda1fb575b3321 * Update V8 to 3.8.9 * Support for sharing streams across Isolates (Igor Zinkovsky) * #2636 - Fix case where http_parsers are freed too early (koichik) * url: Support for IPv6 addresses in URLs (Łukasz Walukiewicz) * child_process: Add disconnect() method to child processes (Andreas Madsen) * fs: add O_EXCL support, exclusive open file (Ben Noordhuis) * fs: more specific error messages (Tj Holowaychuk) * tty: emit 'unknown' key event if key sequence not found (Dan VerWeire, Nathan Rajlich) * build: compile release build too if BUILDTYPE=Debug (Ben Noordhuis) * module: fix --debug-brk on symlinked scripts (Fedor Indutny) * zlib: fix `Failed to set dictionary` issue (Fedor Indutny) * waf: predict target arch for OS X (Fedor Indutny) 2012.01.23, Version 0.7.1 (unstable), a74354735ab5d5b0fa35a1e4ff7e653757d2069b * Update V8 to 3.8.8 * Install node-waf by default (Fedor Indutny) * crypto: Add ability to turn off PKCS padding (Ingmar Runge) * v8: implement VirtualMemory class on SunOS (Ben Noordhuis) * Add cluster.setupMaster (Andreas Madsen) * move `path.exists*` to `fs.exists*` (Maciej Małecki) * typed arrays: set class name (Ben Noordhuis) * libuv bug fixes (Igor Zinkovsky, Ben Noordhuis, Dan VerWeire) 2012.01.16, Version 0.7.0 (unstable), 9cc55dca6f67a6096c858b841c677b0593404321 * Upgrade V8 to 3.8.6 * Use GYP build system on unix (Ben Noordhuis) * Experimenetal isolates support (Ben Noordhuis) * Improvements to Cluster API (Andreas Madsen) * Use isolates for internal debugger (Fedor Indutny) * Bug fixes 2012.07.10 Version 0.6.20 (maintenance), 952e513379169ec1b40909d1db056e9bf4294899 * npm: Upgrade to 1.1.37 (isaacs) * benchmark: Backport improvements made in master (isaacs) * build: always link with -lz (Trent Mick) * core: use proper #include directives (Ben Noordhuis) * cluster: don't silently drop messages when the write queue gets big (Bert Belder) * windows: don't print error when GetConsoleTitleW returns an empty string (Bert Belder) 2012.06.06 Version 0.6.19 (stable), debf552ed2d4a53957446e82ff3c52a8182d5ff4 * npm: upgrade to 1.1.24 * fs: no end emit after createReadStream.pause() (Andreas Madsen) * vm: cleanup module memory leakage (Marcel Laverdet) * unix: fix loop starvation under high network load (Ben Noordhuis) * unix: remove abort() in ev_unref() (Ben Noordhuis) * windows/tty: never report error after forcibly aborting line-buffered read (Bert Belder) * windows: skip GetFileAttributes call when opening a file (Bert Belder) 2012.05.15 Version 0.6.18 (stable), 4bc1d395de6abed2cf1e4d0b7b3a1480a21c368f * windows: skip GetFileAttributes call when opening a file (Bert Belder) * crypto: add PKCS12/PFX support (Sambasiva Suda) * #3240: child_process: delete NODE_CHANNEL_FD from env in spawn (Ben Noordhuis) * windows: add test for path.normalize with UNC paths (Bert Belder) * windows: make path.normalize convert all slashes to backslashes (Bert Belder) * fs: Automatically close FSWatcher on error (Bert Belder) * #3258: fs.ReadStream.pause() emits duplicate data event (koichik) * pipe_wrap: don't assert() on pipe accept errors (Ben Noordhuis) * Better exception output for module load and process.nextTick (Felix Geisendörfer) * zlib: fix error reporting (Ben Noordhuis) * http: Don't destroy on timeout (isaacs) * #3231: http: Don't try to emit error on a null'ed req object (isaacs) * #3236: http: Refactor ClientRequest.onSocket (isaacs) 2012.05.04 Version 0.6.17 (stable), 4ced23deaf36493f4303a18f6fdce768c58becc0 * Upgrade npm to 1.1.21 * uv: Add support for EROFS errors (Ben Noordhuis, Maciej Małecki) * uv: Add support for EIO and ENOSPC errors (Fedor Indutny) * windows: Add support for EXDEV errors (Bert Belder) * http: Fix client memory leaks (isaacs, Vincent Voyer) * fs: fix file descriptor leak in sync functions (Ben Noordhuis) * fs: fix ReadStream / WriteStream double close bug (Ben Noordhuis) 2012.04.30 Version 0.6.16 (stable), a1d193963ddc80a27da5da01b59751e14e33d1d6 * Upgrade V8 to 3.6.6.25 * Upgrade npm to 1.1.19 * Windows: add mappings for UV_ENOENT (Bert Belder) * linux: add IN_MOVE_SELF to inotify event mask (Ben Noordhuis) * unix: call pipe handle connection cb on accept() error (Ben Noordhuis) * unix: handle EWOULDBLOCK (Ben Noordhuis) * map EWOULDBLOCK to UV_EAGAIN (Ben Noordhuis) * Map ENOMEM to UV_ENOMEM (isaacs) * Child process: support the `gid` and `uid` options (Bert Belder) * test: cluster: add worker death event test (Ben Noordhuis) * typo in node_http_parser (isaacs) * http_parser: Eat CRLF between requests, even on connection:close. (Ben Noordhuis) * don't check return value of unsetenv (Ben Noordhuis) 2012.04.09 Version 0.6.15 (stable), f160a45b254e591eb33716311c92be533c6d86c4 * Update npm to 1.1.16 * Show licenses in binary installers. * unix: add uv_fs_read64, uv_fs_write64 and uv_fs_ftruncate64 (Ben Noordhuis) * add 64bit offset fs functions (Igor Zinkovsky) * windows: don't report ENOTSOCK when attempting to bind an udp handle twice (Bert Belder) * windows: backport pipe-connect-to-file fixes from master (Bert Belder) * windows: never call fs event callbacks after closing the watcher (Bert Belder) * fs.readFile: don't make the callback before the fd is closed (Bert Belder) * windows: use 64bit offsets for uv_fs apis (Igor Zinkovsky) * Fix #2061: segmentation fault on OS X due to stat size mismatch (Ben Noordhuis) 2012.03.22 Version 0.6.14 (stable), e513ffef7549a56a5af728e1f0c2c0c8f290518a * net: don't crash when queued write fails (Igor Zinkovsky) * sunos: fix EMFILE on process.memoryUsage() (Bryan Cantrill) * crypto: fix compile-time error with openssl 0.9.7e (Ben Noordhuis) * unix: ignore ECONNABORTED errors from accept() (Ben Noordhuis) * Add UV_ENOSPC and mappings to it (Bert Belder) * http-parser: Fix response body is not read (koichik) * Upgrade npm to 1.1.12 - upgrade node-gyp to 0.3.7 - work around AV-locked directories on Windows - Fix isaacs/npm#2293 Don't try to 'uninstall' / - Exclude symbolic links from packages. - Fix isaacs/npm#2275 Spurious 'unresolvable cycle' error. - Exclude/include dot files as if they were normal files 2012.03.15 Version 0.6.13 (stable), 9f7f86b534f8556290eb8cad915984ff4ca54996 * Windows: Many libuv test fixes (Bert Belder) * Windows: avoid uv_guess_handle crash in when fd < 0 (Bert Belder) * Map EBUSY and ENOTEMPTY errors (Bert Belder) * Windows: include syscall in fs errors (Bert Belder) * Fix fs.watch ENOSYS on Linux kernel version mismatch (Ben Noordhuis) * Update npm to 1.1.9 - upgrade node-gyp to 0.3.5 (Nathan Rajlich) - Fix isaacs/npm#2249 Add cache-max and cache-min configs - Properly redirect across https/http registry requests - log config usage if undefined key in set function (Kris Windham) - Add support for os/cpu fields in package.json (Adam Blackburn) - Automatically node-gyp packages containing a binding.gyp - Fix failures unpacking in UNC shares - Never create un-listable directories - Handle cases where an optionalDependency fails to build 2012.03.02 Version 0.6.12 (stable), 48a2d34cfe6b7e1c9d15202a4ef5e3c82d1fba35 * Upgrade V8 to 3.6.6.24 * dtrace ustack helper improvements (Dave Pacheco) * API Documentation refactor (isaacs) * #2827 net: fix race write() before and after connect() (koichik) * #2554 #2567 throw if fs args for 'start' or 'end' are strings (AJ ONeal) * punycode: Update to v1.0.0 (Mathias Bynens) * Make a fat binary for the OS X pkg (isaacs) * Fix hang on accessing process.stdin (isaacs) * repl: make tab completion work on non-objects (Nathan Rajlich) * Fix fs.watch on OS X (Ben Noordhuis) * Fix #2515 nested setTimeouts cause premature process exit (Ben Noordhuis) * windows: fix time conversion in stat (Igor Zinkovsky) * windows: fs: handle EOF in read (Brandon Philips) * windows: avoid IOCP short-circuit on non-ifs lsps (Igor Zinkovsky) * Upgrade npm to 1.1.4 (isaacs) - windows fixes - Bundle nested bundleDependencies properly - install: support --save with url install targets - shrinkwrap: behave properly with url-installed modules - support installing uncompressed tars or single file modules from urls etc. - don't run make clean on rebuild - support HTTPS-over-HTTP proxy tunneling 2012.02.17 Version 0.6.11 (stable), 1eb1fe32250fc88cb5b0a97cddf3e02be02e3f4a * http: allow multiple WebSocket RFC6455 headers (Einar Otto Stangvik) * http: allow multiple WWW-Authenticate headers (Ben Noordhuis) * windows: support unicode argv and environment variables (Bert Belder) * tls: mitigate session renegotiation attacks (Ben Noordhuis) * tcp, pipe: don't assert on uv_accept() errors (Ben Noordhuis) * tls: Allow establishing secure connection on the existing socket (koichik) * dgram: handle close of dgram socket before DNS lookup completes (Seth Fitzsimmons) * windows: Support half-duplex pipes (Igor Zinkovsky) * build: disable omit-frame-pointer on solaris systems (Dave Pacheco) * debugger: fix --debug-brk (Ben Noordhuis) * net: fix large file downloads failing (koichik) * fs: fix ReadStream failure to read from existing fd (Christopher Jeffrey) * net: destroy socket on DNS error (Stefan Rusu) * dtrace: add missing translator (Dave Pacheco) * unix: don't flush tty on switch to raw mode (Ben Noordhuis) * windows: reset brightness when reverting to default text color (Bert Belder) * npm: update to 1.1.1 - Update which, fstream, mkdirp, request, and rimraf - Fix #2123 Set path properly for lifecycle scripts on windows - Mark the root as seen, so we don't recurse into it. Fixes #1838. (Martin Cooper) 2012.02.02, Version 0.6.10 (stable), 051908e023f87894fa68f5b64d0b99a19a7db01e * Update V8 to 3.6.6.20 * Add npm msysgit bash shim to msi installer (isaacs) * buffers: fix intermittent out of bounds error (Ben Noordhuis) * buffers: honor length argument in base64 decoder (Ben Noordhuis) * windows: Fix path.exists regression (Bert Belder) * Make QueryString.parse run faster (Philip Tellis) * http: avoid freeing http-parser objects too early (koichik) * timers: add v0.4 compatibility hack (Ben Noordhuis) * Proper EPERM error code support (Igor Zinkovsky, Brandon Philips) * dgram: Implement udp multicast methods on windows (Bert Belder) 2012.01.27, Version 0.6.9 (stable), f19e20d33f57c4d2853aaea7d2724d44f3b0012f * dgram: Bring back missing functionality for Unix (Dan VerWeire, Roman Shtylman, Ben Noordhuis) - Note: Windows UDP support not yet complete. * http: Fix parser memory leak (koichik) * zlib: Fix #2365 crashes on invalid input (Nicolas LaCasse) * module: fix --debug-brk on symlinked scripts (Fedor Indutny) * Documentation Restyling (Matthew Fitzsimmons) * Update npm to 1.1.0-3 (isaacs) * Windows: fix regression in stat() calls to C:\ (Bert Belder) 2012.01.19, Version 0.6.8 (stable), d18cebaf8a7ac701dabd71a3aa4eb0571db6a645 * Update V8 to 3.6.6.19 * Numeric key hash collision fix for V8 (Erik Corry, Fedor Indutny) * Add missing TTY key translations for F1-F5 on Windows (Brandon Benvie) * path.extname bugfix with . and .. paths (Bert Belder) * cluster: don't always kill the master on uncaughtException (Ben Noordhuis) * Update npm to 1.1.0-2 (isaacs) * typed arrays: set class name (Ben Noordhuis) * zlib binding cleanup (isaacs, Bert Belder) * dgram: use slab memory allocator (Michael Bernstein) * fix segfault #2473 * #2521 60% improvement in fs.stat on Windows (Igor Zinkovsky) 2012.01.06, Version 0.6.7 (stable), d5a189acef14a851287ee555f7a39431fe276e1c * V8 hash collision fix (Breaks MIPS) (Bert Belder, Erik Corry) * Upgrade V8 to 3.6.6.15 * Upgrade npm to 1.1.0-beta-10 (isaacs) * many doc updates (Ben Noordhuis, Jeremy Martin, koichik, Dave Irvine, Seong-Rak Choi, Shannen, Adam Malcontenti-Wilson, koichik) * Fix segfault in node_http_parser.cc * dgram, timers: fix memory leaks (Ben Noordhuis, Yoshihiro Kikuchi) * repl: fix repl.start not passing the `ignoreUndefined` arg (Damon Oehlman) * #1980: Socket.pause null reference when called on a closed Stream (koichik) * #2263: XMLHttpRequest piped in a writable file stream hang (koichik) * #2069: http resource leak (koichik) * buffer.readInt global pollution fix (Phil Sung) * timers: fix performance regression (Ben Noordhuis) * #2308, #2246: node swallows openssl error on request (koichik) * #2114: timers: remove _idleTimeout from item in .unenroll() (James Hartig) * #2379: debugger: Request backtrace w/o refs (Fedor Indutny) * simple DTrace ustack helper (Dave Pacheco) * crypto: rewrite HexDecode without snprintf (Roman Shtylman) * crypto: don't ignore DH init errors (Ben Noordhuis) 2011.12.14, Version 0.6.6 (stable), 9a059ea69e1f6ebd8899246682d8ca257610b8ab * npm update to 1.1.0-beta-4 (Isaac Z. Schlueter) * cli: fix output of --help (Ben Noordhuis) * new website * pause/resume semantics for stdin (Isaac Z. Schlueter) * Travis CI integration (Maciej Małecki) * child_process: Fix bug regarding closed stdin (Ben Noordhuis) * Enable upgrades in MSI. (Igor Zinkovsky) * net: Fixes memory leak (Ben Noordhuis) * fs: handle fractional or NaN ReadStream buffer size (Ben Noordhuis) * crypto: fix memory leaks in PBKDF2 error path (Ben Noordhuis) 2011.12.04, Version 0.6.5 (stable), 6cc94db653a2739ab28e33b2d6a63c51bd986a9f * npm workaround Windows antivirus software (isaacs) * Upgrade V8 to 3.6.6.11 2011.12.02, Version 0.6.4 (stable), 9170077f13e5e5475b23d1d3c2e7f69bfe139727 * doc improvements (Kyle Young, Tim Oxley, Roman Shtylman, Mathias Bynens) * upgrade bundled npm (Isaac Schlueter) * polish Windows installer (Igor Zinkovsky, Isaac Schlueter) * punycode: upgrade to v0.2.1 (Mathias Bynens) * build: add –without-npm flag to configure script * sys: deprecate module some more, print stack trace if NODE_DEBUG=sys * cli: add -p switch, prints result of –eval * #1997: fix Blowfish ECB encryption and decryption (Ingmar Runge) * #2223: fix socket ‘close’ event being emitted twice * #2224: fix RSS memory usage > 4 GB reporting (Russ Bradberry) * #2225: fix util.inspect() object stringification bug (Nathan Rajlich) 2011.11.25, Version 0.6.3 (stable), b159c6d62e5756d3f8847419d29c6959ea288b56 * #2083 Land NPM in Node. It is included in packages/installers and installed on `make install`. * #2076 Add logos to windows installer. * #1711 Correctly handle http requests without headers. (Ben Noordhuis, Felix Geisendörfer) * TLS: expose more openssl SSL context options and constants. (Ben Noordhuis) * #2177 Windows: don't kill UDP socket when a packet fails to reach its destination. (Bert Belder) * Windows: support paths longer than 260 characters. (Igor Zinkovsky) * Windows: correctly resolve drive-relative paths. (Bert Belder) * #2166 Don't leave file descriptor open after lchmod. (Isaac Schlueter) * #2084 Add OS X .pkg build script to make file. * #2160 Documentation improvements. (Ben Noordhuis) 2011.11.18, Version 0.6.2 (stable), a4402f0b2e410b19375a1d5c5fb7fe7f66f3c7f8 * doc improvements (Artur Adib, Trevor Burnham, Ryan Emery, Trent Mick) * timers: remember extra setTimeout() arguments when timeout==0 * punycode: use Mathias Bynens's punycode library, it's more compliant * repl: improved tab completion (Ryan Emery) * buffer: fix range checks in .writeInt() functions (Lukasz Walukiewicz) * tls: make cipher list configurable * addons: make Buffer and ObjectWrap visible to Windows add-ons (Bert Belder) * crypto: add PKCS#1 a.k.a RSA public key verification support * windows: fix stdout writes when redirected to nul * sunos: fix build on Solaris and Illumos * Upgrade V8 to 3.6.6.8 2011.11.11, Version 0.6.1 (stable), 170f2addb2dd0c625bc4a6d461e89a31ad68b79b * doc improvements (Eric Lovett, Ben Noordhuis, Scott Anderson, Yoji SHIDARA) * crypto: make thread-safe (Ben Noordhuis) * fix process.kill error object * debugger: correctly handle source with multi-byte characters (Shigeki Ohtsu) * make stdout and stderr non-destroyable (Igor Zinkovsky) * fs: don't close uninitialized fs.watch handle (Ben Noordhuis) * #2026 fix man page install on BSDs (Ben Noordhuis) * #2040 fix unrecognized errno assert in uv_err_name * #2043 fs: mkdir() should call callback if mode is omitted * #2045 fs: fix fs.realpath on windows to return on error (Benjamin Pasero) * #2047 minor cluster improvements * #2052 readline get window columns correctly * Upgrade V8 to 3.6.6.7 2011.11.04, Version 0.6.0 (stable), 865b077819a9271a29f982faaef99dc635b57fbc * print undefined on undefined values in REPL (Nathan Rajlich) * doc improvements (koichik, seebees, bnoordhuis, Maciej Małecki, Jacob Kragh) * support native addon loading in windows (Bert Belder) * rename getNetworkInterfaces() to networkInterfaces() (bnoordhuis) * add pending accepts knob for windows (igorzi) * http.request(url.parse(x)) (seebees) * #1929 zlib Respond to 'resume' events properly (isaacs) * stream.pipe: Remove resume and pause events * test fixes for windows (igorzi) * build system improvements (bnoordhuis) * #1936 tls: does not emit 'end' from EncryptedStream (koichik) * #758 tls: add address(), remoteAddress/remotePort * #1399 http: emit Error object after .abort() (bnoordhuis) * #1999 fs: make mkdir() default to 0777 permissions (bnoordhuis) * #2001 fix pipe error codes * #2002 Socket.write should reset timeout timer * stdout and stderr are blocking when associated with file too. * remote debugger support on windows (Bert Belder) * convenience methods for zlib (Matt Robenolt) * process.kill support on windows (igorzi) * process.uptime() support on windows (igorzi) * Return IPv4 addresses before IPv6 addresses from getaddrinfo * util.inspect improvements (Nathan Rajlich) * cluster module api changes * Downgrade V8 to 3.6.6.6 2011.10.21, Version 0.5.10 (unstable), 220e61c1f65bf4db09699fcf6399c0809c0bc446 * Remove cmake build system, support for Cygwin, legacy code base, process.ENV, process.ARGV, process.memoryUsage().vsize, os.openOSHandle * Documentation improvments (Igor Zinkovsky, Bert Belder, Ilya Dmitrichenko, koichik, Maciej Małecki, Guglielmo Ferri, isaacs) * Performance improvements (Daniel Ennis, Bert Belder, Ben Noordhuis) * Long process.title support (Ben Noordhuis) * net: register net.Server callback only once (Simen Brekken) * net: fix connect queue bugs (Ben Noordhuis) * debugger: fix backtrace err handling (Fedor Indutny) * Use getaddrinfo instead of c-ares for dns.lookup * Emit 'end' from crypto streams on close * #1902 buffer: use NO_NULL_TERMINATION flag (koichik) * #1907 http: Added support for HTTP PATCH verb (Thomas Parslow) * #1644 add GetCPUInfo on windows (Karl Skomski) * #1484, #1834, #1482, #771 Don't use a separate context for the repl. (isaacs) * #1882 zlib Update 'availOutBefore' value, and test (isaacs) * #1888 child_process.fork: don't modify args (koichik) * #1516 tls: requestCert unusable with Firefox and Chrome (koichik) * #1467 tls: The TLS API is inconsistent with the TCP API (koichik) * #1894 net: fix error handling in listen() (koichik) * #1860 console.error now goes through uv_tty_t * Upgrade V8 to 3.7.0 * Upgrade GYP to r1081 2011.10.10, Version 0.5.9 (unstable), 3bd9b08fb125b606f97a4079b147accfdeebb07d * fs.watch interface backed by kqueue, inotify, and ReadDirectoryChangesW (Igor Zinkovsky, Ben Noordhuis) * add dns.resolveTxt (Christian Tellnes) * Remove legacy http library (Ben Noordhuis) * child_process.fork returns and works on Windows. Allows passing handles. (Igor Zinkovsky, Bert Belder) * #1774 Lint and clean up for --harmony_block_scoping (Tyler Larson, Colton Baker) * #1813 Fix ctrl+c on Windows (Bert Belder) * #1844 unbreak --use-legacy (Ben Noordhuis) * process.stderr now goes through libuv. Both process.stdout and process.stderr are blocking when referencing a TTY. * net_uv performance improvements (Ben Noordhuis, Bert Belder) 2011.09.30, Version 0.5.8 (unstable), 7cc17a0cea1d25188c103745a7d0c24375e3a609 * zlib bindings (isaacs) * Windows supports TTY ANSI escape codes (Bert Belder) * Debugger improvements (Fedor Indutny) * crypto: look up SSL errors with ERR_print_errors() (Ben Noordhuis) * dns callbacks go through MakeCallback now * Raise an error when a malformed package.json file is found. (Ben Leslie) * buffers: handle bad length argument in constructor (Ben Noordhuis) * #1726, unref process.stdout * Doc improvements (Ben Noordhuis, Fedor Indutny, koichik) * Upgrade libuv to fe18438 2011.09.16, Version 0.5.7 (unstable), 558241166c4f3c516e5a448e676db0b57119212f * Upgrade V8 to 3.6.4 * Improve Windows compatibility * Documentation improvements * Debugger and REPL improvements (Fedor Indutny) * Add legacy API support: net.Stream(fd), process.stdout.writable, process.stdout.fd * Fix mkdir EEXIST handling (isaacs) * Use net_uv instead of net_legacy for stdio * Do not load readline from util.inspect * #1673 Fix bug related to V8 context with accessors (Fedor Indutny) * #1634 util: Fix inspection for Error (koichik) * #1645 fs: Add positioned file writing feature to fs.WriteStream (Thomas Shinnick) * #1637 fs: Unguarded fs.watchFile cache statWatchers checking fixed (Thomas Shinnick) * #1695 Forward customFds to ChildProcess.spawn * #1707 Fix hasOwnProperty security problem in querystring (isaacs) * #1719 Drain OpenSSL error queue 2011.09.08, Version 0.5.6 (unstable), b49bec55806574a47403771bce1ee379c2b09ca2 * #345, #1635, #1648 Documentation improvements (Thomas Shinnick, Abimanyu Raja, AJ ONeal, Koichi Kobayashi, Michael Jackson, Logan Smyth, Ben Noordhuis) * #650 Improve path parsing on windows (Bert Belder) * #752 Remove headers sent check in OutgoingMessage.getHeader() (Peter Lyons) * #1236, #1438, #1506, #1513, #1621, #1640, #1647 Libuv-related bugs fixed (Jorge Chamorro Bieling, Peter Bright, Luis Lavena, Igor Zinkovsky) * #1296, #1612 crypto: Fix BIO's usage. (Koichi Kobayashi) * #1345 Correctly set socket.remoteAddress with libuv backend (Bert Belder) * #1429 Don't clobber quick edit mode on windows (Peter Bright) * #1503 Make libuv backend default on unix, override with `node --use-legacy` * #1565 Fix fs.stat for paths ending with \ on windows (Igor Zinkovsky) * #1568 Fix x509 certificate subject parsing (Koichi Kobayashi) * #1586 Make socket write encoding case-insensitive (Koichi Kobayashi) * #1591, #1656, #1657 Implement fs in libuv, remove libeio and pthread-win32 dependency on windows (Igor Zinkovsky, Ben Noordhuis, Ryan Dahl, Isaac Schlueter) * #1592 Don't load-time link against CreateSymbolicLink on windows (Peter Bright) * #1601 Improve API consistency when dealing with the socket underlying a HTTP client request (Mikeal Rogers) * #1610 Remove DigiNotar CA from trusted list (Isaac Schlueter) * #1617 Added some win32 os functions (Karl Skomski) * #1624 avoid buffer overrun with 'binary' encoding (Koichi Kobayashi) * #1633 make Buffer.write() always set _charsWritten (Koichi Kobayashi) * #1644 Windows: set executables to be console programs (Peter Bright) * #1651 improve inspection for sparse array (Koichi Kobayashi) * #1672 set .code='ECONNRESET' on socket hang up errors (Ben Noordhuis) * Add test case for foaf+ssl client certificate (Niclas Hoyer) * Added RPATH environment variable to override run-time library paths (Ashok Mudukutore) * Added TLS client-side session resumption support (Sean Cunningham) * Added additional properties to getPeerCertificate (Nathan Rixham, Niclas Hoyer) * Don't eval repl command twice when an error is thrown (Nathan Rajlich) * Improve util.isDate() (Nathan Rajlich) * Improvements in libuv backend and bindings, upgrade libuv to bd6066cb349a9b3a1b0d87b146ddaee06db31d10 * Show warning when using lib/sys.js (Maciej Malecki) * Support plus sign in url protocol (Maciej Malecki) * Upgrade V8 to 3.6.2 2011.08.26, Version 0.5.5 (unstable), d2d53d4bb262f517a227cc178a1648094ba54c20 * typed arrays, implementation from Plesk * fix IP multicast on SunOS * fix DNS lookup order: IPv4 first, IPv6 second (--use-uv only) * remove support for UNIX datagram sockets (--use-uv only) * UDP support for Windows (Bert Belder) * #1572 improve tab completion for objects in the REPL (Nathan Rajlich) * #1563 fix buffer overflow in child_process module (reported by Dean McNamee) * #1546 fix performance regression in http module (reported by Brian Geffon) * #1491 add PBKDF2 crypto support (Glen Low) * #1447 remove deprecated http.cat() function (Mikeal Rogers) * #1140 fix incorrect dispatch of vm.runInContext's filename argument (Antranig Basman) * #1140 document vm.runInContext() and vm.createContext() (Antranig Basman) * #1428 fix os.freemem() on 64 bits freebsd (Artem Zaytsev) * #1164 make all DNS lookups async, fixes uncatchable exceptions (Koichi Kobayashi) * fix incorrect ssl shutdown check (Tom Hughes) * various cmake fixes (Tom Hughes) * improved documentation (Koichi Kobayashi, Logan Smyth, Fedor Indutny, Mikeal Rogers, Maciej Małecki, Antranig Basman, Mickaël Delahaye) * upgrade libuv to commit 835782a * upgrade V8 to 3.5.8 2011.08.12, Version 0.5.4 (unstable), cfba1f59224ff8602c3fe9145181cad4c6df89a9 * libuv/Windows compatibility improvements * Build on Microsoft Visual Studio via GYP. Use generate-projects.bat in the to build sln files. (Peter Bright, Igor Zinkovsky) * Make Mikeal's HTTP agent client the default. Use old HTTP client with --use-http1 * Fixes https host header default port handling. (Mikeal Rogers) * #1440 strip byte order marker when loading *.js and *.json files (Ben Noordhuis) * #1434 Improve util.format() compatibility with browser. (Koichi Kobayashi) * Provide unchecked uint entry points for integer Buffer.read/writeInt methods. (Robert Mustacchi) * CMake improvements (Tom Huges) * Upgrade V8 to 3.5.4. 2011.08.01, Version 0.5.3 (unstable), 4585330afef44ddfb6a4054bd9b0f190b352628b * Fix crypto encryption/decryption with Base64. (SAWADA Tadashi) * #243 Add an optional length argument to Buffer.write() (koichik) * #657 convert nonbuffer data to string in fs.writeFile/Sync (Daniel Pihlström) * Add process.features, remove process.useUV (Ben Noordhuis) * #324 Fix crypto hmac to accept binary keys + add test cases from rfc 2202 and 4231 (Stefan Bühler) * Add Socket::bytesRead, Socket::bytesWritten (Alexander Uvarov) * #572 Don't print result of --eval in CLI (Ben Noordhuis) * #1223 Fix http.ClientRequest crashes if end() was called twice (koichik) * #1383 Emit 'close' after all connections have closed (Felix Geisendörfer) * Add sprintf-like util.format() function (Ben Noordhuis) * Add support for TLS SNI (Fedor Indutny) * New http agent implementation. Off by default the command line flag --use-http2 will enable it. "make test-http2" will run the tests for the new implementation. (Mikeal Rogers) * Revert AMD compatibility. (isaacs) * Windows: improvements, child_process support. * Remove pkg-config file. * Fix startup time regressions. * doc improvements 2011.07.22, Version 0.5.2 (unstable), 08ffce1a00dde1199174b390a64a90b60768ddf5 * libuv improvements; named pipe support * #1242 check for SSL_COMP_get_compression_methods() (Ben Noordhuis) * #1348 remove require.paths (isaacs) * #1349 Delimit NODE_PATH with ; on Windows (isaacs) * #1335 Remove EventEmitter from C++ * #1357 Load json files with require() (isaacs) * #1374 fix setting ServerResponse.statusCode in writeHead (Trent Mick) * Fixed: GC was being run too often. * Upgrade V8 to 3.4.14 * doc improvements 2011.07.14, Version 0.5.1 (unstable), f8bfa54d0fa509f9242637bef2869a1b1e842ec8 * #1233 Fix os.totalmem on FreeBSD amd64 (Artem Zaytsev) * #1149 IDNA and Punycode support in url.parse (Jeremy Selier, Ben Noordhuis, isaacs) * Export $CC and $CXX to uv and V8's build systems * Include pthread-win32 static libraries in build (Igor Zinkovsky) * #1199, #1094 Fix fs can't handle large file on 64bit platform (koichik) * #1281 Make require a public member of module (isaacs) * #1303 Stream.pipe returns the destination (Elijah Insua) * #1229 Addons should not -DEV_MULTIPLICITY=0 (Brian White) * libuv backend improvements * Upgrade V8 to 3.4.10 2011.07.05, Version 0.5.0 (unstable), ae7ed8482ea7e53c59acbdf3cf0e0a0ae9d792cd * New non-default libuv backend to support IOCP on Windows. Use --use-uv to enable. * deprecate http.cat * docs improved. * add child_process.fork * add fs.utimes() and fs.futimes() support (Ben Noordhuis) * add process.uptime() (Tom Huges) * add path.relative (Tony Huang) * add os.getNetworkInterfaces() * add remoteAddress and remotePort for client TCP connections (Brian White) * add secureOptions flag, setting ciphers, SSL_OP_CRYPTOPRO_TLSEXT_BUG to TLS (Theo Schlossnagle) * add process.arch (Nathan Rajlich) * add reading/writing of floats and doubles from/to buffers (Brian White) * Allow script to be read from stdin * #477 add Buffer::fill method to do memset (Konstantin Käfer) * #573 Diffie-Hellman support to crypto module (Håvard Stranden) * #695 add 'hex' encoding to buffer (isaacs) * #851 Update how REPLServer uses contexts (Ben Weaver) * #853 add fs.lchow, fs.lchmod, fs.fchmod, fs.fchown (isaacs) * #889 Allow to remove all EventEmitter listeners at once (Felix Geisendörfer) * #926 OpenSSL NPN support (Fedor Indutny) * #955 Change ^C handling in REPL (isaacs) * #979 add support for Unix Domain Sockets to HTTP (Mark Cavage) * #1173 #1170 add AMD, asynchronous module definition (isaacs) * DTrace probes: support X-Forwarded-For (Dave Pacheco) 2011.09.15, Version 0.4.12 (stable), 771ba34ca7b839add2ef96879e1ffc684813cf7c * Improve docs * #1563 overflow in ChildProcess custom_fd. * #1569, parse error on multi-line HTTP headers. (Ben Noordhuis) * #1586 net: Socket write encoding case sensitivity (koichik) * #1610 Remove DigiNotar CA from trusted list (isaacs) * #1624 buffer: Avoid overrun with 'binary' encoding. (koichik) * #1633 buffer: write() should always set _charsWritten. (koichik) * #1707 hasOwnProperty usage security hole in querystring (isaacs) * #1719 Drain OpenSSL error queue * Fix error reporting in net.Server.listen 2011.08.17, Version 0.4.11 (stable), a745d19ce7d1c0e3778371af4f0346be70cf2c8e * #738 Fix crypto encryption/decryption with Base64. (SAWADA Tadashi) * #1202 net.createConnection defer DNS lookup error events to next tick (Ben Noordhuis) * #1374 fix setting ServerResponse.statusCode in writeHead (Trent Mick) * #1417 Fix http.ClientRequest crashes if end() was called twice * #1497 querystring: Replace 'in' test with 'hasOwnProperty' (isaacs) * #1546 http perf improvement * fix memleak in libeio (Tom Hughes) * cmake improvements (Tom Hughes) * node_net.cc: fix incorrect sizeof() (Tom Hughes) * Windows/cygwin: no more GetConsoleTitleW errors on XP (Bert Belder) * Doc improvments (koichik, Logan Smyth, Ben Noordhuis, Arnout Kazemier) 2011.07.19, Version 0.4.10 (stable), 1b8dd65d6e3b82b6863ef38835cc436c5d30c1d5 * #394 Fix Buffer drops last null character in UTF-8 * #829 Backport r8577 from V8 (Ben Noordhuis) * #877 Don't wait for HTTP Agent socket pool to establish connections. * #915 Find kqueue on FreeBSD correctly (Brett Kiefer) * #1085 HTTP: Fix race in abort/dispatch code (Stefan Rusu) * #1274 debugger improvement (Yoshihiro Kikuchi) * #1291 Properly respond to HEAD during end(body) hot path (Reid Burke) * #1304 TLS: Fix race in abort/connection code (Stefan Rusu) * #1360 Allow _ in url hostnames. * Revert 37d529f8 - unbreaks debugger command parsing. * Bring back global execScript * Doc improvements 2011.06.29, Version 0.4.9 (stable), de44eafd7854d06cd85006f509b7051e8540589b * Improve documentation * #1095 error handling bug in stream.pipe() (Felix Geisendörfer) * #1097 Fix a few leaks in node_crypto.cc (Ben Noordhuis) * #562 #1078 Parse file:// urls properly (Ryan Petrello) * #880 Option to disable SSLv2 (Jérémy Lal) * #1087 Disabling SSL compression disabled with early OpenSSLs. * #1144 debugger: don't allow users to input non-valid commands (Siddharth Mahendraker) * Perf improvement for util.inherits * #1166 Support for signature verification with RSA/DSA public keys (Mark Cavage) * #1177 Remove node_modules lookup optimization to better support nested project structures (Mathias Buus) * #1203 Add missing scope.Close to fs.sendfileSync * #1187 Support multiple 'link' headers * #1196 Fix -e/--eval can't load module from node_modules (Koichi Kobayashi) * Upgrade V8 to 3.1.8.25, upgrade http-parser. 2011.05.20, Version 0.4.8 (stable), 7dd22c26e4365698dc3efddf138c4d399cb912c8 * #974 Properly report traceless errors (isaacs) * #983 Better JSON.parse error detection in REPL (isaacs) * #836 Agent socket errors bubble up to req only if req exists * #1041 Fix event listener leak check timing (koichik) * #1038 Fix dns.resolve() with 'PTR' throws Error: Unknown type "PTR" (koichik) * #1073 Share SSL context between server connections (Fedor Indutny) * Disable compression with OpenSSL. Improves memory perf. * Implement os.totalmem() and os.freemem() for SunOS (Alexandre Marangone) * Fix a special characters in URL regression (isaacs) * Fix idle timeouts in HTTPS (Felix Geisendörfer) * SlowBuffer.write() with 'ucs2' throws ReferenceError. (koichik) * http.ServerRequest 'close' sometimes gets an error argument (Felix Geisendörfer) * Doc improvements * cleartextstream.destroy() should close(2) the socket. Previously was being mapped to a shutdown(2) syscall. * No longer compile out asserts and debug statements in normal build. * Debugger improvements. * Upgrade V8 to 3.1.8.16. 2011.04.22, Version 0.4.7 (stable), c85455a954411b38232e79752d4abb61bb75031b * Don't emit error on ECONNRESET from read() #670 * Fix: Multiple pipes to the same stream were broken #929 (Felix Geisendörfer) * URL parsing/formatting corrections #954 (isaacs) * make it possible to do repl.start('', stream) (Wade Simmons) * Add os.loadavg for SunOS (Robert Mustacchi) * Fix timeouts with floating point numbers #897 (Jorge Chamorro Bieling) * Improve docs. 2011.04.13, Version 0.4.6 (stable), 58002d56bc79410c5ff397fc0e1ffec0665db38a * Don't error on ENOTCONN from shutdown() #670 * Auto completion of built-in debugger suggests prefix match rather than partial match. (koichik) * circular reference in vm modules. #822 (Jakub Lekstan) * http response.readable should be false after 'end' #867 (Abe Fettig) * Implement os.cpus() and os.uptime() on Solaris (Scott McWhirter) * fs.ReadStream: Allow omission of end option for range reads #801 (Felix Geisendörfer) * Buffer.write() with UCS-2 should not be write partial char #916 (koichik) * Pass secureProtocol through on tls.Server creation (Theo Schlossnagle) * TLS use RC4-SHA by default * Don't strangely drop out of event loop on HTTPS client uploads #892 * Doc improvements * Upgrade v8 to 3.1.8.10 2011.04.01, Version 0.4.5 (stable), 787a343b588de26784fef97f953420b53a6e1d73 * Fix listener leak in stream.pipe() (Mikeal Rogers) * Retain buffers in fs.read/write() GH-814 (Jorge Chamorro Bieling) * TLS performance improvements * SlowBuffer.prototype.slice bug GH-843 * process.stderr.write should return true * Immediate pause/resume race condition GH-535 (isaacs) * Set default host header properly GH-721 (isaacs) * Upgrade V8 to 3.1.8.8 2011.03.26, Version 0.4.4 (stable), 25122b986a90ba0982697b7abcb0158c302a1019 * CryptoStream.end shouldn't throw if not writable GH-820 * Drop out if connection destroyed before connect() GH-819 * expose https.Agent * Correctly setsid in tty.open GH-815 * Bug fix for failed buffer construction * Added support for removing .once listeners (GH-806) * Upgrade V8 to 3.1.8.5 2011.03.18, Version 0.4.3 (stable), c095ce1a1b41ca015758a713283bf1f0bd41e4c4 * Don't decrease server connection counter again if destroy() is called more than once GH-431 (Andreas Reich, Anders Conbere) * Documentation improvements (koichik) * Fix bug with setMaxListeners GH-682 * Start up memory footprint improvement. (Tom Hughes) * Solaris improvements. * Buffer::Length(Buffer*) should not invoke itself recursively GH-759 (Ben Noordhuis) * TLS: Advertise support for client certs GH-774 (Theo Schlossnagle) * HTTP Agent bugs: GH-787, GH-784, GH-803. * Don't call GetMemoryUsage every 5 seconds. * Upgrade V8 to 3.1.8.3 2011.03.02, Version 0.4.2 (stable), 39280e1b5731f3fcd8cc42ad41b86cdfdcb6d58b * Improve docs. * Fix process.on edge case with signal event (Alexis Sellier) * Pragma HTTP header comma separation * In addition to 'aborted' emit 'close' from incoming requests (Felix Geisendörfer) * Fix memleak in vm.runInNewContext * Do not cache modules that throw exceptions (Felix Geisendörfer) * Build system changes for libnode (Aria Stewart) * Read up the prototype of the 'env' object. (Nathan Rajlich) * Add 'close' and 'aborted' events to Agent responses * http: fix missing 'drain' events (Russell Haering) * Fix process.stdout.end() throws ENOTSOCK error. (Koichi Kobayashi) * REPL bug fixes (isaacs) * node_modules folders should be highest priority (isaacs) * URL parse more safely (isaacs) * Expose errno with a string for dns/cares (Felix Geisendörfer) * Fix tty.setWindowSize * spawn: setuid after chdir (isaacs) * SIGUSR1 should break the VM without delay * Upgrade V8 to 3.1.8. 2011.02.19, Version 0.4.1 (stable), e8aef84191bc2c1ba2bcaa54f30aabde7f03769b * Fixed field merging with progressive fields on writeHead() (TJ Holowaychuk) * Make the repl respect node_modules folders (isaacs) * Fix for DNS fail in HTTP request (Richard Rodger) * Default to port 80 for http.request and http.get. * Improve V8 support for Cygwin (Bert Belder) * Fix fs.open param parsing. (Felix Geisendörfer) * Fixed null signal. * Fix various HTTP and HTTPS bugs * cmake improvements (Tom Hughes) * Fix: TLS sockets should not be writable after 'end' * Fix os.cpus() on cygwin (Brian White) * MinGW: OpenSSL support (Bert Belder) * Upgrade V8 to 3.1.5, libev to 4.4. 2011.02.10, Version 0.4.0 (stable), eb155ea6f6a6aa341aa8c731dca8da545c6a4008 * require() improvements (isaacs) - understand package.json (isaacs) - look for 'node_modules' dir * cmake fixes (Daniel Gröber) * http: fix buffer writes to outgoing messages (Russell Haering) * Expose UCS-2 Encoding (Konstantin Käfer) * Support strings for octal modes (isaacs) * Support array-ish args to Buffer ctor (isaacs) * cygwin and mingw improvements (Bert Belder) * TLS improvements * Fewer syscalls during require (Bert Belder, isaacs) * More DTrace probes (Bryan Cantrill, Robert Mustacchi) * 'pipe' event on pipe() (Mikeal Rogers) * CRL support in TLS (Theo Schlossnagle) * HTTP header manipulation methods (Tim Caswell, Charlie Robbins) * Upgrade V8 to 3.1.2 2011.02.04, Version 0.3.8 (unstable), 9493b7563bff31525b4080df5aeef09747782d5e * Add req.abort() for client side requests. * Add exception.code for easy testing: Example: if (err.code == 'EADDRINUSE'); * Add process.stderr. * require.main is the main module. (Isaac Schlueter) * dgram: setMulticastTTL, setMulticastLoopback and addMembership. (Joe Walnes) * Fix throttling in TLS connections * Add socket.bufferSize * MinGW improvements (Bert Belder) * Upgrade V8 to 3.1.1 2011.01.27, Version 0.3.7 (unstable), d8579c6afdbe868de6dffa8db78bbe4ba2d03e0e * Expose agent in http and https client. (Mikeal Rogers) * Fix bug in http request's end method. (Ali Farhadi) * MinGW: better net support (Bert Belder) * fs.open should set FD_CLOEXEC * DTrace probes (Bryan Cantrill) * REPL fixes and improvements (isaacs, Bert Belder) * Fix many bugs with legacy http.Client interface * Deprecate process.assert. Use require('assert').ok * Add callback parameter to socket.setTimeout(). (Ali Farhadi) * Fixing bug in http request default encoding (Ali Farhadi) * require: A module ID with a trailing slash must be a dir. (isaacs) * Add ext_key_usage to getPeerCertificate (Greg Hughes) * Error when child_process.exec hits maxBuffer. * Fix option parsing in tls.connect() * Upgrade to V8 3.0.10 2011.01.21, Version 0.3.6 (unstable), bb3e71466e5240626d9d21cf791fe43e87d90011 * REPL and other improvements on MinGW (Bert Belder) * listen/bind errors should close net.Server * New HTTP and HTTPS client APIs * Upgrade V8 to 3.0.9 2011.01.16, Version 0.3.5 (unstable), b622bc6305e3c675e0edfcdbaa387d849ad0bba0 * Built-in debugger improvements. * Add setsid, setuid, setgid options to child_process.spawn (Isaac Schlueter) * tty module improvements. * Upgrade libev to 4.3, libeio to latest, c-ares to 1.7.4 * Allow third party hooks before main module load. (See 496be457b6a2bc5b01ec13644b9c9783976159b2) * Don't stat() on cached modules. (Felix Geisendörfer) 2011.01.08, Version 0.3.4 (unstable), 73f53e12e4a5b9ef7dbb4792bd5f8ad403094441 * Primordial mingw build (Bert Belder) * HTTPS server * Built in debugger 'node debug script.js' * realpath files during module load (Mihai Călin Bazon) * Rename net.Stream to net.Socket (existing name will continue to be supported) * Fix process.platform 2011.01.02, Version 0.3.3 (unstable), 57544ba1c54c7d0da890317deeb73076350c5647 * TLS improvements. * url.parse(url, true) defaults query field to {} (Jeremy Martin) * Upgrade V8 to 3.0.4 * Handle ECONNABORT properly (Theo Schlossnagle) * Fix memory leaks (Tom Hughes) * Add os.cpus(), os.freemem(), os.totalmem(), os.loadavg() and other functions for OSX, Linux, and Cygwin. (Brian White) * Fix REPL syntax error bug (GH-543), improve how REPL commands are evaluated. * Use process.stdin instead of process.openStdin(). * Disable TLS tests when node doesn't have OpenSSL. 2010.12.16, Version 0.3.2 (unstable), 4bb914bde9f3c2d6de00853353b6b8fc9c66143a * Rip out the old (broken) TLS implementation introduce new tested implementation and API. See docs. HTTPS not supported in this release. * Introduce 'os' and 'tty' modules. * Callback parameters for socket.write() and socket.connect(). * Support CNAME lookups in DNS module. (Ben Noordhuis) * cmake support (Tom Hughes) * 'make lint' * oprofile support (./configure --oprofile) * Lots of bug fixes, including: - Memory leak in ChildProcess:Spawn(). (Tom Hughes) - buffer.slice(0, 0) - Global variable leaks - clearTimeouts calling multiple times (Michael W) - utils.inspect's detection of circular structures (Tim Cooijmans) - Apple's threaded write()s bug (Jorge Chamorro Bieling) - Make sure raw mode is disabled when exiting a terminal-based REPL. (Brian White) * Deprecate process.compile, process.ENV * Upgrade V8 to 3.0.3, upgrade http-parser. 2010.11.16, Version 0.3.1 (unstable), ce9a54aa1fbf709dd30316af8a2f14d83150e947 * TLS improvements (Paul Querna) - Centralize error handling in SecureStream - Add SecurePair for handling of a ssl/tls stream. * New documentation organization (Micheil Smith) * allowHalfOpen TCP connections disabled by default. * Add C++ API for constructing fast buffer from string * Move idle timers into its own module * Gracefully handle EMFILE and server.maxConnections * make "node --eval" eval in the global scope. (Jorge Chamorro Bieling) * Let exit listeners know the exit code (isaacs) * Handle cyclic links smarter in fs.realpath (isaacs) * Remove node-repl (just use 'node' without args) * Rewrite libeio After callback to use req->result instead of req->errorno for error checking (Micheil Smith) * Remove warning about deprecating 'sys' - too aggressive * Make writes to process.env update the real environment. (Ben Noordhuis) * Set FD_CLOEXEC flag on stdio FDs before spawning. (Guillaume Tuton) * Move ev_loop out of javascript * Switch \n with \r\n for all strings printed out. * Added support for cross compilation (Rasmus Andersson) * Add --profile flag to configure script, enables gprof profiling. (Ben Noordhuis) * writeFileSync could exhibit pathological behavior when a buffer could not be written to the file in a single write() call. * new path.join behavior (isaacs) - Express desired path.join behavior in tests. - Update fs.realpath to reflect new path.join behavior - Update url.resolve() to use new path.join behavior. * API: Move process.binding('evals') to require('vm') * Fix V8 build on Cygwin (Bert Belder) * Add ref to buffer during fs.write and fs.read * Fix segfault on test-crypto * Upgrade http-parser to latest and V8 to 2.5.3 2010.10.23, Version 0.3.0 (unstable) 1582cfebd6719b2d2373547994b3dca5c8c569c0 * Bugfix: Do not spin on accept() with EMFILE * Improvements to readline.js (Trent Mick, Johan Euphrosine, Brian White) * Safe constructors (missing 'new' doesn't segfault) * Fix process.nextTick so thrown errors don't confuse it. (Benjamin Thomas) * Allow Strings for ports on net.Server.listen (Bradley Meck) * fs bugfixes (Tj Holowaychuk, Tobie Langel, Marco Rogers, isaacs) * http bug fixes (Fedor Indutny, Mikeal Rogers) * Faster buffers; breaks C++ API (Tim-Smart, Stéphan Kochen) * crypto, tls improvements (Paul Querna) * Add lfs flags to node addon script * Simpler querystring parsing; breaks API (Peter Griess) * HTTP trailers (Mark Nottingham) * http 100-continue support (Mark Nottingham) * Module system simplifications (Herbert Vojčík, isaacs, Tim-Smart) - remove require.async - remove registerExtension, add .extensions - expose require.resolve - expose require.cache - require looks in node_modules folders * Add --eval command line option (TJ Holowaychuk) * Commas last in sys.inspect * Constants moved from process object to require('constants') * Fix parsing of linux memory (Vitali Lovich) * inspect shows function names (Jorge Chamorro Bieling) * uncaughtException corner cases (Felix Geisendörfer) * TCP clients now buffer writes before connection * Rename sys module to 'util' (Micheil Smith) * Properly set stdio handlers to blocking on SIGTERM and SIGINT (Tom Hughes) * Add destroy methods to HTTP messages * base64 improvements (isaacs, Jorge Chamorro Bieling) * API for defining REPL commands (Sami Samhuri) * child_process.exec timeout fix (Aaron Heckmann) * Upgrade V8 to 2.5.1, Libev to 4.00, libeio, http-parser 2010.08.20, Version 0.2.0, 9283e134e558900ba89d9a33c18a9bdedab07cb9 * process.title support for FreeBSD, Macintosh, Linux * Fix OpenSSL 100% CPU usage on error (Illarionov Oleg) * Implement net.Server.maxConnections. * Fix process.platform, add process.version. * Add --without-snapshot configure option. * Readline REPL improvements (Trent Mick) * Bug fixes. * Upgrade V8 to 2.3.8 2010.08.13, Version 0.1.104, b14dd49222687c12f3e8eac597cff4f2674f84e8 * Various bug fixes (console, querystring, require) * Set cwd for child processes (Bert Belder) * Tab completion for readline (Trent Mick) * process.title getter/setter for OSX, Linux, Cygwin. (Rasmus Andersson, Bert Belder) * Upgrade V8 to 2.3.6 2010.08.04, Version 0.1.103, 0b925d075d359d03426f0b32bb58a5e05825b4ea * Implement keep-alive for http.Client (Mikeal Rogers) * base64 fixes. (Ben Noordhuis) * Fix --debug-brk (Danny Coates) * Don't let path.normalize get above the root. (Isaac Schlueter) * Allow signals to be used with process.on in addition to process.addListener. (Brian White) * Globalize the Buffer object * Use kqueue on recent macintosh builds * Fix addrlen for unix_dgram sockets (Benjamin Kramer) * Fix stats.isDirectory() and friends (Benjamin Kramer) * Upgrade http-parser, V8 to 2.3.5 2010.07.25, Version 0.1.102, 2a4568c85f33869c75ff43ccd30f0ec188b43eab * base64 encoding for Buffers. * Buffer support for Cipher, Decipher, Hmac, Sign and Verify (Andrew Naylor) * Support for reading byte ranges from files using fs.createReadStream. (Chandra Sekar) * Fix Buffer.toString() on 0-length slices. (Peter Griess) * Cache modules based on filename rather than ID (Isaac Schlueter) * querystring improvments (Jan Kassens, Micheil Smith) * Support DEL in the REPL. (Jérémy Lal) * Upgrade http-parser, upgrade V8 to 2.3.2 2010.07.16, Version 0.1.101, 0174ceb6b24caa0bdfc523934c56af9600fa9b58 * Added env to child_process.exec (Сергей Крыжановский) * Allow modules to optionally be loaded in separate contexts with env var NODE_MODULE_CONTEXTS=1. * setTTL and setBroadcast for dgram (Matt Ranney) * Use execPath for default NODE_PATH, not installPrefix (Isaac Schlueter) * Support of console.dir + console.assert (Jerome Etienne) * on() as alias to addListener() * Use javascript port of Ronn to build docs (Jérémy Lal) * Upgrade V8 to 2.3.0 2010.07.03, Version 0.1.100, a6b8586e947f9c3ced180fe68c233d0c252add8b * process.execPath (Marshall Culpepper) * sys.pump (Mikeal Rogers) * Remove ini and mjsunit libraries. * Introduce console.log() and friends. * Switch order of arguments for Buffer.write (Blake Mizerany) * On overlapping buffers use memmove (Matt Ranney) * Resolve .local domains with getaddrinfo() * Upgrade http-parser, V8 to 2.2.21 2010.06.21, Version 0.1.99, a620b7298f68f68a855306437a3b60b650d61d78 * Datagram sockets (Paul Querna) * fs.writeFile could not handle utf8 (Felix Geisendörfer) and now accepts Buffers (Aaron Heckmann) * Fix crypto memory leaks. * A replacement for decodeURIComponent that doesn't throw. (Isaac Schlueter) * Only concatenate some incoming HTTP headers. (Peter Griess) * Upgrade V8 to 2.2.18 2010.06.11, Version 0.1.98, 10d8adb08933d1d4cea60192c2a31c56d896733d * Port to Windows/Cygwin (Raffaele Sena) * File descriptor passing on unix sockets. (Peter Griess) * Simple, builtin readline library. REPL is now entered by executing "node" without arguments. * Add a parameter to spawn() that sets the child's stdio file descriptors. (Orlando Vazquez) * Upgrade V8 to 2.2.16, http-parser fixes, upgrade c-ares to 1.7.3. 2010.05.29, Version 0.1.97, 0c1aa36835fa6a3557843dcbc6ed6714d353a783 * HTTP throttling: outgoing messages emit 'drain' and write() returns false when send buffer is full. * API: readFileSync without encoding argument now returns a Buffer * Improve Buffer C++ API; addons now compile with debugging symbols. * Improvements to path.extname() and REPL; add fs.chown(). * fs.ReadStream now emits buffers, fs.readFileSync returns buffers. * Bugfix: parsing HTTP responses to HEAD requests. * Port to OpenBSD. * Upgrade V8 to 2.2.12, libeio, http-parser. 2010.05.21, Version 0.1.96, 9514a4d5476225e8c8310ce5acae2857033bcaaa * Thrown errors in http and socket call back get bubbled up. * Add fs.fsync (Andrew Johnston) * Bugfix: signal unregistering (Jonas Pfenniger) * Added better error messages for async and sync fs calls with paths (TJ Holowaychuk) * Support arrays and strings in buffer constructor. (Felix Geisendörfer) * Fix errno reporting in DNS exceptions. * Support buffers in fs.WriteStream.write. * Bugfix: Safely decode a utf8 streams that are broken on a multbyte character (http and net). (Felix Geisendörfer) * Make Buffer's C++ constructor public. * Deprecate sys.p() * FIX path.dirname('/tmp') => '/'. (Jonathan Rentzsch) 2010.05.13, Version 0.1.95, 0914d33842976c2c870df06573b68f9192a1fb7a * Change GC idle notify so that it runs alongside setInterval * Install node_buffer.h on make install * fs.readFile returns Buffer by default (Tim Caswell) * Fix error reporting in child_process callbacks * Better logic for testing if an argument is a port * Improve error reporting (single line "node.js:176:9" errors) * Bugfix: Some http responses being truncated (appeared in 0.1.94) * Fix long standing net idle timeout bugs. Enable 2 minute timeout by default in HTTP servers. * Add fs.fstat (Ben Noordhuis) * Upgrade to V8 2.2.9 2010.05.06, Version 0.1.94, f711d5343b29d1e72e87107315708e40951a7826 * Look in /usr/local/lib/node for modules, so that there's a way to install modules globally (Issac Schlueter) * SSL improvements (Rhys Jones, Paulo Matias) * Added c-ares headers for linux-arm (Jonathan Knezek) * Add symbols to release build * HTTP upgrade improvements, docs (Micheil Smith) * HTTP server emits 'clientError' instead of printing message * Bugfix: Don't emit 'error' twice from http.Client * Bugfix: Ignore SIGPIPE * Bugfix: destroy() instead of end() http connection at end of pipeline * Bugfix: http.Client may be prematurely released back to the free pool. (Thomas Lee) * Upgrade V8 to 2.2.8 2010.04.29, Version 0.1.93, 557ba6bd97bad3afe0f9bd3ac07efac0a39978c1 * Fixed no 'end' event on long chunked HTTP messages https://github.com/joyent/node/issues/77 * Remove legacy modules http_old and tcp_old * Support DNS MX queries (Jérémy Lal) * Fix large socket write (tlb@tlb.org) * Fix child process exit codes (Felix Geisendörfer) * Allow callers to disable PHP/Rails style parameter munging in querystring.stringify (Thomas Lee) * Upgrade V8 to 2.2.6 2010.04.23, Version 0.1.92, caa828a242f39b6158084ef4376355161c14fe34 * OpenSSL support. Still undocumented (see tests). (Rhys Jones) * API: Unhandled 'error' events throw. * Script class with eval-function-family in binding('evals') plus tests. (Herbert Vojcik) * stream.setKeepAlive (Julian Lamb) * Bugfix: Force no body on http 204 and 304 * Upgrade Waf to 1.5.16, V8 to 2.2.4.2 2010.04.15, Version 0.1.91, 311d7dee19034ff1c6bc9098c36973b8d687eaba * Add incoming.httpVersion * Object.prototype problem with C-Ares binding * REPL can be run from multiple different streams. (Matt Ranney) * After V8 heap is compact, don't use a timer every 2 seconds. * Improve nextTick implementation. * Add primative support for Upgrading HTTP connections. (See commit log for docs 760bba5) * Add timeout and maxBuffer options to child_process.exec * Fix bugs. * Upgrade V8 to 2.2.3.1 2010.04.09, Version 0.1.90, 07e64d45ffa1856e824c4fa6afd0442ba61d6fd8 * Merge writing of networking system (net2) - New Buffer object for binary data. - Support UNIX sockets, Pipes - Uniform stream API - Currently no SSL - Legacy modules can be accessed at 'http_old' and 'tcp_old' * Replace udns with c-ares. (Krishna Rajendran) * New documentation system using Markdown and Ronn (Tim Caswell, Micheil Smith) * Better idle-time GC * Countless small bug fixes. * Upgrade V8 to 2.2.X, WAF 1.5.15 2010.03.19, Version 0.1.33, 618296ef571e873976f608d91a3d6b9e65fe8284 * Include lib/ directory in node executable. Compile on demand. * evalcx clean ups (Isaac Z. Schlueter, Tim-Smart) * Various fixes, clean ups * V8 upgraded to 2.1.5 2010.03.12, Version 0.1.32, 61c801413544a50000faa7f58376e9b33ba6254f * Optimize event emitter for single listener * Add process.evalcx, require.registerExtension (Tim Smart) * Replace --cflags with --vars * Fix bugs in fs.create*Stream (Felix Geisendörfer) * Deprecate process.mixin, process.unloop * Remove the 'Error: (no message)' exceptions, print stack trace instead * INI parser bug fixes (Isaac Schlueter) * FreeBSD fixes (Vanilla Hsu) * Upgrade to V8 2.1.3, WAF 1.5.14a, libev 2010.03.05, Version 0.1.31, 39b63dfe1737d46a8c8818c92773ef181fd174b3 * API: - Move process.watchFile into fs module - Move process.inherits to sys * Improve Solaris port * tcp.Connection.prototype.write now returns boolean to indicate if argument was flushed to the kernel buffer. * Added fs.link, fs.symlink, fs.readlink, fs.realpath (Rasmus Andersson) * Add setgid,getgid (James Duncan) * Improve sys.inspect (Benjamin Thomas) * Allow passing env to child process (Isaac Schlueter) * fs.createWriteStream, fs.createReadStream (Felix Geisendörfer) * Add INI parser (Rob Ellis) * Bugfix: fs.readFile handling encoding (Jacek Becela) * Upgrade V8 to 2.1.2 2010.02.22, Version 0.1.30, bb0d1e65e1671aaeb21fac186b066701da0bc33b * Major API Changes - Promises removed. See http://groups.google.com/group/nodejs/msg/426f3071f3eec16b http://groups.google.com/group/nodejs/msg/df199d233ff17efa The API for fs was fs.readdir("/usr").addCallback(function (files) { puts("/usr files: " + files); }); It is now fs.readdir("/usr", function (err, files) { if (err) throw err; puts("/usr files: " + files); }); - Synchronous fs operations exposed, use with care. - tcp.Connection.prototype.readPause() and readResume() renamed to pause() and resume() - http.ServerResponse.prototype.sendHeader() renamed to writeHeader(). Now accepts reasonPhrase. * Compact garbage on idle. * Configurable debug ports, and --debug-brk (Zoran Tomicic) * Better command line option parsing (Jeremy Ashkenas) * Add fs.chmod (Micheil Smith), fs.lstat (Isaac Z. Schlueter) * Fixes to process.mixin (Rasmus Andersson, Benjamin Thomas) * Upgrade V8 to 2.1.1 2010.02.17, Version 0.1.29, 87d5e5b316a4276bcf881f176971c1a237dcdc7a * Major API Changes - Remove 'file' module - require('posix') -----------------> require('fs') - fs.cat ---------------------------> fs.readFile - file.write -----------------------> fs.writeFile - TCP 'receive' event --------------> 'data' - TCP 'eof' event ------------------> 'end' - TCP send() -----------------------> write() - HTTP sendBody() ------------------> write() - HTTP finish() --------------------> close() - HTTP 'body' event ----------------> 'data' - HTTP 'complete' event ------------> 'end' - http.Client.prototype.close() (formerly finish()) no longer takes an argument. Add the 'response' listener manually. - Allow strings for the flag argument to fs.open ("r", "r+", "w", "w+", "a", "a+") * Added multiple arg support for sys.puts(), print(), etc. (tj@vision-media.ca) * sys.inspect(Date) now shows the date value (Mark Hansen) * Calculate page size with getpagesize for armel (Jérémy Lal) * Bugfix: stderr flushing. * Bugfix: Promise late chain (Yuichiro MASUI) * Bugfix: wait() on fired promises (Felix Geisendörfer, Jonas Pfenniger) * Bugfix: Use InstanceTemplate() instead of PrototypeTemplate() for accessor methods. Was causing a crash with Eclipse debugger. (Zoran Tomicic) * Bugfix: Throw from connection.connect if resolving. (Reported by James Golick) 2010.02.09, Version 0.1.28, 49de41ef463292988ddacfb01a20543b963d9669 * Use Google's jsmin.py which can be used for evil. * Add posix.truncate() * Throw errors from server.listen() * stdio bugfix (test by Mikeal Rogers) * Module system refactor (Felix Geisendörfer, Blaine Cook) * Add process.setuid(), getuid() (Michael Carter) * sys.inspect refactor (Tim Caswell) * Multipart library rewrite (isaacs) 2010.02.03, Version 0.1.27, 0cfa789cc530848725a8cb5595224e78ae7b9dd0 * Implemented __dirname (Felix Geisendörfer) * Downcase process.ARGV, process.ENV, GLOBAL (now process.argv, process.env, global) * Bug Fix: Late promise promise callbacks firing (Felix Geisendörfer, Jonas Pfenniger) * Make assert.AssertionError instance of Error * Removed inline require call for querystring (self@cloudhead.net) * Add support for MX, TXT, and SRV records in DNS module. (Blaine Cook) * Bugfix: HTTP client automatically reconnecting * Adding OS X .dmg build scripts. (Standa Opichal) * Bugfix: ObjectWrap memory leak * Bugfix: Multipart handle Content-Type headers with charset (Felix Geisendörfer) * Upgrade http-parser to fix header overflow attack. * Upgrade V8 to 2.1.0 * Various other bug fixes, performance improvements. 2010.01.20, Version 0.1.26, da00413196e432247346d9e587f8c78ce5ceb087 * Bugfix, HTTP eof causing crash (Ben Williamson) * Better error message on SyntaxError * API: Move Promise and EventEmitter into 'events' module * API: Add process.nextTick() * Allow optional params to setTimeout, setInterval (Micheil Smith) * API: change some Promise behavior (Felix Geisendörfer) - Removed Promise.cancel() - Support late callback binding - Make unhandled Promise errors throw an exception * Upgrade V8 to 2.0.6.1 * Solaris port (Erich Ocean) 2010.01.09, Version 0.1.25, 39ca93549af91575ca9d4cbafd1e170fbcef3dfa * sys.inspect() improvements (Tim Caswell) * path module improvements (isaacs, Benjamin Thomas) * API: request.uri -> request.url It is no longer an object, but a string. The 'url' module was addded to parse that string. That is, node no longer parses the request URL automatically. require('url').parse(request.url) is roughly equivlent to the old request.uri object. (isaacs) * Bugfix: Several libeio related race conditions. * Better errors for multipart library (Felix Geisendörfer) * Bugfix: Update node-waf version to 1.5.10 * getmem for freebsd (Vanilla Hsu) 2009.12.31, Version 0.1.24, 642c2773a7eb2034f597af1cd404b9e086b59632 * Bugfix: don't chunk responses to HTTP/1.0 clients, even if they send Connection: Keep-Alive (e.g. wget) * Bugfix: libeio race condition * Bugfix: Don't segfault on unknown http method * Simplify exception reporting * Upgrade V8 to 2.0.5.4 2009.12.22, Version 0.1.23, f91e347eeeeac1a8bd6a7b462df0321b60f3affc * Bugfix: require("../blah") issues (isaacs) * Bugfix: posix.cat (Jonas Pfenniger) * Do not pause request for multipart parsing (Felix Geisendörfer) 2009.12.19, Version 0.1.22, a2d809fe902f6c4102dba8f2e3e9551aad137c0f * Bugfix: child modules get wrong id with "index.js" (isaacs) * Bugfix: require("../foo") cycles (isaacs) * Bugfix: require() should throw error if module does. * New URI parser stolen from Narwhal (isaacs) * Bugfix: correctly check kqueue and epoll. (Rasmus Andersson) * Upgrade WAF to 1.5.10 * Bugfix: posix.statSync() was crashing * Statically define string symbols for performance improvement * Bugfix: ARGV[0] weirdness * Added superCtor to ctor.super_ instead superCtor.prototype. (Johan Dahlberg) * http-parser supports webdav methods * API: http.Client.prototype.request() (Christopher Lenz) 2009.12.06, Version 0.1.21, c6affb64f96a403a14d20035e7fbd6d0ce089db5 * Feature: Add HTTP client TLS support (Rhys Jones) * Bugfix: use --jobs=1 with WAF * Bugfix: Don't use chunked encoding for 1.0 requests * Bugfix: Duplicated header weren't handled correctly * Improve sys.inspect (Xavier Shay) * Upgrade v8 to 2.0.3 * Use CommonJS assert API (Felix Geisendörfer, Karl Guertin) 2009.11.28, Version 0.1.20, aa42c6790da8ed2cd2b72051c07f6251fe1724d8 * Add gnutls version to configure script * Add V8 heap info to process.memoryUsage() * process.watchFile callback has 2 arguments with the stat object (choonkeat@gmail.com) 2009.11.28, Version 0.1.19, 633d6be328708055897b72327b88ac88e158935f * Feature: Initial TLS support for TCP servers and clients. (Rhys Jones) * Add options to process.watchFile() * Add process.umask() (Friedemann Altrock) * Bugfix: only detach timers when active. * Bugfix: lib/file.js write(), shouldn't always emit errors or success (onne@onnlucky.com) * Bugfix: Memory leak in fs.write (Reported by onne@onnlucky.com) * Bugfix: Fix regular expressions detecting outgoing message headers. (Reported by Elliott Cable) * Improvements to Multipart parser (Felix Geisendörfer) * New HTTP parser * Upgrade v8 to 2.0.2 2009.11.17, Version 0.1.18, 027829d2853a14490e6de9fc5f7094652d045ab8 * Feature: process.watchFile() process.unwatchFile() * Feature: "uncaughtException" event on process (Felix Geisendörfer) * Feature: 'drain' event to tcp.Connection * Bugfix: Promise.timeout() blocked the event loop (Felix Geisendörfer) * Bugfix: sendBody() and chunked utf8 strings (Felix Geisendörfer) * Supply the strerror as a second arg to the tcp.Connection close event (Johan Sørensen) * Add EventEmitter.removeListener (frodenius@gmail.com) * Format JSON for inspecting objects (Felix Geisendörfer) * Upgrade libev to latest CVS 2009.11.07, Version 0.1.17, d1f69ef35dac810530df8249d523add168e09f03 * Feature: process.chdir() (Brandon Beacher) * Revert http parser upgrade. (b893859c34f05db5c45f416949ebc0eee665cca6) Broke keep-alive. * API: rename process.inherits to sys.inherits 2009.11.03, Version 0.1.16, 726865af7bbafe58435986f4a193ff11c84e4bfe * API: Use CommonJS-style module requiring - require("/sys.js") becomes require("sys") - require("circle.js") becomes require("./circle") - process.path.join() becomes require("path").join() - __module becomes module * API: Many namespacing changes - Move node.* into process.* - Move node.dns into module "dns" - Move node.fs into module "posix" - process is no longer the global object. GLOBAL is. For more information on the API changes see: http://thread.gmane.org/gmane.comp.lang.javascript.nodejs/6 http://thread.gmane.org/gmane.comp.lang.javascript.nodejs/14 * Feature: process.platform, process.memoryUsage() * Feature: promise.cancel() (Felix Geisendörfer) * Upgrade V8 to 1.3.18 2009.10.28, Version 0.1.15, eca2de73ed786b935507fd1c6faccd8df9938fd3 * Many build system fixes (esp. for OSX users) * Feature: promise.timeout() (Felix Geisendörfer) * Feature: Added external interface for signal handlers, process.pid, and process.kill() (Brandon Beacher) * API: Rename node.libraryPaths to require.paths * Bugfix: 'data' event for stdio should emit a string * Large file support * Upgrade http_parser * Upgrade v8 to 1.3.16 2009.10.09, Version 0.1.14, b12c809bb84d1265b6a4d970a5b54ee8a4890513 * Feature: Improved addon builds with node-waf * Feature: node.SignalHandler (Brandon Beacher) * Feature: Enable V8 debugging (but still need to make a debugger) * API: Rename library /utils.js to /sys.js * Clean up Node's build system * Don't use parseUri for HTTP server * Remove node.pc * Don't use /bin/sh to create child process except with exec() * API: Add __module to reference current module * API: Remove include() add node.mixin() * Normalize http headers; "Content-Length" becomes "content-length" * Upgrade V8 to 1.3.15 2009.09.30, Version 0.1.13, 58493bb05b3da3dc8051fabc0bdea9e575c1a107 * Feature: Multipart stream parser (Felix Geisendörfer) * API: Move node.puts(), node.exec() and others to /utils.js * API: Move http, tcp libraries to /http.js and /tcp.js * API: Rename node.exit() to process.exit() * Bugfix: require() and include() should work in callbacks. * Pass the Host header in http.cat calls * Add warning when coroutine stack size grows too large. * Enhance repl library (Ray Morgan) * Bugfix: build script for GCC 4.4 (removed -Werror in V8), on Linux 2.4, and with Python 2.4.4. * Add read() and write() to /file.js to read and write whole files at once. 2009.09.24, Version 0.1.12, 2f56ccb45e87510de712f56705598b3b4e3548ec * Feature: System modules, node.libraryPaths * API: Remove "raw" encoding, rename "raws" to "binary". * API: Added connection.setNoDElay() to disable Nagle algo. * Decrease default TCP server backlog to 128 * Bugfix: memory leak involving node.fs.* methods. * Upgrade v8 to 1.3.13 2009.09.18, Version 0.1.11, 5ddc4f5d0c002bac0ae3d62fc0dc58f0d2d83ec4 * API: default to utf8 encoding for node.fs.cat() * API: add node.exec() * API: node.fs.read() takes a normal encoding parameter. * API: Change arguments of emit(), emitSuccess(), emitError() * Bugfix: node.fs.write() was stack allocating buffer. * Bugfix: ReportException shouldn't forget the top frame. * Improve buffering for HTTP outgoing messages * Fix and reenable x64 macintosh build. * Upgrade v8 to 1.3.11 2009.09.11, Version 0.1.10, 12bb0d46ce761e3d00a27170e63b40408c15b558 * Feature: raw string encoding "raws" * Feature: access to environ through "ENV" * Feature: add isDirectory, isFile, isSocket, ... methods to stats object. * Bugfix: Internally use full paths when loading modules this fixes a shebang loading problem. * Bugfix: Add '--' command line argument for seperating v8 args from program args. * Add man page. * Add node-repl * Upgrade v8 to 1.3.10 2009.09.05, Version 0.1.9, d029764bb32058389ecb31ed54a5d24d2915ad4c * Bugfix: Compile on Snow Leopard. * Bugfix: Malformed URIs raising exceptions. 2009.09.04, Version 0.1.8, e6d712a937b61567e81b15085edba863be16ba96 * Feature: External modules * Feature: setTimeout() for node.tcp.Connection * Feature: add node.cwd(), node.fs.readdir(), node.fs.mkdir() * Bugfix: promise.wait() releasing out of order. * Bugfix: Asyncly do getaddrinfo() on Apple. * Disable useless evcom error messages. * Better stack traces. * Built natively on x64. * Upgrade v8 to 1.3.9 2009.08.27, Version 0.1.7, f7acef9acf8ba8433d697ad5ed99d2e857387e4b * Feature: global 'process' object. Emits "exit". * Feature: promise.wait() * Feature: node.stdio * Feature: EventEmitters emit "newListener" when listeners are added * API: Use flat object instead of array-of-arrays for HTTP headers. * API: Remove buffered file object (node.File) * API: require(), include() are synchronous. (Uses continuations.) * API: Deprecate onLoad and onExit. * API: Rename node.Process to node.ChildProcess * Refactor node.Process to take advantage of evcom_reader/writer. * Upgrade v8 to 1.3.7 2009.08.22, Version 0.1.6, 9c97b1db3099d61cd292aa59ec2227a619f3a7ab * Bugfix: Ignore SIGPIPE. 2009.08.21, Version 0.1.5, b0fd3e281cb5f7cd8d3a26bd2b89e1b59998e5ed * Bugfix: Buggy connections could crash node.js. Now check connection before sending data every time (Kevin van Zonneveld) * Bugfix: stdin fd (0) being ignored by node.File. (Abe Fettig) * API: Remove connnection.fullClose() * API: Return the EventEmitter from addListener for chaining. * API: tcp.Connection "disconnect" event renamed to "close" * Upgrade evcom Upgrade v8 to 1.3.6 2009.08.13, Version 0.1.4, 0f888ed6de153f68c17005211d7e0f960a5e34f3 * Major refactor to evcom. * Enable test-tcp-many-clients. * Add -m32 gcc flag to udns. * Add connection.readPause() and connection.readResume() Add IncomingMessage.prototype.pause() and resume(). * Fix http benchmark. Wasn't correctly dispatching. * Bugfix: response.setBodyEncoding("ascii") not working. * Bugfix: Negative ints in HTTP's on_body and node.fs.read() * Upgrade v8 to 1.3.4 Upgrade libev to 3.8 Upgrade http_parser to v0.2 2009.08.06, Version 0.1.3, 695f0296e35b30cf8322fd1bd934810403cca9f3 * Upgrade v8 to 1.3.2 * Bugfix: node.http.ServerRequest.setBodyEncoding('ascii') not working * Bugfix: node.encodeUtf8 was broken. (Connor Dunn) * Add ranlib to udns Makefile. * Upgrade evcom - fix accepting too many connections issue. * Initial support for shebang * Add simple command line switches * Add node.version API 2009.08.01, Version 0.1.2, 025a34244d1cea94d6d40ad7bf92671cb909a96c * Add DNS API * node.tcp.Server's backlog option is now an argument to listen() * Upgrade V8 to 1.3.1 * Bugfix: Default to chunked for client requests without Content-Length. * Bugfix: Line numbers in stack traces. * Bugfix: negative integers in raw encoding stream * Bugfix: node.fs.File was not passing args to promise callbacks. 2009.07.27, Version 0.1.1, 77d407df2826b20e9177c26c0d2bb4481e497937 * Simplify and clean up ObjectWrap. * Upgrade liboi (which is now called evcom) Upgrade libev to 3.7 Upgrade V8 to 1.2.14 * Array.prototype.encodeUtf8 renamed to node.encodeUtf8(array) * Move EventEmitter.prototype.emit() completely into C++. * Bugfix: Fix memory leak in event emitters. http://groups.google.com/group/nodejs/browse_thread/thread/a8d1dfc2fd57a6d1 * Bugfix: Had problems reading scripts with non-ascii characters. * Bugfix: Fix Detach() in node::Server * Bugfix: Sockets not properly reattached if reconnected during disconnect event. * Bugfix: Server-side clients not attached between creation and on_connect. * Add 'close' event to node.tcp.Server * Simplify and clean up http.js. (Takes more advantage of event infrastructure.) * Add benchmark scripts. Run with "make benchmark". 2009.06.30, Version 0.1.0, 0fe44d52fe75f151bceb59534394658aae6ac328 * Update documentation, use asciidoc. * EventEmitter and Promise interfaces. (Breaks previous API.) * Remove node.Process constructor in favor of node.createProcess * Add -m32 flags for compiling on x64 platforms. (Thanks to András Bártházi) * Upgrade v8 to 1.2.10 and libev to 3.6 * Bugfix: Timer::RepeatSetter wasn't working. * Bugfix: Spawning many processes in a loop (reported by Felix Geisendörfer) 2009.06.24, Version 0.0.6, fbe0be19ebfb422d8fa20ea5204c1713e9214d5f * Load modules via HTTP URLs (Urban Hafner) * Bugfix: Add HTTPConnection->size() and HTTPServer->size() * New node.Process API * Clean up build tools, use v8's test runner. * Use ev_unref() instead of starting/stopping the eio thread pool watcher. 2009.06.18, Version 0.0.5, 3a2b41de74b6c343b8464a68eff04c4bfd9aebea * Support for IPv6 * Remove namespace node.constants * Upgrade v8 to 1.2.8.1 * Accept ports as strings in the TCP client and server. * Bugfix: HTTP Client race * Bugfix: freeaddrinfo() wasn't getting called after getaddrinfo() for TCP servers * Add "opening" to TCP client readyState * Add remoteAddress to TCP client * Add global print() function. 2009.06.13, Version 0.0.4, 916b9ca715b229b0703f0ed6c2fc065410fb189c * Add interrupt() method to server-side HTTP requests. * Bugfix: onBodyComplete was not getting called on server-side HTTP 2009.06.11, Version 0.0.3, 6e0dfe50006ae4f5dac987f055e0c9338662f40a * Many bug fixes including the problem with http.Client on macintosh * Upgrades v8 to 1.2.7 * Adds onExit hook * Guard against buffer overflow in http parser * require() and include() now need the ".js" extension * http.Client uses identity transfer encoding by default. node-v0.10.25~dfsg2/.travis.yml0000644000000000000000000000023612270121457014727 0ustar rootrootlanguage: node_js before_script: - "./configure" - "make" script: - "make test" notifications: email: false irc: - "irc.freenode.net#libuv" node-v0.10.25~dfsg2/configure0000755000000000000000000005073112270121457014532 0ustar rootroot#!/usr/bin/env python import optparse import os import pprint import re import shlex import subprocess import sys CC = os.environ.get('CC', 'cc') root_dir = os.path.dirname(__file__) sys.path.insert(0, os.path.join(root_dir, 'tools', 'gyp', 'pylib')) from gyp.common import GetFlavor # parse our options parser = optparse.OptionParser() parser.add_option("--debug", action="store_true", dest="debug", help="Also build debug build") parser.add_option("--prefix", action="store", dest="prefix", help="Select the install prefix (defaults to /usr/local)") parser.add_option("--without-npm", action="store_true", dest="without_npm", help="Don\'t install the bundled npm package manager") parser.add_option("--without-ssl", action="store_true", dest="without_ssl", help="Build without SSL") parser.add_option("--without-snapshot", action="store_true", dest="without_snapshot", help="Build without snapshotting V8 libraries. You might want to set" " this for cross-compiling. [Default: False]") parser.add_option("--shared-v8", action="store_true", dest="shared_v8", help="Link to a shared V8 DLL instead of static linking") parser.add_option("--shared-v8-includes", action="store", dest="shared_v8_includes", help="Directory containing V8 header files") parser.add_option("--shared-v8-libpath", action="store", dest="shared_v8_libpath", help="A directory to search for the shared V8 DLL") parser.add_option("--shared-v8-libname", action="store", dest="shared_v8_libname", help="Alternative lib name to link to (default: 'v8')") parser.add_option("--shared-openssl", action="store_true", dest="shared_openssl", help="Link to a shared OpenSSl DLL instead of static linking") parser.add_option("--shared-openssl-includes", action="store", dest="shared_openssl_includes", help="Directory containing OpenSSL header files") parser.add_option("--shared-openssl-libpath", action="store", dest="shared_openssl_libpath", help="A directory to search for the shared OpenSSL DLLs") parser.add_option("--shared-openssl-libname", action="store", dest="shared_openssl_libname", help="Alternative lib name to link to (default: 'crypto,ssl')") # deprecated parser.add_option("--openssl-use-sys", action="store_true", dest="shared_openssl", help=optparse.SUPPRESS_HELP) # deprecated parser.add_option("--openssl-includes", action="store", dest="shared_openssl_includes", help=optparse.SUPPRESS_HELP) # deprecated parser.add_option("--openssl-libpath", action="store", dest="shared_openssl_libpath", help=optparse.SUPPRESS_HELP) # TODO document when we've decided on what the tracing API and its options will # look like parser.add_option("--systemtap-includes", action="store", dest="systemtap_includes", help=optparse.SUPPRESS_HELP) parser.add_option("--no-ssl2", action="store_true", dest="no_ssl2", help="Disable OpenSSL v2") parser.add_option("--shared-zlib", action="store_true", dest="shared_zlib", help="Link to a shared zlib DLL instead of static linking") parser.add_option("--shared-zlib-includes", action="store", dest="shared_zlib_includes", help="Directory containing zlib header files") parser.add_option("--shared-zlib-libpath", action="store", dest="shared_zlib_libpath", help="A directory to search for the shared zlib DLL") parser.add_option("--shared-zlib-libname", action="store", dest="shared_zlib_libname", help="Alternative lib name to link to (default: 'z')") parser.add_option("--shared-http-parser", action="store_true", dest="shared_http_parser", help="Link to a shared http_parser DLL instead of static linking") parser.add_option("--shared-http-parser-includes", action="store", dest="shared_http_parser_includes", help="Directory containing http_parser header files") parser.add_option("--shared-http-parser-libpath", action="store", dest="shared_http_parser_libpath", help="A directory to search for the shared http_parser DLL") parser.add_option("--shared-http-parser-libname", action="store", dest="shared_http_parser_libname", help="Alternative lib name to link to (default: 'http_parser')") parser.add_option("--shared-cares", action="store_true", dest="shared_cares", help="Link to a shared cares DLL instead of static linking") parser.add_option("--shared-cares-includes", action="store", dest="shared_cares_includes", help="Directory containing cares header files") parser.add_option("--shared-cares-libpath", action="store", dest="shared_cares_libpath", help="A directory to search for the shared cares DLL") parser.add_option("--shared-cares-libname", action="store", dest="shared_cares_libname", help="Alternative lib name to link to (default: 'cares')") parser.add_option("--shared-libuv", action="store_true", dest="shared_libuv", help="Link to a shared libuv DLL instead of static linking") parser.add_option("--shared-libuv-includes", action="store", dest="shared_libuv_includes", help="Directory containing libuv header files") parser.add_option("--shared-libuv-libpath", action="store", dest="shared_libuv_libpath", help="A directory to search for the shared libuv DLL") parser.add_option("--shared-libuv-libname", action="store", dest="shared_libuv_libname", help="Alternative lib name to link to (default: 'uv')") parser.add_option("--with-dtrace", action="store_true", dest="with_dtrace", help="Build with DTrace (default is true on sunos)") parser.add_option("--without-dtrace", action="store_true", dest="without_dtrace", help="Build without DTrace") parser.add_option("--with-etw", action="store_true", dest="with_etw", help="Build with ETW (default is true on Windows)") parser.add_option("--without-etw", action="store_true", dest="without_etw", help="Build without ETW") parser.add_option("--with-perfctr", action="store_true", dest="with_perfctr", help="Build with performance counters (default is true on Windows)") parser.add_option("--without-perfctr", action="store_true", dest="without_perfctr", help="Build without performance counters") # CHECKME does this still work with recent releases of V8? parser.add_option("--gdb", action="store_true", dest="gdb", help="add gdb support") parser.add_option("--dest-cpu", action="store", dest="dest_cpu", help="CPU architecture to build for. Valid values are: arm, ia32, x64") parser.add_option("--dest-os", action="store", dest="dest_os", help="Operating system to build for. Valid values are: " "win, mac, solaris, freebsd, openbsd, linux") parser.add_option("--no-ifaddrs", action="store_true", dest="no_ifaddrs", help="Use on deprecated SunOS systems that do not support ifaddrs.h") parser.add_option("--with-arm-float-abi", action="store", dest="arm_float_abi", help="Specifies which floating-point ABI to use. Valid values are: " "soft, softfp, hard") parser.add_option("--with-mips-float-abi", action="store", dest="mips_float_abi", help="Specifies which floating-point ABI to use. Valid values are: " "soft, hard") parser.add_option("--ninja", action="store_true", dest="use_ninja", help="Generate files for the ninja build system") # Using --unsafe-optimizations voids your warranty. parser.add_option("--unsafe-optimizations", action="store_true", dest="unsafe_optimizations", help=optparse.SUPPRESS_HELP) parser.add_option("--xcode", action="store_true", dest="use_xcode", help="Generate build files for use with xcode") parser.add_option("--tag", action="store", dest="tag", help="Custom build tag") (options, args) = parser.parse_args() def b(value): """Returns the string 'true' if value is truthy, 'false' otherwise.""" if value: return 'true' else: return 'false' def pkg_config(pkg): cmd = os.popen('pkg-config --libs %s' % pkg, 'r') libs = cmd.readline().strip() ret = cmd.close() if (ret): return None cmd = os.popen('pkg-config --cflags %s' % pkg, 'r') cflags = cmd.readline().strip() ret = cmd.close() if (ret): return None return (libs, cflags) def cc_macros(): """Checks predefined macros using the CC command.""" try: p = subprocess.Popen(shlex.split(CC) + ['-dM', '-E', '-'], stdin=subprocess.PIPE, stdout=subprocess.PIPE, stderr=subprocess.PIPE) except OSError: print '''Node.js configure error: No acceptable C compiler found! Please make sure you have a C compiler installed on your system and/or consider adjusting the CC environment variable if you installed it in a non-standard prefix. ''' sys.exit() p.stdin.write('\n') out = p.communicate()[0] out = str(out).split('\n') k = {} for line in out: lst = shlex.split(line) if len(lst) > 2: key = lst[1] val = lst[2] k[key] = val return k def is_arch_armv7(): """Check for ARMv7 instructions""" cc_macros_cache = cc_macros() return ('__ARM_ARCH_7__' in cc_macros_cache or '__ARM_ARCH_7A__' in cc_macros_cache or '__ARM_ARCH_7R__' in cc_macros_cache or '__ARM_ARCH_7M__' in cc_macros_cache) def is_arm_neon(): """Check for ARM NEON support""" return '__ARM_NEON__' in cc_macros() def arm_hard_float_abi(): """Check for hardfloat or softfloat eabi on ARM""" # GCC versions 4.6 and above define __ARM_PCS or __ARM_PCS_VFP to specify # the Floating Point ABI used (PCS stands for Procedure Call Standard). # We use these as well as a couple of other defines to statically determine # what FP ABI used. # GCC versions 4.4 and below don't support hard-fp. # GCC versions 4.5 may support hard-fp without defining __ARM_PCS or # __ARM_PCS_VFP. if compiler_version() >= (4, 6, 0): return '__ARM_PCS_VFP' in cc_macros() elif compiler_version() < (4, 5, 0): return False elif '__ARM_PCS_VFP' in cc_macros(): return True elif ('__ARM_PCS' in cc_macros() or '__SOFTFP' in cc_macros() or not '__VFP_FP__' in cc_macros()): return False else: print '''Node.js configure error: Your version of GCC does not report the Floating-Point ABI to compile for your hardware Please manually specify which floating-point ABI to use with the --with-arm-float-abi option. ''' sys.exit() def host_arch_cc(): """Host architecture check using the CC command.""" k = cc_macros() matchup = { '__x86_64__' : 'x64', '__i386__' : 'ia32', '__arm__' : 'arm', '__mips__' : 'mips', } rtn = 'ia32' # default for i in matchup: if i in k and k[i] != '0': rtn = matchup[i] break return rtn def host_arch_win(): """Host architecture check using environ vars (better way to do this?)""" arch = os.environ.get('PROCESSOR_ARCHITECTURE', 'x86') matchup = { 'AMD64' : 'x64', 'x86' : 'ia32', 'arm' : 'arm', 'mips' : 'mips', } return matchup.get(arch, 'ia32') def compiler_version(): try: proc = subprocess.Popen(shlex.split(CC) + ['--version'], stdout=subprocess.PIPE) except WindowsError: return (0, False) is_clang = 'clang' in proc.communicate()[0].split('\n')[0] proc = subprocess.Popen(shlex.split(CC) + ['-dumpversion'], stdout=subprocess.PIPE) version = tuple(map(int, proc.communicate()[0].split('.'))) return (version, is_clang) def configure_arm(o): # V8 on ARM requires that armv7 is set. CPU Model detected by # the presence of __ARM_ARCH_7__ and the like defines in compiler if options.arm_float_abi: hard_float = options.arm_float_abi == 'hard' else: hard_float = arm_hard_float_abi() armv7 = is_arch_armv7() # CHECKME VFPv3 implies ARMv7+ but is the reverse true as well? fpu = 'vfpv3' if armv7 else 'vfpv2' o['variables']['armv7'] = int(armv7) o['variables']['arm_fpu'] = fpu o['variables']['arm_neon'] = int(is_arm_neon()) o['variables']['v8_use_arm_eabi_hardfloat'] = b(hard_float) def configure_mips(o): if options.mips_float_abi: if options.mips_float_abi in ('soft', 'hard'): o['variables']['v8_use_mips_abi_hardfloat'] = b( options.mips_float_abi == 'hard') else: raise Exception( 'Invalid mips-float-abi value. Valid values are: soft, hard') def configure_node(o): o['variables']['v8_enable_gdbjit'] = 1 if options.gdb else 0 o['variables']['v8_no_strict_aliasing'] = 1 # work around compiler bugs o['variables']['node_prefix'] = os.path.expanduser(options.prefix or '') o['variables']['node_install_npm'] = b(not options.without_npm) o['variables']['node_unsafe_optimizations'] = ( 1 if options.unsafe_optimizations else 0) o['default_configuration'] = 'Debug' if options.debug else 'Release' host_arch = host_arch_win() if os.name == 'nt' else host_arch_cc() target_arch = options.dest_cpu or host_arch o['variables']['host_arch'] = host_arch o['variables']['target_arch'] = target_arch if target_arch == 'arm': configure_arm(o) elif target_arch in ('mips', 'mipsel'): configure_mips(o) cc_version, is_clang = compiler_version() o['variables']['clang'] = 1 if is_clang else 0 if not is_clang and cc_version != 0: o['variables']['gcc_version'] = 10 * cc_version[0] + cc_version[1] # clang has always supported -fvisibility=hidden, right? if not is_clang and cc_version < (4,0,0): o['variables']['visibility'] = '' # By default, enable DTrace on SunOS systems. Don't allow it on other # systems, since it won't work. (The MacOS build process is different than # SunOS, and we haven't implemented it.) if flavor in ('solaris', 'mac'): o['variables']['node_use_dtrace'] = b(not options.without_dtrace) elif flavor == 'linux': o['variables']['node_use_dtrace'] = 'false' o['variables']['node_use_systemtap'] = b(options.with_dtrace) if options.systemtap_includes: o['include_dirs'] += [options.systemtap_includes] elif options.with_dtrace: raise Exception( 'DTrace is currently only supported on SunOS, MacOS or Linux systems.') else: o['variables']['node_use_dtrace'] = 'false' o['variables']['node_use_systemtap'] = 'false' if options.no_ifaddrs: o['defines'] += ['SUNOS_NO_IFADDRS'] # By default, enable ETW on Windows. if flavor == 'win': o['variables']['node_use_etw'] = b(not options.without_etw); elif options.with_etw: raise Exception('ETW is only supported on Windows.') else: o['variables']['node_use_etw'] = 'false' # By default, enable Performance counters on Windows. if flavor == 'win': o['variables']['node_use_perfctr'] = b(not options.without_perfctr); elif options.with_perfctr: raise Exception('Performance counter is only supported on Windows.') else: o['variables']['node_use_perfctr'] = 'false' if options.tag: o['variables']['node_tag'] = '-' + options.tag else: o['variables']['node_tag'] = '' def configure_libz(o): o['variables']['node_shared_zlib'] = b(options.shared_zlib) # assume shared_zlib if one of these is set? if options.shared_zlib_libpath: o['libraries'] += ['-L%s' % options.shared_zlib_libpath] if options.shared_zlib_libname: o['libraries'] += ['-l%s' % options.shared_zlib_libname] elif options.shared_zlib: o['libraries'] += ['-lz'] if options.shared_zlib_includes: o['include_dirs'] += [options.shared_zlib_includes] def configure_http_parser(o): o['variables']['node_shared_http_parser'] = b(options.shared_http_parser) # assume shared http_parser if one of these is set? if options.shared_http_parser_libpath: o['libraries'] += ['-L%s' % options.shared_http_parser_libpath] if options.shared_http_parser_libname: o['libraries'] += ['-l%s' % options.shared_http_parser_libname] elif options.shared_http_parser: o['libraries'] += ['-lhttp_parser'] if options.shared_http_parser_includes: o['include_dirs'] += [options.shared_http_parser_includes] def configure_cares(o): o['variables']['node_shared_cares'] = b(options.shared_cares) # assume shared cares if one of these is set? if options.shared_cares_libpath: o['libraries'] += ['-L%s' % options.shared_cares_libpath] if options.shared_cares_libname: o['libraries'] += ['-l%s' % options.shared_cares_libname] elif options.shared_cares: o['libraries'] += ['-lcares'] if options.shared_cares_includes: o['include_dirs'] += [options.shared_cares_includes] def configure_libuv(o): o['variables']['node_shared_libuv'] = b(options.shared_libuv) # assume shared libuv if one of these is set? if options.shared_libuv_libpath: o['libraries'] += ['-L%s' % options.shared_libuv_libpath] if options.shared_libuv_libname: o['libraries'] += ['-l%s' % options.shared_libuv_libname] elif options.shared_libuv: o['libraries'] += ['-luv'] if options.shared_libuv_includes: o['include_dirs'] += [options.shared_libuv_includes] def configure_v8(o): o['variables']['v8_use_snapshot'] = b(not options.without_snapshot) o['variables']['node_shared_v8'] = b(options.shared_v8) # assume shared_v8 if one of these is set? if options.shared_v8_libpath: o['libraries'] += ['-L%s' % options.shared_v8_libpath] if options.shared_v8_libname: o['libraries'] += ['-l%s' % options.shared_v8_libname] elif options.shared_v8: o['libraries'] += ['-lv8'] if options.shared_v8_includes: o['include_dirs'] += [options.shared_v8_includes] def configure_openssl(o): o['variables']['node_use_openssl'] = b(not options.without_ssl) o['variables']['node_shared_openssl'] = b(options.shared_openssl) if options.without_ssl: return if options.no_ssl2: o['defines'] += ['OPENSSL_NO_SSL2=1'] if options.shared_openssl: (libs, cflags) = pkg_config('openssl') or ('-lssl -lcrypto', '') if options.shared_openssl_libpath: o['libraries'] += ['-L%s' % options.shared_openssl_libpath] if options.shared_openssl_libname: libnames = options.shared_openssl_libname.split(',') o['libraries'] += ['-l%s' % s for s in libnames] else: o['libraries'] += libs.split() if options.shared_openssl_includes: o['include_dirs'] += [options.shared_openssl_includes] else: o['cflags'] += cflags.split() def configure_winsdk(o): if flavor != 'win': return winsdk_dir = os.environ.get("WindowsSdkDir") if winsdk_dir and os.path.isfile(winsdk_dir + '\\bin\\ctrpp.exe'): print "Found ctrpp in WinSDK--will build generated files into tools/msvs/genfiles." o['variables']['node_has_winsdk'] = 'true' return print "ctrpp not found in WinSDK path--using pre-gen files from tools/msvs/genfiles." # determine the "flavor" (operating system) we're building for, # leveraging gyp's GetFlavor function flavor_params = {}; if (options.dest_os): flavor_params['flavor'] = options.dest_os; flavor = GetFlavor(flavor_params); output = { 'variables': { 'python': sys.executable }, 'include_dirs': [], 'libraries': [], 'defines': [], 'cflags': [], } configure_node(output) configure_libz(output) configure_http_parser(output) configure_cares(output) configure_libuv(output) configure_v8(output) configure_openssl(output) configure_winsdk(output) # variables should be a root level element, # move everything else to target_defaults variables = output['variables'] del output['variables'] output = { 'variables': variables, 'target_defaults': output } pprint.pprint(output, indent=2) def write(filename, data): filename = os.path.join(root_dir, filename) print "creating ", filename f = open(filename, 'w+') f.write(data) write('config.gypi', "# Do not edit. Generated by the configure script.\n" + pprint.pformat(output, indent=2) + "\n") config = { 'BUILDTYPE': 'Debug' if options.debug else 'Release', 'USE_NINJA': str(int(options.use_ninja or 0)), 'USE_XCODE': str(int(options.use_xcode or 0)), 'PYTHON': sys.executable, } config = '\n'.join(map('='.join, config.iteritems())) + '\n' write('config.mk', '# Do not edit. Generated by the configure script.\n' + config) gyp_args = [sys.executable, 'tools/gyp_node.py', '--no-parallel'] if options.use_ninja: gyp_args += ['-f', 'ninja-' + flavor] elif options.use_xcode: gyp_args += ['-f', 'xcode'] elif flavor == 'win': gyp_args += ['-f', 'msvs', '-G', 'msvs_version=auto'] else: gyp_args += ['-f', 'make-' + flavor] gyp_args += args subprocess.call(gyp_args) node-v0.10.25~dfsg2/LICENSE0000644000000000000000000012061412270121457013626 0ustar rootrootNode's license follows: ==== Copyright Joyent, Inc. and other Node contributors. All rights reserved. Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. ==== This license applies to all parts of Node that are not externally maintained libraries. The externally maintained libraries used by Node are: - V8, located at deps/v8. V8's license follows: """ This license applies to all parts of V8 that are not externally maintained libraries. The externally maintained libraries used by V8 are: - PCRE test suite, located in test/mjsunit/third_party/regexp-pcre.js. This is based on the test suite from PCRE-7.3, which is copyrighted by the University of Cambridge and Google, Inc. The copyright notice and license are embedded in regexp-pcre.js. - Layout tests, located in test/mjsunit/third_party. These are based on layout tests from webkit.org which are copyrighted by Apple Computer, Inc. and released under a 3-clause BSD license. - Strongtalk assembler, the basis of the files assembler-arm-inl.h, assembler-arm.cc, assembler-arm.h, assembler-ia32-inl.h, assembler-ia32.cc, assembler-ia32.h, assembler-x64-inl.h, assembler-x64.cc, assembler-x64.h, assembler-mips-inl.h, assembler-mips.cc, assembler-mips.h, assembler.cc and assembler.h. This code is copyrighted by Sun Microsystems Inc. and released under a 3-clause BSD license. - Valgrind client API header, located at third_party/valgrind/valgrind.h This is release under the BSD license. These libraries have their own licenses; we recommend you read them, as their terms may differ from the terms below. Copyright 2006-2012, the V8 project authors. All rights reserved. Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: * Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. * Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution. * Neither the name of Google Inc. nor the names of its contributors may be used to endorse or promote products derived from this software without specific prior written permission. THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. """ - C-Ares, an asynchronous DNS client, located at deps/cares. C-Ares license follows: """ /* Copyright 1998 by the Massachusetts Institute of Technology. * * Permission to use, copy, modify, and distribute this * software and its documentation for any purpose and without * fee is hereby granted, provided that the above copyright * notice appear in all copies and that both that copyright * notice and this permission notice appear in supporting * documentation, and that the name of M.I.T. not be used in * advertising or publicity pertaining to distribution of the * software without specific, written prior permission. * M.I.T. makes no representations about the suitability of * this software for any purpose. It is provided "as is" * without express or implied warranty. """ - OpenSSL located at deps/openssl. OpenSSL is cryptographic software written by Eric Young (eay@cryptsoft.com) to provide SSL/TLS encryption. OpenSSL's license follows: """ /* ==================================================================== * Copyright (c) 1998-2011 The OpenSSL Project. All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * * 1. Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * 2. Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in * the documentation and/or other materials provided with the * distribution. * * 3. All advertising materials mentioning features or use of this * software must display the following acknowledgment: * "This product includes software developed by the OpenSSL Project * for use in the OpenSSL Toolkit. (http://www.openssl.org/)" * * 4. The names "OpenSSL Toolkit" and "OpenSSL Project" must not be used to * endorse or promote products derived from this software without * prior written permission. For written permission, please contact * openssl-core@openssl.org. * * 5. Products derived from this software may not be called "OpenSSL" * nor may "OpenSSL" appear in their names without prior written * permission of the OpenSSL Project. * * 6. Redistributions of any form whatsoever must retain the following * acknowledgment: * "This product includes software developed by the OpenSSL Project * for use in the OpenSSL Toolkit (http://www.openssl.org/)" * * THIS SOFTWARE IS PROVIDED BY THE OpenSSL PROJECT ``AS IS'' AND ANY * EXPRESSED OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE OpenSSL PROJECT OR * ITS CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, * STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED * OF THE POSSIBILITY OF SUCH DAMAGE. * ==================================================================== * * This product includes cryptographic software written by Eric Young * (eay@cryptsoft.com). This product includes software written by Tim * Hudson (tjh@cryptsoft.com). * */ """ - HTTP Parser, located at deps/http_parser. HTTP Parser's license follows: """ http_parser.c is based on src/http/ngx_http_parse.c from NGINX copyright Igor Sysoev. Additional changes are licensed under the same terms as NGINX and copyright Joyent, Inc. and other Node contributors. All rights reserved. Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. """ - Closure Linter is located at tools/closure_linter. Closure's license follows: """ # Copyright (c) 2007, Google Inc. # All rights reserved. # # Redistribution and use in source and binary forms, with or without # modification, are permitted provided that the following conditions are # met: # # * Redistributions of source code must retain the above copyright # notice, this list of conditions and the following disclaimer. # * Redistributions in binary form must reproduce the above # copyright notice, this list of conditions and the following disclaimer # in the documentation and/or other materials provided with the # distribution. # * Neither the name of Google Inc. nor the names of its # contributors may be used to endorse or promote products derived from # this software without specific prior written permission. # # THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS # "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT # LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR # A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT # OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, # SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT # LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, # DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY # THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT # (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE # OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. """ - tools/cpplint.py is a C++ linter. Its license follows: """ # Copyright (c) 2009 Google Inc. All rights reserved. # # Redistribution and use in source and binary forms, with or without # modification, are permitted provided that the following conditions are # met: # # * Redistributions of source code must retain the above copyright # notice, this list of conditions and the following disclaimer. # * Redistributions in binary form must reproduce the above # copyright notice, this list of conditions and the following disclaimer # in the documentation and/or other materials provided with the # distribution. # * Neither the name of Google Inc. nor the names of its # contributors may be used to endorse or promote products derived from # this software without specific prior written permission. # # THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS # "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT # LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR # A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT # OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, # SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT # LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, # DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY # THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT # (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE # OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. """ - lib/punycode.js is copyright 2011 Mathias Bynens and released under the MIT license. """ * Punycode.js * Copyright 2011 Mathias Bynens * Available under MIT license """ - tools/gyp. GYP is a meta-build system. GYP's license follows: """ Copyright (c) 2009 Google Inc. All rights reserved. Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: * Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. * Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution. * Neither the name of Google Inc. nor the names of its contributors may be used to endorse or promote products derived from this software without specific prior written permission. THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. """ - Zlib at deps/zlib. zlib's license follows: """ /* zlib.h -- interface of the 'zlib' general purpose compression library version 1.2.4, March 14th, 2010 Copyright (C) 1995-2010 Jean-loup Gailly and Mark Adler This software is provided 'as-is', without any express or implied warranty. In no event will the authors be held liable for any damages arising from the use of this software. Permission is granted to anyone to use this software for any purpose, including commercial applications, and to alter it and redistribute it freely, subject to the following restrictions: 1. The origin of this software must not be misrepresented; you must not claim that you wrote the original software. If you use this software in a product, an acknowledgment in the product documentation would be appreciated but is not required. 2. Altered source versions must be plainly marked as such, and must not be misrepresented as being the original software. 3. This notice may not be removed or altered from any source distribution. Jean-loup Gailly Mark Adler */ """ - npm is a package manager program located at deps/npm. npm's license follows: """ Copyright (c) Isaac Z. Schlueter All rights reserved. npm is released under the Artistic 2.0 License. The text of the License follows: -------- The Artistic License 2.0 Copyright (c) 2000-2006, The Perl Foundation. Everyone is permitted to copy and distribute verbatim copies of this license document, but changing it is not allowed. Preamble This license establishes the terms under which a given free software Package may be copied, modified, distributed, and/or redistributed. The intent is that the Copyright Holder maintains some artistic control over the development of that Package while still keeping the Package available as open source and free software. You are always permitted to make arrangements wholly outside of this license directly with the Copyright Holder of a given Package. If the terms of this license do not permit the full use that you propose to make of the Package, you should contact the Copyright Holder and seek a different licensing arrangement. Definitions "Copyright Holder" means the individual(s) or organization(s) named in the copyright notice for the entire Package. "Contributor" means any party that has contributed code or other material to the Package, in accordance with the Copyright Holder's procedures. "You" and "your" means any person who would like to copy, distribute, or modify the Package. "Package" means the collection of files distributed by the Copyright Holder, and derivatives of that collection and/or of those files. A given Package may consist of either the Standard Version, or a Modified Version. "Distribute" means providing a copy of the Package or making it accessible to anyone else, or in the case of a company or organization, to others outside of your company or organization. "Distributor Fee" means any fee that you charge for Distributing this Package or providing support for this Package to another party. It does not mean licensing fees. "Standard Version" refers to the Package if it has not been modified, or has been modified only in ways explicitly requested by the Copyright Holder. "Modified Version" means the Package, if it has been changed, and such changes were not explicitly requested by the Copyright Holder. "Original License" means this Artistic License as Distributed with the Standard Version of the Package, in its current version or as it may be modified by The Perl Foundation in the future. "Source" form means the source code, documentation source, and configuration files for the Package. "Compiled" form means the compiled bytecode, object code, binary, or any other form resulting from mechanical transformation or translation of the Source form. Permission for Use and Modification Without Distribution (1) You are permitted to use the Standard Version and create and use Modified Versions for any purpose without restriction, provided that you do not Distribute the Modified Version. Permissions for Redistribution of the Standard Version (2) You may Distribute verbatim copies of the Source form of the Standard Version of this Package in any medium without restriction, either gratis or for a Distributor Fee, provided that you duplicate all of the original copyright notices and associated disclaimers. At your discretion, such verbatim copies may or may not include a Compiled form of the Package. (3) You may apply any bug fixes, portability changes, and other modifications made available from the Copyright Holder. The resulting Package will still be considered the Standard Version, and as such will be subject to the Original License. Distribution of Modified Versions of the Package as Source (4) You may Distribute your Modified Version as Source (either gratis or for a Distributor Fee, and with or without a Compiled form of the Modified Version) provided that you clearly document how it differs from the Standard Version, including, but not limited to, documenting any non-standard features, executables, or modules, and provided that you do at least ONE of the following: (a) make the Modified Version available to the Copyright Holder of the Standard Version, under the Original License, so that the Copyright Holder may include your modifications in the Standard Version. (b) ensure that installation of your Modified Version does not prevent the user installing or running the Standard Version. In addition, the Modified Version must bear a name that is different from the name of the Standard Version. (c) allow anyone who receives a copy of the Modified Version to make the Source form of the Modified Version available to others under (i) the Original License or (ii) a license that permits the licensee to freely copy, modify and redistribute the Modified Version using the same licensing terms that apply to the copy that the licensee received, and requires that the Source form of the Modified Version, and of any works derived from it, be made freely available in that license fees are prohibited but Distributor Fees are allowed. Distribution of Compiled Forms of the Standard Version or Modified Versions without the Source (5) You may Distribute Compiled forms of the Standard Version without the Source, provided that you include complete instructions on how to get the Source of the Standard Version. Such instructions must be valid at the time of your distribution. If these instructions, at any time while you are carrying out such distribution, become invalid, you must provide new instructions on demand or cease further distribution. If you provide valid instructions or cease distribution within thirty days after you become aware that the instructions are invalid, then you do not forfeit any of your rights under this license. (6) You may Distribute a Modified Version in Compiled form without the Source, provided that you comply with Section 4 with respect to the Source of the Modified Version. Aggregating or Linking the Package (7) You may aggregate the Package (either the Standard Version or Modified Version) with other packages and Distribute the resulting aggregation provided that you do not charge a licensing fee for the Package. Distributor Fees are permitted, and licensing fees for other components in the aggregation are permitted. The terms of this license apply to the use and Distribution of the Standard or Modified Versions as included in the aggregation. (8) You are permitted to link Modified and Standard Versions with other works, to embed the Package in a larger work of your own, or to build stand-alone binary or bytecode versions of applications that include the Package, and Distribute the result without restriction, provided the result does not expose a direct interface to the Package. Items That are Not Considered Part of a Modified Version (9) Works (including, but not limited to, modules and scripts) that merely extend or make use of the Package, do not, by themselves, cause the Package to be a Modified Version. In addition, such works are not considered parts of the Package itself, and are not subject to the terms of this license. General Provisions (10) Any use, modification, and distribution of the Standard or Modified Versions is governed by this Artistic License. By using, modifying or distributing the Package, you accept this license. Do not use, modify, or distribute the Package, if you do not accept this license. (11) If your Modified Version has been derived from a Modified Version made by someone other than you, you are nevertheless required to ensure that your Modified Version complies with the requirements of this license. (12) This license does not grant you the right to use any trademark, service mark, tradename, or logo of the Copyright Holder. (13) This license includes the non-exclusive, worldwide, free-of-charge patent license to make, have made, use, offer to sell, sell, import and otherwise transfer the Package with respect to any patent claims licensable by the Copyright Holder that are necessarily infringed by the Package. If you institute patent litigation (including a cross-claim or counterclaim) against any party alleging that the Package constitutes direct or contributory patent infringement, then this Artistic License to you shall terminate on the date that such litigation is filed. (14) Disclaimer of Warranty: THE PACKAGE IS PROVIDED BY THE COPYRIGHT HOLDER AND CONTRIBUTORS "AS IS' AND WITHOUT ANY EXPRESS OR IMPLIED WARRANTIES. THE IMPLIED WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE, OR NON-INFRINGEMENT ARE DISCLAIMED TO THE EXTENT PERMITTED BY YOUR LOCAL LAW. UNLESS REQUIRED BY LAW, NO COPYRIGHT HOLDER OR CONTRIBUTOR WILL BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, OR CONSEQUENTIAL DAMAGES ARISING IN ANY WAY OUT OF THE USE OF THE PACKAGE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. -------- "Node.js" and "node" trademark Joyent, Inc. npm is not officially part of the Node.js project, and is neither owned by nor officially affiliated with Joyent, Inc. Packages published in the npm registry (other than the Software and its included dependencies) are not part of npm itself, are the sole property of their respective maintainers, and are not covered by this license. "npm Logo" created by Mathias Pettersson and Brian Hammond, used with permission. "Gubblebum Blocky" font Copyright (c) by Tjarda Koster, http://jelloween.deviantart.com included for use in the npm website and documentation, used with permission. This program uses several Node modules contained in the node_modules/ subdirectory, according to the terms of their respective licenses. """ - tools/doc/node_modules/marked. Marked is a Markdown parser. Marked's license follows: """ Copyright (c) 2011-2012, Christopher Jeffrey (https://github.com/chjj/) Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. """ - test/gc/node_modules/weak. Node-weak is a node.js addon that provides garbage collector notifications. Node-weak's license follows: """ Copyright (c) 2011, Ben Noordhuis Permission to use, copy, modify, and/or distribute this software for any purpose with or without fee is hereby granted, provided that the above copyright notice and this permission notice appear in all copies. THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. """ - src/ngx-queue.h. ngx-queue.h is taken from the nginx source tree. nginx's license follows: """ Copyright (C) 2002-2012 Igor Sysoev Copyright (C) 2011,2012 Nginx, Inc. Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: 1. Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. 2. Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution. THIS SOFTWARE IS PROVIDED BY AUTHOR AND CONTRIBUTORS ``AS IS'' AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL AUTHOR OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. """ - wrk is located at tools/wrk. wrk's license follows: """ Apache License Version 2.0, January 2004 http://www.apache.org/licenses/ TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION 1. Definitions. "License" shall mean the terms and conditions for use, reproduction, and distribution as defined by Sections 1 through 9 of this document. "Licensor" shall mean the copyright owner or entity authorized by the copyright owner that is granting the License. "Legal Entity" shall mean the union of the acting entity and all other entities that control, are controlled by, or are under common control with that entity. For the purposes of this definition, "control" means (i) the power, direct or indirect, to cause the direction or management of such entity, whether by contract or otherwise, or (ii) ownership of fifty percent (50%) or more of the outstanding shares, or (iii) beneficial ownership of such entity. "You" (or "Your") shall mean an individual or Legal Entity exercising permissions granted by this License. "Source" form shall mean the preferred form for making modifications, including but not limited to software source code, documentation source, and configuration files. "Object" form shall mean any form resulting from mechanical transformation or translation of a Source form, including but not limited to compiled object code, generated documentation, and conversions to other media types. "Work" shall mean the work of authorship, whether in Source or Object form, made available under the License, as indicated by a copyright notice that is included in or attached to the work (an example is provided in the Appendix below). "Derivative Works" shall mean any work, whether in Source or Object form, that is based on (or derived from) the Work and for which the editorial revisions, annotations, elaborations, or other modifications represent, as a whole, an original work of authorship. For the purposes of this License, Derivative Works shall not include works that remain separable from, or merely link (or bind by name) to the interfaces of, the Work and Derivative Works thereof. "Contribution" shall mean any work of authorship, including the original version of the Work and any modifications or additions to that Work or Derivative Works thereof, that is intentionally submitted to Licensor for inclusion in the Work by the copyright owner or by an individual or Legal Entity authorized to submit on behalf of the copyright owner. For the purposes of this definition, "submitted" means any form of electronic, verbal, or written communication sent to the Licensor or its representatives, including but not limited to communication on electronic mailing lists, source code control systems, and issue tracking systems that are managed by, or on behalf of, the Licensor for the purpose of discussing and improving the Work, but excluding communication that is conspicuously marked or otherwise designated in writing by the copyright owner as "Not a Contribution." "Contributor" shall mean Licensor and any individual or Legal Entity on behalf of whom a Contribution has been received by Licensor and subsequently incorporated within the Work. 2. Grant of Copyright License. Subject to the terms and conditions of this License, each Contributor hereby grants to You a perpetual, worldwide, non-exclusive, no-charge, royalty-free, irrevocable copyright license to reproduce, prepare Derivative Works of, publicly display, publicly perform, sublicense, and distribute the Work and such Derivative Works in Source or Object form. 3. Grant of Patent License. Subject to the terms and conditions of this License, each Contributor hereby grants to You a perpetual, worldwide, non-exclusive, no-charge, royalty-free, irrevocable (except as stated in this section) patent license to make, have made, use, offer to sell, sell, import, and otherwise transfer the Work, where such license applies only to those patent claims licensable by such Contributor that are necessarily infringed by their Contribution(s) alone or by combination of their Contribution(s) with the Work to which such Contribution(s) was submitted. If You institute patent litigation against any entity (including a cross-claim or counterclaim in a lawsuit) alleging that the Work or a Contribution incorporated within the Work constitutes direct or contributory patent infringement, then any patent licenses granted to You under this License for that Work shall terminate as of the date such litigation is filed. 4. Redistribution. You may reproduce and distribute copies of the Work or Derivative Works thereof in any medium, with or without modifications, and in Source or Object form, provided that You meet the following conditions: (a) You must give any other recipients of the Work or Derivative Works a copy of this License; and (b) You must cause any modified files to carry prominent notices stating that You changed the files; and (c) You must retain, in the Source form of any Derivative Works that You distribute, all copyright, patent, trademark, and attribution notices from the Source form of the Work, excluding those notices that do not pertain to any part of the Derivative Works; and (d) If the Work includes a "NOTICE" text file as part of its distribution, then any Derivative Works that You distribute must include a readable copy of the attribution notices contained within such NOTICE file, excluding those notices that do not pertain to any part of the Derivative Works, in at least one of the following places: within a NOTICE text file distributed as part of the Derivative Works; within the Source form or documentation, if provided along with the Derivative Works; or, within a display generated by the Derivative Works, if and wherever such third-party notices normally appear. The contents of the NOTICE file are for informational purposes only and do not modify the License. You may add Your own attribution notices within Derivative Works that You distribute, alongside or as an addendum to the NOTICE text from the Work, provided that such additional attribution notices cannot be construed as modifying the License. You may add Your own copyright statement to Your modifications and may provide additional or different license terms and conditions for use, reproduction, or distribution of Your modifications, or for any such Derivative Works as a whole, provided Your use, reproduction, and distribution of the Work otherwise complies with the conditions stated in this License. 5. Submission of Contributions. Unless You explicitly state otherwise, any Contribution intentionally submitted for inclusion in the Work by You to the Licensor shall be under the terms and conditions of this License, without any additional terms or conditions. Notwithstanding the above, nothing herein shall supersede or modify the terms of any separate license agreement you may have executed with Licensor regarding such Contributions. 6. Trademarks. This License does not grant permission to use the trade names, trademarks, service marks, or product names of the Licensor, except as required for reasonable and customary use in describing the origin of the Work and reproducing the content of the NOTICE file. 7. Disclaimer of Warranty. Unless required by applicable law or agreed to in writing, Licensor provides the Work (and each Contributor provides its Contributions) on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied, including, without limitation, any warranties or conditions of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A PARTICULAR PURPOSE. You are solely responsible for determining the appropriateness of using or redistributing the Work and assume any risks associated with Your exercise of permissions under this License. 8. Limitation of Liability. In no event and under no legal theory, whether in tort (including negligence), contract, or otherwise, unless required by applicable law (such as deliberate and grossly negligent acts) or agreed to in writing, shall any Contributor be liable to You for damages, including any direct, indirect, special, incidental, or consequential damages of any character arising as a result of this License or out of the use or inability to use the Work (including but not limited to damages for loss of goodwill, work stoppage, computer failure or malfunction, or any and all other commercial damages or losses), even if such Contributor has been advised of the possibility of such damages. 9. Accepting Warranty or Additional Liability. While redistributing the Work or Derivative Works thereof, You may choose to offer, and charge a fee for, acceptance of support, warranty, indemnity, or other liability obligations and/or rights consistent with this License. However, in accepting such obligations, You may act only on Your own behalf and on Your sole responsibility, not on behalf of any other Contributor, and only if You agree to indemnify, defend, and hold each Contributor harmless for any liability incurred by, or claims asserted against, such Contributor by reason of your accepting any such warranty or additional liability. END OF TERMS AND CONDITIONS """ node-v0.10.25~dfsg2/.gitattributes0000644000000000000000000000002612270121457015506 0ustar rootroottest/fixtures/* -text node-v0.10.25~dfsg2/CONTRIBUTING.md0000644000000000000000000001101012270121457015037 0ustar rootroot# CONTRIBUTING The node.js project welcomes new contributors. This document will guide you through the process. ### FORK Fork the project [on GitHub](https://github.com/joyent/node) and check out your copy. ``` $ git clone git@github.com:username/node.git $ cd node $ git remote add upstream git://github.com/joyent/node.git ``` Now decide if you want your feature or bug fix to go into the master branch or the stable branch. As a rule of thumb, bug fixes go into the stable branch while new features go into the master branch. The stable branch is effectively frozen; patches that change the node.js API/ABI or affect the run-time behavior of applications get rejected. The rules for the master branch are less strict; consult the [stability index page][] for details. In a nutshell, modules are at varying levels of API stability. Bug fixes are always welcome but API or behavioral changes to modules at stability level 3 and up are off-limits. Node.js has several bundled dependencies in the deps/ and the tools/ directories that are not part of the project proper. Any changes to files in those directories or its subdirectories should be sent to their respective projects. Do not send your patch to us, we cannot accept it. In case of doubt, open an issue in the [issue tracker][], post your question to the [node.js mailing list][] or contact one of the [project maintainers][] on [IRC][]. Especially do so if you plan to work on something big. Nothing is more frustrating than seeing your hard work go to waste because your vision does not align with that of a project maintainer. ### BRANCH Okay, so you have decided on the proper branch. Create a feature branch and start hacking: ``` $ git checkout -b my-feature-branch -t origin/v0.10 ``` (Where v0.10 is the latest stable branch as of this writing.) ### COMMIT Make sure git knows your name and email address: ``` $ git config --global user.name "J. Random User" $ git config --global user.email "j.random.user@example.com" ``` Writing good commit logs is important. A commit log should describe what changed and why. Follow these guidelines when writing one: 1. The first line should be 50 characters or less and contain a short description of the change prefixed with the name of the changed subsystem (e.g. "net: add localAddress and localPort to Socket"). 2. Keep the second line blank. 3. Wrap all other lines at 72 columns. A good commit log looks like this: ``` subsystem: explaining the commit in one line Body of commit message is a few lines of text, explaining things in more detail, possibly giving some background about the issue being fixed, etc etc. The body of the commit message can be several paragraphs, and please do proper word-wrap and keep columns shorter than about 72 characters or so. That way `git log` will show things nicely even when it is indented. ``` The header line should be meaningful; it is what other people see when they run `git shortlog` or `git log --oneline`. Check the output of `git log --oneline files_that_you_changed` to find out what subsystem (or subsystems) your changes touch. ### REBASE Use `git rebase` (not `git merge`) to sync your work from time to time. ``` $ git fetch upstream $ git rebase upstream/v0.10 # or upstream/master ``` ### TEST Bug fixes and features should come with tests. Add your tests in the test/simple/ directory. Look at other tests to see how they should be structured (license boilerplate, common includes, etc.). ``` $ make jslint test ``` Make sure the linter is happy and that all tests pass. Please, do not submit patches that fail either check. ### PUSH ``` $ git push origin my-feature-branch ``` Go to https://github.com/username/node and select your feature branch. Click the 'Pull Request' button and fill out the form. Pull requests are usually reviewed within a few days. If there are comments to address, apply your changes in a separate commit and push that to your feature branch. Post a comment in the pull request afterwards; GitHub does not send out notifications when you add commits. ### CONTRIBUTOR LICENSE AGREEMENT Please visit http://nodejs.org/cla.html and sign the Contributor License Agreement. You only need to do that once. [stability index page]: https://github.com/joyent/node/blob/master/doc/api/documentation.markdown [issue tracker]: https://github.com/joyent/node/issues [node.js mailing list]: http://groups.google.com/group/nodejs [IRC]: http://webchat.freenode.net/?channels=node.js [project maintainers]: https://github.com/joyent/node/wiki/Project-Organization node-v0.10.25~dfsg2/src/0000755000000000000000000000000012270121457013404 5ustar rootrootnode-v0.10.25~dfsg2/src/macros.py0000644000000000000000000000073312270121457015245 0ustar rootroot# This file is used by tools/js2c.py to preprocess out the DTRACE symbols in # builds that don't support DTrace. This is not used in builds that support # DTrace. macro DTRACE_HTTP_CLIENT_REQUEST(x) = ; macro DTRACE_HTTP_CLIENT_RESPONSE(x) = ; macro DTRACE_HTTP_SERVER_REQUEST(x) = ; macro DTRACE_HTTP_SERVER_RESPONSE(x) = ; macro DTRACE_NET_SERVER_CONNECTION(x) = ; macro DTRACE_NET_STREAM_END(x) = ; macro DTRACE_NET_SOCKET_READ(x) = ; macro DTRACE_NET_SOCKET_WRITE(x) = ; node-v0.10.25~dfsg2/src/node_win32_perfctr_provider.cc0000644000000000000000000002701112270121457021322 0ustar rootroot// Copyright Joyent, Inc. and other Node contributors. // // Permission is hereby granted, free of charge, to any person obtaining a // copy of this software and associated documentation files (the // "Software"), to deal in the Software without restriction, including // without limitation the rights to use, copy, modify, merge, publish, // distribute, sublicense, and/or sell copies of the Software, and to permit // persons to whom the Software is furnished to do so, subject to the // following conditions: // // The above copyright notice and this permission notice shall be included // in all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS // OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF // MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN // NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, // DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR // OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE // USE OR OTHER DEALINGS IN THE SOFTWARE. #include "node_counters.h" #include #include "node_win32_perfctr_provider.h" #define __INIT_node_perfctr_provider_IMP #include typedef ULONG (WINAPI *PerfStartProviderExFunc)( __in LPGUID ProviderGuid, __in_opt PPERF_PROVIDER_CONTEXT ProviderContext, __out PHANDLE Provider ); typedef ULONG (WINAPI *PerfStopProviderFunc)( __in HANDLE ProviderHandle ); typedef ULONG (WINAPI *PerfSetCounterSetInfoFunc)( __in HANDLE ProviderHandle, __inout_bcount(TemplateSize) PPERF_COUNTERSET_INFO Template, __in ULONG TemplateSize ); typedef PPERF_COUNTERSET_INSTANCE (WINAPI *PerfCreateInstanceFunc)( __in HANDLE ProviderHandle, __in LPCGUID CounterSetGuid, __in PCWSTR Name, __in ULONG Id ); typedef ULONG (WINAPI *PerfDeleteInstanceFunc)( __in HANDLE Provider, __in PPERF_COUNTERSET_INSTANCE InstanceBlock ); typedef ULONG (WINAPI *PerfSetULongCounterValueFunc)( __in HANDLE Provider, __inout PPERF_COUNTERSET_INSTANCE Instance, __in ULONG CounterId, __in ULONG Value ); typedef ULONG (WINAPI *PerfSetULongLongCounterValueFunc)( __in HANDLE Provider, __inout PPERF_COUNTERSET_INSTANCE Instance, __in ULONG CounterId, __in ULONGLONG Value ); typedef ULONG (WINAPI *PerfIncrementULongCounterValueFunc)( __in HANDLE Provider, __inout PPERF_COUNTERSET_INSTANCE Instance, __in ULONG CounterId, __in ULONG Value ); typedef ULONG (WINAPI *PerfIncrementULongLongCounterValueFunc)( __in HANDLE Provider, __inout PPERF_COUNTERSET_INSTANCE Instance, __in ULONG CounterId, __in ULONGLONG Value ); typedef ULONG (WINAPI *PerfDecrementULongCounterValueFunc)( __in HANDLE Provider, __inout PPERF_COUNTERSET_INSTANCE Instance, __in ULONG CounterId, __in ULONG Value ); typedef ULONG (WINAPI *PerfDecrementULongLongCounterValueFunc)( __in HANDLE Provider, __inout PPERF_COUNTERSET_INSTANCE Instance, __in ULONG CounterId, __in ULONGLONG Value ); HMODULE advapimod; PerfStartProviderExFunc perfctr_startProvider; PerfStopProviderFunc perfctr_stopProvider; PerfSetCounterSetInfoFunc perfctr_setCounterSetInfo; PerfCreateInstanceFunc perfctr_createInstance; PerfDeleteInstanceFunc perfctr_deleteInstance; PerfSetULongCounterValueFunc perfctr_setULongValue; PerfSetULongLongCounterValueFunc perfctr_setULongLongValue; PerfIncrementULongCounterValueFunc perfctr_incrementULongValue; PerfIncrementULongLongCounterValueFunc perfctr_incrementULongLongValue; PerfDecrementULongCounterValueFunc perfctr_decrementULongValue; PerfDecrementULongLongCounterValueFunc perfctr_decrementULongLongValue; PPERF_COUNTERSET_INSTANCE perfctr_instance; #define NODE_COUNTER_HTTP_SERVER_REQUEST 1 #define NODE_COUNTER_HTTP_SERVER_RESPONSE 2 #define NODE_COUNTER_HTTP_CLIENT_REQUEST 3 #define NODE_COUNTER_HTTP_CLIENT_RESPONSE 4 #define NODE_COUNTER_SERVER_CONNS 5 #define NODE_COUNTER_NET_BYTES_SENT 6 #define NODE_COUNTER_NET_BYTES_RECV 7 #define NODE_COUNTER_GC_PERCENTTIME 8 #define NODE_COUNTER_PIPE_BYTES_SENT 9 #define NODE_COUNTER_PIPE_BYTES_RECV 10 namespace node { EXTERN_C DECLSPEC_SELECTANY HANDLE NodeCounterProvider = NULL; void InitPerfCountersWin32() { ULONG status; PERF_PROVIDER_CONTEXT providerContext; // create instance name using pid #define INST_MAX_LEN 32 #define INST_PREFIX_LEN 5 #define INST_PREFIX L"node_" wchar_t Inst[INST_MAX_LEN]; DWORD pid = GetCurrentProcessId(); wcscpy_s(Inst, INST_MAX_LEN, INST_PREFIX); _itow_s(pid, Inst + INST_PREFIX_LEN, INST_MAX_LEN - INST_PREFIX_LEN, 10); advapimod = LoadLibrary("advapi32.dll"); if (advapimod) { perfctr_startProvider = (PerfStartProviderExFunc) GetProcAddress(advapimod, "PerfStartProviderEx"); perfctr_stopProvider = (PerfStopProviderFunc) GetProcAddress(advapimod, "PerfStopProvider"); perfctr_setCounterSetInfo = (PerfSetCounterSetInfoFunc) GetProcAddress(advapimod, "PerfSetCounterSetInfo"); perfctr_createInstance = (PerfCreateInstanceFunc) GetProcAddress(advapimod, "PerfCreateInstance"); perfctr_deleteInstance = (PerfDeleteInstanceFunc) GetProcAddress(advapimod, "PerfDeleteInstance"); perfctr_setULongValue = (PerfSetULongCounterValueFunc) GetProcAddress(advapimod, "PerfSetULongCounterValue"); perfctr_setULongLongValue = (PerfSetULongLongCounterValueFunc) GetProcAddress(advapimod, "PerfSetULongLongCounterValue"); perfctr_incrementULongValue = (PerfIncrementULongCounterValueFunc) GetProcAddress(advapimod, "PerfIncrementULongCounterValue"); perfctr_incrementULongLongValue = (PerfIncrementULongLongCounterValueFunc) GetProcAddress(advapimod, "PerfIncrementULongLongCounterValue"); perfctr_decrementULongValue = (PerfDecrementULongCounterValueFunc) GetProcAddress(advapimod, "PerfDecrementULongCounterValue"); perfctr_decrementULongLongValue = (PerfDecrementULongLongCounterValueFunc) GetProcAddress(advapimod, "PerfDecrementULongLongCounterValue"); ZeroMemory(&providerContext, sizeof(providerContext)); providerContext.ContextSize = sizeof(providerContext); if (!perfctr_startProvider || !perfctr_setCounterSetInfo || !perfctr_createInstance) { NodeCounterProvider = NULL; return; } status = perfctr_startProvider(&NodeCounterSetGuid, &providerContext, &NodeCounterProvider); if (status != ERROR_SUCCESS) { NodeCounterProvider = NULL; return; } status = perfctr_setCounterSetInfo(NodeCounterProvider, &NodeCounterSetInfo.CounterSet, sizeof(NodeCounterSetInfo)); if (status != ERROR_SUCCESS) { perfctr_stopProvider(NodeCounterProvider); NodeCounterProvider = NULL; return; } perfctr_instance = perfctr_createInstance(NodeCounterProvider, &NodeCounterSetGuid, Inst, 1); if (perfctr_instance == NULL) { perfctr_stopProvider(NodeCounterProvider); NodeCounterProvider = NULL; } } } void TermPerfCountersWin32() { if (NodeCounterProvider != NULL && perfctr_stopProvider != NULL) { perfctr_stopProvider(NodeCounterProvider); NodeCounterProvider = NULL; } if (advapimod) { FreeLibrary(advapimod); advapimod = NULL; } } void NODE_COUNT_HTTP_SERVER_REQUEST() { if (NodeCounterProvider != NULL && perfctr_incrementULongValue != NULL) { perfctr_incrementULongValue(NodeCounterProvider, perfctr_instance, NODE_COUNTER_HTTP_SERVER_REQUEST, 1); } } void NODE_COUNT_HTTP_SERVER_RESPONSE() { if (NodeCounterProvider != NULL && perfctr_incrementULongValue != NULL) { perfctr_incrementULongValue(NodeCounterProvider, perfctr_instance, NODE_COUNTER_HTTP_SERVER_RESPONSE, 1); } } void NODE_COUNT_HTTP_CLIENT_REQUEST() { if (NodeCounterProvider != NULL && perfctr_incrementULongValue != NULL) { perfctr_incrementULongValue(NodeCounterProvider, perfctr_instance, NODE_COUNTER_HTTP_CLIENT_REQUEST, 1); } } void NODE_COUNT_HTTP_CLIENT_RESPONSE() { if (NodeCounterProvider != NULL && perfctr_incrementULongValue != NULL) { perfctr_incrementULongValue(NodeCounterProvider, perfctr_instance, NODE_COUNTER_HTTP_CLIENT_RESPONSE, 1); } } void NODE_COUNT_SERVER_CONN_OPEN() { if (NodeCounterProvider != NULL && perfctr_incrementULongValue != NULL) { perfctr_incrementULongValue(NodeCounterProvider, perfctr_instance, NODE_COUNTER_SERVER_CONNS, 1); } } void NODE_COUNT_SERVER_CONN_CLOSE() { if (NodeCounterProvider != NULL && perfctr_decrementULongValue != NULL) { perfctr_decrementULongValue(NodeCounterProvider, perfctr_instance, NODE_COUNTER_SERVER_CONNS, 1); } } void NODE_COUNT_NET_BYTES_SENT(int bytes) { if (NodeCounterProvider != NULL && perfctr_incrementULongLongValue != NULL) { perfctr_incrementULongLongValue(NodeCounterProvider, perfctr_instance, NODE_COUNTER_NET_BYTES_SENT, static_cast(bytes)); } } void NODE_COUNT_NET_BYTES_RECV(int bytes) { if (NodeCounterProvider != NULL && perfctr_incrementULongLongValue != NULL) { perfctr_incrementULongLongValue(NodeCounterProvider, perfctr_instance, NODE_COUNTER_NET_BYTES_RECV, static_cast(bytes)); } } uint64_t NODE_COUNT_GET_GC_RAWTIME() { LARGE_INTEGER timegc; if (QueryPerformanceCounter(&timegc)) { return timegc.QuadPart; } else { return static_cast(GetTickCount()); } } void NODE_COUNT_GC_PERCENTTIME(unsigned int percent) { if (NodeCounterProvider != NULL && perfctr_setULongValue != NULL) { perfctr_setULongValue(NodeCounterProvider, perfctr_instance, NODE_COUNTER_GC_PERCENTTIME, percent); } } void NODE_COUNT_PIPE_BYTES_SENT(int bytes) { if (NodeCounterProvider != NULL && perfctr_incrementULongLongValue != NULL) { perfctr_incrementULongLongValue(NodeCounterProvider, perfctr_instance, NODE_COUNTER_PIPE_BYTES_SENT, static_cast(bytes)); } } void NODE_COUNT_PIPE_BYTES_RECV(int bytes) { if (NodeCounterProvider != NULL && perfctr_incrementULongLongValue != NULL) { perfctr_incrementULongLongValue(NodeCounterProvider, perfctr_instance, NODE_COUNTER_PIPE_BYTES_RECV, static_cast(bytes)); } } } node-v0.10.25~dfsg2/src/timer_wrap.cc0000644000000000000000000001145112270121457016066 0ustar rootroot// Copyright Joyent, Inc. and other Node contributors. // // Permission is hereby granted, free of charge, to any person obtaining a // copy of this software and associated documentation files (the // "Software"), to deal in the Software without restriction, including // without limitation the rights to use, copy, modify, merge, publish, // distribute, sublicense, and/or sell copies of the Software, and to permit // persons to whom the Software is furnished to do so, subject to the // following conditions: // // The above copyright notice and this permission notice shall be included // in all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS // OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF // MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN // NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, // DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR // OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE // USE OR OTHER DEALINGS IN THE SOFTWARE. #include "node.h" #include "handle_wrap.h" namespace node { using v8::Object; using v8::Handle; using v8::Local; using v8::Persistent; using v8::Value; using v8::HandleScope; using v8::FunctionTemplate; using v8::String; using v8::Function; using v8::TryCatch; using v8::Context; using v8::Arguments; using v8::Integer; static Persistent ontimeout_sym; class TimerWrap : public HandleWrap { public: static void Initialize(Handle target) { HandleScope scope; HandleWrap::Initialize(target); Local constructor = FunctionTemplate::New(New); constructor->InstanceTemplate()->SetInternalFieldCount(1); constructor->SetClassName(String::NewSymbol("Timer")); NODE_SET_PROTOTYPE_METHOD(constructor, "close", HandleWrap::Close); NODE_SET_PROTOTYPE_METHOD(constructor, "ref", HandleWrap::Ref); NODE_SET_PROTOTYPE_METHOD(constructor, "unref", HandleWrap::Unref); NODE_SET_PROTOTYPE_METHOD(constructor, "start", Start); NODE_SET_PROTOTYPE_METHOD(constructor, "stop", Stop); NODE_SET_PROTOTYPE_METHOD(constructor, "setRepeat", SetRepeat); NODE_SET_PROTOTYPE_METHOD(constructor, "getRepeat", GetRepeat); NODE_SET_PROTOTYPE_METHOD(constructor, "again", Again); ontimeout_sym = NODE_PSYMBOL("ontimeout"); target->Set(String::NewSymbol("Timer"), constructor->GetFunction()); } private: static Handle New(const Arguments& args) { // This constructor should not be exposed to public javascript. // Therefore we assert that we are not trying to call this as a // normal function. assert(args.IsConstructCall()); HandleScope scope; TimerWrap *wrap = new TimerWrap(args.This()); assert(wrap); return scope.Close(args.This()); } TimerWrap(Handle object) : HandleWrap(object, (uv_handle_t*) &handle_) { int r = uv_timer_init(uv_default_loop(), &handle_); assert(r == 0); handle_.data = this; } ~TimerWrap() { } static Handle Start(const Arguments& args) { HandleScope scope; UNWRAP(TimerWrap) int64_t timeout = args[0]->IntegerValue(); int64_t repeat = args[1]->IntegerValue(); int r = uv_timer_start(&wrap->handle_, OnTimeout, timeout, repeat); if (r) SetErrno(uv_last_error(uv_default_loop())); return scope.Close(Integer::New(r)); } static Handle Stop(const Arguments& args) { HandleScope scope; UNWRAP(TimerWrap) int r = uv_timer_stop(&wrap->handle_); if (r) SetErrno(uv_last_error(uv_default_loop())); return scope.Close(Integer::New(r)); } static Handle Again(const Arguments& args) { HandleScope scope; UNWRAP(TimerWrap) int r = uv_timer_again(&wrap->handle_); if (r) SetErrno(uv_last_error(uv_default_loop())); return scope.Close(Integer::New(r)); } static Handle SetRepeat(const Arguments& args) { HandleScope scope; UNWRAP(TimerWrap) int64_t repeat = args[0]->IntegerValue(); uv_timer_set_repeat(&wrap->handle_, repeat); return scope.Close(Integer::New(0)); } static Handle GetRepeat(const Arguments& args) { HandleScope scope; UNWRAP(TimerWrap) int64_t repeat = uv_timer_get_repeat(&wrap->handle_); if (repeat < 0) SetErrno(uv_last_error(uv_default_loop())); return scope.Close(Integer::New(repeat)); } static void OnTimeout(uv_timer_t* handle, int status) { HandleScope scope; TimerWrap* wrap = static_cast(handle->data); assert(wrap); Local argv[1] = { Integer::New(status) }; MakeCallback(wrap->object_, ontimeout_sym, ARRAY_SIZE(argv), argv); } uv_timer_t handle_; }; } // namespace node NODE_MODULE(node_timer_wrap, node::TimerWrap::Initialize) node-v0.10.25~dfsg2/src/node_http_parser.h0000644000000000000000000000246212270121457017121 0ustar rootroot// Copyright Joyent, Inc. and other Node contributors. // // Permission is hereby granted, free of charge, to any person obtaining a // copy of this software and associated documentation files (the // "Software"), to deal in the Software without restriction, including // without limitation the rights to use, copy, modify, merge, publish, // distribute, sublicense, and/or sell copies of the Software, and to permit // persons to whom the Software is furnished to do so, subject to the // following conditions: // // The above copyright notice and this permission notice shall be included // in all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS // OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF // MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN // NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, // DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR // OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE // USE OR OTHER DEALINGS IN THE SOFTWARE. #ifndef NODE_HTTP_PARSER #define NODE_HTTP_PARSER #include "v8.h" #include "http_parser.h" namespace node { void InitHttpParser(v8::Handle target); } #endif // NODE_HTTP_PARSER node-v0.10.25~dfsg2/src/node_file.cc0000644000000000000000000007402512270121457015647 0ustar rootroot// Copyright Joyent, Inc. and other Node contributors. // // Permission is hereby granted, free of charge, to any person obtaining a // copy of this software and associated documentation files (the // "Software"), to deal in the Software without restriction, including // without limitation the rights to use, copy, modify, merge, publish, // distribute, sublicense, and/or sell copies of the Software, and to permit // persons to whom the Software is furnished to do so, subject to the // following conditions: // // The above copyright notice and this permission notice shall be included // in all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS // OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF // MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN // NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, // DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR // OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE // USE OR OTHER DEALINGS IN THE SOFTWARE. #include "node.h" #include "node_file.h" #include "node_buffer.h" #include "node_stat_watcher.h" #include "req_wrap.h" #include #include #include #include #include #include #include #if defined(__MINGW32__) || defined(_MSC_VER) # include #endif namespace node { using namespace v8; #define MIN(a,b) ((a) < (b) ? (a) : (b)) #define TYPE_ERROR(msg) \ ThrowException(Exception::TypeError(String::New(msg))); #define THROW_BAD_ARGS TYPE_ERROR("Bad argument") class FSReqWrap: public ReqWrap { public: void* operator new(size_t size, char* storage) { return storage; } FSReqWrap(const char* syscall) : syscall_(syscall), dest_len_(0) { } inline const char* syscall() const { return syscall_; } inline const char* dest() const { return dest_; } inline unsigned int dest_len() const { return dest_len_; } inline void dest_len(unsigned int dest_len) { dest_len_ = dest_len; } private: const char* syscall_; unsigned int dest_len_; char dest_[1]; }; static Persistent oncomplete_sym; #define ASSERT_OFFSET(a) \ if (!(a)->IsUndefined() && !(a)->IsNull() && !IsInt64((a)->NumberValue())) { \ return ThrowException(Exception::TypeError(String::New("Not an integer"))); \ } #define ASSERT_TRUNCATE_LENGTH(a) \ if (!(a)->IsUndefined() && !(a)->IsNull() && !IsInt64((a)->NumberValue())) { \ return ThrowException(Exception::TypeError(String::New("Not an integer"))); \ } #define GET_OFFSET(a) ((a)->IsNumber() ? (a)->IntegerValue() : -1) #define GET_TRUNCATE_LENGTH(a) ((a)->IntegerValue()) static inline bool IsInt64(double x) { return x == static_cast(static_cast(x)); } static void After(uv_fs_t *req) { HandleScope scope; FSReqWrap* req_wrap = (FSReqWrap*) req->data; assert(&req_wrap->req_ == req); // there is always at least one argument. "error" int argc = 1; // Allocate space for two args. We may only use one depending on the case. // (Feel free to increase this if you need more) Local argv[2]; // NOTE: This may be needed to be changed if something returns a -1 // for a success, which is possible. if (req->result == -1) { // If the request doesn't have a path parameter set. if (!req->path) { argv[0] = UVException(req->errorno, NULL, req_wrap->syscall()); } else if ((req->errorno == UV_EEXIST || req->errorno == UV_ENOTEMPTY || req->errorno == UV_EPERM) && req_wrap->dest_len() > 0) { argv[0] = UVException(req->errorno, NULL, req_wrap->syscall(), req_wrap->dest()); } else { argv[0] = UVException(req->errorno, NULL, req_wrap->syscall(), static_cast(req->path)); } } else { // error value is empty or null for non-error. argv[0] = Local::New(Null()); // All have at least two args now. argc = 2; switch (req->fs_type) { // These all have no data to pass. case UV_FS_CLOSE: case UV_FS_RENAME: case UV_FS_UNLINK: case UV_FS_RMDIR: case UV_FS_MKDIR: case UV_FS_FTRUNCATE: case UV_FS_FSYNC: case UV_FS_FDATASYNC: case UV_FS_LINK: case UV_FS_SYMLINK: case UV_FS_CHMOD: case UV_FS_FCHMOD: case UV_FS_CHOWN: case UV_FS_FCHOWN: // These, however, don't. argc = 1; break; case UV_FS_UTIME: case UV_FS_FUTIME: argc = 0; break; case UV_FS_OPEN: argv[1] = Integer::New(req->result); break; case UV_FS_WRITE: argv[1] = Integer::New(req->result); break; case UV_FS_STAT: case UV_FS_LSTAT: case UV_FS_FSTAT: argv[1] = BuildStatsObject(static_cast(req->ptr)); break; case UV_FS_READLINK: argv[1] = String::New(static_cast(req->ptr)); break; case UV_FS_READ: // Buffer interface argv[1] = Integer::New(req->result); break; case UV_FS_READDIR: { char *namebuf = static_cast(req->ptr); int nnames = req->result; Local names = Array::New(nnames); for (int i = 0; i < nnames; i++) { Local name = String::New(namebuf); names->Set(Integer::New(i), name); #ifndef NDEBUG namebuf += strlen(namebuf); assert(*namebuf == '\0'); namebuf += 1; #else namebuf += strlen(namebuf) + 1; #endif } argv[1] = names; } break; default: assert(0 && "Unhandled eio response"); } } if (oncomplete_sym.IsEmpty()) { oncomplete_sym = NODE_PSYMBOL("oncomplete"); } MakeCallback(req_wrap->object_, oncomplete_sym, argc, argv); uv_fs_req_cleanup(&req_wrap->req_); delete req_wrap; } // This struct is only used on sync fs calls. // For async calls FSReqWrap is used. struct fs_req_wrap { fs_req_wrap() {} ~fs_req_wrap() { uv_fs_req_cleanup(&req); } // Ensure that copy ctor and assignment operator are not used. fs_req_wrap(const fs_req_wrap& req); fs_req_wrap& operator=(const fs_req_wrap& req); uv_fs_t req; }; #define ASYNC_DEST_CALL(func, callback, dest_path, ...) \ FSReqWrap* req_wrap; \ char* dest_str = (dest_path); \ int dest_len = dest_str == NULL ? 0 : strlen(dest_str); \ char* storage = new char[sizeof(*req_wrap) + dest_len]; \ req_wrap = new (storage) FSReqWrap(#func); \ req_wrap->dest_len(dest_len); \ if (dest_str != NULL) { \ memcpy(const_cast(req_wrap->dest()), \ dest_str, \ dest_len + 1); \ } \ int r = uv_fs_##func(uv_default_loop(), \ &req_wrap->req_, \ __VA_ARGS__, \ After); \ req_wrap->object_->Set(oncomplete_sym, callback); \ req_wrap->Dispatched(); \ if (r < 0) { \ uv_fs_t* req = &req_wrap->req_; \ req->result = r; \ req->path = NULL; \ req->errorno = uv_last_error(uv_default_loop()).code; \ After(req); \ } \ return scope.Close(req_wrap->object_); #define ASYNC_CALL(func, callback, ...) \ ASYNC_DEST_CALL(func, callback, NULL, __VA_ARGS__) \ #define SYNC_DEST_CALL(func, path, dest, ...) \ fs_req_wrap req_wrap; \ int result = uv_fs_##func(uv_default_loop(), \ &req_wrap.req, \ __VA_ARGS__, \ NULL); \ if (result < 0) { \ int code = uv_last_error(uv_default_loop()).code; \ if (dest != NULL && \ (code == UV_EEXIST || \ code == UV_ENOTEMPTY || \ code == UV_EPERM)) { \ return ThrowException(UVException(code, #func, "", dest)); \ } else { \ return ThrowException(UVException(code, #func, "", path)); \ } \ } \ #define SYNC_CALL(func, path, ...) \ SYNC_DEST_CALL(func, path, NULL, __VA_ARGS__) \ #define SYNC_REQ req_wrap.req #define SYNC_RESULT result static Handle Close(const Arguments& args) { HandleScope scope; if (args.Length() < 1 || !args[0]->IsInt32()) { return THROW_BAD_ARGS; } int fd = args[0]->Int32Value(); if (args[1]->IsFunction()) { ASYNC_CALL(close, args[1], fd) } else { SYNC_CALL(close, 0, fd) return Undefined(); } } static Persistent stats_constructor_template; static Persistent dev_symbol; static Persistent ino_symbol; static Persistent mode_symbol; static Persistent nlink_symbol; static Persistent uid_symbol; static Persistent gid_symbol; static Persistent rdev_symbol; static Persistent size_symbol; static Persistent blksize_symbol; static Persistent blocks_symbol; static Persistent atime_symbol; static Persistent mtime_symbol; static Persistent ctime_symbol; Local BuildStatsObject(const uv_statbuf_t* s) { HandleScope scope; if (dev_symbol.IsEmpty()) { dev_symbol = NODE_PSYMBOL("dev"); ino_symbol = NODE_PSYMBOL("ino"); mode_symbol = NODE_PSYMBOL("mode"); nlink_symbol = NODE_PSYMBOL("nlink"); uid_symbol = NODE_PSYMBOL("uid"); gid_symbol = NODE_PSYMBOL("gid"); rdev_symbol = NODE_PSYMBOL("rdev"); size_symbol = NODE_PSYMBOL("size"); blksize_symbol = NODE_PSYMBOL("blksize"); blocks_symbol = NODE_PSYMBOL("blocks"); atime_symbol = NODE_PSYMBOL("atime"); mtime_symbol = NODE_PSYMBOL("mtime"); ctime_symbol = NODE_PSYMBOL("ctime"); } Local stats = stats_constructor_template->GetFunction()->NewInstance(); if (stats.IsEmpty()) return Local(); // The code below is very nasty-looking but it prevents a segmentation fault // when people run JS code like the snippet below. It's apparently more // common than you would expect, several people have reported this crash... // // function crash() { // fs.statSync('.'); // crash(); // } // // We need to check the return value of Integer::New() and Date::New() // and make sure that we bail out when V8 returns an empty handle. #define X(name) \ { \ Local val = Integer::New(s->st_##name); \ if (val.IsEmpty()) return Local(); \ stats->Set(name##_symbol, val); \ } X(dev) X(mode) X(nlink) X(uid) X(gid) X(rdev) # if defined(__POSIX__) X(blksize) # endif #undef X #define X(name) \ { \ Local val = Number::New(static_cast(s->st_##name)); \ if (val.IsEmpty()) return Local(); \ stats->Set(name##_symbol, val); \ } X(ino) X(size) # if defined(__POSIX__) X(blocks) # endif #undef X #define X(name) \ { \ Local val = NODE_UNIXTIME_V8(s->st_##name); \ if (val.IsEmpty()) return Local(); \ stats->Set(name##_symbol, val); \ } X(atime) X(mtime) X(ctime) #undef X return scope.Close(stats); } static Handle Stat(const Arguments& args) { HandleScope scope; if (args.Length() < 1) return TYPE_ERROR("path required"); if (!args[0]->IsString()) return TYPE_ERROR("path must be a string"); String::Utf8Value path(args[0]); if (args[1]->IsFunction()) { ASYNC_CALL(stat, args[1], *path) } else { SYNC_CALL(stat, *path, *path) return scope.Close( BuildStatsObject(static_cast(SYNC_REQ.ptr))); } } static Handle LStat(const Arguments& args) { HandleScope scope; if (args.Length() < 1) return TYPE_ERROR("path required"); if (!args[0]->IsString()) return TYPE_ERROR("path must be a string"); String::Utf8Value path(args[0]); if (args[1]->IsFunction()) { ASYNC_CALL(lstat, args[1], *path) } else { SYNC_CALL(lstat, *path, *path) return scope.Close( BuildStatsObject(static_cast(SYNC_REQ.ptr))); } } static Handle FStat(const Arguments& args) { HandleScope scope; if (args.Length() < 1 || !args[0]->IsInt32()) { return THROW_BAD_ARGS; } int fd = args[0]->Int32Value(); if (args[1]->IsFunction()) { ASYNC_CALL(fstat, args[1], fd) } else { SYNC_CALL(fstat, 0, fd) return scope.Close( BuildStatsObject(static_cast(SYNC_REQ.ptr))); } } static Handle Symlink(const Arguments& args) { HandleScope scope; int len = args.Length(); if (len < 1) return TYPE_ERROR("dest path required"); if (len < 2) return TYPE_ERROR("src path required"); if (!args[0]->IsString()) return TYPE_ERROR("dest path must be a string"); if (!args[1]->IsString()) return TYPE_ERROR("src path must be a string"); String::Utf8Value dest(args[0]); String::Utf8Value path(args[1]); int flags = 0; if (args[2]->IsString()) { String::Utf8Value mode(args[2]); if (strcmp(*mode, "dir") == 0) { flags |= UV_FS_SYMLINK_DIR; } else if (strcmp(*mode, "junction") == 0) { flags |= UV_FS_SYMLINK_JUNCTION; } else if (strcmp(*mode, "file") != 0) { return ThrowException(Exception::Error( String::New("Unknown symlink type"))); } } if (args[3]->IsFunction()) { ASYNC_DEST_CALL(symlink, args[3], *dest, *dest, *path, flags) } else { SYNC_DEST_CALL(symlink, *path, *dest, *dest, *path, flags) return Undefined(); } } static Handle Link(const Arguments& args) { HandleScope scope; int len = args.Length(); if (len < 1) return TYPE_ERROR("dest path required"); if (len < 2) return TYPE_ERROR("src path required"); if (!args[0]->IsString()) return TYPE_ERROR("dest path must be a string"); if (!args[1]->IsString()) return TYPE_ERROR("src path must be a string"); String::Utf8Value orig_path(args[0]); String::Utf8Value new_path(args[1]); if (args[2]->IsFunction()) { ASYNC_DEST_CALL(link, args[2], *new_path, *orig_path, *new_path) } else { SYNC_DEST_CALL(link, *orig_path, *new_path, *orig_path, *new_path) return Undefined(); } } static Handle ReadLink(const Arguments& args) { HandleScope scope; if (args.Length() < 1) return TYPE_ERROR("path required"); if (!args[0]->IsString()) return TYPE_ERROR("path must be a string"); String::Utf8Value path(args[0]); if (args[1]->IsFunction()) { ASYNC_CALL(readlink, args[1], *path) } else { SYNC_CALL(readlink, *path, *path) return scope.Close(String::New((char*)SYNC_REQ.ptr)); } } static Handle Rename(const Arguments& args) { HandleScope scope; int len = args.Length(); if (len < 1) return TYPE_ERROR("old path required"); if (len < 2) return TYPE_ERROR("new path required"); if (!args[0]->IsString()) return TYPE_ERROR("old path must be a string"); if (!args[1]->IsString()) return TYPE_ERROR("new path must be a string"); String::Utf8Value old_path(args[0]); String::Utf8Value new_path(args[1]); if (args[2]->IsFunction()) { ASYNC_DEST_CALL(rename, args[2], *new_path, *old_path, *new_path) } else { SYNC_DEST_CALL(rename, *old_path, *new_path, *old_path, *new_path) return Undefined(); } } static Handle FTruncate(const Arguments& args) { HandleScope scope; if (args.Length() < 2 || !args[0]->IsInt32()) { return THROW_BAD_ARGS; } int fd = args[0]->Int32Value(); ASSERT_TRUNCATE_LENGTH(args[1]); int64_t len = GET_TRUNCATE_LENGTH(args[1]); if (args[2]->IsFunction()) { ASYNC_CALL(ftruncate, args[2], fd, len) } else { SYNC_CALL(ftruncate, 0, fd, len) return Undefined(); } } static Handle Fdatasync(const Arguments& args) { HandleScope scope; if (args.Length() < 1 || !args[0]->IsInt32()) { return THROW_BAD_ARGS; } int fd = args[0]->Int32Value(); if (args[1]->IsFunction()) { ASYNC_CALL(fdatasync, args[1], fd) } else { SYNC_CALL(fdatasync, 0, fd) return Undefined(); } } static Handle Fsync(const Arguments& args) { HandleScope scope; if (args.Length() < 1 || !args[0]->IsInt32()) { return THROW_BAD_ARGS; } int fd = args[0]->Int32Value(); if (args[1]->IsFunction()) { ASYNC_CALL(fsync, args[1], fd) } else { SYNC_CALL(fsync, 0, fd) return Undefined(); } } static Handle Unlink(const Arguments& args) { HandleScope scope; if (args.Length() < 1) return TYPE_ERROR("path required"); if (!args[0]->IsString()) return TYPE_ERROR("path must be a string"); String::Utf8Value path(args[0]); if (args[1]->IsFunction()) { ASYNC_CALL(unlink, args[1], *path) } else { SYNC_CALL(unlink, *path, *path) return Undefined(); } } static Handle RMDir(const Arguments& args) { HandleScope scope; if (args.Length() < 1) return TYPE_ERROR("path required"); if (!args[0]->IsString()) return TYPE_ERROR("path must be a string"); String::Utf8Value path(args[0]); if (args[1]->IsFunction()) { ASYNC_CALL(rmdir, args[1], *path) } else { SYNC_CALL(rmdir, *path, *path) return Undefined(); } } static Handle MKDir(const Arguments& args) { HandleScope scope; if (args.Length() < 2 || !args[0]->IsString() || !args[1]->IsInt32()) { return THROW_BAD_ARGS; } String::Utf8Value path(args[0]); int mode = static_cast(args[1]->Int32Value()); if (args[2]->IsFunction()) { ASYNC_CALL(mkdir, args[2], *path, mode) } else { SYNC_CALL(mkdir, *path, *path, mode) return Undefined(); } } static Handle ReadDir(const Arguments& args) { HandleScope scope; if (args.Length() < 1) return TYPE_ERROR("path required"); if (!args[0]->IsString()) return TYPE_ERROR("path must be a string"); String::Utf8Value path(args[0]); if (args[1]->IsFunction()) { ASYNC_CALL(readdir, args[1], *path, 0 /*flags*/) } else { SYNC_CALL(readdir, *path, *path, 0 /*flags*/) char *namebuf = static_cast(SYNC_REQ.ptr); int nnames = req_wrap.req.result; Local names = Array::New(nnames); for (int i = 0; i < nnames; i++) { Local name = String::New(namebuf); names->Set(Integer::New(i), name); #ifndef NDEBUG namebuf += strlen(namebuf); assert(*namebuf == '\0'); namebuf += 1; #else namebuf += strlen(namebuf) + 1; #endif } return scope.Close(names); } } static Handle Open(const Arguments& args) { HandleScope scope; int len = args.Length(); if (len < 1) return TYPE_ERROR("path required"); if (len < 2) return TYPE_ERROR("flags required"); if (len < 3) return TYPE_ERROR("mode required"); if (!args[0]->IsString()) return TYPE_ERROR("path must be a string"); if (!args[1]->IsInt32()) return TYPE_ERROR("flags must be an int"); if (!args[2]->IsInt32()) return TYPE_ERROR("mode must be an int"); String::Utf8Value path(args[0]); int flags = args[1]->Int32Value(); int mode = static_cast(args[2]->Int32Value()); if (args[3]->IsFunction()) { ASYNC_CALL(open, args[3], *path, flags, mode) } else { SYNC_CALL(open, *path, *path, flags, mode) int fd = SYNC_RESULT; return scope.Close(Integer::New(fd)); } } // bytesWritten = write(fd, data, position, enc, callback) // Wrapper for write(2). // // 0 fd integer. file descriptor // 1 buffer the data to write // 2 offset where in the buffer to start from // 3 length how much to write // 4 position if integer, position to write at in the file. // if null, write from the current position static Handle Write(const Arguments& args) { HandleScope scope; if (!args[0]->IsInt32()) { return THROW_BAD_ARGS; } int fd = args[0]->Int32Value(); if (!Buffer::HasInstance(args[1])) { return ThrowException(Exception::Error( String::New("Second argument needs to be a buffer"))); } Local buffer_obj = args[1]->ToObject(); char *buffer_data = Buffer::Data(buffer_obj); size_t buffer_length = Buffer::Length(buffer_obj); size_t off = args[2]->Int32Value(); if (off >= buffer_length) { return ThrowException(Exception::Error( String::New("Offset is out of bounds"))); } ssize_t len = args[3]->Int32Value(); if (off + len > buffer_length) { return ThrowException(Exception::Error( String::New("off + len > buffer.length"))); } ASSERT_OFFSET(args[4]); int64_t pos = GET_OFFSET(args[4]); char * buf = (char*)buffer_data + off; Local cb = args[5]; if (cb->IsFunction()) { ASYNC_CALL(write, cb, fd, buf, len, pos) } else { SYNC_CALL(write, 0, fd, buf, len, pos) return scope.Close(Integer::New(SYNC_RESULT)); } } /* * Wrapper for read(2). * * bytesRead = fs.read(fd, buffer, offset, length, position) * * 0 fd integer. file descriptor * 1 buffer instance of Buffer * 2 offset integer. offset to start reading into inside buffer * 3 length integer. length to read * 4 position file position - null for current position * */ static Handle Read(const Arguments& args) { HandleScope scope; if (args.Length() < 2 || !args[0]->IsInt32()) { return THROW_BAD_ARGS; } int fd = args[0]->Int32Value(); Local cb; size_t len; int64_t pos; char * buf = NULL; if (!Buffer::HasInstance(args[1])) { return ThrowException(Exception::Error( String::New("Second argument needs to be a buffer"))); } Local buffer_obj = args[1]->ToObject(); char *buffer_data = Buffer::Data(buffer_obj); size_t buffer_length = Buffer::Length(buffer_obj); size_t off = args[2]->Int32Value(); if (off >= buffer_length) { return ThrowException(Exception::Error( String::New("Offset is out of bounds"))); } len = args[3]->Int32Value(); if (off + len > buffer_length) { return ThrowException(Exception::Error( String::New("Length extends beyond buffer"))); } pos = GET_OFFSET(args[4]); buf = buffer_data + off; cb = args[5]; if (cb->IsFunction()) { ASYNC_CALL(read, cb, fd, buf, len, pos); } else { SYNC_CALL(read, 0, fd, buf, len, pos) Local bytesRead = Integer::New(SYNC_RESULT); return scope.Close(bytesRead); } } /* fs.chmod(path, mode); * Wrapper for chmod(1) / EIO_CHMOD */ static Handle Chmod(const Arguments& args) { HandleScope scope; if(args.Length() < 2 || !args[0]->IsString() || !args[1]->IsInt32()) { return THROW_BAD_ARGS; } String::Utf8Value path(args[0]); int mode = static_cast(args[1]->Int32Value()); if(args[2]->IsFunction()) { ASYNC_CALL(chmod, args[2], *path, mode); } else { SYNC_CALL(chmod, *path, *path, mode); return Undefined(); } } /* fs.fchmod(fd, mode); * Wrapper for fchmod(1) / EIO_FCHMOD */ static Handle FChmod(const Arguments& args) { HandleScope scope; if(args.Length() < 2 || !args[0]->IsInt32() || !args[1]->IsInt32()) { return THROW_BAD_ARGS; } int fd = args[0]->Int32Value(); int mode = static_cast(args[1]->Int32Value()); if(args[2]->IsFunction()) { ASYNC_CALL(fchmod, args[2], fd, mode); } else { SYNC_CALL(fchmod, 0, fd, mode); return Undefined(); } } /* fs.chown(path, uid, gid); * Wrapper for chown(1) / EIO_CHOWN */ static Handle Chown(const Arguments& args) { HandleScope scope; int len = args.Length(); if (len < 1) return TYPE_ERROR("path required"); if (len < 2) return TYPE_ERROR("uid required"); if (len < 3) return TYPE_ERROR("gid required"); if (!args[0]->IsString()) return TYPE_ERROR("path must be a string"); if (!args[1]->IsUint32()) return TYPE_ERROR("uid must be an unsigned int"); if (!args[2]->IsUint32()) return TYPE_ERROR("gid must be an unsigned int"); String::Utf8Value path(args[0]); uv_uid_t uid = static_cast(args[1]->Uint32Value()); uv_gid_t gid = static_cast(args[2]->Uint32Value()); if (args[3]->IsFunction()) { ASYNC_CALL(chown, args[3], *path, uid, gid); } else { SYNC_CALL(chown, *path, *path, uid, gid); return Undefined(); } } /* fs.fchown(fd, uid, gid); * Wrapper for fchown(1) / EIO_FCHOWN */ static Handle FChown(const Arguments& args) { HandleScope scope; int len = args.Length(); if (len < 1) return TYPE_ERROR("fd required"); if (len < 2) return TYPE_ERROR("uid required"); if (len < 3) return TYPE_ERROR("gid required"); if (!args[0]->IsInt32()) return TYPE_ERROR("fd must be an int"); if (!args[1]->IsUint32()) return TYPE_ERROR("uid must be an unsigned int"); if (!args[2]->IsUint32()) return TYPE_ERROR("gid must be an unsigned int"); int fd = args[0]->Int32Value(); uv_uid_t uid = static_cast(args[1]->Uint32Value()); uv_gid_t gid = static_cast(args[2]->Uint32Value()); if (args[3]->IsFunction()) { ASYNC_CALL(fchown, args[3], fd, uid, gid); } else { SYNC_CALL(fchown, 0, fd, uid, gid); return Undefined(); } } static Handle UTimes(const Arguments& args) { HandleScope scope; int len = args.Length(); if (len < 1) return TYPE_ERROR("path required"); if (len < 2) return TYPE_ERROR("atime required"); if (len < 3) return TYPE_ERROR("mtime required"); if (!args[0]->IsString()) return TYPE_ERROR("path must be a string"); if (!args[1]->IsNumber()) return TYPE_ERROR("atime must be a number"); if (!args[2]->IsNumber()) return TYPE_ERROR("mtime must be a number"); const String::Utf8Value path(args[0]); const double atime = static_cast(args[1]->NumberValue()); const double mtime = static_cast(args[2]->NumberValue()); if (args[3]->IsFunction()) { ASYNC_CALL(utime, args[3], *path, atime, mtime); } else { SYNC_CALL(utime, *path, *path, atime, mtime); return Undefined(); } } static Handle FUTimes(const Arguments& args) { HandleScope scope; int len = args.Length(); if (len < 1) return TYPE_ERROR("fd required"); if (len < 2) return TYPE_ERROR("atime required"); if (len < 3) return TYPE_ERROR("mtime required"); if (!args[0]->IsInt32()) return TYPE_ERROR("fd must be an int"); if (!args[1]->IsNumber()) return TYPE_ERROR("atime must be a number"); if (!args[2]->IsNumber()) return TYPE_ERROR("mtime must be a number"); const int fd = args[0]->Int32Value(); const double atime = static_cast(args[1]->NumberValue()); const double mtime = static_cast(args[2]->NumberValue()); if (args[3]->IsFunction()) { ASYNC_CALL(futime, args[3], fd, atime, mtime); } else { SYNC_CALL(futime, 0, fd, atime, mtime); return Undefined(); } } void File::Initialize(Handle target) { HandleScope scope; NODE_SET_METHOD(target, "close", Close); NODE_SET_METHOD(target, "open", Open); NODE_SET_METHOD(target, "read", Read); NODE_SET_METHOD(target, "fdatasync", Fdatasync); NODE_SET_METHOD(target, "fsync", Fsync); NODE_SET_METHOD(target, "rename", Rename); NODE_SET_METHOD(target, "ftruncate", FTruncate); NODE_SET_METHOD(target, "rmdir", RMDir); NODE_SET_METHOD(target, "mkdir", MKDir); NODE_SET_METHOD(target, "readdir", ReadDir); NODE_SET_METHOD(target, "stat", Stat); NODE_SET_METHOD(target, "lstat", LStat); NODE_SET_METHOD(target, "fstat", FStat); NODE_SET_METHOD(target, "link", Link); NODE_SET_METHOD(target, "symlink", Symlink); NODE_SET_METHOD(target, "readlink", ReadLink); NODE_SET_METHOD(target, "unlink", Unlink); NODE_SET_METHOD(target, "write", Write); NODE_SET_METHOD(target, "chmod", Chmod); NODE_SET_METHOD(target, "fchmod", FChmod); //NODE_SET_METHOD(target, "lchmod", LChmod); NODE_SET_METHOD(target, "chown", Chown); NODE_SET_METHOD(target, "fchown", FChown); //NODE_SET_METHOD(target, "lchown", LChown); NODE_SET_METHOD(target, "utimes", UTimes); NODE_SET_METHOD(target, "futimes", FUTimes); } void InitFs(Handle target) { HandleScope scope; // Initialize the stats object Local stat_templ = FunctionTemplate::New(); stats_constructor_template = Persistent::New(stat_templ); target->Set(String::NewSymbol("Stats"), stats_constructor_template->GetFunction()); File::Initialize(target); oncomplete_sym = NODE_PSYMBOL("oncomplete"); StatWatcher::Initialize(target); } } // end namespace node NODE_MODULE(node_fs, node::InitFs) node-v0.10.25~dfsg2/src/node_extensions.h0000644000000000000000000000333612270121457016766 0ustar rootroot// Copyright Joyent, Inc. and other Node contributors. // // Permission is hereby granted, free of charge, to any person obtaining a // copy of this software and associated documentation files (the // "Software"), to deal in the Software without restriction, including // without limitation the rights to use, copy, modify, merge, publish, // distribute, sublicense, and/or sell copies of the Software, and to permit // persons to whom the Software is furnished to do so, subject to the // following conditions: // // The above copyright notice and this permission notice shall be included // in all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS // OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF // MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN // NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, // DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR // OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE // USE OR OTHER DEALINGS IN THE SOFTWARE. NODE_EXT_LIST_START NODE_EXT_LIST_ITEM(node_buffer) #if HAVE_OPENSSL NODE_EXT_LIST_ITEM(node_crypto) #endif NODE_EXT_LIST_ITEM(node_evals) NODE_EXT_LIST_ITEM(node_fs) NODE_EXT_LIST_ITEM(node_http_parser) NODE_EXT_LIST_ITEM(node_os) NODE_EXT_LIST_ITEM(node_zlib) // libuv rewrite NODE_EXT_LIST_ITEM(node_timer_wrap) NODE_EXT_LIST_ITEM(node_tcp_wrap) NODE_EXT_LIST_ITEM(node_udp_wrap) NODE_EXT_LIST_ITEM(node_pipe_wrap) NODE_EXT_LIST_ITEM(node_cares_wrap) NODE_EXT_LIST_ITEM(node_tty_wrap) NODE_EXT_LIST_ITEM(node_process_wrap) NODE_EXT_LIST_ITEM(node_fs_event_wrap) NODE_EXT_LIST_ITEM(node_signal_wrap) NODE_EXT_LIST_END node-v0.10.25~dfsg2/src/node_extensions.cc0000644000000000000000000000424712270121457017126 0ustar rootroot// Copyright Joyent, Inc. and other Node contributors. // // Permission is hereby granted, free of charge, to any person obtaining a // copy of this software and associated documentation files (the // "Software"), to deal in the Software without restriction, including // without limitation the rights to use, copy, modify, merge, publish, // distribute, sublicense, and/or sell copies of the Software, and to permit // persons to whom the Software is furnished to do so, subject to the // following conditions: // // The above copyright notice and this permission notice shall be included // in all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS // OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF // MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN // NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, // DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR // OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE // USE OR OTHER DEALINGS IN THE SOFTWARE. #include "node.h" #include "node_version.h" #include #include #undef NODE_EXT_LIST_START #undef NODE_EXT_LIST_ITEM #undef NODE_EXT_LIST_END #define NODE_EXT_LIST_START #define NODE_EXT_LIST_ITEM NODE_MODULE_DECL #define NODE_EXT_LIST_END #include "node_extensions.h" #undef NODE_EXT_LIST_START #undef NODE_EXT_LIST_ITEM #undef NODE_EXT_LIST_END #define NODE_EXT_STRING(x) &x ## _module, #define NODE_EXT_LIST_START node::node_module_struct *node_module_list[] = { #define NODE_EXT_LIST_ITEM NODE_EXT_STRING #define NODE_EXT_LIST_END NULL}; #include "node_extensions.h" namespace node { node_module_struct* get_builtin_module(const char *name) { char buf[128]; node_module_struct *cur = NULL; snprintf(buf, sizeof(buf), "node_%s", name); /* TODO: you could look these up in a hash, but there are only * a few, and once loaded they are cached. */ for (int i = 0; node_module_list[i] != NULL; i++) { cur = node_module_list[i]; if (strcmp(cur->modname, buf) == 0) { return cur; } } return NULL; } }; // namespace node node-v0.10.25~dfsg2/src/node_string.h0000644000000000000000000000415412270121457016074 0ustar rootroot// Copyright Joyent, Inc. and other Node contributors. // // Permission is hereby granted, free of charge, to any person obtaining a // copy of this software and associated documentation files (the // "Software"), to deal in the Software without restriction, including // without limitation the rights to use, copy, modify, merge, publish, // distribute, sublicense, and/or sell copies of the Software, and to permit // persons to whom the Software is furnished to do so, subject to the // following conditions: // // The above copyright notice and this permission notice shall be included // in all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS // OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF // MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN // NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, // DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR // OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE // USE OR OTHER DEALINGS IN THE SOFTWARE. #ifndef SRC_NODE_STRING_H_ #define SRC_NODE_STRING_H_ #include "v8.h" namespace node { #define IMMUTABLE_STRING(string_literal) \ ::node::ImmutableAsciiSource::CreateFromLiteral( \ string_literal "", sizeof(string_literal) - 1) #define BUILTIN_ASCII_ARRAY(array, len) \ ::node::ImmutableAsciiSource::CreateFromLiteral(array, len) class ImmutableAsciiSource : public v8::String::ExternalAsciiStringResource { public: static v8::Handle CreateFromLiteral(const char *string_literal, size_t length); ImmutableAsciiSource(const char *src, size_t src_len) : buffer_(src), buf_len_(src_len) { } ~ImmutableAsciiSource() { } const char *data() const { return buffer_; } size_t length() const { return buf_len_; } private: const char *buffer_; size_t buf_len_; }; } // namespace node #endif // SRC_NODE_STRING_H_ node-v0.10.25~dfsg2/src/res/0000755000000000000000000000000012270121457014175 5ustar rootrootnode-v0.10.25~dfsg2/src/res/node.rc0000644000000000000000000000437412270121457015460 0ustar rootroot// Copyright Joyent, Inc. and other Node contributors. // // Permission is hereby granted, free of charge, to any person obtaining a // copy of this software and associated documentation files (the // "Software"), to deal in the Software without restriction, including // without limitation the rights to use, copy, modify, merge, publish, // distribute, sublicense, and/or sell copies of the Software, and to permit // persons to whom the Software is furnished to do so, subject to the // following conditions: // // The above copyright notice and this permission notice shall be included // in all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS // OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF // MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN // NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, // DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR // OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE // USE OR OTHER DEALINGS IN THE SOFTWARE. #include "winresrc.h" #include "node_version.h" // Application icon 1 ICON node.ico // Version resource VS_VERSION_INFO VERSIONINFO FILEVERSION NODE_MAJOR_VERSION,NODE_MINOR_VERSION,NODE_PATCH_VERSION,0 PRODUCTVERSION NODE_MAJOR_VERSION,NODE_MINOR_VERSION,NODE_PATCH_VERSION,0 FILEFLAGSMASK 0x3fL #ifdef _DEBUG FILEFLAGS VS_FF_DEBUG #else # ifdef NODE_VERSION_IS_RELEASE FILEFLAGS 0x0L # else FILEFLAGS VS_FF_PRERELEASE # endif #endif FILEOS VOS_NT_WINDOWS32 FILETYPE VFT_APP FILESUBTYPE 0x0L BEGIN BLOCK "StringFileInfo" BEGIN BLOCK "040904b0" BEGIN VALUE "CompanyName", "Joyent, Inc" VALUE "ProductName", "Node.js" VALUE "FileDescription", "Evented I/O for V8 JavaScript" VALUE "FileVersion", NODE_VERSION_STRING VALUE "ProductVersion", NODE_VERSION_STRING VALUE "OriginalFilename", "node.exe" VALUE "InternalName", "node" VALUE "LegalCopyright", "Copyright Joyent, Inc. and other Node contributors. MIT license." END END BLOCK "VarFileInfo" BEGIN VALUE "Translation", 0x409, 1200 END END node-v0.10.25~dfsg2/src/res/node.ico0000644000000000000000000030253612270121457015627 0ustar rootroot hV  00 %f@@ (B; (6}(   ϳ7oi'c_2i!5jC'c _"`"`"`!_$_@rG 8g(d"b$b$b$b#b#b"a"a!`!\&ck)uO'd'e'e?u&e%e$d#d"c"b!a!`_(eK*xS,i+j+j£.m'h&g%f#d#cM!` ^#`,xV3q3r3r}2s/o,k*j&^B^}خ?9{5v1q.m-k*`G=`w߭VѕIȊC=~8x4s0o,l0eK_1gKcu\ܞUԖN̏Gć@;{6u2p0k/gK.eJFitkbZכRϒKNjD>}6t3sq3f/fLa2gLrzqh_۟WіOɍGA}={4iO.eJLowmdݢ[ӘQɐLÈI0gMc4hQx{qhۤ^՚Tƍ 4iO/dKNr~u殻oީ'/dKe2jQtY1jJ-dJPrǏ????(0` H !###!!!%'+---+)'##!! #)-37531-)#! e?1i&aY['))'%!UU'`G!]![!^!]^5l 8q %_e#_!^!^!^!^!^!^!^"_(k/g#a#`"_"_!_"_!_!_!_!^!^!^"\&e5)b1$`#`"`"`"`"`"`"`"_!_!_!_!_!_!^!\&akUU&dO%a#`"`"`"`"`"`"`"`"`!`!`!`!`!_!_!_!_!_#`'b 3f'bo%_#`#a#a#a#a#a#a#a"a"a"a"a"a"`!`!`!`!_ _!_ ^"\'`-.d!'a%a$a$a$a$a$b#b#b#b#b#b#b#b"a"a"a"a!a!`!`!`!`!_!_ _ \"`_.mMy"_%a%b%b%b%b$b$c$c$c$c$c#c#c#b#b"b"b"b"a!a!a!`!` ` _ _ ^ ^"_8q /eLq,iK&b&c&c&c&c&d%d%d%d%d%d$d$d$d$c#c#c#c"b"b"b!a!a!a!` ` _ _ _ ^!\)`%.cK,jK'd'd'd'e'e'e'eEx>u&e&e%e%e%e$e$d$d#d#d#c"c"b"b!a!a!` ` _ _ ^ ^^$`U.eI+kL(e(f)f(f(f(g(g_f'g'g&g&f&f%f%e$e$e#d#d#c"c"b!b!a!a ` ` _ ^ ^ Z!]$m.eI+lM*g*g*h*h*h*i*ibǰ1n(h'h'h&g&g%g%f$f$e#d#d"c"c"b!a!a ` ` _ ^ ^]!]%^+dJ,nN,i,j,j,j,k,k,keO)j(j(i'i'h&g%g%f$f#e#d#d"c"c[Ǯ ` ` _ ^ ]]!_[,bJ,oN/l/l/m/m/m.m.niĢ+l)k)j(j'i'h&h%g%f$f#eY!a ` _ _ ^]$_c,cI,qP2o2p2p2p2q2q1qm5s+m*l)k(j'j'i&hX!b!a!` _ _ ^#_k-dI-sQ6s6t6t6t5t5u5uqJ-p,o+n*m)l+m"c"b!a!` _ ^"_u+cI.vS:w:x:x:y:y9y9yvŞN0s/r.q-p,o0q#d"c"b!a!` _"_}+cG0xU?|?}?}?~?~>~>~{ɣR4w3v1t0s/r2s$f$d#c"b"a!`"a+aF1{WCCCCCCCΨWď8{7z5x4w2u4v&h%f$e#d#b"a$a)cG2}YFGGGG‡GÇGćҬ\ɔ=;:}8{6z7y(j'h&g%f$d$c%c)aE4[JJˆKĉKŊKƊKNjKȋձ`̘AÄ?‚=;:}:}+m*k(i'h&f%e&e)bH6]NŋNƌOȍOɎOʏOˏȌٵcЛDLJBŅ@Ã><;~.p,m*l)j(i(g)f)bG8`RɏSːS̒TΓTϓTДTє޺GʋEȈCƆAĄ>‚=2s,n+l*k)i(h'g'aG:cW͔XϕXіYӘYԘZՙZ֙VϔFʊDȈ\͖7v-o+m*k)i(h(h'aE=f\ҙ]՛^֜_؝_ٞ_۟_ܟݱ={.p,n+l)j(h'h&^C@jbמcڠdܢeޣeߤffC/q-o,l*j)i(hUU)`BCngݤiߦjklllI1r/p-m+k)i)fUUU&]AGrmoqrssssO3t0q.o,l*j*h3ff$_AKvsuwxyzzzzyٺ<|5v2s0p.n,k+j$mH&[@Nzz|~~VȐ=:{7x4u1r/o-l,j.sE %]BJsuبGȉCÅ@<}9z6v3s1p.m-hU3ff,dH-dIFlUԗOϑKʌFňB>;{8x5t2q0n.l3f0gMc+eG3nRlŜj]ܞXיSҔN͏IȊEÆA=}:y6v3r1o/i8q 1jR/dK-dJNtlfaߢ[ڜVԗQϒLʍHĈC?<{8w5s1m1lgUUU/dKe-dJ6pTyɪ|vpke_ܠZךTєOˏJƊFA=|:u8u7y1jR-dJ.eJU{{uoicߢ]ٝWӗR͑MnjH†C@|@y?UUU/eLg-dJ8qW˴yslf`ڟZԙTΓOȍJˆFwH6dM!.cI.eJZ|voicۡ]՚WΔSɍRŋUUU0eKi-dJ:sYιyrleܢ`ӛ\ИM6dM!/eK.eK]{ukiۤsТ UUU2fLk.bJ;t[Ѹ}u鱿p+2eP#0eI/eK\]UUU1fMm/bJ;v[ӯŗ7gK%0eL0dKh7???????????(@  !!##!!! !#%'')))''%%#! !%)+/13331/+)'%##!  !%)-157753/-)%#!  #Buw%a4h/++++)'#!Bq,e _!]!]!]'ak9)h1#`"[!^!^!^!^!^!^ _9oY  UU'cM$a"_!_!^!^!^!_!^!^!^!^!^$aHm:u &ak$`"_"_"_"_"_"_!_!_!_!_!^!^!^!^ ^+i1j&a#`"_"_"_"_"_"_"_"_!_!_!_!_!_!_!_!_!^_'dG,f9%b _"`"`"`"`"`"`"`"`"`"`"`"`!`!`!`!_!_!_!_!_!\%bUU3f)cW&a#`#`#`#`#`#`#`#`"`"`"`"`"`"`"`"`!`!`!`!_!_!_!_!_!^#_,c-i'bu%a#`#`#`#a#a#a#a#a#a#a#a"a"a"a"a"a"a"`"`"`!`!`!`!_!_!_!_!^"])d=-h'&a!_$a$a$a$a$a$a#a#a#a#b#b#a#a#a#a"a"a"a"a"a"a!a!`!`!`!`!`!_!_!_ __$`wU,e?&b%^$a$a$a$a$b$b$b$b$b$b$b#b#b#b#b#b#b"b"b"b"a"a"a"a!a!a!`!`!`!`!_ _ _ ^ ^"`(k0eM}'[%a%a%b%b%b%b%b%c%c$c$c$c$c$c$c$c#c#c#b#b#b"b"b"b"b"a!a!a!a!a!`!`!` _ _ _ _ ^!\&e51gK,dI'\&b&b&c&c&c&c%c%c%d%d%d%d%d%d$d$d$d$c$c#c#c#c#c"c"b"b"b"a!a!a!a!`!`!` _ _ _ ^ ^^&ak/cJ,dI(^'c'c'd'd'd&d&d&e&e,i&e&e%e%e%e%e%d$d$d$d$d#d#c#c#c"c"b"b"b"a!a!a!a!` ` _ _ _ ^ ^ ^#`'b ,eI,dI(_(d(e(e(e(e'e'e'f'fo,i&f&f&f&f%f%e%e%e$e$e$d#d#d#c#c"c"c"b"b!a!a!a!`!` ` _ _ ^ ^ ^!\'`-.cI,dI)a)f)f)f)f)f(g(g(g(grCy'g'g'g&g&g&f%f%f%f$e$e$e#d#d#d"c"c"b!b!b!a!a!`!` ` _ _ ^ ^ ] [%`_+eH,dI*b*g*g*h*h*h*h*h*h)itn(h(h'h'h'g&g&g&g%f%f$f$e$e#e#d"d"c"c"b!b!a!a!a!` ` _ _ ^ ^]]"_8q +eJ,cH+d+i+i+i+i+j+j+j+j+jw˶5q)i(i(i'i'h'h&h&g%g%f$f$e#e#d#d"d"c"b"b!b,hZ ` ` _ _ ^ ^ ]]#_s+cJ+cH-f-j-k-k-k-k-k-l-l,lzT)k)j)j(j(i'i'h&h&g%g%f$f$e#e#d#d"c+i~!a ` ` _ ^ ^]]"_}*aJ+cH/i/l/m/m/m/m/n/n.n.n}Ƨ-m*l)k)k(j(j'i'i&h&h%g%f$f$e+j| !a!a ` _ _ ^ ^ ]"_*bI+cH1l2o2o2p1p1p1p1p1p1p¢A{+m*l*l)k)k(j'j'i&h%h+kzß!b!a!a!` _ _ ^ ^#`*dG+cH4p4r4r4r4s4s4s4s4s3sťͯ-o,n+n+m*l)l)k(j,mxğ"c!b!a!a!` _ _ ^#`)aF+cG7s7u7u7v7v7v7v7v6v6vȨϲ/q.q.p-o,o+n*m*lqÛ"c"c"b!a!a!` _ _!`,cE+cH:w;x;y;y;y;y:z:z:z9zʫҴ2t1s0r/r.q-p,o+nqĜ#d#d"c"b!a!a!` _#`U+`E+dH>{>|>|>}>}>}>}>}=}=}ͯԷ4w3v2u1t0s/r.q-ppŜ$f$e#d#c"b"b!a!`!amm+bG+eIA~ABBBBBBAAѳ׺8z7y6y4w3v2u1t0soǜ%g%f$e#d#c"b"b"a"`Nub *bG+fJDDEEEEEEEE…Զڽ;~:}9|8{6z5x4w2voɝ'i&g%g%e$e#d#c#b"`Cx]*bG,hKFGGGHH‡HÇHĈHĈHňֹ?><;~:}8|7z6yoʞ)j(i'h&g%f%e$d$c#d7nX*bG,jLIIJˆJÈJĉJŊJƊKƊJNjJNjٽAą@Ä?‚><;~:}8|n̞+m*k)j(i'h&g&e%d$e4iO*bF-lNLÉLĊMŋMƋMnjMȌNɍNɍNʎMˎDƇBņAĄ@Ã>=;:~m͞-o,m+l*k)j(i'g'f%g2mP#*aF.oOOŌPǍPȎPɎQʏQːQ̐Q͑Q͑QΑFɉEȈCƇBŅ@Ą?‚=<l͞0q,n+m+l*k)j)i(h(h1iP)*aF/qQRɏSʐSˑT͒TΓUϔUДUЕUѕUҕiԠGʋFɉDȈBƆAŅ?Ã=kΞ4t-o,m+l*k)j(i(h)h2eO-)aF0sSV̒V͔WϕXЖXіXҗYӘYԘYՙYՙJ̍GʊEɉCLJAŅsӤ9x-o,n+m*k)j(i(g&e2dK3)`E2vUZЖZї[ә\Ԛ\՛]כ]ל]؜]ٝ]ڝ\ҙȞjԡ?|.p-n,m*k)j)i(h%d1fL9)`E4xW^Ӛ_՜`ם`؞aٟa۠aܠbݡbݡbޢE/q.o,n+l*k)i(h(gm0eH?(`E5{Ybמc٠dۡeܢeޣfߤffggJ0r/p-n,m+k*j)h(gDw-bHC(`E7~\fۢgݤhߥijkkkllP1s0q.o-n+l*j)i(g7n-aII'_D9^kߦlmnoppqqqqV3t1r/q.o,m+k*i)h1j)`GO'_D;aoprstuuvvvvu~W4v2t1r/p-n,l+j*h4o'*`HU&^C>dtuvxyzz{{{{{zyhɚ8z6w4u2s0q/o-m,k*i.m1*aDY%]B@gxz{}~~}ز@<~:{7y5v3t1r0p.n-l+j1k9(]C_%]ACj}~QʏDĆA><}9z7x5u3s1q/n-l,j/mA(_De'^C3oRhɚiסL͎IɋFƈC„@=~;|8y6v4t2r0o.m-k0lI4iO-dJ-dI-dJPxV֘RӔOϑLˍHȊEĆB?=}:z8w5u3r1p/n.l2nQ1gLg-dJ-dI8vXuԨc]ܞYؚU՗RѓN͏KɌGƈD…A>~<{9x7v4s2q0n/l/m[6lM!.fI-dJ-eJWwhd`ߡ\۝XיTӕQϒMˎINJFÇC@=}:z8w6t3r1o/m4n5UUU0eMi.bJ-dJ;x[״tpkgc_ݠ[ٜW՘SГO̐LȌHĈEB?~<{9x7u5o5oz_ٿ{vrmie`ܠ\؜XӗTϓPˏLƋH‡EB{0r0r/r/q.q.q.p-p-o,o,o+n+n+m*m*m)lѼ#d#c"c"c"c"b"b!a!a!a!`!`!` _ _ _ ^-jC-dJ+bH+bG+cH9v:w:w:w:x:x:x:x:x:x:y:y9y9y9y9y9y9y9y8y:z?}1t1s0s0s/r/r/q.q.q-p-p,o,o+n+n+m*m#d#d#d"c"c"c"b"b!a!a!a!`!`!_!_ _ _(eK-dJ+bG+bG+dH;x|=|=|=|=|=}=|=|=|=|<|<|>}C4w3v3v2u2u1t1t0s0s/r/r/r.q.q-p-p,o$f$e$e#d#d#c#c"c"b"b"b"a"a!`!`!_!_)e]mm,_D+bG+bG+fI?|?|?}?}?}?}?}?~?~?~?~?~?~?~?~?~>~>~>~>~AE5x5x4w4w3v3v2u2u1t1t0s0s/r/r.q.q-p%f$f$e$e$e#d#d#c#c"b"b"b"a"a!`!`!`*dess +bH+bG+bG+gJ@~A~A~A~AAAAAAAAAAAAA@@@CG7z6y6y5x5x4w4w3v3v2u2u1t1t0s0s/r.r%g%g%f$e$e$e#d#d#c#c"b"b"b"a"a"`!`'dmfw+bG+bG*bG,iKBBBBBBBCCCCCCCCCBBBBFJ9|8{8{7z7z6y5x5x4w4w3v2v2u1u1t0s0s&h&g%g%f%f$e$e$d#d#c#c#c"b"b"a"a"`(fwTya+bG*bG*bG,kLCDDDDDDDDDDDDDDDDDDDIˆL‰;~:}9|9|8{8{7z6z6y5x5x4w3w3v2u1u1t'h&h&g&g%g%f%e$e$e$d#c#c#c#b#b"a"a(e}Bq^*bG*bG*bG-lNDEEEEEEFEEFFFFFF†F†E†F†E†LĊNċ=<<;~:}9}9|8|8{7z6z5y5x4x4w3v2v(i'i'h&h&g&g%f%e%e$e$d$d$c#c#b#b"a)dEs\!*bG*bG*bG-nOFFFFFFGGGGGG†G†G‡GÇGÇGÇGćGćGćOƌQƍ>>=<<;:~:}9}9|8{7{6z6y5y5x4w(j(j(i'i'h&h&g&f%f%e%e$d$d$d$c#c#b)eDuY%*bG*bG*bG.pPGGGGHHHHH‡H‡H‡HÇHĈHĈIĈIňHňIʼnHʼnHʼnQǎRȎ@ƒ?‚?>==<;;~:~9}9|8|7{7z6z5y)k)k(j(j(i'h'h&g&g&f%f%e%e$d$d$c#c(e;jS+*bG*bG*bG/rRHHIIII‡I‡IÈIÈJÈJĉJĉJʼnJʼnJƉJƊJƊJƊJNJJNJTɐTɐAĄAÄ@Ã?ƒ?>==<;;~:~9}9|8|7{7z*l*l)k)k(j(i(i'h'h&g&f&f%e%e%d$d$c)f9mS1*bG*bG*bG0tSIJJJˆJÈKÉKÉKĉKŊKŊKƊKƊKƋKNjKNjKNjKNjKȋKȌKɌV˒VʒBŅBąAĄAÄ@Ã?ƒ>>=<<;:~:~9}8|8{,n+m+l*l)k)j(j(i(i'h'g'g&f&f%e%e%d(f>=<;;~:~9}9|-o,n+m+m*l*k)k)j)i(i(h'h'g'g&f&f&e+f3gR;*bG*bF*aF2xVLÉMĊMĊMŋMƋNƌNƌNnjNnjNȍNɍNɍOɎNʎNʎNʎNˎNˎNˏN̏\ϗY͕DLjDLJCƇBƆBŅAĄ@Ą@Ã?ƒ>‚>=<;;:~9}/q-o,n,n+m+l*l*k*j)j)i(i(h(g'g'f'f)g6iNA*bG*aF*aF3{XNŋNŋOƌOƌOǍOȍOȎPɎPɎPɎPʏPˏPˏPːP̐P̐P̐P͐P͐P͐_Й[ΗFȉEȈDLjDLJCƆBņBŅAĄ@Ą?Ã>‚>=<<;:~ݿ2s-o-o,n,m+m+l+l*k*k)j)i)i(h(h(g'g+h5kRG*aF*aF)aF4}ZPƌPƍPǍQȎQɎQɏQʏQʏQːR̐ȒȒR͑R͑R͑RΒRΒRΒRϒRϒbҜ]ИGʊFɊFɉEȈDLjCLJBƆBŅAŅ@Ą?Ã?Ã>‚=<<;ݾ5t-o-o,n,n+m+l+l*k*k*j)j)i)i(h(g(g+i4fOM*aF*aF)aF5[QǎRȏRɏRʐRʐSˑSˑS̑S͒S͒TΒTΓTϓTϓTϓTДTДTєTєTєeԞ޸IˌHˋGʊFɊEȉDȈDLJCLJBƆAŅAĄ@Ą?Ã>‚==<ݽ8w.p-o,n,n+m+m+l*k*k)j)j)i)i(h(h(g+i2gKQ*aF*aF)aF6]SɐSʐTʑTˑT̒T̒U͓UΓUΓUϔVЕVДVЕVѕVѕVҖVҖVҖVӖVӖh֡UϔIˌHˋGʊFɉEɉDȈCLJCƆBŅAŅ@Ą?Ã>‚>‚=ݼ=z.p-o-n,n,m+m+l*k*j)j)j)i(h(h(g(g+f1fOW)aF)aF)aF7_UˑU̒U̓V͓VΔVϔWϔWЕWЕWіWіXҗXҗXӗXӗXӗXԘXԘXԘX՘k٣v٩I̍ȞGˋFʊFɉEɉDȈCLJBƆAŅ@Ą?Ã@Ã֬B~.p-o-o,n,m+m+l*k*k*j)j)i(h(h(g'g(h4hL])aF)aF)aF9aV̓W͔WΔWϕXϕXЖYіYїYҗYӘYӘYӘYԘZԙZՙZՙZ֚Z֚Z֚Z֚nڦNΐǏHˌGˋFʊEɉDȈCLJCdžBŅtԥG.q.p-o-n,n,m+l*l*k*j)j)i(h(h(g'g*i0dJc)aF)aF)aF:cYϕYϖYЖZїZїZҘZӘ[ә[ԙ[՚\֚\֛\֛\֛\כ\؜\؜\؜\ٜ\ٜrݩf՟J͍ǏHˋGˋFɊEɉhҟL/q.p.p-o,n,m+l+l*k*j)j)i)i(h(g(g$c0eKi)aE)`E)`Eh\ҙ]Ӛ]Ԛ^՛^֜_֜_ל_ם`؝`ٞ`ٞ`ڟ`۟`۟a۠`ܠ`ܠaݠ`ݡ`ݡxh֡V0r/q.q.p-o,n,m+m+l*k*j)j)i(h(h(g(bT .cIs)aF)`E)`E@j^ԛ_՜`֜`֝`םa؞aٟaڟbڟb۠bܡcܡcݡcݢcݢcޢcޢcߣcߣcߣ|\0s0r/q.p-o-n,n,m+l+k*j*j)i)h(h(g'ff.cIy(`E(`E(`EAm`֝a֝aמbٟc٠cڠcۡdܡdܢdݢdޣeޣeߤeߤeeefeeaÓ1s0r/q/p.p.o-n,m,l+k+k*j)i)i(h(g(gBy.dJ(`E(`E(`ECoc؟c٠dڠdۡeܢeܢfݣfޣfޤgߤggghhhhhhhfŖ2t1s0r/q/p.o-n,n,m+l+k*j)i)i)h(g(gE{!.cI(`E(`E(`EFre١eۢfۢgݣgݤgޥhߥhiiijjjjjjjjjkƚ2t1s0r0r/q.p.o-n,m+l+k*j*j)i)h)h(g7o),bH(`E(`E(`EHtgܣhݤhޥiޥijjkkklllmmmmmmmopɝ3u2t1s0r0q/p.o.n-m,m,l+k*j*j)i)h(g9r1,cI(_D(`D(`DJwiݥjߦjkllmmmnnooooooooooouˡ4v3t2t1s0r/q/p.o-n,m,l+k+k*j)i)h(g5o9,cI(_D'_D'_DLzklmmnoooppqqqrrrrrrrrrrvzͤ5w4u3t2s1r0q/p.o.n-n,m,l+k*j*i)h)h2mA+bG'_D'_D'_DO}nnoppqqrssstttttuuuuuutttϨ5w4v3u3t2s1r0q/p.o.n-m,l,k+j*j*i)h2lK+`F'_D'_D'_CQpqqrssttuuvvvwwwwwwwwwwwvv}sˠ6x5w4v3u2t1s1r0p/o.n-m-l,l+k+j*i*h1kS+aG&^C&^C&^CTrsttuvvwwxxyyyyzzzzzzzzyyxxw_Ɣ8z7y6x5v4u3t2s1r0q/p/o.n-m-l,k+j+j*i2m[(_F&^C&^C&^CWtuvwwxyyzz{{||||}}}}}}||{{zzy}Ѩ<~:|9{8z7x6w5v4u3t2s1r0q/o.n.m-m,l+k+j*i0lc'`D&^B&^C&^BZvwxyzz{||}}~~~~~}}|{zݽF…=<~;}:|9z8y6x6w4u3t2s2r1q0p/o.n-m-l,k+j+i1mm*^F%]B%]B%]B\yzz{|}}~~~}|WʒAƒ@>=<~;|9{8z7x6w5v4u3t2s1q0p0o/n.m-l-l,j+j/lu'_E%]B%]B%]B_{|}~~pӣEƇDĆBÄA@>=<}:|9z8y7x6w5u4t3s2r1q0p/o.n.m-l,k,j0l}'_C%]A%]A%]AcÔ}~~޷KˍHɊFLjEŇCĆB„A?>=~;}:{9z8y7w6v5u3t2r2q1p0o/n.m-l-k,j/k&]B$\A%\A'_DJr{WіL͏KˍIʋHȊFƈEŇCÅB@?><};|:{9y7x6w5u4t3s2r1q0p/o/m.m-l,j0l(^B(_D,cH-dJ-dJ8xYnѡi٣QғOБNΐL̎KˌIɋGljFŇDĆC„A@?=~<};{9z8y7w6v5u4s3r2q1p0o/n.m.l-k1m3fMm.eJ-dJ-dJ-dI-dJ.eJS}V֘TԖSӕQѓOϑM͏L̎JʌHȊGƈEćDÅBA?>=};|:{9y8x7w6u4t3s2q2q1o0n/m.l-k0m;jS+0eL-dJ-dJ-dJ-dI-dI;z\uب]ܟYڛXؚV֘TԖRҔQВOΐM͏KˍJɋHljGňEÆC„B@?>~<};{:z8x7w6v5t4s3r2q1p0n/m.m.l/lfff3hOw.eJ-dJ.dJ-dJ-dI.fKYk_ߡ]ݟ[۝YٛWיU՗TӕRєPВNΐM̎KʌIȊHƉFćD…CA@?=}<|:z9y8w7v6u5t3r3q2p1o0n/m.l1m;jS+1eL-dJ-dJ-dJ-dJ-dJ=}^|ݰ~dba_ޠ]ܞ[ڜYؚW֘U՗SӕRГPϑN̏LˍJɋINJGňEÆDBA?>~=};{:z9x8w6u5t4s3r2p1o0n/m/l1kff3iN{.eJ-dJ-dJ-dJ-dJ.fL^jhfdb`ߢ^ݠ\۝ZٜXךV՘UӖSєQϒO͐M̎KʌJNJHƉGćE…CB@?=}<|;z9y8w7v6t5s4r2q2o1n0m/l1m8kT-.gL-dJ.eJ-dJ-dJ-dI@a߸snljhfdb`ޡ^ܟ\ڝZ؛X֙VԗTҕRГPΑN̏MʍKɌIƊHňF†DCA@>~=|;{:y9x7v7u5t4r3q2p1o0i2mByfff3iN{.eE-dJ-dJ-dJ-dJ/gLctrpnljgecaߢ_ݠ]۞[ٜYךW՘UӖSєQϒP͐NˎLɌJNJHʼnGÇEDB@?~>}<{;y9x8v7u6t5s4q2p3p8q?;lQ/0cI.dJ-dJ-dJ-dJ-dJBdzxvtrpmkigecaޡ^ܟ\ڝZ؛X֙WԗUҕSГQΑȌMɍKȋJƉHĈF†DCA@>}={}={;y:x;s@zOHm4hN.eE.eJ.eJ.eJ.eJ1iNn}{ywtrpnligecߣaݡ^۞\ٜZ֚XԘVҖTДR͒PːNɍLNjKŊIÇGECB@~?}>{=u@zE 9mS11gL.eJ.eJ.eJ.eJ-eJHk}{xvtromkifdbޡ`۟^ٝ[כYՙWҖUДSΒQ̐OʎMnjKŊJÈHFDCA@~?}G+Hmm3hO.eE.eJ.eJ.eJ.eJ2jOr~|zxvsqoljhecޢaܡ_ڞ]ל[՚XӗVѕTΓȒPʏNȍLƋJĉIGEC?E_U node-v0.10.25~dfsg2/src/res/node_etw_provider.man0000644000000000000000000001713712270121457020421 0ustar rootroot node-v0.10.25~dfsg2/src/node_constants.h0000644000000000000000000000247412270121457016605 0ustar rootroot// Copyright Joyent, Inc. and other Node contributors. // // Permission is hereby granted, free of charge, to any person obtaining a // copy of this software and associated documentation files (the // "Software"), to deal in the Software without restriction, including // without limitation the rights to use, copy, modify, merge, publish, // distribute, sublicense, and/or sell copies of the Software, and to permit // persons to whom the Software is furnished to do so, subject to the // following conditions: // // The above copyright notice and this permission notice shall be included // in all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS // OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF // MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN // NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, // DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR // OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE // USE OR OTHER DEALINGS IN THE SOFTWARE. #ifndef SRC_CONSTANTS_H_ #define SRC_CONSTANTS_H_ #include "node.h" #include "v8.h" namespace node { void DefineConstants(v8::Handle target); } // namespace node #endif // SRC_CONSTANTS_H_ node-v0.10.25~dfsg2/src/node.cc0000644000000000000000000023012212270121457014640 0ustar rootroot// Copyright Joyent, Inc. and other Node contributors. // // Permission is hereby granted, free of charge, to any person obtaining a // copy of this software and associated documentation files (the // "Software"), to deal in the Software without restriction, including // without limitation the rights to use, copy, modify, merge, publish, // distribute, sublicense, and/or sell copies of the Software, and to permit // persons to whom the Software is furnished to do so, subject to the // following conditions: // // The above copyright notice and this permission notice shall be included // in all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS // OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF // MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN // NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, // DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR // OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE // USE OR OTHER DEALINGS IN THE SOFTWARE. #include "node.h" #include "req_wrap.h" #include "handle_wrap.h" #include "string_bytes.h" #include "ares.h" #include "uv.h" #include "v8-debug.h" #if defined HAVE_DTRACE || defined HAVE_ETW || defined HAVE_SYSTEMTAP # include "node_dtrace.h" #endif #if defined HAVE_PERFCTR # include "node_counters.h" #endif #include #include #include #include #include #if !defined(_MSC_VER) #include #else #define strcasecmp _stricmp #endif #include /* PATH_MAX */ #include #if !defined(_MSC_VER) #include /* setuid, getuid */ #else #include #include #define getpid _getpid #include #define umask _umask typedef int mode_t; #endif #include #include #include "zlib.h" #ifdef __POSIX__ # include /* getpwnam() */ # include /* getgrnam() */ #endif #include "node_buffer.h" #include "node_file.h" #include "node_http_parser.h" #include "node_constants.h" #include "node_javascript.h" #include "node_version.h" #include "node_string.h" #if HAVE_OPENSSL # include "node_crypto.h" #endif #if HAVE_SYSTEMTAP #include "node_systemtap.h" #endif #include "node_script.h" #include "v8_typed_array.h" using namespace v8; # ifdef __APPLE__ # include # define environ (*_NSGetEnviron()) # elif !defined(_MSC_VER) extern char **environ; # endif namespace node { ngx_queue_t handle_wrap_queue = { &handle_wrap_queue, &handle_wrap_queue }; ngx_queue_t req_wrap_queue = { &req_wrap_queue, &req_wrap_queue }; // declared in req_wrap.h Persistent process_symbol; Persistent domain_symbol; // declared in node_internals.h Persistent process; static Persistent process_tickFromSpinner; static Persistent process_tickCallback; static Persistent exports_symbol; static Persistent errno_symbol; static Persistent syscall_symbol; static Persistent errpath_symbol; static Persistent code_symbol; static Persistent rss_symbol; static Persistent heap_total_symbol; static Persistent heap_used_symbol; static Persistent fatal_exception_symbol; static Persistent enter_symbol; static Persistent exit_symbol; static Persistent disposed_symbol; static bool print_eval = false; static bool force_repl = false; static bool trace_deprecation = false; static bool throw_deprecation = false; static char *eval_string = NULL; static int option_end_index = 0; static bool use_debug_agent = false; static bool debug_wait_connect = false; static int debug_port=5858; static int max_stack_size = 0; static bool using_domains = false; // used by C++ modules as well bool no_deprecation = false; static uv_idle_t tick_spinner; static bool need_tick_cb; static Persistent tick_callback_sym; static uv_check_t check_immediate_watcher; static uv_idle_t idle_immediate_dummy; static bool need_immediate_cb; static Persistent immediate_callback_sym; // for quick ref to tickCallback values static struct { uint32_t length; uint32_t index; uint32_t depth; } tick_infobox; #ifdef OPENSSL_NPN_NEGOTIATED static bool use_npn = true; #else static bool use_npn = false; #endif #ifdef SSL_CTRL_SET_TLSEXT_SERVERNAME_CB static bool use_sni = true; #else static bool use_sni = false; #endif // process-relative uptime base, initialized at start-up static double prog_start_time; static volatile bool debugger_running = false; static uv_async_t dispatch_debug_messages_async; // Declared in node_internals.h Isolate* node_isolate = NULL; static void Spin(uv_idle_t* handle, int status) { assert((uv_idle_t*) handle == &tick_spinner); assert(status == 0); // Avoid entering a V8 scope. if (!need_tick_cb) return; need_tick_cb = false; uv_idle_stop(&tick_spinner); HandleScope scope; if (process_tickFromSpinner.IsEmpty()) { Local cb_v = process->Get(String::New("_tickFromSpinner")); if (!cb_v->IsFunction()) { fprintf(stderr, "process._tickFromSpinner assigned to non-function\n"); abort(); } Local cb = cb_v.As(); process_tickFromSpinner = Persistent::New(cb); } TryCatch try_catch; process_tickFromSpinner->Call(process, 0, NULL); if (try_catch.HasCaught()) { FatalException(try_catch); } } static Handle NeedTickCallback(const Arguments& args) { need_tick_cb = true; uv_idle_start(&tick_spinner, Spin); return Undefined(); } static void CheckImmediate(uv_check_t* handle, int status) { assert(handle == &check_immediate_watcher); assert(status == 0); HandleScope scope; if (immediate_callback_sym.IsEmpty()) { immediate_callback_sym = NODE_PSYMBOL("_immediateCallback"); } MakeCallback(process, immediate_callback_sym, 0, NULL); } static void IdleImmediateDummy(uv_idle_t* handle, int status) { // Do nothing. Only for maintaining event loop assert(handle == &idle_immediate_dummy); assert(status == 0); } static inline const char *errno_string(int errorno) { #define ERRNO_CASE(e) case e: return #e; switch (errorno) { #ifdef EACCES ERRNO_CASE(EACCES); #endif #ifdef EADDRINUSE ERRNO_CASE(EADDRINUSE); #endif #ifdef EADDRNOTAVAIL ERRNO_CASE(EADDRNOTAVAIL); #endif #ifdef EAFNOSUPPORT ERRNO_CASE(EAFNOSUPPORT); #endif #ifdef EAGAIN ERRNO_CASE(EAGAIN); #endif #ifdef EWOULDBLOCK # if EAGAIN != EWOULDBLOCK ERRNO_CASE(EWOULDBLOCK); # endif #endif #ifdef EALREADY ERRNO_CASE(EALREADY); #endif #ifdef EBADF ERRNO_CASE(EBADF); #endif #ifdef EBADMSG ERRNO_CASE(EBADMSG); #endif #ifdef EBUSY ERRNO_CASE(EBUSY); #endif #ifdef ECANCELED ERRNO_CASE(ECANCELED); #endif #ifdef ECHILD ERRNO_CASE(ECHILD); #endif #ifdef ECONNABORTED ERRNO_CASE(ECONNABORTED); #endif #ifdef ECONNREFUSED ERRNO_CASE(ECONNREFUSED); #endif #ifdef ECONNRESET ERRNO_CASE(ECONNRESET); #endif #ifdef EDEADLK ERRNO_CASE(EDEADLK); #endif #ifdef EDESTADDRREQ ERRNO_CASE(EDESTADDRREQ); #endif #ifdef EDOM ERRNO_CASE(EDOM); #endif #ifdef EDQUOT ERRNO_CASE(EDQUOT); #endif #ifdef EEXIST ERRNO_CASE(EEXIST); #endif #ifdef EFAULT ERRNO_CASE(EFAULT); #endif #ifdef EFBIG ERRNO_CASE(EFBIG); #endif #ifdef EHOSTUNREACH ERRNO_CASE(EHOSTUNREACH); #endif #ifdef EIDRM ERRNO_CASE(EIDRM); #endif #ifdef EILSEQ ERRNO_CASE(EILSEQ); #endif #ifdef EINPROGRESS ERRNO_CASE(EINPROGRESS); #endif #ifdef EINTR ERRNO_CASE(EINTR); #endif #ifdef EINVAL ERRNO_CASE(EINVAL); #endif #ifdef EIO ERRNO_CASE(EIO); #endif #ifdef EISCONN ERRNO_CASE(EISCONN); #endif #ifdef EISDIR ERRNO_CASE(EISDIR); #endif #ifdef ELOOP ERRNO_CASE(ELOOP); #endif #ifdef EMFILE ERRNO_CASE(EMFILE); #endif #ifdef EMLINK ERRNO_CASE(EMLINK); #endif #ifdef EMSGSIZE ERRNO_CASE(EMSGSIZE); #endif #ifdef EMULTIHOP ERRNO_CASE(EMULTIHOP); #endif #ifdef ENAMETOOLONG ERRNO_CASE(ENAMETOOLONG); #endif #ifdef ENETDOWN ERRNO_CASE(ENETDOWN); #endif #ifdef ENETRESET ERRNO_CASE(ENETRESET); #endif #ifdef ENETUNREACH ERRNO_CASE(ENETUNREACH); #endif #ifdef ENFILE ERRNO_CASE(ENFILE); #endif #ifdef ENOBUFS ERRNO_CASE(ENOBUFS); #endif #ifdef ENODATA ERRNO_CASE(ENODATA); #endif #ifdef ENODEV ERRNO_CASE(ENODEV); #endif #ifdef ENOENT ERRNO_CASE(ENOENT); #endif #ifdef ENOEXEC ERRNO_CASE(ENOEXEC); #endif #ifdef ENOLINK ERRNO_CASE(ENOLINK); #endif #ifdef ENOLCK # if ENOLINK != ENOLCK ERRNO_CASE(ENOLCK); # endif #endif #ifdef ENOMEM ERRNO_CASE(ENOMEM); #endif #ifdef ENOMSG ERRNO_CASE(ENOMSG); #endif #ifdef ENOPROTOOPT ERRNO_CASE(ENOPROTOOPT); #endif #ifdef ENOSPC ERRNO_CASE(ENOSPC); #endif #ifdef ENOSR ERRNO_CASE(ENOSR); #endif #ifdef ENOSTR ERRNO_CASE(ENOSTR); #endif #ifdef ENOSYS ERRNO_CASE(ENOSYS); #endif #ifdef ENOTCONN ERRNO_CASE(ENOTCONN); #endif #ifdef ENOTDIR ERRNO_CASE(ENOTDIR); #endif #ifdef ENOTEMPTY ERRNO_CASE(ENOTEMPTY); #endif #ifdef ENOTSOCK ERRNO_CASE(ENOTSOCK); #endif #ifdef ENOTSUP ERRNO_CASE(ENOTSUP); #else # ifdef EOPNOTSUPP ERRNO_CASE(EOPNOTSUPP); # endif #endif #ifdef ENOTTY ERRNO_CASE(ENOTTY); #endif #ifdef ENXIO ERRNO_CASE(ENXIO); #endif #ifdef EOVERFLOW ERRNO_CASE(EOVERFLOW); #endif #ifdef EPERM ERRNO_CASE(EPERM); #endif #ifdef EPIPE ERRNO_CASE(EPIPE); #endif #ifdef EPROTO ERRNO_CASE(EPROTO); #endif #ifdef EPROTONOSUPPORT ERRNO_CASE(EPROTONOSUPPORT); #endif #ifdef EPROTOTYPE ERRNO_CASE(EPROTOTYPE); #endif #ifdef ERANGE ERRNO_CASE(ERANGE); #endif #ifdef EROFS ERRNO_CASE(EROFS); #endif #ifdef ESPIPE ERRNO_CASE(ESPIPE); #endif #ifdef ESRCH ERRNO_CASE(ESRCH); #endif #ifdef ESTALE ERRNO_CASE(ESTALE); #endif #ifdef ETIME ERRNO_CASE(ETIME); #endif #ifdef ETIMEDOUT ERRNO_CASE(ETIMEDOUT); #endif #ifdef ETXTBSY ERRNO_CASE(ETXTBSY); #endif #ifdef EXDEV ERRNO_CASE(EXDEV); #endif default: return ""; } } const char *signo_string(int signo) { #define SIGNO_CASE(e) case e: return #e; switch (signo) { #ifdef SIGHUP SIGNO_CASE(SIGHUP); #endif #ifdef SIGINT SIGNO_CASE(SIGINT); #endif #ifdef SIGQUIT SIGNO_CASE(SIGQUIT); #endif #ifdef SIGILL SIGNO_CASE(SIGILL); #endif #ifdef SIGTRAP SIGNO_CASE(SIGTRAP); #endif #ifdef SIGABRT SIGNO_CASE(SIGABRT); #endif #ifdef SIGIOT # if SIGABRT != SIGIOT SIGNO_CASE(SIGIOT); # endif #endif #ifdef SIGBUS SIGNO_CASE(SIGBUS); #endif #ifdef SIGFPE SIGNO_CASE(SIGFPE); #endif #ifdef SIGKILL SIGNO_CASE(SIGKILL); #endif #ifdef SIGUSR1 SIGNO_CASE(SIGUSR1); #endif #ifdef SIGSEGV SIGNO_CASE(SIGSEGV); #endif #ifdef SIGUSR2 SIGNO_CASE(SIGUSR2); #endif #ifdef SIGPIPE SIGNO_CASE(SIGPIPE); #endif #ifdef SIGALRM SIGNO_CASE(SIGALRM); #endif SIGNO_CASE(SIGTERM); #ifdef SIGCHLD SIGNO_CASE(SIGCHLD); #endif #ifdef SIGSTKFLT SIGNO_CASE(SIGSTKFLT); #endif #ifdef SIGCONT SIGNO_CASE(SIGCONT); #endif #ifdef SIGSTOP SIGNO_CASE(SIGSTOP); #endif #ifdef SIGTSTP SIGNO_CASE(SIGTSTP); #endif #ifdef SIGBREAK SIGNO_CASE(SIGBREAK); #endif #ifdef SIGTTIN SIGNO_CASE(SIGTTIN); #endif #ifdef SIGTTOU SIGNO_CASE(SIGTTOU); #endif #ifdef SIGURG SIGNO_CASE(SIGURG); #endif #ifdef SIGXCPU SIGNO_CASE(SIGXCPU); #endif #ifdef SIGXFSZ SIGNO_CASE(SIGXFSZ); #endif #ifdef SIGVTALRM SIGNO_CASE(SIGVTALRM); #endif #ifdef SIGPROF SIGNO_CASE(SIGPROF); #endif #ifdef SIGWINCH SIGNO_CASE(SIGWINCH); #endif #ifdef SIGIO SIGNO_CASE(SIGIO); #endif #ifdef SIGPOLL # if SIGPOLL != SIGIO SIGNO_CASE(SIGPOLL); # endif #endif #ifdef SIGLOST SIGNO_CASE(SIGLOST); #endif #ifdef SIGPWR # if SIGPWR != SIGLOST SIGNO_CASE(SIGPWR); # endif #endif #ifdef SIGSYS SIGNO_CASE(SIGSYS); #endif default: return ""; } } Local ErrnoException(int errorno, const char *syscall, const char *msg, const char *path) { Local e; Local estring = String::NewSymbol(errno_string(errorno)); if (!msg[0]) { msg = strerror(errorno); } Local message = String::NewSymbol(msg); Local cons1 = String::Concat(estring, String::NewSymbol(", ")); Local cons2 = String::Concat(cons1, message); if (syscall_symbol.IsEmpty()) { syscall_symbol = NODE_PSYMBOL("syscall"); errno_symbol = NODE_PSYMBOL("errno"); errpath_symbol = NODE_PSYMBOL("path"); code_symbol = NODE_PSYMBOL("code"); } if (path) { Local cons3 = String::Concat(cons2, String::NewSymbol(" '")); Local cons4 = String::Concat(cons3, String::New(path)); Local cons5 = String::Concat(cons4, String::NewSymbol("'")); e = Exception::Error(cons5); } else { e = Exception::Error(cons2); } Local obj = e->ToObject(); obj->Set(errno_symbol, Integer::New(errorno)); obj->Set(code_symbol, estring); if (path) obj->Set(errpath_symbol, String::New(path)); if (syscall) obj->Set(syscall_symbol, String::NewSymbol(syscall)); return e; } static const char* get_uv_errno_string(int errorno) { uv_err_t err; memset(&err, 0, sizeof err); err.code = (uv_err_code)errorno; return uv_err_name(err); } static const char* get_uv_errno_message(int errorno) { uv_err_t err; memset(&err, 0, sizeof err); err.code = (uv_err_code)errorno; return uv_strerror(err); } // hack alert! copy of ErrnoException, tuned for uv errors Local UVException(int errorno, const char *syscall, const char *msg, const char *path) { if (syscall_symbol.IsEmpty()) { syscall_symbol = NODE_PSYMBOL("syscall"); errno_symbol = NODE_PSYMBOL("errno"); errpath_symbol = NODE_PSYMBOL("path"); code_symbol = NODE_PSYMBOL("code"); } if (!msg || !msg[0]) msg = get_uv_errno_message(errorno); Local estring = String::NewSymbol(get_uv_errno_string(errorno)); Local message = String::NewSymbol(msg); Local cons1 = String::Concat(estring, String::NewSymbol(", ")); Local cons2 = String::Concat(cons1, message); Local e; Local path_str; if (path) { #ifdef _WIN32 if (strncmp(path, "\\\\?\\UNC\\", 8) == 0) { path_str = String::Concat(String::New("\\\\"), String::New(path + 8)); } else if (strncmp(path, "\\\\?\\", 4) == 0) { path_str = String::New(path + 4); } else { path_str = String::New(path); } #else path_str = String::New(path); #endif Local cons3 = String::Concat(cons2, String::NewSymbol(" '")); Local cons4 = String::Concat(cons3, path_str); Local cons5 = String::Concat(cons4, String::NewSymbol("'")); e = Exception::Error(cons5); } else { e = Exception::Error(cons2); } Local obj = e->ToObject(); // TODO errno should probably go obj->Set(errno_symbol, Integer::New(errorno)); obj->Set(code_symbol, estring); if (path) obj->Set(errpath_symbol, path_str); if (syscall) obj->Set(syscall_symbol, String::NewSymbol(syscall)); return e; } #ifdef _WIN32 // Does about the same as strerror(), // but supports all windows error messages static const char *winapi_strerror(const int errorno) { char *errmsg = NULL; FormatMessage(FORMAT_MESSAGE_ALLOCATE_BUFFER | FORMAT_MESSAGE_FROM_SYSTEM | FORMAT_MESSAGE_IGNORE_INSERTS, NULL, errorno, MAKELANGID(LANG_NEUTRAL, SUBLANG_DEFAULT), (LPTSTR)&errmsg, 0, NULL); if (errmsg) { // Remove trailing newlines for (int i = strlen(errmsg) - 1; i >= 0 && (errmsg[i] == '\n' || errmsg[i] == '\r'); i--) { errmsg[i] = '\0'; } return errmsg; } else { // FormatMessage failed return "Unknown error"; } } Local WinapiErrnoException(int errorno, const char* syscall, const char* msg, const char* path) { Local e; if (!msg || !msg[0]) { msg = winapi_strerror(errorno); } Local message = String::NewSymbol(msg); if (syscall_symbol.IsEmpty()) { syscall_symbol = NODE_PSYMBOL("syscall"); errno_symbol = NODE_PSYMBOL("errno"); errpath_symbol = NODE_PSYMBOL("path"); code_symbol = NODE_PSYMBOL("code"); } if (path) { Local cons1 = String::Concat(message, String::NewSymbol(" '")); Local cons2 = String::Concat(cons1, String::New(path)); Local cons3 = String::Concat(cons2, String::NewSymbol("'")); e = Exception::Error(cons3); } else { e = Exception::Error(message); } Local obj = e->ToObject(); obj->Set(errno_symbol, Integer::New(errorno)); if (path) obj->Set(errpath_symbol, String::New(path)); if (syscall) obj->Set(syscall_symbol, String::NewSymbol(syscall)); return e; } #endif Handle FromConstructorTemplate(Persistent t, const Arguments& args) { HandleScope scope; Local argv[32]; unsigned argc = args.Length(); if (argc > ARRAY_SIZE(argv)) argc = ARRAY_SIZE(argv); for (unsigned i = 0; i < argc; ++i) argv[i] = args[i]; return scope.Close(t->GetFunction()->NewInstance(argc, argv)); } Handle UsingDomains(const Arguments& args) { HandleScope scope; if (using_domains) return scope.Close(Undefined()); using_domains = true; Local tdc_v = process->Get(String::New("_tickDomainCallback")); Local ndt_v = process->Get(String::New("_nextDomainTick")); if (!tdc_v->IsFunction()) { fprintf(stderr, "process._tickDomainCallback assigned to non-function\n"); abort(); } if (!ndt_v->IsFunction()) { fprintf(stderr, "process._nextDomainTick assigned to non-function\n"); abort(); } Local tdc = tdc_v.As(); Local ndt = ndt_v.As(); process->Set(String::New("_tickCallback"), tdc); process->Set(String::New("nextTick"), ndt); process_tickCallback.Dispose(); // Possibly already set by MakeCallback(). process_tickCallback = Persistent::New(tdc); return Undefined(); } Handle MakeDomainCallback(const Handle object, const Handle callback, int argc, Handle argv[]) { // TODO Hook for long stack traces to be made here. // lazy load domain specific symbols if (enter_symbol.IsEmpty()) { enter_symbol = NODE_PSYMBOL("enter"); exit_symbol = NODE_PSYMBOL("exit"); disposed_symbol = NODE_PSYMBOL("_disposed"); } Local domain_v = object->Get(domain_symbol); Local domain; Local enter; Local exit; TryCatch try_catch; bool has_domain = domain_v->IsObject(); if (has_domain) { domain = domain_v->ToObject(); assert(!domain.IsEmpty()); if (domain->Get(disposed_symbol)->IsTrue()) { // domain has been disposed of. return Undefined(); } enter = Local::Cast(domain->Get(enter_symbol)); assert(!enter.IsEmpty()); enter->Call(domain, 0, NULL); if (try_catch.HasCaught()) { FatalException(try_catch); return Undefined(); } } Local ret = callback->Call(object, argc, argv); if (try_catch.HasCaught()) { FatalException(try_catch); return Undefined(); } if (has_domain) { exit = Local::Cast(domain->Get(exit_symbol)); assert(!exit.IsEmpty()); exit->Call(domain, 0, NULL); if (try_catch.HasCaught()) { FatalException(try_catch); return Undefined(); } } if (tick_infobox.length == 0) { tick_infobox.index = 0; tick_infobox.depth = 0; return ret; } // process nextTicks after call process_tickCallback->Call(process, 0, NULL); if (try_catch.HasCaught()) { FatalException(try_catch); return Undefined(); } return ret; } Handle MakeCallback(const Handle object, const Handle callback, int argc, Handle argv[]) { // TODO Hook for long stack traces to be made here. if (using_domains) return MakeDomainCallback(object, callback, argc, argv); // lazy load no domain next tick callbacks if (process_tickCallback.IsEmpty()) { Local cb_v = process->Get(String::New("_tickCallback")); if (!cb_v->IsFunction()) { fprintf(stderr, "process._tickCallback assigned to non-function\n"); abort(); } Local cb = cb_v.As(); process_tickCallback = Persistent::New(cb); } TryCatch try_catch; Local ret = callback->Call(object, argc, argv); if (try_catch.HasCaught()) { FatalException(try_catch); return Undefined(); } if (tick_infobox.length == 0) { tick_infobox.index = 0; tick_infobox.depth = 0; return ret; } // process nextTicks after call process_tickCallback->Call(process, 0, NULL); if (try_catch.HasCaught()) { FatalException(try_catch); return Undefined(); } return ret; } Handle MakeCallback(const Handle object, const Handle symbol, int argc, Handle argv[]) { HandleScope scope; Local callback = object->Get(symbol).As(); if (using_domains) return scope.Close(MakeDomainCallback(object, callback, argc, argv)); return scope.Close(MakeCallback(object, callback, argc, argv)); } Handle MakeCallback(const Handle object, const char* method, int argc, Handle argv[]) { HandleScope scope; Handle ret = MakeCallback(object, String::NewSymbol(method), argc, argv); return scope.Close(ret); } void SetErrno(uv_err_t err) { HandleScope scope; static Persistent errno_symbol; if (errno_symbol.IsEmpty()) { errno_symbol = NODE_PSYMBOL("_errno"); } if (err.code == UV_UNKNOWN) { char errno_buf[100]; snprintf(errno_buf, 100, "Unknown system errno %d", err.sys_errno_); process->Set(errno_symbol, String::New(errno_buf)); } else { process->Set(errno_symbol, String::NewSymbol(uv_err_name(err))); } } enum encoding ParseEncoding(Handle encoding_v, enum encoding _default) { HandleScope scope; if (!encoding_v->IsString()) return _default; String::Utf8Value encoding(encoding_v); if (strcasecmp(*encoding, "utf8") == 0) { return UTF8; } else if (strcasecmp(*encoding, "utf-8") == 0) { return UTF8; } else if (strcasecmp(*encoding, "ascii") == 0) { return ASCII; } else if (strcasecmp(*encoding, "base64") == 0) { return BASE64; } else if (strcasecmp(*encoding, "ucs2") == 0) { return UCS2; } else if (strcasecmp(*encoding, "ucs-2") == 0) { return UCS2; } else if (strcasecmp(*encoding, "utf16le") == 0) { return UCS2; } else if (strcasecmp(*encoding, "utf-16le") == 0) { return UCS2; } else if (strcasecmp(*encoding, "binary") == 0) { return BINARY; } else if (strcasecmp(*encoding, "buffer") == 0) { return BUFFER; } else if (strcasecmp(*encoding, "hex") == 0) { return HEX; } else if (strcasecmp(*encoding, "raw") == 0) { if (!no_deprecation) { fprintf(stderr, "'raw' (array of integers) has been removed. " "Use 'binary'.\n"); } return BINARY; } else if (strcasecmp(*encoding, "raws") == 0) { if (!no_deprecation) { fprintf(stderr, "'raws' encoding has been renamed to 'binary'. " "Please update your code.\n"); } return BINARY; } else { return _default; } } Local Encode(const void *buf, size_t len, enum encoding encoding) { return StringBytes::Encode(static_cast(buf), len, encoding); } // Returns -1 if the handle was not valid for decoding ssize_t DecodeBytes(v8::Handle val, enum encoding encoding) { HandleScope scope; if (val->IsArray()) { fprintf(stderr, "'raw' encoding (array of integers) has been removed. " "Use 'binary'.\n"); assert(0); return -1; } return StringBytes::Size(val, encoding); } #ifndef MIN # define MIN(a, b) ((a) < (b) ? (a) : (b)) #endif // Returns number of bytes written. ssize_t DecodeWrite(char *buf, size_t buflen, v8::Handle val, enum encoding encoding) { HandleScope scope; if (val->IsArray()) { fprintf(stderr, "'raw' encoding (array of integers) has been removed.\n"); assert(0); return -1; } return StringBytes::Write(buf, buflen, val, encoding, NULL); } void DisplayExceptionLine (TryCatch &try_catch) { // Prevent re-entry into this function. For example, if there is // a throw from a program in vm.runInThisContext(code, filename, true), // then we want to show the original failure, not the secondary one. static bool displayed_error = false; if (displayed_error) return; displayed_error = true; HandleScope scope; Handle message = try_catch.Message(); uv_tty_reset_mode(); fprintf(stderr, "\n"); if (!message.IsEmpty()) { // Print (filename):(line number): (message). String::Utf8Value filename(message->GetScriptResourceName()); const char* filename_string = *filename; int linenum = message->GetLineNumber(); fprintf(stderr, "%s:%i\n", filename_string, linenum); // Print line of source code. String::Utf8Value sourceline(message->GetSourceLine()); const char* sourceline_string = *sourceline; // Because of how node modules work, all scripts are wrapped with a // "function (module, exports, __filename, ...) {" // to provide script local variables. // // When reporting errors on the first line of a script, this wrapper // function is leaked to the user. There used to be a hack here to // truncate off the first 62 characters, but it caused numerous other // problems when vm.runIn*Context() methods were used for non-module // code. // // If we ever decide to re-instate such a hack, the following steps // must be taken: // // 1. Pass a flag around to say "this code was wrapped" // 2. Update the stack frame output so that it is also correct. // // It would probably be simpler to add a line rather than add some // number of characters to the first line, since V8 truncates the // sourceline to 78 characters, and we end up not providing very much // useful debugging info to the user if we remove 62 characters. int start = message->GetStartColumn(); int end = message->GetEndColumn(); // fprintf(stderr, "---\nsourceline:%s\noffset:%d\nstart:%d\nend:%d\n---\n", sourceline_string, start, end); fprintf(stderr, "%s\n", sourceline_string); // Print wavy underline (GetUnderline is deprecated). for (int i = 0; i < start; i++) { fputc((sourceline_string[i] == '\t') ? '\t' : ' ', stderr); } for (int i = start; i < end; i++) { fputc('^', stderr); } fputc('\n', stderr); } } static void ReportException(TryCatch &try_catch, bool show_line) { HandleScope scope; if (show_line) DisplayExceptionLine(try_catch); String::Utf8Value trace(try_catch.StackTrace()); // range errors have a trace member set to undefined if (trace.length() > 0 && !try_catch.StackTrace()->IsUndefined()) { fprintf(stderr, "%s\n", *trace); } else { // this really only happens for RangeErrors, since they're the only // kind that won't have all this info in the trace, or when non-Error // objects are thrown manually. Local er = try_catch.Exception(); bool isErrorObject = er->IsObject() && !(er->ToObject()->Get(String::New("message"))->IsUndefined()) && !(er->ToObject()->Get(String::New("name"))->IsUndefined()); if (isErrorObject) { String::Utf8Value name(er->ToObject()->Get(String::New("name"))); fprintf(stderr, "%s: ", *name); } String::Utf8Value msg(!isErrorObject ? er : er->ToObject()->Get(String::New("message"))); fprintf(stderr, "%s\n", *msg); } fflush(stderr); } // Executes a str within the current v8 context. Local ExecuteString(Handle source, Handle filename) { HandleScope scope; TryCatch try_catch; Local script = v8::Script::Compile(source, filename); if (script.IsEmpty()) { ReportException(try_catch, true); exit(3); } Local result = script->Run(); if (result.IsEmpty()) { ReportException(try_catch, true); exit(4); } return scope.Close(result); } static Handle GetActiveRequests(const Arguments& args) { HandleScope scope; Local ary = Array::New(); ngx_queue_t* q = NULL; int i = 0; ngx_queue_foreach(q, &req_wrap_queue) { ReqWrap* w = container_of(q, ReqWrap, req_wrap_queue_); if (w->object_.IsEmpty()) continue; ary->Set(i++, w->object_); } return scope.Close(ary); } // Non-static, friend of HandleWrap. Could have been a HandleWrap method but // implemented here for consistency with GetActiveRequests(). Handle GetActiveHandles(const Arguments& args) { HandleScope scope; Local ary = Array::New(); ngx_queue_t* q = NULL; int i = 0; Local owner_sym = String::New("owner"); ngx_queue_foreach(q, &handle_wrap_queue) { HandleWrap* w = container_of(q, HandleWrap, handle_wrap_queue_); if (w->object_.IsEmpty() || (w->flags_ & HandleWrap::kUnref)) continue; Local obj = w->object_->Get(owner_sym); if (obj->IsUndefined()) obj = *w->object_; ary->Set(i++, obj); } return scope.Close(ary); } static Handle Abort(const Arguments& args) { abort(); return Undefined(); } static Handle Chdir(const Arguments& args) { HandleScope scope; if (args.Length() != 1 || !args[0]->IsString()) { return ThrowException(Exception::Error(String::New("Bad argument."))); } String::Utf8Value path(args[0]); uv_err_t r = uv_chdir(*path); if (r.code != UV_OK) { return ThrowException(UVException(r.code, "uv_chdir")); } return Undefined(); } static Handle Cwd(const Arguments& args) { HandleScope scope; #ifdef _WIN32 /* MAX_PATH is in characters, not bytes. Make sure we have enough headroom. */ char buf[MAX_PATH * 4 + 1]; #else char buf[PATH_MAX + 1]; #endif uv_err_t r = uv_cwd(buf, ARRAY_SIZE(buf) - 1); if (r.code != UV_OK) { return ThrowException(UVException(r.code, "uv_cwd")); } buf[ARRAY_SIZE(buf) - 1] = '\0'; Local cwd = String::New(buf); return scope.Close(cwd); } static Handle Umask(const Arguments& args) { HandleScope scope; unsigned int old; if (args.Length() < 1 || args[0]->IsUndefined()) { old = umask(0); umask((mode_t)old); } else if(!args[0]->IsInt32() && !args[0]->IsString()) { return ThrowException(Exception::TypeError( String::New("argument must be an integer or octal string."))); } else { int oct; if(args[0]->IsInt32()) { oct = args[0]->Uint32Value(); } else { oct = 0; String::Utf8Value str(args[0]); // Parse the octal string. for (int i = 0; i < str.length(); i++) { char c = (*str)[i]; if (c > '7' || c < '0') { return ThrowException(Exception::TypeError( String::New("invalid octal string"))); } oct *= 8; oct += c - '0'; } } old = umask(static_cast(oct)); } return scope.Close(Uint32::New(old)); } #ifdef __POSIX__ static const uid_t uid_not_found = static_cast(-1); static const gid_t gid_not_found = static_cast(-1); static uid_t uid_by_name(const char* name) { struct passwd pwd; struct passwd* pp; char buf[8192]; errno = 0; pp = NULL; if (getpwnam_r(name, &pwd, buf, sizeof(buf), &pp) == 0 && pp != NULL) { return pp->pw_uid; } return uid_not_found; } static char* name_by_uid(uid_t uid) { struct passwd pwd; struct passwd* pp; char buf[8192]; int rc; errno = 0; pp = NULL; if ((rc = getpwuid_r(uid, &pwd, buf, sizeof(buf), &pp)) == 0 && pp != NULL) { return strdup(pp->pw_name); } if (rc == 0) { errno = ENOENT; } return NULL; } static gid_t gid_by_name(const char* name) { struct group pwd; struct group* pp; char buf[8192]; errno = 0; pp = NULL; if (getgrnam_r(name, &pwd, buf, sizeof(buf), &pp) == 0 && pp != NULL) { return pp->gr_gid; } return gid_not_found; } #if 0 // For future use. static const char* name_by_gid(gid_t gid) { struct group pwd; struct group* pp; char buf[8192]; int rc; errno = 0; pp = NULL; if ((rc = getgrgid_r(gid, &pwd, buf, sizeof(buf), &pp)) == 0 && pp != NULL) { return strdup(pp->gr_name); } if (rc == 0) { errno = ENOENT; } return NULL; } #endif static uid_t uid_by_name(Handle value) { if (value->IsUint32()) { return static_cast(value->Uint32Value()); } else { String::Utf8Value name(value); return uid_by_name(*name); } } static gid_t gid_by_name(Handle value) { if (value->IsUint32()) { return static_cast(value->Uint32Value()); } else { String::Utf8Value name(value); return gid_by_name(*name); } } static Handle GetUid(const Arguments& args) { HandleScope scope; uid_t uid = getuid(); return scope.Close(Integer::NewFromUnsigned(uid)); } static Handle GetGid(const Arguments& args) { HandleScope scope; gid_t gid = getgid(); return scope.Close(Integer::NewFromUnsigned(gid)); } static Handle SetGid(const Arguments& args) { HandleScope scope; if (!args[0]->IsUint32() && !args[0]->IsString()) { return ThrowTypeError("setgid argument must be a number or a string"); } gid_t gid = gid_by_name(args[0]); if (gid == gid_not_found) { return ThrowError("setgid group id does not exist"); } if (setgid(gid)) { return ThrowException(ErrnoException(errno, "setgid")); } return Undefined(); } static Handle SetUid(const Arguments& args) { HandleScope scope; if (!args[0]->IsUint32() && !args[0]->IsString()) { return ThrowTypeError("setuid argument must be a number or a string"); } uid_t uid = uid_by_name(args[0]); if (uid == uid_not_found) { return ThrowError("setuid user id does not exist"); } if (setuid(uid)) { return ThrowException(ErrnoException(errno, "setuid")); } return Undefined(); } static Handle GetGroups(const Arguments& args) { HandleScope scope; int ngroups = getgroups(0, NULL); if (ngroups == -1) { return ThrowException(ErrnoException(errno, "getgroups")); } gid_t* groups = new gid_t[ngroups]; ngroups = getgroups(ngroups, groups); if (ngroups == -1) { delete[] groups; return ThrowException(ErrnoException(errno, "getgroups")); } Local groups_list = Array::New(ngroups); bool seen_egid = false; gid_t egid = getegid(); for (int i = 0; i < ngroups; i++) { groups_list->Set(i, Integer::New(groups[i])); if (groups[i] == egid) seen_egid = true; } delete[] groups; if (seen_egid == false) { groups_list->Set(ngroups, Integer::New(egid)); } return scope.Close(groups_list); } static Handle SetGroups(const Arguments& args) { HandleScope scope; if (!args[0]->IsArray()) { return ThrowTypeError("argument 1 must be an array"); } Local groups_list = args[0].As(); size_t size = groups_list->Length(); gid_t* groups = new gid_t[size]; for (size_t i = 0; i < size; i++) { gid_t gid = gid_by_name(groups_list->Get(i)); if (gid == gid_not_found) { delete[] groups; return ThrowError("group name not found"); } groups[i] = gid; } int rc = setgroups(size, groups); delete[] groups; if (rc == -1) { return ThrowException(ErrnoException(errno, "setgroups")); } return Undefined(); } static Handle InitGroups(const Arguments& args) { HandleScope scope; if (!args[0]->IsUint32() && !args[0]->IsString()) { return ThrowTypeError("argument 1 must be a number or a string"); } if (!args[1]->IsUint32() && !args[1]->IsString()) { return ThrowTypeError("argument 2 must be a number or a string"); } String::Utf8Value arg0(args[0]); gid_t extra_group; bool must_free; char* user; if (args[0]->IsUint32()) { user = name_by_uid(args[0]->Uint32Value()); must_free = true; } else { user = *arg0; must_free = false; } if (user == NULL) { return ThrowError("initgroups user not found"); } extra_group = gid_by_name(args[1]); if (extra_group == gid_not_found) { if (must_free) free(user); return ThrowError("initgroups extra group not found"); } int rc = initgroups(user, extra_group); if (must_free) { free(user); } if (rc) { return ThrowException(ErrnoException(errno, "initgroups")); } return Undefined(); } #endif // __POSIX__ v8::Handle Exit(const v8::Arguments& args) { HandleScope scope; exit(args[0]->IntegerValue()); return Undefined(); } static Handle Uptime(const Arguments& args) { HandleScope scope; double uptime; uv_err_t err = uv_uptime(&uptime); if (err.code != UV_OK) { return Undefined(); } return scope.Close(Number::New(uptime - prog_start_time)); } v8::Handle MemoryUsage(const v8::Arguments& args) { HandleScope scope; size_t rss; uv_err_t err = uv_resident_set_memory(&rss); if (err.code != UV_OK) { return ThrowException(UVException(err.code, "uv_resident_set_memory")); } Local info = Object::New(); if (rss_symbol.IsEmpty()) { rss_symbol = NODE_PSYMBOL("rss"); heap_total_symbol = NODE_PSYMBOL("heapTotal"); heap_used_symbol = NODE_PSYMBOL("heapUsed"); } info->Set(rss_symbol, Number::New(rss)); // V8 memory usage HeapStatistics v8_heap_stats; V8::GetHeapStatistics(&v8_heap_stats); info->Set(heap_total_symbol, Integer::NewFromUnsigned(v8_heap_stats.total_heap_size())); info->Set(heap_used_symbol, Integer::NewFromUnsigned(v8_heap_stats.used_heap_size())); return scope.Close(info); } Handle Kill(const Arguments& args) { HandleScope scope; if (args.Length() != 2) { return ThrowException(Exception::Error(String::New("Bad argument."))); } int pid = args[0]->IntegerValue(); int sig = args[1]->Int32Value(); uv_err_t err = uv_kill(pid, sig); if (err.code != UV_OK) { SetErrno(err); return scope.Close(Integer::New(-1)); } return Undefined(); } // used in Hrtime() below #define NANOS_PER_SEC 1000000000 // Hrtime exposes libuv's uv_hrtime() high-resolution timer. // The value returned by uv_hrtime() is a 64-bit int representing nanoseconds, // so this function instead returns an Array with 2 entries representing seconds // and nanoseconds, to avoid any integer overflow possibility. // Pass in an Array from a previous hrtime() call to instead get a time diff. Handle Hrtime(const v8::Arguments& args) { HandleScope scope; uint64_t t = uv_hrtime(); if (args.Length() > 0) { // return a time diff tuple if (!args[0]->IsArray()) { Local exception = Exception::TypeError( String::New("process.hrtime() only accepts an Array tuple.")); return ThrowException(exception); } Local inArray = Local::Cast(args[0]); uint64_t seconds = inArray->Get(0)->Uint32Value(); uint64_t nanos = inArray->Get(1)->Uint32Value(); t -= (seconds * NANOS_PER_SEC) + nanos; } Local tuple = Array::New(2); tuple->Set(0, Integer::NewFromUnsigned(t / NANOS_PER_SEC)); tuple->Set(1, Integer::NewFromUnsigned(t % NANOS_PER_SEC)); return scope.Close(tuple); } typedef void (UV_DYNAMIC* extInit)(Handle exports); // DLOpen is process.dlopen(module, filename). // Used to load 'module.node' dynamically shared objects. Handle DLOpen(const v8::Arguments& args) { HandleScope scope; char symbol[1024], *base, *pos; uv_lib_t lib; int r; if (args.Length() < 2) { Local exception = Exception::Error( String::New("process.dlopen takes exactly 2 arguments.")); return ThrowException(exception); } Local module = args[0]->ToObject(); // Cast String::Utf8Value filename(args[1]); // Cast if (exports_symbol.IsEmpty()) { exports_symbol = NODE_PSYMBOL("exports"); } Local exports = module->Get(exports_symbol)->ToObject(); if (uv_dlopen(*filename, &lib)) { Local errmsg = String::New(uv_dlerror(&lib)); #ifdef _WIN32 // Windows needs to add the filename into the error message errmsg = String::Concat(errmsg, args[1]->ToString()); #endif return ThrowException(Exception::Error(errmsg)); } String::Utf8Value path(args[1]); base = *path; /* Find the shared library filename within the full path. */ #ifdef __POSIX__ pos = strrchr(base, '/'); if (pos != NULL) { base = pos + 1; } #else // Windows for (;;) { pos = strpbrk(base, "\\/:"); if (pos == NULL) { break; } base = pos + 1; } #endif /* Strip the .node extension. */ pos = strrchr(base, '.'); if (pos != NULL) { *pos = '\0'; } /* Add the `_module` suffix to the extension name. */ r = snprintf(symbol, sizeof symbol, "%s_module", base); if (r <= 0 || static_cast(r) >= sizeof symbol) { Local exception = Exception::Error(String::New("Out of memory.")); return ThrowException(exception); } /* Replace dashes with underscores. When loading foo-bar.node, * look for foo_bar_module, not foo-bar_module. */ for (pos = symbol; *pos != '\0'; ++pos) { if (*pos == '-') *pos = '_'; } node_module_struct *mod; if (uv_dlsym(&lib, symbol, reinterpret_cast(&mod))) { char errmsg[1024]; snprintf(errmsg, sizeof(errmsg), "Symbol %s not found.", symbol); return ThrowError(errmsg); } if (mod->version != NODE_MODULE_VERSION) { char errmsg[1024]; snprintf(errmsg, sizeof(errmsg), "Module version mismatch. Expected %d, got %d.", NODE_MODULE_VERSION, mod->version); return ThrowError(errmsg); } // Execute the C++ module mod->register_func(exports, module); // Tell coverity that 'handle' should not be freed when we return. // coverity[leaked_storage] return Undefined(); } static void OnFatalError(const char* location, const char* message) { if (location) { fprintf(stderr, "FATAL ERROR: %s %s\n", location, message); } else { fprintf(stderr, "FATAL ERROR: %s\n", message); } abort(); } void FatalException(TryCatch &try_catch) { HandleScope scope; if (fatal_exception_symbol.IsEmpty()) fatal_exception_symbol = NODE_PSYMBOL("_fatalException"); Local fatal_v = process->Get(fatal_exception_symbol); if (!fatal_v->IsFunction()) { // failed before the process._fatalException function was added! // this is probably pretty bad. Nothing to do but report and exit. ReportException(try_catch, true); exit(6); } Local fatal_f = Local::Cast(fatal_v); Local error = try_catch.Exception(); Local argv[] = { error }; TryCatch fatal_try_catch; // this will return true if the JS layer handled it, false otherwise Local caught = fatal_f->Call(process, ARRAY_SIZE(argv), argv); if (fatal_try_catch.HasCaught()) { // the fatal exception function threw, so we must exit ReportException(fatal_try_catch, true); exit(7); } if (false == caught->BooleanValue()) { ReportException(try_catch, true); exit(8); } } Persistent binding_cache; Persistent module_load_list; static Handle Binding(const Arguments& args) { HandleScope scope; Local module = args[0]->ToString(); String::Utf8Value module_v(module); node_module_struct* modp; if (binding_cache.IsEmpty()) { binding_cache = Persistent::New(Object::New()); } Local exports; if (binding_cache->Has(module)) { exports = binding_cache->Get(module)->ToObject(); return scope.Close(exports); } // Append a string to process.moduleLoadList char buf[1024]; snprintf(buf, 1024, "Binding %s", *module_v); uint32_t l = module_load_list->Length(); module_load_list->Set(l, String::New(buf)); if ((modp = get_builtin_module(*module_v)) != NULL) { exports = Object::New(); // Internal bindings don't have a "module" object, // only exports. modp->register_func(exports, Undefined()); binding_cache->Set(module, exports); } else if (!strcmp(*module_v, "constants")) { exports = Object::New(); DefineConstants(exports); binding_cache->Set(module, exports); } else if (!strcmp(*module_v, "natives")) { exports = Object::New(); DefineJavaScript(exports); binding_cache->Set(module, exports); } else { return ThrowException(Exception::Error(String::New("No such module"))); } return scope.Close(exports); } static Handle ProcessTitleGetter(Local property, const AccessorInfo& info) { HandleScope scope; char buffer[512]; uv_get_process_title(buffer, sizeof(buffer)); return scope.Close(String::New(buffer)); } static void ProcessTitleSetter(Local property, Local value, const AccessorInfo& info) { HandleScope scope; String::Utf8Value title(value); // TODO: protect with a lock uv_set_process_title(*title); } static Handle EnvGetter(Local property, const AccessorInfo& info) { HandleScope scope; #ifdef __POSIX__ String::Utf8Value key(property); const char* val = getenv(*key); if (val) { return scope.Close(String::New(val)); } #else // _WIN32 String::Value key(property); WCHAR buffer[32767]; // The maximum size allowed for environment variables. DWORD result = GetEnvironmentVariableW(reinterpret_cast(*key), buffer, ARRAY_SIZE(buffer)); // If result >= sizeof buffer the buffer was too small. That should never // happen. If result == 0 and result != ERROR_SUCCESS the variable was not // not found. if ((result > 0 || GetLastError() == ERROR_SUCCESS) && result < ARRAY_SIZE(buffer)) { return scope.Close(String::New(reinterpret_cast(buffer), result)); } #endif // Not found. Fetch from prototype. return scope.Close(info.Data().As()->Get(property)); } static Handle EnvSetter(Local property, Local value, const AccessorInfo& info) { HandleScope scope; #ifdef __POSIX__ String::Utf8Value key(property); String::Utf8Value val(value); setenv(*key, *val, 1); #else // _WIN32 String::Value key(property); String::Value val(value); WCHAR* key_ptr = reinterpret_cast(*key); // Environment variables that start with '=' are read-only. if (key_ptr[0] != L'=') { SetEnvironmentVariableW(key_ptr, reinterpret_cast(*val)); } #endif // Whether it worked or not, always return rval. return scope.Close(value); } static Handle EnvQuery(Local property, const AccessorInfo& info) { HandleScope scope; #ifdef __POSIX__ String::Utf8Value key(property); if (getenv(*key)) { return scope.Close(Integer::New(0)); } #else // _WIN32 String::Value key(property); WCHAR* key_ptr = reinterpret_cast(*key); if (GetEnvironmentVariableW(key_ptr, NULL, 0) > 0 || GetLastError() == ERROR_SUCCESS) { if (key_ptr[0] == L'=') { // Environment variables that start with '=' are hidden and read-only. return scope.Close(Integer::New(v8::ReadOnly || v8::DontDelete || v8::DontEnum)); } else { return scope.Close(Integer::New(0)); } } #endif // Not found return scope.Close(Handle()); } static Handle EnvDeleter(Local property, const AccessorInfo& info) { HandleScope scope; #ifdef __POSIX__ String::Utf8Value key(property); if (!getenv(*key)) return False(); unsetenv(*key); // can't check return value, it's void on some platforms return True(); #else String::Value key(property); WCHAR* key_ptr = reinterpret_cast(*key); if (key_ptr[0] == L'=' || !SetEnvironmentVariableW(key_ptr, NULL)) { // Deletion failed. Return true if the key wasn't there in the first place, // false if it is still there. bool rv = GetEnvironmentVariableW(key_ptr, NULL, NULL) == 0 && GetLastError() != ERROR_SUCCESS; return scope.Close(Boolean::New(rv)); } return True(); #endif } static Handle EnvEnumerator(const AccessorInfo& info) { HandleScope scope; #ifdef __POSIX__ int size = 0; while (environ[size]) size++; Local env = Array::New(size); for (int i = 0; i < size; ++i) { const char* var = environ[i]; const char* s = strchr(var, '='); const int length = s ? s - var : strlen(var); env->Set(i, String::New(var, length)); } #else // _WIN32 WCHAR* environment = GetEnvironmentStringsW(); if (environment == NULL) { // This should not happen. return scope.Close(Handle()); } Local env = Array::New(); WCHAR* p = environment; int i = 0; while (*p != NULL) { WCHAR *s; if (*p == L'=') { // If the key starts with '=' it is a hidden environment variable. p += wcslen(p) + 1; continue; } else { s = wcschr(p, L'='); } if (!s) { s = p + wcslen(p); } env->Set(i++, String::New(reinterpret_cast(p), s - p)); p = s + wcslen(s) + 1; } FreeEnvironmentStringsW(environment); #endif return scope.Close(env); } static Handle GetFeatures() { HandleScope scope; Local obj = Object::New(); obj->Set(String::NewSymbol("debug"), #if defined(DEBUG) && DEBUG True() #else False() #endif ); obj->Set(String::NewSymbol("uv"), True()); obj->Set(String::NewSymbol("ipv6"), True()); // TODO ping libuv obj->Set(String::NewSymbol("tls_npn"), Boolean::New(use_npn)); obj->Set(String::NewSymbol("tls_sni"), Boolean::New(use_sni)); obj->Set(String::NewSymbol("tls"), Boolean::New(get_builtin_module("crypto") != NULL)); return scope.Close(obj); } static Handle DebugPortGetter(Local property, const AccessorInfo& info) { HandleScope scope; return scope.Close(Integer::NewFromUnsigned(debug_port)); } static void DebugPortSetter(Local property, Local value, const AccessorInfo& info) { HandleScope scope; debug_port = value->NumberValue(); } static Handle DebugProcess(const Arguments& args); static Handle DebugPause(const Arguments& args); static Handle DebugEnd(const Arguments& args); Handle NeedImmediateCallbackGetter(Local property, const AccessorInfo& info) { return Boolean::New(need_immediate_cb); } static void NeedImmediateCallbackSetter(Local property, Local value, const AccessorInfo& info) { HandleScope scope; bool bool_value = value->BooleanValue(); if (need_immediate_cb == bool_value) return; need_immediate_cb = bool_value; if (need_immediate_cb) { uv_check_start(&check_immediate_watcher, node::CheckImmediate); // idle handle is needed only to maintain event loop uv_idle_start(&idle_immediate_dummy, node::IdleImmediateDummy); } else { uv_check_stop(&check_immediate_watcher); uv_idle_stop(&idle_immediate_dummy); } } Handle SetupProcessObject(int argc, char *argv[]) { HandleScope scope; int i, j; Local process_template = FunctionTemplate::New(); process_template->SetClassName(String::NewSymbol("process")); process = Persistent::New(process_template->GetFunction()->NewInstance()); process->SetAccessor(String::New("title"), ProcessTitleGetter, ProcessTitleSetter); // process.version process->Set(String::NewSymbol("version"), String::New(NODE_VERSION)); // process.moduleLoadList module_load_list = Persistent::New(Array::New()); process->Set(String::NewSymbol("moduleLoadList"), module_load_list); // process.versions Local versions = Object::New(); process->Set(String::NewSymbol("versions"), versions); versions->Set(String::NewSymbol("http_parser"), String::New( NODE_STRINGIFY(HTTP_PARSER_VERSION_MAJOR) "." NODE_STRINGIFY(HTTP_PARSER_VERSION_MINOR))); // +1 to get rid of the leading 'v' versions->Set(String::NewSymbol("node"), String::New(NODE_VERSION+1)); versions->Set(String::NewSymbol("v8"), String::New(V8::GetVersion())); versions->Set(String::NewSymbol("ares"), String::New(ARES_VERSION_STR)); versions->Set(String::NewSymbol("uv"), String::New(uv_version_string())); versions->Set(String::NewSymbol("zlib"), String::New(ZLIB_VERSION)); versions->Set(String::NewSymbol("modules"), String::New(NODE_STRINGIFY(NODE_MODULE_VERSION))); #if HAVE_OPENSSL // Stupid code to slice out the version string. int c, l = strlen(OPENSSL_VERSION_TEXT); for (i = j = 0; i < l; i++) { c = OPENSSL_VERSION_TEXT[i]; if ('0' <= c && c <= '9') { for (j = i + 1; j < l; j++) { c = OPENSSL_VERSION_TEXT[j]; if (c == ' ') break; } break; } } versions->Set(String::NewSymbol("openssl"), String::New(OPENSSL_VERSION_TEXT + i, j - i)); #endif // process.arch process->Set(String::NewSymbol("arch"), String::New(ARCH)); // process.platform process->Set(String::NewSymbol("platform"), String::New(PLATFORM)); // process.argv Local arguments = Array::New(argc - option_end_index + 1); arguments->Set(Integer::New(0), String::New(argv[0])); for (j = 1, i = option_end_index; i < argc; j++, i++) { Local arg = String::New(argv[i]); arguments->Set(Integer::New(j), arg); } // assign it process->Set(String::NewSymbol("argv"), arguments); // process.execArgv Local execArgv = Array::New(option_end_index - 1); for (j = 1, i = 0; j < option_end_index; j++, i++) { execArgv->Set(Integer::New(i), String::New(argv[j])); } // assign it process->Set(String::NewSymbol("execArgv"), execArgv); // create process.env Local envTemplate = ObjectTemplate::New(); envTemplate->SetNamedPropertyHandler(EnvGetter, EnvSetter, EnvQuery, EnvDeleter, EnvEnumerator, Object::New()); Local env = envTemplate->NewInstance(); process->Set(String::NewSymbol("env"), env); process->Set(String::NewSymbol("pid"), Integer::New(getpid())); process->Set(String::NewSymbol("features"), GetFeatures()); process->SetAccessor(String::New("_needImmediateCallback"), NeedImmediateCallbackGetter, NeedImmediateCallbackSetter); // -e, --eval if (eval_string) { process->Set(String::NewSymbol("_eval"), String::New(eval_string)); } // -p, --print if (print_eval) { process->Set(String::NewSymbol("_print_eval"), True()); } // -i, --interactive if (force_repl) { process->Set(String::NewSymbol("_forceRepl"), True()); } // --no-deprecation if (no_deprecation) { process->Set(String::NewSymbol("noDeprecation"), True()); } // --throw-deprecation if (throw_deprecation) { process->Set(String::NewSymbol("throwDeprecation"), True()); } // --trace-deprecation if (trace_deprecation) { process->Set(String::NewSymbol("traceDeprecation"), True()); } size_t size = 2*PATH_MAX; char* execPath = new char[size]; if (uv_exepath(execPath, &size) != 0) { // as a last ditch effort, fallback on argv[0] ? process->Set(String::NewSymbol("execPath"), String::New(argv[0])); } else { process->Set(String::NewSymbol("execPath"), String::New(execPath, size)); } delete [] execPath; process->SetAccessor(String::New("debugPort"), DebugPortGetter, DebugPortSetter); // define various internal methods NODE_SET_METHOD(process, "_getActiveRequests", GetActiveRequests); NODE_SET_METHOD(process, "_getActiveHandles", GetActiveHandles); NODE_SET_METHOD(process, "_needTickCallback", NeedTickCallback); NODE_SET_METHOD(process, "reallyExit", Exit); NODE_SET_METHOD(process, "abort", Abort); NODE_SET_METHOD(process, "chdir", Chdir); NODE_SET_METHOD(process, "cwd", Cwd); NODE_SET_METHOD(process, "umask", Umask); #ifdef __POSIX__ NODE_SET_METHOD(process, "getuid", GetUid); NODE_SET_METHOD(process, "setuid", SetUid); NODE_SET_METHOD(process, "setgid", SetGid); NODE_SET_METHOD(process, "getgid", GetGid); NODE_SET_METHOD(process, "getgroups", GetGroups); NODE_SET_METHOD(process, "setgroups", SetGroups); NODE_SET_METHOD(process, "initgroups", InitGroups); #endif // __POSIX__ NODE_SET_METHOD(process, "_kill", Kill); NODE_SET_METHOD(process, "_debugProcess", DebugProcess); NODE_SET_METHOD(process, "_debugPause", DebugPause); NODE_SET_METHOD(process, "_debugEnd", DebugEnd); NODE_SET_METHOD(process, "hrtime", Hrtime); NODE_SET_METHOD(process, "dlopen", DLOpen); NODE_SET_METHOD(process, "uptime", Uptime); NODE_SET_METHOD(process, "memoryUsage", MemoryUsage); NODE_SET_METHOD(process, "binding", Binding); NODE_SET_METHOD(process, "_usingDomains", UsingDomains); // values use to cross communicate with processNextTick Local info_box = Object::New(); info_box->SetIndexedPropertiesToExternalArrayData(&tick_infobox, kExternalUnsignedIntArray, 3); process->Set(String::NewSymbol("_tickInfoBox"), info_box); // pre-set _events object for faster emit checks process->Set(String::NewSymbol("_events"), Object::New()); return process; } static void AtExit() { uv_tty_reset_mode(); } static void SignalExit(int signal) { uv_tty_reset_mode(); _exit(128 + signal); } void Load(Handle process_l) { process_symbol = NODE_PSYMBOL("process"); domain_symbol = NODE_PSYMBOL("domain"); // Compile, execute the src/node.js file. (Which was included as static C // string in node_natives.h. 'natve_node' is the string containing that // source code.) // The node.js file returns a function 'f' atexit(AtExit); TryCatch try_catch; Local f_value = ExecuteString(MainSource(), IMMUTABLE_STRING("node.js")); if (try_catch.HasCaught()) { ReportException(try_catch, true); exit(10); } assert(f_value->IsFunction()); Local f = Local::Cast(f_value); // Now we call 'f' with the 'process' variable that we've built up with // all our bindings. Inside node.js we'll take care of assigning things to // their places. // We start the process this way in order to be more modular. Developers // who do not like how 'src/node.js' setups the module system but do like // Node's I/O bindings may want to replace 'f' with their own function. // Add a reference to the global object Local global = v8::Context::GetCurrent()->Global(); Local args[1] = { Local::New(process_l) }; #if defined HAVE_DTRACE || defined HAVE_ETW || defined HAVE_SYSTEMTAP InitDTrace(global); #endif #if defined HAVE_PERFCTR InitPerfCounters(global); #endif f->Call(global, 1, args); if (try_catch.HasCaught()) { FatalException(try_catch); } } static void PrintHelp(); static void ParseDebugOpt(const char* arg) { const char *p = 0; use_debug_agent = true; if (!strcmp (arg, "--debug-brk")) { debug_wait_connect = true; return; } else if (!strcmp(arg, "--debug")) { return; } else if (strstr(arg, "--debug-brk=") == arg) { debug_wait_connect = true; p = 1 + strchr(arg, '='); debug_port = atoi(p); } else if (strstr(arg, "--debug=") == arg) { p = 1 + strchr(arg, '='); debug_port = atoi(p); } if (p && debug_port > 1024 && debug_port < 65536) return; fprintf(stderr, "Bad debug option.\n"); if (p) fprintf(stderr, "Debug port must be in range 1025 to 65535.\n"); PrintHelp(); exit(12); } static void PrintHelp() { printf("Usage: node [options] [ -e script | script.js ] [arguments] \n" " node debug script.js [arguments] \n" "\n" "Options:\n" " -v, --version print node's version\n" " -e, --eval script evaluate script\n" " -p, --print evaluate script and print result\n" " -i, --interactive always enter the REPL even if stdin\n" " does not appear to be a terminal\n" " --no-deprecation silence deprecation warnings\n" " --trace-deprecation show stack traces on deprecations\n" " --v8-options print v8 command line options\n" " --max-stack-size=val set max v8 stack size (bytes)\n" "\n" "Environment variables:\n" #ifdef _WIN32 "NODE_PATH ';'-separated list of directories\n" #else "NODE_PATH ':'-separated list of directories\n" #endif " prefixed to the module search path.\n" "NODE_MODULE_CONTEXTS Set to 1 to load modules in their own\n" " global contexts.\n" "NODE_DISABLE_COLORS Set to 1 to disable colors in the REPL\n" "\n" "Documentation can be found at http://nodejs.org/\n"); } // Parse node command line arguments. static void ParseArgs(int argc, char **argv) { int i; // TODO use parse opts for (i = 1; i < argc; i++) { const char *arg = argv[i]; if (strstr(arg, "--debug") == arg) { ParseDebugOpt(arg); argv[i] = const_cast(""); } else if (strcmp(arg, "--version") == 0 || strcmp(arg, "-v") == 0) { printf("%s\n", NODE_VERSION); exit(0); } else if (strstr(arg, "--max-stack-size=") == arg) { const char *p = 0; p = 1 + strchr(arg, '='); max_stack_size = atoi(p); argv[i] = const_cast(""); } else if (strcmp(arg, "--help") == 0 || strcmp(arg, "-h") == 0) { PrintHelp(); exit(0); } else if (strcmp(arg, "--eval") == 0 || strcmp(arg, "-e") == 0 || strcmp(arg, "--print") == 0 || strcmp(arg, "-pe") == 0 || strcmp(arg, "-p") == 0) { bool is_eval = strchr(arg, 'e') != NULL; bool is_print = strchr(arg, 'p') != NULL; // argument to -p and --print is optional if (is_eval == true && i + 1 >= argc) { fprintf(stderr, "Error: %s requires an argument\n", arg); exit(13); } print_eval = print_eval || is_print; argv[i] = const_cast(""); // --eval, -e and -pe always require an argument if (is_eval == true) { eval_string = argv[++i]; continue; } // next arg is the expression to evaluate unless it starts with: // - a dash, then it's another switch // - "\\-", then it's an escaped expression, drop the backslash if (argv[i + 1] == NULL) continue; if (argv[i + 1][0] == '-') continue; eval_string = argv[++i]; if (strncmp(eval_string, "\\-", 2) == 0) ++eval_string; } else if (strcmp(arg, "--interactive") == 0 || strcmp(arg, "-i") == 0) { force_repl = true; argv[i] = const_cast(""); } else if (strcmp(arg, "--v8-options") == 0) { argv[i] = const_cast("--help"); } else if (strcmp(arg, "--no-deprecation") == 0) { argv[i] = const_cast(""); no_deprecation = true; } else if (strcmp(arg, "--trace-deprecation") == 0) { argv[i] = const_cast(""); trace_deprecation = true; } else if (strcmp(arg, "--throw-deprecation") == 0) { argv[i] = const_cast(""); throw_deprecation = true; } else if (argv[i][0] != '-') { break; } } option_end_index = i; } // Called from the main thread. static void DispatchDebugMessagesAsyncCallback(uv_async_t* handle, int status) { v8::Debug::ProcessDebugMessages(); } // Called from V8 Debug Agent TCP thread. static void DispatchMessagesDebugAgentCallback() { uv_async_send(&dispatch_debug_messages_async); } static void EnableDebug(bool wait_connect) { // If we're called from another thread, make sure to enter the right // v8 isolate. node_isolate->Enter(); v8::Debug::SetDebugMessageDispatchHandler(DispatchMessagesDebugAgentCallback, false); uv_async_init(uv_default_loop(), &dispatch_debug_messages_async, DispatchDebugMessagesAsyncCallback); uv_unref((uv_handle_t*) &dispatch_debug_messages_async); // Start the debug thread and it's associated TCP server on port 5858. bool r = v8::Debug::EnableAgent("node " NODE_VERSION, debug_port, wait_connect); // Crappy check that everything went well. FIXME assert(r); // Print out some information. fprintf(stderr, "debugger listening on port %d\n", debug_port); fflush(stderr); debugger_running = true; node_isolate->Exit(); } #ifdef __POSIX__ static void EnableDebugSignalHandler(uv_signal_t* handle, int) { // Break once process will return execution to v8 v8::Debug::DebugBreak(node_isolate); if (!debugger_running) { fprintf(stderr, "Hit SIGUSR1 - starting debugger agent.\n"); EnableDebug(false); } } static void RegisterSignalHandler(int signal, void (*handler)(int)) { struct sigaction sa; memset(&sa, 0, sizeof(sa)); sa.sa_handler = handler; sigfillset(&sa.sa_mask); sigaction(signal, &sa, NULL); } Handle DebugProcess(const Arguments& args) { HandleScope scope; if (args.Length() != 1) { return ThrowException(Exception::Error( String::New("Invalid number of arguments."))); } pid_t pid; int r; pid = args[0]->IntegerValue(); r = kill(pid, SIGUSR1); if (r != 0) { return ThrowException(ErrnoException(errno, "kill")); } return Undefined(); } #endif // __POSIX__ #ifdef _WIN32 DWORD WINAPI EnableDebugThreadProc(void* arg) { // Break once process will return execution to v8 if (!debugger_running) { for (int i = 0; i < 1; i++) { fprintf(stderr, "Starting debugger agent.\r\n"); fflush(stderr); EnableDebug(false); } } v8::Debug::DebugBreak(); return 0; } static int GetDebugSignalHandlerMappingName(DWORD pid, wchar_t* buf, size_t buf_len) { return _snwprintf(buf, buf_len, L"node-debug-handler-%u", pid); } static int RegisterDebugSignalHandler() { wchar_t mapping_name[32]; HANDLE mapping_handle; DWORD pid; LPTHREAD_START_ROUTINE* handler; pid = GetCurrentProcessId(); if (GetDebugSignalHandlerMappingName(pid, mapping_name, ARRAY_SIZE(mapping_name)) < 0) { return -1; } mapping_handle = CreateFileMappingW(INVALID_HANDLE_VALUE, NULL, PAGE_READWRITE, 0, sizeof *handler, mapping_name); if (mapping_handle == NULL) { return -1; } handler = reinterpret_cast( MapViewOfFile(mapping_handle, FILE_MAP_ALL_ACCESS, 0, 0, sizeof *handler)); if (handler == NULL) { CloseHandle(mapping_handle); return -1; } *handler = EnableDebugThreadProc; UnmapViewOfFile((void*) handler); return 0; } static Handle DebugProcess(const Arguments& args) { HandleScope scope; Handle rv = Undefined(); DWORD pid; HANDLE process = NULL; HANDLE thread = NULL; HANDLE mapping = NULL; wchar_t mapping_name[32]; LPTHREAD_START_ROUTINE* handler = NULL; if (args.Length() != 1) { rv = ThrowException(Exception::Error(String::New("Invalid number of arguments."))); goto out; } pid = (DWORD) args[0]->IntegerValue(); process = OpenProcess(PROCESS_CREATE_THREAD | PROCESS_QUERY_INFORMATION | PROCESS_VM_OPERATION | PROCESS_VM_WRITE | PROCESS_VM_READ, FALSE, pid); if (process == NULL) { rv = ThrowException(WinapiErrnoException(GetLastError(), "OpenProcess")); goto out; } if (GetDebugSignalHandlerMappingName(pid, mapping_name, ARRAY_SIZE(mapping_name)) < 0) { rv = ThrowException(ErrnoException(errno, "sprintf")); goto out; } mapping = OpenFileMappingW(FILE_MAP_READ, FALSE, mapping_name); if (mapping == NULL) { rv = ThrowException(WinapiErrnoException(GetLastError(), "OpenFileMappingW")); goto out; } handler = reinterpret_cast( MapViewOfFile(mapping, FILE_MAP_READ, 0, 0, sizeof *handler)); if (handler == NULL || *handler == NULL) { rv = ThrowException(WinapiErrnoException(GetLastError(), "MapViewOfFile")); goto out; } thread = CreateRemoteThread(process, NULL, 0, *handler, NULL, 0, NULL); if (thread == NULL) { rv = ThrowException(WinapiErrnoException(GetLastError(), "CreateRemoteThread")); goto out; } // Wait for the thread to terminate if (WaitForSingleObject(thread, INFINITE) != WAIT_OBJECT_0) { rv = ThrowException(WinapiErrnoException(GetLastError(), "WaitForSingleObject")); goto out; } out: if (process != NULL) { CloseHandle(process); } if (thread != NULL) { CloseHandle(thread); } if (handler != NULL) { UnmapViewOfFile(handler); } if (mapping != NULL) { CloseHandle(mapping); } return Undefined(); } #endif // _WIN32 static Handle DebugPause(const Arguments& args) { v8::Debug::DebugBreak(node_isolate); return Undefined(); } static Handle DebugEnd(const Arguments& args) { if (debugger_running) { v8::Debug::DisableAgent(); debugger_running = false; } return Undefined(); } char** Init(int argc, char *argv[]) { // Initialize prog_start_time to get relative uptime. uv_uptime(&prog_start_time); // Make inherited handles noninheritable. uv_disable_stdio_inheritance(); // Parse a few arguments which are specific to Node. node::ParseArgs(argc, argv); // Parse the rest of the args (up to the 'option_end_index' (where '--' was // in the command line)) int v8argc = option_end_index; char **v8argv = argv; if (debug_wait_connect) { // v8argv is a copy of argv up to the script file argument +2 if --debug-brk // to expose the v8 debugger js object so that node.js can set // a breakpoint on the first line of the startup script v8argc += 2; v8argv = new char*[v8argc]; memcpy(v8argv, argv, sizeof(*argv) * option_end_index); v8argv[option_end_index] = const_cast("--expose_debug_as"); v8argv[option_end_index + 1] = const_cast("v8debug"); } // For the normal stack which moves from high to low addresses when frames // are pushed, we can compute the limit as stack_size bytes below the // the address of a stack variable (e.g. &stack_var) as an approximation // of the start of the stack (we're assuming that we haven't pushed a lot // of frames yet). if (max_stack_size != 0) { uint32_t stack_var; ResourceConstraints constraints; uint32_t *stack_limit = &stack_var - (max_stack_size / sizeof(uint32_t)); constraints.set_stack_limit(stack_limit); SetResourceConstraints(&constraints); // Must be done before V8::Initialize } V8::SetFlagsFromCommandLine(&v8argc, v8argv, false); #ifdef __POSIX__ // Ignore SIGPIPE RegisterSignalHandler(SIGPIPE, SIG_IGN); RegisterSignalHandler(SIGINT, SignalExit); RegisterSignalHandler(SIGTERM, SignalExit); #endif // __POSIX__ uv_idle_init(uv_default_loop(), &tick_spinner); uv_check_init(uv_default_loop(), &check_immediate_watcher); uv_unref((uv_handle_t*) &check_immediate_watcher); uv_idle_init(uv_default_loop(), &idle_immediate_dummy); V8::SetFatalErrorHandler(node::OnFatalError); // Fetch a reference to the main isolate, so we have a reference to it // even when we need it to access it from another (debugger) thread. node_isolate = Isolate::GetCurrent(); // If the --debug flag was specified then initialize the debug thread. if (use_debug_agent) { EnableDebug(debug_wait_connect); } else { #ifdef _WIN32 RegisterDebugSignalHandler(); #else // Posix static uv_signal_t signal_watcher; uv_signal_init(uv_default_loop(), &signal_watcher); uv_signal_start(&signal_watcher, EnableDebugSignalHandler, SIGUSR1); uv_unref((uv_handle_t*)&signal_watcher); #endif // __POSIX__ } return argv; } struct AtExitCallback { AtExitCallback* next_; void (*cb_)(void* arg); void* arg_; }; static AtExitCallback* at_exit_functions_; void RunAtExit() { AtExitCallback* p = at_exit_functions_; at_exit_functions_ = NULL; while (p) { AtExitCallback* q = p->next_; p->cb_(p->arg_); delete p; p = q; } } void AtExit(void (*cb)(void* arg), void* arg) { AtExitCallback* p = new AtExitCallback; p->cb_ = cb; p->arg_ = arg; p->next_ = at_exit_functions_; at_exit_functions_ = p; } void EmitExit(v8::Handle process_l) { // process.emit('exit') process_l->Set(String::NewSymbol("_exiting"), True()); Local emit_v = process_l->Get(String::New("emit")); assert(emit_v->IsFunction()); Local emit = Local::Cast(emit_v); Local args[] = { String::New("exit"), Integer::New(0) }; TryCatch try_catch; emit->Call(process_l, 2, args); if (try_catch.HasCaught()) { FatalException(try_catch); } } static char **copy_argv(int argc, char **argv) { size_t strlen_sum; char **argv_copy; char *argv_data; size_t len; int i; strlen_sum = 0; for(i = 0; i < argc; i++) { strlen_sum += strlen(argv[i]) + 1; } argv_copy = (char **) malloc(sizeof(char *) * (argc + 1) + strlen_sum); if (!argv_copy) { return NULL; } argv_data = (char *) argv_copy + sizeof(char *) * (argc + 1); for(i = 0; i < argc; i++) { argv_copy[i] = argv_data; len = strlen(argv[i]) + 1; memcpy(argv_data, argv[i], len); argv_data += len; } argv_copy[argc] = NULL; return argv_copy; } int Start(int argc, char *argv[]) { // Hack aroung with the argv pointer. Used for process.title = "blah". argv = uv_setup_args(argc, argv); // Logic to duplicate argv as Init() modifies arguments // that are passed into it. char **argv_copy = copy_argv(argc, argv); // This needs to run *before* V8::Initialize() // Use copy here as to not modify the original argv: Init(argc, argv_copy); V8::Initialize(); { Locker locker; HandleScope handle_scope; // Create the one and only Context. Persistent context = Context::New(); Context::Scope context_scope(context); // Use original argv, as we're just copying values out of it. Handle process_l = SetupProcessObject(argc, argv); v8_typed_array::AttachBindings(context->Global()); // Create all the objects, load modules, do everything. // so your next reading stop should be node::Load()! Load(process_l); // All our arguments are loaded. We've evaluated all of the scripts. We // might even have created TCP servers. Now we enter the main eventloop. If // there are no watchers on the loop (except for the ones that were // uv_unref'd) then this function exits. As long as there are active // watchers, it blocks. uv_run(uv_default_loop(), UV_RUN_DEFAULT); EmitExit(process_l); RunAtExit(); #ifndef NDEBUG context.Dispose(); #endif } #ifndef NDEBUG // Clean up. Not strictly necessary. V8::Dispose(); #endif // NDEBUG // Clean up the copy: free(argv_copy); return 0; } } // namespace node node-v0.10.25~dfsg2/src/node_os.h0000644000000000000000000000250512270121457015205 0ustar rootroot// Copyright Joyent, Inc. and other Node contributors. // // Permission is hereby granted, free of charge, to any person obtaining a // copy of this software and associated documentation files (the // "Software"), to deal in the Software without restriction, including // without limitation the rights to use, copy, modify, merge, publish, // distribute, sublicense, and/or sell copies of the Software, and to permit // persons to whom the Software is furnished to do so, subject to the // following conditions: // // The above copyright notice and this permission notice shall be included // in all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS // OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF // MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN // NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, // DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR // OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE // USE OR OTHER DEALINGS IN THE SOFTWARE. #ifndef node_os_h #define node_os_h #include "node.h" #include "v8.h" namespace node { class OS { public: static void Initialize (v8::Handle target); }; } // namespace node #endif // node_os_h node-v0.10.25~dfsg2/src/node_dtrace.h0000644000000000000000000000532012270121457016024 0ustar rootroot// Copyright Joyent, Inc. and other Node contributors. // // Permission is hereby granted, free of charge, to any person obtaining a // copy of this software and associated documentation files (the // "Software"), to deal in the Software without restriction, including // without limitation the rights to use, copy, modify, merge, publish, // distribute, sublicense, and/or sell copies of the Software, and to permit // persons to whom the Software is furnished to do so, subject to the // following conditions: // // The above copyright notice and this permission notice shall be included // in all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS // OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF // MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN // NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, // DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR // OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE // USE OR OTHER DEALINGS IN THE SOFTWARE. #ifndef NODE_DTRACE_H_ #define NODE_DTRACE_H_ #include "node.h" #include "v8.h" extern "C" { /* * The following structures are passed directly to DTrace when probes are fired. * Translators in node.d translate these structures into the corresponding D * structures, taking care of dealing with the user process data model (32-bit * or 64-bit) and structure versions (see node_dtrace_http_server_request_t * below). */ typedef struct { int32_t fd; int32_t port; char *remote; int32_t buffered; } node_dtrace_connection_t; typedef struct { char *url; char *method; } node_dtrace_http_client_request_t; /* * The original version of this structure contained only a url and method, just * like the client request above. To add the new forwardedFor field, the * structure layout was changed to begin with an integer version. The * translator knows whether it's looking at an old- or new-version structure * based on whether the version field's value is a reasonable pointer (i.e. * address greater than 4K). No doubt this is filthy, but there's not much else * we can do, and it works reliably. * * This version of the structure also contains padding that should be zeroed out * by the consumer so that future versions of the translator can simply check if * a field is present by checking it against NULL. */ typedef struct { union { uint32_t version; uintptr_t unused; /* for compat. with old 64-bit struct */ } _un; char *url; char *method; char *forwardedFor; char *_pad[8]; } node_dtrace_http_server_request_t; } namespace node { void InitDTrace(v8::Handle target); } #endif node-v0.10.25~dfsg2/src/pipe_wrap.h0000644000000000000000000000411712270121457015546 0ustar rootroot// Copyright Joyent, Inc. and other Node contributors. // // Permission is hereby granted, free of charge, to any person obtaining a // copy of this software and associated documentation files (the // "Software"), to deal in the Software without restriction, including // without limitation the rights to use, copy, modify, merge, publish, // distribute, sublicense, and/or sell copies of the Software, and to permit // persons to whom the Software is furnished to do so, subject to the // following conditions: // // The above copyright notice and this permission notice shall be included // in all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS // OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF // MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN // NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, // DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR // OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE // USE OR OTHER DEALINGS IN THE SOFTWARE. #ifndef PIPE_WRAP_H_ #define PIPE_WRAP_H_ #include "stream_wrap.h" namespace node { class PipeWrap : StreamWrap { public: uv_pipe_t* UVHandle(); static v8::Local Instantiate(); static PipeWrap* Unwrap(v8::Local obj); static void Initialize(v8::Handle target); private: PipeWrap(v8::Handle object, bool ipc); static v8::Handle New(const v8::Arguments& args); static v8::Handle Bind(const v8::Arguments& args); static v8::Handle Listen(const v8::Arguments& args); static v8::Handle Connect(const v8::Arguments& args); static v8::Handle Open(const v8::Arguments& args); #ifdef _WIN32 static v8::Handle SetPendingInstances(const v8::Arguments& args); #endif static void OnConnection(uv_stream_t* handle, int status); static void AfterConnect(uv_connect_t* req, int status); uv_pipe_t handle_; }; } // namespace node #endif // PIPE_WRAP_H_ node-v0.10.25~dfsg2/src/node_stat_watcher.cc0000644000000000000000000001023012270121457017404 0ustar rootroot// Copyright Joyent, Inc. and other Node contributors. // // Permission is hereby granted, free of charge, to any person obtaining a // copy of this software and associated documentation files (the // "Software"), to deal in the Software without restriction, including // without limitation the rights to use, copy, modify, merge, publish, // distribute, sublicense, and/or sell copies of the Software, and to permit // persons to whom the Software is furnished to do so, subject to the // following conditions: // // The above copyright notice and this permission notice shall be included // in all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS // OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF // MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN // NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, // DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR // OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE // USE OR OTHER DEALINGS IN THE SOFTWARE. #include "node_stat_watcher.h" #include #include #include namespace node { using namespace v8; Persistent StatWatcher::constructor_template; static Persistent onchange_sym; static Persistent onstop_sym; void StatWatcher::Initialize(Handle target) { HandleScope scope; Local t = FunctionTemplate::New(StatWatcher::New); constructor_template = Persistent::New(t); constructor_template->InstanceTemplate()->SetInternalFieldCount(1); constructor_template->SetClassName(String::NewSymbol("StatWatcher")); NODE_SET_PROTOTYPE_METHOD(constructor_template, "start", StatWatcher::Start); NODE_SET_PROTOTYPE_METHOD(constructor_template, "stop", StatWatcher::Stop); target->Set(String::NewSymbol("StatWatcher"), constructor_template->GetFunction()); } static void Delete(uv_handle_t* handle) { delete reinterpret_cast(handle); } StatWatcher::StatWatcher() : ObjectWrap() , watcher_(new uv_fs_poll_t) { uv_fs_poll_init(uv_default_loop(), watcher_); watcher_->data = static_cast(this); } StatWatcher::~StatWatcher() { Stop(); uv_close(reinterpret_cast(watcher_), Delete); } void StatWatcher::Callback(uv_fs_poll_t* handle, int status, const uv_statbuf_t* prev, const uv_statbuf_t* curr) { StatWatcher* wrap = static_cast(handle->data); assert(wrap->watcher_ == handle); HandleScope scope; Local argv[3]; argv[0] = BuildStatsObject(curr); argv[1] = BuildStatsObject(prev); argv[2] = Integer::New(status); if (status == -1) { SetErrno(uv_last_error(wrap->watcher_->loop)); } if (onchange_sym.IsEmpty()) { onchange_sym = NODE_PSYMBOL("onchange"); } MakeCallback(wrap->handle_, onchange_sym, ARRAY_SIZE(argv), argv); } Handle StatWatcher::New(const Arguments& args) { assert(args.IsConstructCall()); HandleScope scope; StatWatcher* s = new StatWatcher(); s->Wrap(args.Holder()); return args.This(); } Handle StatWatcher::Start(const Arguments& args) { assert(args.Length() == 3); HandleScope scope; StatWatcher* wrap = ObjectWrap::Unwrap(args.Holder()); String::Utf8Value path(args[0]); const bool persistent = args[1]->BooleanValue(); const uint32_t interval = args[2]->Uint32Value(); if (!persistent) uv_unref(reinterpret_cast(wrap->watcher_)); uv_fs_poll_start(wrap->watcher_, Callback, *path, interval); wrap->Ref(); return Undefined(); } Handle StatWatcher::Stop(const Arguments& args) { HandleScope scope; StatWatcher* wrap = ObjectWrap::Unwrap(args.Holder()); if (onstop_sym.IsEmpty()) { onstop_sym = NODE_PSYMBOL("onstop"); } MakeCallback(wrap->handle_, onstop_sym, 0, NULL); wrap->Stop(); return Undefined(); } void StatWatcher::Stop () { if (!uv_is_active(reinterpret_cast(watcher_))) return; uv_fs_poll_stop(watcher_); Unref(); } } // namespace node node-v0.10.25~dfsg2/src/slab_allocator.h0000644000000000000000000000350112270121457016535 0ustar rootroot// Copyright Joyent, Inc. and other Node contributors. // // Permission is hereby granted, free of charge, to any person obtaining a // copy of this software and associated documentation files (the // "Software"), to deal in the Software without restriction, including // without limitation the rights to use, copy, modify, merge, publish, // distribute, sublicense, and/or sell copies of the Software, and to permit // persons to whom the Software is furnished to do so, subject to the // following conditions: // // The above copyright notice and this permission notice shall be included // in all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS // OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF // MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN // NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, // DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR // OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE // USE OR OTHER DEALINGS IN THE SOFTWARE. #include "v8.h" namespace node { class SlabAllocator { public: SlabAllocator(unsigned int size = 10485760); // default to 10M ~SlabAllocator(); // allocate memory from slab, attaches the slice to `obj` char* Allocate(v8::Handle obj, unsigned int size); // return excess memory to the slab, returns a handle to the parent buffer v8::Local Shrink(v8::Handle obj, char* ptr, unsigned int size); private: void Initialize(); bool initialized_; v8::Persistent slab_; v8::Persistent slab_sym_; unsigned int offset_; unsigned int size_; char* last_ptr_; }; } // namespace node node-v0.10.25~dfsg2/src/cares_wrap.cc0000644000000000000000000006255112270121457016052 0ustar rootroot// Copyright Joyent, Inc. and other Node contributors. // // Permission is hereby granted, free of charge, to any person obtaining a // copy of this software and associated documentation files (the // "Software"), to deal in the Software without restriction, including // without limitation the rights to use, copy, modify, merge, publish, // distribute, sublicense, and/or sell copies of the Software, and to permit // persons to whom the Software is furnished to do so, subject to the // following conditions: // // The above copyright notice and this permission notice shall be included // in all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS // OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF // MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN // NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, // DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR // OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE // USE OR OTHER DEALINGS IN THE SOFTWARE. #include #include #include #include #define CARES_STATICLIB #include "ares.h" #include "node.h" #include "req_wrap.h" #include "tree.h" #include "uv.h" #if defined(__OpenBSD__) || defined(__MINGW32__) || defined(_MSC_VER) # include #else # include #endif namespace node { namespace cares_wrap { using v8::Arguments; using v8::Array; using v8::Context; using v8::Function; using v8::Handle; using v8::HandleScope; using v8::Integer; using v8::Local; using v8::Null; using v8::Object; using v8::Persistent; using v8::String; using v8::Value; typedef class ReqWrap GetAddrInfoReqWrap; struct ares_task_t { UV_HANDLE_FIELDS ares_socket_t sock; uv_poll_t poll_watcher; RB_ENTRY(ares_task_t) node; }; static Persistent oncomplete_sym; static ares_channel ares_channel; static uv_timer_t ares_timer; static RB_HEAD(ares_task_list, ares_task_t) ares_tasks; static int cmp_ares_tasks(const ares_task_t* a, const ares_task_t* b) { if (a->sock < b->sock) return -1; if (a->sock > b->sock) return 1; return 0; } RB_GENERATE_STATIC(ares_task_list, ares_task_t, node, cmp_ares_tasks) /* This is called once per second by loop->timer. It is used to constantly */ /* call back into c-ares for possibly processing timeouts. */ static void ares_timeout(uv_timer_t* handle, int status) { assert(!RB_EMPTY(&ares_tasks)); ares_process_fd(ares_channel, ARES_SOCKET_BAD, ARES_SOCKET_BAD); } static void ares_poll_cb(uv_poll_t* watcher, int status, int events) { ares_task_t* task = container_of(watcher, ares_task_t, poll_watcher); /* Reset the idle timer */ uv_timer_again(&ares_timer); if (status < 0) { /* An error happened. Just pretend that the socket is both readable and */ /* writable. */ ares_process_fd(ares_channel, task->sock, task->sock); return; } /* Process DNS responses */ ares_process_fd(ares_channel, events & UV_READABLE ? task->sock : ARES_SOCKET_BAD, events & UV_WRITABLE ? task->sock : ARES_SOCKET_BAD); } static void ares_poll_close_cb(uv_handle_t* watcher) { ares_task_t* task = container_of(watcher, ares_task_t, poll_watcher); free(task); } /* Allocates and returns a new ares_task_t */ static ares_task_t* ares_task_create(uv_loop_t* loop, ares_socket_t sock) { ares_task_t* task = (ares_task_t*) malloc(sizeof *task); if (task == NULL) { /* Out of memory. */ return NULL; } task->loop = loop; task->sock = sock; if (uv_poll_init_socket(loop, &task->poll_watcher, sock) < 0) { /* This should never happen. */ free(task); return NULL; } return task; } /* Callback from ares when socket operation is started */ static void ares_sockstate_cb(void* data, ares_socket_t sock, int read, int write) { uv_loop_t* loop = (uv_loop_t*) data; ares_task_t* task; ares_task_t lookup_task; lookup_task.sock = sock; task = RB_FIND(ares_task_list, &ares_tasks, &lookup_task); if (read || write) { if (!task) { /* New socket */ /* If this is the first socket then start the timer. */ if (!uv_is_active((uv_handle_t*) &ares_timer)) { assert(RB_EMPTY(&ares_tasks)); uv_timer_start(&ares_timer, ares_timeout, 1000, 1000); } task = ares_task_create(loop, sock); if (task == NULL) { /* This should never happen unless we're out of memory or something */ /* is seriously wrong. The socket won't be polled, but the the query */ /* will eventually time out. */ return; } RB_INSERT(ares_task_list, &ares_tasks, task); } /* This should never fail. If it fails anyway, the query will eventually */ /* time out. */ uv_poll_start(&task->poll_watcher, (read ? UV_READABLE : 0) | (write ? UV_WRITABLE : 0), ares_poll_cb); } else { /* read == 0 and write == 0 this is c-ares's way of notifying us that */ /* the socket is now closed. We must free the data associated with */ /* socket. */ assert(task && "When an ares socket is closed we should have a handle for it"); RB_REMOVE(ares_task_list, &ares_tasks, task); uv_close((uv_handle_t*) &task->poll_watcher, ares_poll_close_cb); if (RB_EMPTY(&ares_tasks)) { uv_timer_stop(&ares_timer); } } } static Local HostentToAddresses(struct hostent* host) { HandleScope scope; Local addresses = Array::New(); char ip[INET6_ADDRSTRLEN]; for (int i = 0; host->h_addr_list[i]; ++i) { uv_inet_ntop(host->h_addrtype, host->h_addr_list[i], ip, sizeof(ip)); Local address = String::New(ip); addresses->Set(Integer::New(i), address); } return scope.Close(addresses); } static Local HostentToNames(struct hostent* host) { HandleScope scope; Local names = Array::New(); for (int i = 0; host->h_aliases[i]; ++i) { Local address = String::New(host->h_aliases[i]); names->Set(Integer::New(i), address); } return scope.Close(names); } static const char* AresErrnoString(int errorno) { switch (errorno) { #define ERRNO_CASE(e) case ARES_##e: return #e; ERRNO_CASE(SUCCESS) ERRNO_CASE(ENODATA) ERRNO_CASE(EFORMERR) ERRNO_CASE(ESERVFAIL) ERRNO_CASE(ENOTFOUND) ERRNO_CASE(ENOTIMP) ERRNO_CASE(EREFUSED) ERRNO_CASE(EBADQUERY) ERRNO_CASE(EBADNAME) ERRNO_CASE(EBADFAMILY) ERRNO_CASE(EBADRESP) ERRNO_CASE(ECONNREFUSED) ERRNO_CASE(ETIMEOUT) ERRNO_CASE(EOF) ERRNO_CASE(EFILE) ERRNO_CASE(ENOMEM) ERRNO_CASE(EDESTRUCTION) ERRNO_CASE(EBADSTR) ERRNO_CASE(EBADFLAGS) ERRNO_CASE(ENONAME) ERRNO_CASE(EBADHINTS) ERRNO_CASE(ENOTINITIALIZED) ERRNO_CASE(ELOADIPHLPAPI) ERRNO_CASE(EADDRGETNETWORKPARAMS) ERRNO_CASE(ECANCELLED) #undef ERRNO_CASE default: assert(0 && "Unhandled c-ares error"); return "(UNKNOWN)"; } } static void SetAresErrno(int errorno) { HandleScope scope; Local key = String::NewSymbol("_errno"); Local value = String::NewSymbol(AresErrnoString(errorno)); node::process->Set(key, value); } class QueryWrap { public: QueryWrap() { HandleScope scope; object_ = Persistent::New(Object::New()); } virtual ~QueryWrap() { assert(!object_.IsEmpty()); object_->Delete(oncomplete_sym); object_.Dispose(); object_.Clear(); } Handle GetObject() { return object_; } void SetOnComplete(Handle oncomplete) { assert(oncomplete->IsFunction()); object_->Set(oncomplete_sym, oncomplete); } // Subclasses should implement the appropriate Send method. virtual int Send(const char* name) { assert(0); return 0; } virtual int Send(const char* name, int family) { assert(0); return 0; } protected: void* GetQueryArg() { return static_cast(this); } static void Callback(void *arg, int status, int timeouts, unsigned char* answer_buf, int answer_len) { QueryWrap* wrap = static_cast(arg); if (status != ARES_SUCCESS) { wrap->ParseError(status); } else { wrap->Parse(answer_buf, answer_len); } delete wrap; } static void Callback(void *arg, int status, int timeouts, struct hostent* host) { QueryWrap* wrap = static_cast(arg); if (status != ARES_SUCCESS) { wrap->ParseError(status); } else { wrap->Parse(host); } delete wrap; } void CallOnComplete(Local answer) { HandleScope scope; Local argv[2] = { Integer::New(0), answer }; MakeCallback(object_, oncomplete_sym, ARRAY_SIZE(argv), argv); } void CallOnComplete(Local answer, Local family) { HandleScope scope; Local argv[3] = { Integer::New(0), answer, family }; MakeCallback(object_, oncomplete_sym, ARRAY_SIZE(argv), argv); } void ParseError(int status) { assert(status != ARES_SUCCESS); SetAresErrno(status); HandleScope scope; Local argv[1] = { Integer::New(-1) }; MakeCallback(object_, oncomplete_sym, ARRAY_SIZE(argv), argv); } // Subclasses should implement the appropriate Parse method. virtual void Parse(unsigned char* buf, int len) { assert(0); }; virtual void Parse(struct hostent* host) { assert(0); }; private: Persistent object_; }; class QueryAWrap: public QueryWrap { public: int Send(const char* name) { ares_query(ares_channel, name, ns_c_in, ns_t_a, Callback, GetQueryArg()); return 0; } protected: void Parse(unsigned char* buf, int len) { HandleScope scope; struct hostent* host; int status = ares_parse_a_reply(buf, len, &host, NULL, NULL); if (status != ARES_SUCCESS) { this->ParseError(status); return; } Local addresses = HostentToAddresses(host); ares_free_hostent(host); this->CallOnComplete(addresses); } }; class QueryAaaaWrap: public QueryWrap { public: int Send(const char* name) { ares_query(ares_channel, name, ns_c_in, ns_t_aaaa, Callback, GetQueryArg()); return 0; } protected: void Parse(unsigned char* buf, int len) { HandleScope scope; struct hostent* host; int status = ares_parse_aaaa_reply(buf, len, &host, NULL, NULL); if (status != ARES_SUCCESS) { this->ParseError(status); return; } Local addresses = HostentToAddresses(host); ares_free_hostent(host); this->CallOnComplete(addresses); } }; class QueryCnameWrap: public QueryWrap { public: int Send(const char* name) { ares_query(ares_channel, name, ns_c_in, ns_t_cname, Callback, GetQueryArg()); return 0; } protected: void Parse(unsigned char* buf, int len) { HandleScope scope; struct hostent* host; int status = ares_parse_a_reply(buf, len, &host, NULL, NULL); if (status != ARES_SUCCESS) { this->ParseError(status); return; } // A cname lookup always returns a single record but we follow the // common API here. Local result = Array::New(1); result->Set(0, String::New(host->h_name)); ares_free_hostent(host); this->CallOnComplete(result); } }; class QueryMxWrap: public QueryWrap { public: int Send(const char* name) { ares_query(ares_channel, name, ns_c_in, ns_t_mx, Callback, GetQueryArg()); return 0; } protected: void Parse(unsigned char* buf, int len) { HandleScope scope; struct ares_mx_reply* mx_start; int status = ares_parse_mx_reply(buf, len, &mx_start); if (status != ARES_SUCCESS) { this->ParseError(status); return; } Local mx_records = Array::New(); Local exchange_symbol = String::NewSymbol("exchange"); Local priority_symbol = String::NewSymbol("priority"); int i = 0; for (struct ares_mx_reply* mx_current = mx_start; mx_current; mx_current = mx_current->next) { Local mx_record = Object::New(); mx_record->Set(exchange_symbol, String::New(mx_current->host)); mx_record->Set(priority_symbol, Integer::New(mx_current->priority)); mx_records->Set(Integer::New(i++), mx_record); } ares_free_data(mx_start); this->CallOnComplete(mx_records); } }; class QueryNsWrap: public QueryWrap { public: int Send(const char* name) { ares_query(ares_channel, name, ns_c_in, ns_t_ns, Callback, GetQueryArg()); return 0; } protected: void Parse(unsigned char* buf, int len) { struct hostent* host; int status = ares_parse_ns_reply(buf, len, &host); if (status != ARES_SUCCESS) { this->ParseError(status); return; } Local names = HostentToNames(host); ares_free_hostent(host); this->CallOnComplete(names); } }; class QueryTxtWrap: public QueryWrap { public: int Send(const char* name) { ares_query(ares_channel, name, ns_c_in, ns_t_txt, Callback, GetQueryArg()); return 0; } protected: void Parse(unsigned char* buf, int len) { struct ares_txt_reply* txt_out; int status = ares_parse_txt_reply(buf, len, &txt_out); if (status != ARES_SUCCESS) { this->ParseError(status); return; } Local txt_records = Array::New(); struct ares_txt_reply *current = txt_out; for (int i = 0; current; ++i, current = current->next) { Local txt = String::New(reinterpret_cast(current->txt)); txt_records->Set(Integer::New(i), txt); } ares_free_data(txt_out); this->CallOnComplete(txt_records); } }; class QuerySrvWrap: public QueryWrap { public: int Send(const char* name) { ares_query(ares_channel, name, ns_c_in, ns_t_srv, Callback, GetQueryArg()); return 0; } protected: void Parse(unsigned char* buf, int len) { HandleScope scope; struct ares_srv_reply* srv_start; int status = ares_parse_srv_reply(buf, len, &srv_start); if (status != ARES_SUCCESS) { this->ParseError(status); return; } Local srv_records = Array::New(); Local name_symbol = String::NewSymbol("name"); Local port_symbol = String::NewSymbol("port"); Local priority_symbol = String::NewSymbol("priority"); Local weight_symbol = String::NewSymbol("weight"); int i = 0; for (struct ares_srv_reply* srv_current = srv_start; srv_current; srv_current = srv_current->next) { Local srv_record = Object::New(); srv_record->Set(name_symbol, String::New(srv_current->host)); srv_record->Set(port_symbol, Integer::New(srv_current->port)); srv_record->Set(priority_symbol, Integer::New(srv_current->priority)); srv_record->Set(weight_symbol, Integer::New(srv_current->weight)); srv_records->Set(Integer::New(i++), srv_record); } ares_free_data(srv_start); this->CallOnComplete(srv_records); } }; class QueryNaptrWrap: public QueryWrap { public: int Send(const char* name) { ares_query(ares_channel, name, ns_c_in, ns_t_naptr, Callback, GetQueryArg()); return 0; } protected: void Parse(unsigned char* buf, int len) { HandleScope scope; ares_naptr_reply* naptr_start; int status = ares_parse_naptr_reply(buf, len, &naptr_start); if (status != ARES_SUCCESS) { this->ParseError(status); return; } Local naptr_records = Array::New(); Local flags_symbol = String::NewSymbol("flags"); Local service_symbol = String::NewSymbol("service"); Local regexp_symbol = String::NewSymbol("regexp"); Local replacement_symbol = String::NewSymbol("replacement"); Local order_symbol = String::NewSymbol("order"); Local preference_symbol = String::NewSymbol("preference"); int i = 0; for (ares_naptr_reply* naptr_current = naptr_start; naptr_current; naptr_current = naptr_current->next) { Local naptr_record = Object::New(); naptr_record->Set(flags_symbol, String::New(reinterpret_cast(naptr_current->flags))); naptr_record->Set(service_symbol, String::New(reinterpret_cast(naptr_current->service))); naptr_record->Set(regexp_symbol, String::New(reinterpret_cast(naptr_current->regexp))); naptr_record->Set(replacement_symbol, String::New(naptr_current->replacement)); naptr_record->Set(order_symbol, Integer::New(naptr_current->order)); naptr_record->Set(preference_symbol, Integer::New(naptr_current->preference)); naptr_records->Set(Integer::New(i++), naptr_record); } ares_free_data(naptr_start); this->CallOnComplete(naptr_records); } }; class GetHostByAddrWrap: public QueryWrap { public: int Send(const char* name) { int length, family; char address_buffer[sizeof(struct in6_addr)]; if (uv_inet_pton(AF_INET, name, &address_buffer).code == UV_OK) { length = sizeof(struct in_addr); family = AF_INET; } else if (uv_inet_pton(AF_INET6, name, &address_buffer).code == UV_OK) { length = sizeof(struct in6_addr); family = AF_INET6; } else { return ARES_ENOTIMP; } ares_gethostbyaddr(ares_channel, address_buffer, length, family, Callback, GetQueryArg()); return 0; } protected: void Parse(struct hostent* host) { HandleScope scope; this->CallOnComplete(HostentToNames(host)); } }; class GetHostByNameWrap: public QueryWrap { public: int Send(const char* name, int family) { ares_gethostbyname(ares_channel, name, family, Callback, GetQueryArg()); return 0; } protected: void Parse(struct hostent* host) { HandleScope scope; Local addresses = HostentToAddresses(host); Local family = Integer::New(host->h_addrtype); this->CallOnComplete(addresses, family); } }; template static Handle Query(const Arguments& args) { HandleScope scope; assert(!args.IsConstructCall()); assert(args.Length() >= 2); assert(args[1]->IsFunction()); Wrap* wrap = new Wrap(); wrap->SetOnComplete(args[1]); // We must cache the wrap's js object here, because cares might make the // callback from the wrap->Send stack. This will destroy the wrap's internal // object reference, causing wrap->GetObject() to return undefined. Local object = Local::New(wrap->GetObject()); String::Utf8Value name(args[0]); int r = wrap->Send(*name); if (r) { SetAresErrno(r); delete wrap; return scope.Close(v8::Null()); } else { return scope.Close(object); } } template static Handle QueryWithFamily(const Arguments& args) { HandleScope scope; assert(!args.IsConstructCall()); assert(args.Length() >= 3); assert(args[2]->IsFunction()); Wrap* wrap = new Wrap(); wrap->SetOnComplete(args[2]); // We must cache the wrap's js object here, because cares might make the // callback from the wrap->Send stack. This will destroy the wrap's internal // object reference, causing wrap->GetObject() to return undefined. Local object = Local::New(wrap->GetObject()); String::Utf8Value name(args[0]); int family = args[1]->Int32Value(); int r = wrap->Send(*name, family); if (r) { SetAresErrno(r); delete wrap; return scope.Close(v8::Null()); } else { return scope.Close(object); } } void AfterGetAddrInfo(uv_getaddrinfo_t* req, int status, struct addrinfo* res) { HandleScope scope; GetAddrInfoReqWrap* req_wrap = (GetAddrInfoReqWrap*) req->data; Local argv[1]; if (status) { // Error SetErrno(uv_last_error(uv_default_loop())); argv[0] = Local::New(Null()); } else { // Success struct addrinfo *address; int n = 0; // Count the number of responses. for (address = res; address; address = address->ai_next) { n++; } // Create the response array. Local results = Array::New(n); char ip[INET6_ADDRSTRLEN]; const char *addr; n = 0; // Iterate over the IPv4 responses again this time creating javascript // strings for each IP and filling the results array. address = res; while (address) { assert(address->ai_socktype == SOCK_STREAM); // Ignore random ai_family types. if (address->ai_family == AF_INET) { // Juggle pointers addr = (char*) &((struct sockaddr_in*) address->ai_addr)->sin_addr; uv_err_t err = uv_inet_ntop(address->ai_family, addr, ip, INET6_ADDRSTRLEN); if (err.code != UV_OK) continue; // Create JavaScript string Local s = String::New(ip); results->Set(n, s); n++; } // Increment address = address->ai_next; } // Iterate over the IPv6 responses putting them in the array. address = res; while (address) { assert(address->ai_socktype == SOCK_STREAM); // Ignore random ai_family types. if (address->ai_family == AF_INET6) { // Juggle pointers addr = (char*) &((struct sockaddr_in6*) address->ai_addr)->sin6_addr; uv_err_t err = uv_inet_ntop(address->ai_family, addr, ip, INET6_ADDRSTRLEN); if (err.code != UV_OK) continue; // Create JavaScript string Local s = String::New(ip); results->Set(n, s); n++; } // Increment address = address->ai_next; } argv[0] = results; } uv_freeaddrinfo(res); // Make the callback into JavaScript MakeCallback(req_wrap->object_, oncomplete_sym, ARRAY_SIZE(argv), argv); delete req_wrap; } static Handle IsIP(const Arguments& args) { HandleScope scope; String::AsciiValue ip(args[0]); char address_buffer[sizeof(struct in6_addr)]; if (uv_inet_pton(AF_INET, *ip, &address_buffer).code == UV_OK) { return scope.Close(v8::Integer::New(4)); } if (uv_inet_pton(AF_INET6, *ip, &address_buffer).code == UV_OK) { return scope.Close(v8::Integer::New(6)); } return scope.Close(v8::Integer::New(0)); } static Handle GetAddrInfo(const Arguments& args) { HandleScope scope; String::Utf8Value hostname(args[0]); int fam = AF_UNSPEC; if (args[1]->IsInt32()) { switch (args[1]->Int32Value()) { case 6: fam = AF_INET6; break; case 4: fam = AF_INET; break; } } GetAddrInfoReqWrap* req_wrap = new GetAddrInfoReqWrap(); struct addrinfo hints; memset(&hints, 0, sizeof(struct addrinfo)); hints.ai_family = fam; hints.ai_socktype = SOCK_STREAM; int r = uv_getaddrinfo(uv_default_loop(), &req_wrap->req_, AfterGetAddrInfo, *hostname, NULL, &hints); req_wrap->Dispatched(); if (r) { SetErrno(uv_last_error(uv_default_loop())); delete req_wrap; return scope.Close(v8::Null()); } else { return scope.Close(req_wrap->object_); } } static void Initialize(Handle target) { HandleScope scope; int r; r = ares_library_init(ARES_LIB_INIT_ALL); assert(r == ARES_SUCCESS); struct ares_options options; memset(&options, 0, sizeof(options)); options.flags = ARES_FLAG_NOCHECKRESP; options.sock_state_cb = ares_sockstate_cb; options.sock_state_cb_data = uv_default_loop(); /* We do the call to ares_init_option for caller. */ r = ares_init_options(&ares_channel, &options, ARES_OPT_FLAGS | ARES_OPT_SOCK_STATE_CB); assert(r == ARES_SUCCESS); /* Initialize the timeout timer. The timer won't be started until the */ /* first socket is opened. */ uv_timer_init(uv_default_loop(), &ares_timer); NODE_SET_METHOD(target, "queryA", Query); NODE_SET_METHOD(target, "queryAaaa", Query); NODE_SET_METHOD(target, "queryCname", Query); NODE_SET_METHOD(target, "queryMx", Query); NODE_SET_METHOD(target, "queryNs", Query); NODE_SET_METHOD(target, "queryTxt", Query); NODE_SET_METHOD(target, "querySrv", Query); NODE_SET_METHOD(target, "queryNaptr", Query); NODE_SET_METHOD(target, "getHostByAddr", Query); NODE_SET_METHOD(target, "getHostByName", QueryWithFamily); NODE_SET_METHOD(target, "getaddrinfo", GetAddrInfo); NODE_SET_METHOD(target, "isIP", IsIP); target->Set(String::NewSymbol("AF_INET"), Integer::New(AF_INET)); target->Set(String::NewSymbol("AF_INET6"), Integer::New(AF_INET6)); target->Set(String::NewSymbol("AF_UNSPEC"), Integer::New(AF_UNSPEC)); oncomplete_sym = NODE_PSYMBOL("oncomplete"); } } // namespace cares_wrap } // namespace node NODE_MODULE(node_cares_wrap, node::cares_wrap::Initialize) node-v0.10.25~dfsg2/src/perfctr_macros.py0000644000000000000000000000070312270121457016767 0ustar rootroot# This file is used by tools/js2c.py to preprocess out the performance counters # symbols in builds that don't support counters. This is not used in builds # that support performance counters. macro COUNTER_NET_SERVER_CONNECTION(x) = ; macro COUNTER_NET_SERVER_CONNECTION_CLOSE(x) = ; macro COUNTER_HTTP_SERVER_REQUEST(x) = ; macro COUNTER_HTTP_SERVER_RESPONSE(x) = ; macro COUNTER_HTTP_CLIENT_REQUEST(x) = ; macro COUNTER_HTTP_CLIENT_RESPONSE(x) = ; node-v0.10.25~dfsg2/src/tcp_wrap.h0000644000000000000000000000476612270121457015411 0ustar rootroot// Copyright Joyent, Inc. and other Node contributors. // // Permission is hereby granted, free of charge, to any person obtaining a // copy of this software and associated documentation files (the // "Software"), to deal in the Software without restriction, including // without limitation the rights to use, copy, modify, merge, publish, // distribute, sublicense, and/or sell copies of the Software, and to permit // persons to whom the Software is furnished to do so, subject to the // following conditions: // // The above copyright notice and this permission notice shall be included // in all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS // OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF // MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN // NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, // DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR // OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE // USE OR OTHER DEALINGS IN THE SOFTWARE. #ifndef TCP_WRAP_H_ #define TCP_WRAP_H_ #include "stream_wrap.h" namespace node { class TCPWrap : public StreamWrap { public: static v8::Local Instantiate(); static TCPWrap* Unwrap(v8::Local obj); static void Initialize(v8::Handle target); uv_tcp_t* UVHandle(); private: TCPWrap(v8::Handle object); ~TCPWrap(); static v8::Handle New(const v8::Arguments& args); static v8::Handle GetSockName(const v8::Arguments& args); static v8::Handle GetPeerName(const v8::Arguments& args); static v8::Handle SetNoDelay(const v8::Arguments& args); static v8::Handle SetKeepAlive(const v8::Arguments& args); static v8::Handle Bind(const v8::Arguments& args); static v8::Handle Bind6(const v8::Arguments& args); static v8::Handle Listen(const v8::Arguments& args); static v8::Handle Connect(const v8::Arguments& args); static v8::Handle Connect6(const v8::Arguments& args); static v8::Handle Open(const v8::Arguments& args); #ifdef _WIN32 static v8::Handle SetSimultaneousAccepts(const v8::Arguments& args); #endif static void OnConnection(uv_stream_t* handle, int status); static void AfterConnect(uv_connect_t* req, int status); uv_tcp_t handle_; }; } // namespace node #endif // TCP_WRAP_H_ node-v0.10.25~dfsg2/src/node_script.cc0000644000000000000000000003320212270121457016224 0ustar rootroot// Copyright Joyent, Inc. and other Node contributors. // // Permission is hereby granted, free of charge, to any person obtaining a // copy of this software and associated documentation files (the // "Software"), to deal in the Software without restriction, including // without limitation the rights to use, copy, modify, merge, publish, // distribute, sublicense, and/or sell copies of the Software, and to permit // persons to whom the Software is furnished to do so, subject to the // following conditions: // // The above copyright notice and this permission notice shall be included // in all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS // OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF // MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN // NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, // DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR // OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE // USE OR OTHER DEALINGS IN THE SOFTWARE. #include "node.h" #include "node_script.h" #include namespace node { using v8::Context; using v8::Script; using v8::Value; using v8::Handle; using v8::HandleScope; using v8::Object; using v8::Arguments; using v8::ThrowException; using v8::TryCatch; using v8::String; using v8::Exception; using v8::Local; using v8::Array; using v8::Persistent; using v8::Integer; using v8::Function; using v8::FunctionTemplate; class WrappedContext : ObjectWrap { public: static void Initialize(Handle target); static Handle New(const Arguments& args); Persistent GetV8Context(); static Local NewInstance(); static bool InstanceOf(Handle value); protected: static Persistent constructor_template; WrappedContext(); ~WrappedContext(); Persistent context_; }; Persistent WrappedContext::constructor_template; class WrappedScript : ObjectWrap { public: static void Initialize(Handle target); enum EvalInputFlags { compileCode, unwrapExternal }; enum EvalContextFlags { thisContext, newContext, userContext }; enum EvalOutputFlags { returnResult, wrapExternal }; template static Handle EvalMachine(const Arguments& args); protected: static Persistent constructor_template; WrappedScript() : ObjectWrap() {} ~WrappedScript(); static Handle New(const Arguments& args); static Handle CreateContext(const Arguments& arg); static Handle RunInContext(const Arguments& args); static Handle RunInThisContext(const Arguments& args); static Handle RunInNewContext(const Arguments& args); static Handle CompileRunInContext(const Arguments& args); static Handle CompileRunInThisContext(const Arguments& args); static Handle CompileRunInNewContext(const Arguments& args); Persistent

    V8 Benchmark Suite - version ?

    Warning! This is not the latest version of the V8 benchmark suite. Consider running the latest version.
    This page contains a suite of pure JavaScript benchmarks that we have used to tune V8. The final score is computed as the geometric mean of the individual results to make it independent of the running times of the individual benchmarks and of a reference system (score 100). Scores are not comparable across benchmark suite versions and higher scores means better performance: Bigger is better!
    • Richards
      OS kernel simulation benchmark, originally written in BCPL by Martin Richards (539 lines).
    • DeltaBlue
      One-way constraint solver, originally written in Smalltalk by John Maloney and Mario Wolczko (880 lines).
    • Crypto
      Encryption and decryption benchmark based on code by Tom Wu (1698 lines).
    • RayTrace
      Ray tracer benchmark based on code by Adam Burmister (904 lines).
    • EarleyBoyer
      Classic Scheme benchmarks, translated to JavaScript by Florian Loitsch's Scheme2Js compiler (4684 lines).
    • RegExp
      Regular expression benchmark generated by extracting regular expression operations from 50 of the most popular web pages (1761 lines).
    • Splay
      Data manipulation benchmark that deals with splay trees and exercises the automatic memory management subsystem (394 lines).
    • NavierStokes
      Solves NavierStokes equations in 2D, heavily manipulating double precision arrays. Based on Oliver Hunt's code (387 lines).

    Note that benchmark results are not comparable unless both results are run with the same revision of the benchmark suite. We will be making revisions from time to time in order to fix bugs or expand the scope of the benchmark suite. For previous revisions and the change log see the revisions page.

    Starting...
    node-v0.10.25~dfsg2/deps/v8/benchmarks/raytrace.js0000644000000000000000000006653412270121457020410 0ustar rootroot// The ray tracer code in this file is written by Adam Burmister. It // is available in its original form from: // // http://labs.flog.nz.co/raytracer/ // // It has been modified slightly by Google to work as a standalone // benchmark, but the all the computational code remains // untouched. This file also contains a copy of parts of the Prototype // JavaScript framework which is used by the ray tracer. var RayTrace = new BenchmarkSuite('RayTrace', 739989, [ new Benchmark('RayTrace', renderScene) ]); // Variable used to hold a number that can be used to verify that // the scene was ray traced correctly. var checkNumber; // ------------------------------------------------------------------------ // ------------------------------------------------------------------------ // The following is a copy of parts of the Prototype JavaScript library: // Prototype JavaScript framework, version 1.5.0 // (c) 2005-2007 Sam Stephenson // // Prototype is freely distributable under the terms of an MIT-style license. // For details, see the Prototype web site: http://prototype.conio.net/ var Class = { create: function() { return function() { this.initialize.apply(this, arguments); } } }; Object.extend = function(destination, source) { for (var property in source) { destination[property] = source[property]; } return destination; }; // ------------------------------------------------------------------------ // ------------------------------------------------------------------------ // The rest of this file is the actual ray tracer written by Adam // Burmister. It's a concatenation of the following files: // // flog/color.js // flog/light.js // flog/vector.js // flog/ray.js // flog/scene.js // flog/material/basematerial.js // flog/material/solid.js // flog/material/chessboard.js // flog/shape/baseshape.js // flog/shape/sphere.js // flog/shape/plane.js // flog/intersectioninfo.js // flog/camera.js // flog/background.js // flog/engine.js /* Fake a Flog.* namespace */ if(typeof(Flog) == 'undefined') var Flog = {}; if(typeof(Flog.RayTracer) == 'undefined') Flog.RayTracer = {}; Flog.RayTracer.Color = Class.create(); Flog.RayTracer.Color.prototype = { red : 0.0, green : 0.0, blue : 0.0, initialize : function(r, g, b) { if(!r) r = 0.0; if(!g) g = 0.0; if(!b) b = 0.0; this.red = r; this.green = g; this.blue = b; }, add : function(c1, c2){ var result = new Flog.RayTracer.Color(0,0,0); result.red = c1.red + c2.red; result.green = c1.green + c2.green; result.blue = c1.blue + c2.blue; return result; }, addScalar: function(c1, s){ var result = new Flog.RayTracer.Color(0,0,0); result.red = c1.red + s; result.green = c1.green + s; result.blue = c1.blue + s; result.limit(); return result; }, subtract: function(c1, c2){ var result = new Flog.RayTracer.Color(0,0,0); result.red = c1.red - c2.red; result.green = c1.green - c2.green; result.blue = c1.blue - c2.blue; return result; }, multiply : function(c1, c2) { var result = new Flog.RayTracer.Color(0,0,0); result.red = c1.red * c2.red; result.green = c1.green * c2.green; result.blue = c1.blue * c2.blue; return result; }, multiplyScalar : function(c1, f) { var result = new Flog.RayTracer.Color(0,0,0); result.red = c1.red * f; result.green = c1.green * f; result.blue = c1.blue * f; return result; }, divideFactor : function(c1, f) { var result = new Flog.RayTracer.Color(0,0,0); result.red = c1.red / f; result.green = c1.green / f; result.blue = c1.blue / f; return result; }, limit: function(){ this.red = (this.red > 0.0) ? ( (this.red > 1.0) ? 1.0 : this.red ) : 0.0; this.green = (this.green > 0.0) ? ( (this.green > 1.0) ? 1.0 : this.green ) : 0.0; this.blue = (this.blue > 0.0) ? ( (this.blue > 1.0) ? 1.0 : this.blue ) : 0.0; }, distance : function(color) { var d = Math.abs(this.red - color.red) + Math.abs(this.green - color.green) + Math.abs(this.blue - color.blue); return d; }, blend: function(c1, c2, w){ var result = new Flog.RayTracer.Color(0,0,0); result = Flog.RayTracer.Color.prototype.add( Flog.RayTracer.Color.prototype.multiplyScalar(c1, 1 - w), Flog.RayTracer.Color.prototype.multiplyScalar(c2, w) ); return result; }, brightness : function() { var r = Math.floor(this.red*255); var g = Math.floor(this.green*255); var b = Math.floor(this.blue*255); return (r * 77 + g * 150 + b * 29) >> 8; }, toString : function () { var r = Math.floor(this.red*255); var g = Math.floor(this.green*255); var b = Math.floor(this.blue*255); return "rgb("+ r +","+ g +","+ b +")"; } } /* Fake a Flog.* namespace */ if(typeof(Flog) == 'undefined') var Flog = {}; if(typeof(Flog.RayTracer) == 'undefined') Flog.RayTracer = {}; Flog.RayTracer.Light = Class.create(); Flog.RayTracer.Light.prototype = { position: null, color: null, intensity: 10.0, initialize : function(pos, color, intensity) { this.position = pos; this.color = color; this.intensity = (intensity ? intensity : 10.0); }, toString : function () { return 'Light [' + this.position.x + ',' + this.position.y + ',' + this.position.z + ']'; } } /* Fake a Flog.* namespace */ if(typeof(Flog) == 'undefined') var Flog = {}; if(typeof(Flog.RayTracer) == 'undefined') Flog.RayTracer = {}; Flog.RayTracer.Vector = Class.create(); Flog.RayTracer.Vector.prototype = { x : 0.0, y : 0.0, z : 0.0, initialize : function(x, y, z) { this.x = (x ? x : 0); this.y = (y ? y : 0); this.z = (z ? z : 0); }, copy: function(vector){ this.x = vector.x; this.y = vector.y; this.z = vector.z; }, normalize : function() { var m = this.magnitude(); return new Flog.RayTracer.Vector(this.x / m, this.y / m, this.z / m); }, magnitude : function() { return Math.sqrt((this.x * this.x) + (this.y * this.y) + (this.z * this.z)); }, cross : function(w) { return new Flog.RayTracer.Vector( -this.z * w.y + this.y * w.z, this.z * w.x - this.x * w.z, -this.y * w.x + this.x * w.y); }, dot : function(w) { return this.x * w.x + this.y * w.y + this.z * w.z; }, add : function(v, w) { return new Flog.RayTracer.Vector(w.x + v.x, w.y + v.y, w.z + v.z); }, subtract : function(v, w) { if(!w || !v) throw 'Vectors must be defined [' + v + ',' + w + ']'; return new Flog.RayTracer.Vector(v.x - w.x, v.y - w.y, v.z - w.z); }, multiplyVector : function(v, w) { return new Flog.RayTracer.Vector(v.x * w.x, v.y * w.y, v.z * w.z); }, multiplyScalar : function(v, w) { return new Flog.RayTracer.Vector(v.x * w, v.y * w, v.z * w); }, toString : function () { return 'Vector [' + this.x + ',' + this.y + ',' + this.z + ']'; } } /* Fake a Flog.* namespace */ if(typeof(Flog) == 'undefined') var Flog = {}; if(typeof(Flog.RayTracer) == 'undefined') Flog.RayTracer = {}; Flog.RayTracer.Ray = Class.create(); Flog.RayTracer.Ray.prototype = { position : null, direction : null, initialize : function(pos, dir) { this.position = pos; this.direction = dir; }, toString : function () { return 'Ray [' + this.position + ',' + this.direction + ']'; } } /* Fake a Flog.* namespace */ if(typeof(Flog) == 'undefined') var Flog = {}; if(typeof(Flog.RayTracer) == 'undefined') Flog.RayTracer = {}; Flog.RayTracer.Scene = Class.create(); Flog.RayTracer.Scene.prototype = { camera : null, shapes : [], lights : [], background : null, initialize : function() { this.camera = new Flog.RayTracer.Camera( new Flog.RayTracer.Vector(0,0,-5), new Flog.RayTracer.Vector(0,0,1), new Flog.RayTracer.Vector(0,1,0) ); this.shapes = new Array(); this.lights = new Array(); this.background = new Flog.RayTracer.Background(new Flog.RayTracer.Color(0,0,0.5), 0.2); } } /* Fake a Flog.* namespace */ if(typeof(Flog) == 'undefined') var Flog = {}; if(typeof(Flog.RayTracer) == 'undefined') Flog.RayTracer = {}; if(typeof(Flog.RayTracer.Material) == 'undefined') Flog.RayTracer.Material = {}; Flog.RayTracer.Material.BaseMaterial = Class.create(); Flog.RayTracer.Material.BaseMaterial.prototype = { gloss: 2.0, // [0...infinity] 0 = matt transparency: 0.0, // 0=opaque reflection: 0.0, // [0...infinity] 0 = no reflection refraction: 0.50, hasTexture: false, initialize : function() { }, getColor: function(u, v){ }, wrapUp: function(t){ t = t % 2.0; if(t < -1) t += 2.0; if(t >= 1) t -= 2.0; return t; }, toString : function () { return 'Material [gloss=' + this.gloss + ', transparency=' + this.transparency + ', hasTexture=' + this.hasTexture +']'; } } /* Fake a Flog.* namespace */ if(typeof(Flog) == 'undefined') var Flog = {}; if(typeof(Flog.RayTracer) == 'undefined') Flog.RayTracer = {}; Flog.RayTracer.Material.Solid = Class.create(); Flog.RayTracer.Material.Solid.prototype = Object.extend( new Flog.RayTracer.Material.BaseMaterial(), { initialize : function(color, reflection, refraction, transparency, gloss) { this.color = color; this.reflection = reflection; this.transparency = transparency; this.gloss = gloss; this.hasTexture = false; }, getColor: function(u, v){ return this.color; }, toString : function () { return 'SolidMaterial [gloss=' + this.gloss + ', transparency=' + this.transparency + ', hasTexture=' + this.hasTexture +']'; } } ); /* Fake a Flog.* namespace */ if(typeof(Flog) == 'undefined') var Flog = {}; if(typeof(Flog.RayTracer) == 'undefined') Flog.RayTracer = {}; Flog.RayTracer.Material.Chessboard = Class.create(); Flog.RayTracer.Material.Chessboard.prototype = Object.extend( new Flog.RayTracer.Material.BaseMaterial(), { colorEven: null, colorOdd: null, density: 0.5, initialize : function(colorEven, colorOdd, reflection, transparency, gloss, density) { this.colorEven = colorEven; this.colorOdd = colorOdd; this.reflection = reflection; this.transparency = transparency; this.gloss = gloss; this.density = density; this.hasTexture = true; }, getColor: function(u, v){ var t = this.wrapUp(u * this.density) * this.wrapUp(v * this.density); if(t < 0.0) return this.colorEven; else return this.colorOdd; }, toString : function () { return 'ChessMaterial [gloss=' + this.gloss + ', transparency=' + this.transparency + ', hasTexture=' + this.hasTexture +']'; } } ); /* Fake a Flog.* namespace */ if(typeof(Flog) == 'undefined') var Flog = {}; if(typeof(Flog.RayTracer) == 'undefined') Flog.RayTracer = {}; if(typeof(Flog.RayTracer.Shape) == 'undefined') Flog.RayTracer.Shape = {}; Flog.RayTracer.Shape.Sphere = Class.create(); Flog.RayTracer.Shape.Sphere.prototype = { initialize : function(pos, radius, material) { this.radius = radius; this.position = pos; this.material = material; }, intersect: function(ray){ var info = new Flog.RayTracer.IntersectionInfo(); info.shape = this; var dst = Flog.RayTracer.Vector.prototype.subtract(ray.position, this.position); var B = dst.dot(ray.direction); var C = dst.dot(dst) - (this.radius * this.radius); var D = (B * B) - C; if(D > 0){ // intersection! info.isHit = true; info.distance = (-B) - Math.sqrt(D); info.position = Flog.RayTracer.Vector.prototype.add( ray.position, Flog.RayTracer.Vector.prototype.multiplyScalar( ray.direction, info.distance ) ); info.normal = Flog.RayTracer.Vector.prototype.subtract( info.position, this.position ).normalize(); info.color = this.material.getColor(0,0); } else { info.isHit = false; } return info; }, toString : function () { return 'Sphere [position=' + this.position + ', radius=' + this.radius + ']'; } } /* Fake a Flog.* namespace */ if(typeof(Flog) == 'undefined') var Flog = {}; if(typeof(Flog.RayTracer) == 'undefined') Flog.RayTracer = {}; if(typeof(Flog.RayTracer.Shape) == 'undefined') Flog.RayTracer.Shape = {}; Flog.RayTracer.Shape.Plane = Class.create(); Flog.RayTracer.Shape.Plane.prototype = { d: 0.0, initialize : function(pos, d, material) { this.position = pos; this.d = d; this.material = material; }, intersect: function(ray){ var info = new Flog.RayTracer.IntersectionInfo(); var Vd = this.position.dot(ray.direction); if(Vd == 0) return info; // no intersection var t = -(this.position.dot(ray.position) + this.d) / Vd; if(t <= 0) return info; info.shape = this; info.isHit = true; info.position = Flog.RayTracer.Vector.prototype.add( ray.position, Flog.RayTracer.Vector.prototype.multiplyScalar( ray.direction, t ) ); info.normal = this.position; info.distance = t; if(this.material.hasTexture){ var vU = new Flog.RayTracer.Vector(this.position.y, this.position.z, -this.position.x); var vV = vU.cross(this.position); var u = info.position.dot(vU); var v = info.position.dot(vV); info.color = this.material.getColor(u,v); } else { info.color = this.material.getColor(0,0); } return info; }, toString : function () { return 'Plane [' + this.position + ', d=' + this.d + ']'; } } /* Fake a Flog.* namespace */ if(typeof(Flog) == 'undefined') var Flog = {}; if(typeof(Flog.RayTracer) == 'undefined') Flog.RayTracer = {}; Flog.RayTracer.IntersectionInfo = Class.create(); Flog.RayTracer.IntersectionInfo.prototype = { isHit: false, hitCount: 0, shape: null, position: null, normal: null, color: null, distance: null, initialize : function() { this.color = new Flog.RayTracer.Color(0,0,0); }, toString : function () { return 'Intersection [' + this.position + ']'; } } /* Fake a Flog.* namespace */ if(typeof(Flog) == 'undefined') var Flog = {}; if(typeof(Flog.RayTracer) == 'undefined') Flog.RayTracer = {}; Flog.RayTracer.Camera = Class.create(); Flog.RayTracer.Camera.prototype = { position: null, lookAt: null, equator: null, up: null, screen: null, initialize : function(pos, lookAt, up) { this.position = pos; this.lookAt = lookAt; this.up = up; this.equator = lookAt.normalize().cross(this.up); this.screen = Flog.RayTracer.Vector.prototype.add(this.position, this.lookAt); }, getRay: function(vx, vy){ var pos = Flog.RayTracer.Vector.prototype.subtract( this.screen, Flog.RayTracer.Vector.prototype.subtract( Flog.RayTracer.Vector.prototype.multiplyScalar(this.equator, vx), Flog.RayTracer.Vector.prototype.multiplyScalar(this.up, vy) ) ); pos.y = pos.y * -1; var dir = Flog.RayTracer.Vector.prototype.subtract( pos, this.position ); var ray = new Flog.RayTracer.Ray(pos, dir.normalize()); return ray; }, toString : function () { return 'Ray []'; } } /* Fake a Flog.* namespace */ if(typeof(Flog) == 'undefined') var Flog = {}; if(typeof(Flog.RayTracer) == 'undefined') Flog.RayTracer = {}; Flog.RayTracer.Background = Class.create(); Flog.RayTracer.Background.prototype = { color : null, ambience : 0.0, initialize : function(color, ambience) { this.color = color; this.ambience = ambience; } } /* Fake a Flog.* namespace */ if(typeof(Flog) == 'undefined') var Flog = {}; if(typeof(Flog.RayTracer) == 'undefined') Flog.RayTracer = {}; Flog.RayTracer.Engine = Class.create(); Flog.RayTracer.Engine.prototype = { canvas: null, /* 2d context we can render to */ initialize: function(options){ this.options = Object.extend({ canvasHeight: 100, canvasWidth: 100, pixelWidth: 2, pixelHeight: 2, renderDiffuse: false, renderShadows: false, renderHighlights: false, renderReflections: false, rayDepth: 2 }, options || {}); this.options.canvasHeight /= this.options.pixelHeight; this.options.canvasWidth /= this.options.pixelWidth; /* TODO: dynamically include other scripts */ }, setPixel: function(x, y, color){ var pxW, pxH; pxW = this.options.pixelWidth; pxH = this.options.pixelHeight; if (this.canvas) { this.canvas.fillStyle = color.toString(); this.canvas.fillRect (x * pxW, y * pxH, pxW, pxH); } else { if (x === y) { checkNumber += color.brightness(); } // print(x * pxW, y * pxH, pxW, pxH); } }, renderScene: function(scene, canvas){ checkNumber = 0; /* Get canvas */ if (canvas) { this.canvas = canvas.getContext("2d"); } else { this.canvas = null; } var canvasHeight = this.options.canvasHeight; var canvasWidth = this.options.canvasWidth; for(var y=0; y < canvasHeight; y++){ for(var x=0; x < canvasWidth; x++){ var yp = y * 1.0 / canvasHeight * 2 - 1; var xp = x * 1.0 / canvasWidth * 2 - 1; var ray = scene.camera.getRay(xp, yp); var color = this.getPixelColor(ray, scene); this.setPixel(x, y, color); } } if (checkNumber !== 2321) { throw new Error("Scene rendered incorrectly"); } }, getPixelColor: function(ray, scene){ var info = this.testIntersection(ray, scene, null); if(info.isHit){ var color = this.rayTrace(info, ray, scene, 0); return color; } return scene.background.color; }, testIntersection: function(ray, scene, exclude){ var hits = 0; var best = new Flog.RayTracer.IntersectionInfo(); best.distance = 2000; for(var i=0; i= 0 && info.distance < best.distance){ best = info; hits++; } } } best.hitCount = hits; return best; }, getReflectionRay: function(P,N,V){ var c1 = -N.dot(V); var R1 = Flog.RayTracer.Vector.prototype.add( Flog.RayTracer.Vector.prototype.multiplyScalar(N, 2*c1), V ); return new Flog.RayTracer.Ray(P, R1); }, rayTrace: function(info, ray, scene, depth){ // Calc ambient var color = Flog.RayTracer.Color.prototype.multiplyScalar(info.color, scene.background.ambience); var oldColor = color; var shininess = Math.pow(10, info.shape.material.gloss + 1); for(var i=0; i 0.0){ color = Flog.RayTracer.Color.prototype.add( color, Flog.RayTracer.Color.prototype.multiply( info.color, Flog.RayTracer.Color.prototype.multiplyScalar( light.color, L ) ) ); } } // The greater the depth the more accurate the colours, but // this is exponentially (!) expensive if(depth <= this.options.rayDepth){ // calculate reflection ray if(this.options.renderReflections && info.shape.material.reflection > 0) { var reflectionRay = this.getReflectionRay(info.position, info.normal, ray.direction); var refl = this.testIntersection(reflectionRay, scene, info.shape); if (refl.isHit && refl.distance > 0){ refl.color = this.rayTrace(refl, reflectionRay, scene, depth + 1); } else { refl.color = scene.background.color; } color = Flog.RayTracer.Color.prototype.blend( color, refl.color, info.shape.material.reflection ); } // Refraction /* TODO */ } /* Render shadows and highlights */ var shadowInfo = new Flog.RayTracer.IntersectionInfo(); if(this.options.renderShadows){ var shadowRay = new Flog.RayTracer.Ray(info.position, v); shadowInfo = this.testIntersection(shadowRay, scene, info.shape); if(shadowInfo.isHit && shadowInfo.shape != info.shape /*&& shadowInfo.shape.type != 'PLANE'*/){ var vA = Flog.RayTracer.Color.prototype.multiplyScalar(color, 0.5); var dB = (0.5 * Math.pow(shadowInfo.shape.material.transparency, 0.5)); color = Flog.RayTracer.Color.prototype.addScalar(vA,dB); } } // Phong specular highlights if(this.options.renderHighlights && !shadowInfo.isHit && info.shape.material.gloss > 0){ var Lv = Flog.RayTracer.Vector.prototype.subtract( info.shape.position, light.position ).normalize(); var E = Flog.RayTracer.Vector.prototype.subtract( scene.camera.position, info.shape.position ).normalize(); var H = Flog.RayTracer.Vector.prototype.subtract( E, Lv ).normalize(); var glossWeight = Math.pow(Math.max(info.normal.dot(H), 0), shininess); color = Flog.RayTracer.Color.prototype.add( Flog.RayTracer.Color.prototype.multiplyScalar(light.color, glossWeight), color ); } } color.limit(); return color; } }; function renderScene(){ var scene = new Flog.RayTracer.Scene(); scene.camera = new Flog.RayTracer.Camera( new Flog.RayTracer.Vector(0, 0, -15), new Flog.RayTracer.Vector(-0.2, 0, 5), new Flog.RayTracer.Vector(0, 1, 0) ); scene.background = new Flog.RayTracer.Background( new Flog.RayTracer.Color(0.5, 0.5, 0.5), 0.4 ); var sphere = new Flog.RayTracer.Shape.Sphere( new Flog.RayTracer.Vector(-1.5, 1.5, 2), 1.5, new Flog.RayTracer.Material.Solid( new Flog.RayTracer.Color(0,0.5,0.5), 0.3, 0.0, 0.0, 2.0 ) ); var sphere1 = new Flog.RayTracer.Shape.Sphere( new Flog.RayTracer.Vector(1, 0.25, 1), 0.5, new Flog.RayTracer.Material.Solid( new Flog.RayTracer.Color(0.9,0.9,0.9), 0.1, 0.0, 0.0, 1.5 ) ); var plane = new Flog.RayTracer.Shape.Plane( new Flog.RayTracer.Vector(0.1, 0.9, -0.5).normalize(), 1.2, new Flog.RayTracer.Material.Chessboard( new Flog.RayTracer.Color(1,1,1), new Flog.RayTracer.Color(0,0,0), 0.2, 0.0, 1.0, 0.7 ) ); scene.shapes.push(plane); scene.shapes.push(sphere); scene.shapes.push(sphere1); var light = new Flog.RayTracer.Light( new Flog.RayTracer.Vector(5, 10, -1), new Flog.RayTracer.Color(0.8, 0.8, 0.8) ); var light1 = new Flog.RayTracer.Light( new Flog.RayTracer.Vector(-3, 5, -15), new Flog.RayTracer.Color(0.8, 0.8, 0.8), 100 ); scene.lights.push(light); scene.lights.push(light1); var imageWidth = 100; // $F('imageWidth'); var imageHeight = 100; // $F('imageHeight'); var pixelSize = "5,5".split(','); // $F('pixelSize').split(','); var renderDiffuse = true; // $F('renderDiffuse'); var renderShadows = true; // $F('renderShadows'); var renderHighlights = true; // $F('renderHighlights'); var renderReflections = true; // $F('renderReflections'); var rayDepth = 2;//$F('rayDepth'); var raytracer = new Flog.RayTracer.Engine( { canvasWidth: imageWidth, canvasHeight: imageHeight, pixelWidth: pixelSize[0], pixelHeight: pixelSize[1], "renderDiffuse": renderDiffuse, "renderHighlights": renderHighlights, "renderShadows": renderShadows, "renderReflections": renderReflections, "rayDepth": rayDepth } ); raytracer.renderScene(scene, null, 0); } node-v0.10.25~dfsg2/deps/v8/benchmarks/v8-logo.png0000644000000000000000000005734512270121457020241 0ustar rootrootPNG  IHDR7vubKGD pHYs  tIME  % IDATxvʮ, f&;><]xiʖlIkYU2y?w-weYhYjfӸ0o4+C~Ӹ13圩i9Ӳ,d!c zzĘe**m&Z?q?rΔRi(HKDMC,S$g]GZJ)/BZ1Q۶Q?y=D݌h1DMC3Q, WQ<7 TRS3d}q?{G3hQ֖ȝ"|x1j׶zƬizR{ާ#4u۽ a-g0K >6{üѡm u]' +iBm[97:C&- Xu3ƍQ3YG1<- 9G91~֚Nu*O0x/tW+|#ӴRzF ~?pzbԶ-:G)r?g :'?Z:9c. c:E3MӐgJ9QtZ]y}{1FOڙCNJEii396nNb1 m8%%Y4C @)Qʉi*i96rkURNPC gmL(VD 3T~0H1/>?#Fvd*->3[mp0oKG r֭BɐSWMБqT?ϪTji:HkRnR^'72,M}B,Cܓ3u]/?c[/u]/Nj@Q' ia ֚:H>DZ h\ NJc%ߡ.-sK]ׯZbq:׮Rˇl=Yr4lNۯmوQx ~W>Xu5MHee&=m44"8}?>,!ZeXB˲ȁ)9Xk>X>1sy_-g2r"Z$%yCI׫S^c tQ]3 gWז\Xxe8G#ZV_822BT[ǶUD4{ylۖ2\_ࡌmDiѵ1 (Ad8$=&wÐ#i7|6xlLl(«ϳ|GÑk;2Uz{D9@FPӀCd#iqܽےmLNt][׾iEiVٗe_%h!j3%ߚ1cV6-&l%gY܋yYАA%ըm. 8g^25t42\Tա7MC3ĠLba۩H瀺yE82!J2nlbMPp-o`=1,:@J n1?~}Z>;0XD[HBqUHGl2_P^_b)BFQ݁U (%X^*y2Q ;SـԙiV0%?β,DL~nY?ʸeyŨd#ߩWE1IDhғdH5:,h7m;}PYp4 y_"sCWXf[Ssuī\VvAmʎD[]t8e8Sks@ v SGp*CCA+3]wyR )ǥ1Fa> ZCF?Lzk>lMSE`Qéh˓j2itؾx #3JVj1 Ժv|vɎ4vӲ̤0|s׭I=:m]tc,֔"l4NAn9oWF]}wx#UΊ}Q:ե=>MЁZZ"t@60X#jТ%jpJʥEmHj"'he,tD͇~XS%;P( 3#䐄/𼯊}!L!O)F5L̢=j/XRb s0h'iftHH+pHu3V&u{ܺ3Q5 RAe} !dbTP#W:/|Q{NܳR,b&6#ϸԤ:ќo+x H==W}+~U-PCԬmvFOX Z:eC:9M7䙦iȲYo0UV_y`BHh){$䞈3XNUPLs:Il@Þs |ٸ(c H _nZMurkFQ!,t8Rx+ ml9j[e#zZ sw+ HeÈ ofPǞ.Y3[^¡>?}.\^\YJydlZczi"z}+f]e0\rf~y9xeR1._j3jq!eYr̺#Z*HRJeI}AJ- ;(QVx$;l+raW#O0Aa*{޺t½)9*E9Q 2薬eg%>H8Ji㤁:G}4X̧[SpMvgBU|sqCAȐ^)z0J9pTD D,tLZג%Nـ5V!""6QC)hQ:)Pd0~]F395)rpLz3a܀,{/#@χqdP!}&*臌Z+KjzI"غaPF QN㒶 /j.ubW:?ߗ{Nk:?ZĠ'~ϮUdX9qv!,Ŗ]m9G Bi]sEZ\OFPYg{MVH:"J#֠jc$ !1W|(,@Ÿϭ侲QO!D ?ce*R%gj0b8Y]30A~V0dQx^omi:hV%;,L7ƍ+f>ci,(4P;+m&Nz_06ܪm'BʨS[g8kl]孉+9 \{6'S,YS"j]*bR>r4÷p#z{&dڵ @m yɫts{Z fW QE[f[V (,]W1PCz3&RsjVO󊏐cqkzyϜyﭰ1^nbf笗LF:=۸ݏHu^ 6 |!8 pڙvؑڃoZنA#t=xL5Y5O߿hfຖGO1/3ϋNbDua<䡍3~f:>T:OSiQϬ׶ P)N ~{M2g-Pl3}FZ6cC:㹺Sʧ7Li῜Vz)-j]uouM'δ;J/R/1`z5PsTq֑ϞˢI} Y?_Xrg^\}TBAkc-TYk [OVꍘߞRS7SGXs HRHɀs`w1k\_{o*]|mܨKS$s+VRi:9L8X*, Rxo\P+ooC~-+"-yͲ,t8%j6emܗ8VQґEtQh%4B9zkfH #[&o UZ,!W{>b7n-AҪzrZn\dE;kۧa|pE !/ D\\F}Tci1CmFl, oxߵdžr*ep^s!"ԑ'"aW #@ٖ懱cZCzLmiBWҋdRaEOcp̘4]təjQ>˞ݚ%1ncp^2-8tjWƭm>( в% V"ڶVT?a-6W־% }+{ @5|J<jyxj:vnJD+͞z 0 +֒Q5Zq44){k%Zw;Y6 $ oϬ8ֵzbV{_ZU۶L -2 Adt$YKD% IO4iԷ-C)TDm˸<_}@.d2w6~[4 M$;N4z&㫓Zsv%!Nm!޷iJ_O3oyX<4RjEu)::ۣ5;|!JF!6xfCJ,Kjp(a)~l M6%|/.LC(% .y"QͥMR^`%:{9ƝF0knpum~謧-Rj8[.e9 4O=_Z졡b,k`Ba^択=5a/K0Y6 j+ȩ{ kt:©ck~r*7GsbZK)x;g^c4 QϞ Y2S+r|SLD$2="FEoc E^, 2,hxv`=GI|]Owgc|306U[QNƭ  aogwь#sr@6wYSI/,g{{d @A'n.·VgSHH=(۶=Xnj,o"pyyg(c(_^HtH`VLRnQCEɉFm^ݍi:q|y4;1=mXk,^^)E+87S͆HYK)Ѹ{yXᰧ%,B+xOgHks!bEIؓXrY4i#rЃlYrzqAiڎB G=ySD1G2)6Eﵹtu\ YG!QyT8qw>bwHTM#9 BWӸ =Ƒbt8"*hmж ,jyiG}w_cm/tzsH4M4vΜќˈ3w֭HZ2깦jǣ]*Xt F6.9瑎D=?ς)ȖWD~4pHkx*B.-B[T֣?<]C~@M7<4|iCr0:.S06JDrpVἙS-A6'*=!#}^a?0C;R\G9Q{~R[ɷDzia0 N`ə R4 }h. "ڶ4M9P)F ]tK" y!j^`cж4s1ݎ"{,eبE[?l4eF/՜{Vm{_g98ޤ+Y]DzrL HC?Y~^[C2n!(Vh1Tz}]ɐ:䘈x=/}_+k-hU(o Dκx%{~.X,Lc(.QZJ]T--"fU8aY@Sgh(>@\DmbQ-=ύ5xE -!]ĵ4sxEQ$ԇ8z0EF*]{/i1AF3xACo[6ڜ`'p@SJ+[(Ot֪(m1nV1f`Vy $*T; SeC*=.">]yPg]4ǭ$ zN9ruG8E;ſpkRo]![g3f.H\EXi9Qu]O -JH{aw zė^XCdǵ-um!,)ukEk{1t8 %u3OLAgYK)Bպ·57iVE!0YGs: 15p*9eY$~Jx0^?+A™0=V9$JXVgmj[/]qrVl/!$}% !3"fM9#}4l-7Zp?zYc(AxԐW8SrFcƍ{i9jFk0hQMZ4P}nm (mB(xWvL;6F]Xq-u궢oq[݌~A\6JMܛYyYZө8Pݤ+.0Fiݼ귞A#-=O.dE9:6a4"bzpC;傑4lzkf۶'yߵ6ȍ?LA5ѿNlm-zJUr?%j--2>{55es~Op1CrδMHʨav>{m`پ{^L^<82#<}S^T\ i2ǎB=YjLt7!FHl^^HrMC2g.@C+ӚR3.uvԧH\vsmg[8K+pO]IFݰX7}T'"K8bd5{sfZ\ qB?G 04:զC)^ъ8ϫR";Sĕ&[YtGc1r^A$:aUG.g!ܗ^:xFH,fv/40mT߹~Ns$"-tT՚`A߈#3=Ը[׾Iem p!}ʞ  194Xo"dKhVAњ]jڞ܉m7ҕM=9^Ͳ\[آLj"rgtnۖ)%|X|~`f5bE=96#VXW,RoiY_cO@JqQc[72h 5,x[| /tPmXmmt~A(aZ[ -y5l4ʮ9zy#PkG MtfzUn9[= c}OڣW泇 But S=i 1|tzk !A<$(B}H74\N!cت-#5Ptvd|ȭŢ~֥&m}uqiV41u ;/!mW=a- ^mwv8^7^ ,MC݋(\rjj9*uxf~9SB,w]9dV lY>03@z []*1nG"P^P`"-(3mZK  R8JqMON)\ӱ ]yu@^;x/ulʉLBKypmϔR/Ē̏8F8`@ɒ̈́g\5~Mu)?4d( 6 ]>^Zl]l[-"62܆a\aHɵ^`"b j6ure5neE C`RRLP<+"0VZ}뛟Oz:$=CJj,#[J;, 0We룵)hl,|(WҸ۝mXZ_Z+ Q1fࢨ(ip][Q10OS) M'|"akcΙeiuQHH'k~ OTXYJtBv]l־[j~Oy@5>κȿSc卐bX %[tLc(7Y9,]۰u/8gZHӸ)89*\u]Mo-EgPMWhYrLA2٩c_"uR,ђm^ҟY>[Z=d b__D)c:Z8ԛ?!\daNm˸vSP* h]Lm8`=u R4:qы]3` 6Z^Jծi˭&_ȨMȊ%osN桡v/oWH+A zə|b}9Ui&hY= C_)tYQe`)c7?殽-&汵aj@*5n➴DQk^c[jAJmBA~%2;Բxl!@(J4Qc]׋kVmy7Vy$G;'•[^ʣզpsD?Űᐵ{>ȭjC,{ɡִT-oh#TZnnXqfVy QvuMi``ާgy4 #zV9< *eRdM0o,PPIE$vz;.-Zq'ŔEIq z:=1l5xBJ|AO!i%?ϲYD3Rgueo?#+hޞܰkL%U Pk%7j a\iA,`gs5w_&uuԾlTэVS,X.r-R\{P6e,;z)*T( uoJsu% #+aԇKd͎=W(z;Skֿ(HƦt|TND7e5joX)Qv}>}ڻ/ + 1<d%gJes}gM!OAj+)+sRwN!dZJKµ.@36fU%+b na] ≺6>Q~`əP`I+Dْ*H-~vqky=ضEި1t}/ת)vיQI%xUKh@PtXoxDƳi>> dͭJ](FiQϼW,:$91u蒳a XiEOѢ떵gB4MD4ޣv Ê-F6hYH5-L໣{N`90 P#*fx=m6TD d--~Y/2"pՈ-R)8-< R^ڲs·k?lR!`?)Hs3ZP(J-gK;i[p*tưΆm@+& 0R€^S\QSzc4g0BZ0bxeBY,Ĕ=u}U2;h*j-2(cx-L g=9%"Ln7MgreGrb&iw>D`X:0qf׶2Z }L1+t W=eg? baK)|DV Ջ%a%oZE犭"T&wZEO0oax(q |7C``ean{yh:-Gi0hX=Ycep}p=T(e  pRk+4R,R b!H*1غUG,rn \@ o ]EWZ_3 nB gE@0Oqɦv\3]_e\SM -XcтINzina-'kWS[FwXu}/8luE9U]NMpTa;z ?? s-@b\6Y΅{:z5wF]2rĕd/iO,=J2#Յh 2d/:OY]9%zv] u]g_Mia,ԶtyVf5f[+֞RuU½um{;0jH> )g'.Z$z;CpAeӒ]:ɋ7yZ9S|aVحս[Zw{hw佧U2ֵRw䥇_6np Î1Z#9NŦe=Xv,!Ib׿+ySaQ42#{ (RI!d\Ddr6KΑ_<1v]i3B2l47VJ -{A\ozCf6l4_\Co322 AEeYȶ\Ni/}!aI=oؔF}Z<@4I]2T/H8вضV#eM)QZ٨L9/}Lׁ!LCqXcyvвqNqHt'D;A&@ѓ,|(uq j9X#fC{#]"h"l? b tM1JaF3ʋaړG4R5 f6&G;x@4Z+%7lH"UbRB~/T׊زKQW%"ѯI5IL3!TԢDK<`=HҨés4SڑuY\Ga捲%jԮd7~NXGNe [Wrsj Bsu5 ³gZwBN=iG@ozj& -5r/FhIM<,['h`A.=+b,$,u[r.-uhӔAm}ݨIsjsqf_/ɤ^/NUϜӺ(e;o 5_TF-["S[W*nj܈"j9r$ )3{j u8Zl(b6pBMŶ adH636wH5-t\H q/j9LQs{{2G{Iޣa?mW1SgjAџ}HIaLj(K8 'ZN g]>ԇ;_h*Kh{s֭3FiqTlZySYki@:!W`QXMA:j࣡F"~]שG-YOE%_/B_ 9բ+F!Pݸ۽ƁT[Q3pDikm@U~9xC5΢>z6B^{ԀO -"~ZpՌ۽obܦ:rK>9G%ޣE#0H u;4SNe)O Qsr:9_^`Ȃ#3u߬ ]v=vы.ś^9P޼x"0Eӈ<k9k;׏kf w4"IZ\zIjúc~9*}+*6L)q=ƠEc=^νKD溞M4|?U_'-۠! gPw#]SٿԿq )EyC?;cVq+9$B\ ?x]fD6@]8cpvO@Ԫ6ny^q!sC:&4V*xGn+ jƭJ 'HE1y;ѳՑPω/_+yڎ:~.iq\ 4fQtF[+i%5kU^䥾Ѹ5[0#Tgs&W!c@۽иP|' bQ hXC-kbL ;'ˌ)b֕_d0"Doi/{Κ-WA޶ SO/oK4F n?4qG?BJU^1Ԧ0g~nagYxLSDć!2 NVZ2^1eQ =d-ty ;WIi伴"t)%*k3CXL~qkhjWZHo k~X0; ׳ ϕV!%BYӜmdsHkkVyF::yLa%$Ҹ[x!ecR~qiK1R^"̒5zVFMcO}:H>m ^6e1c9k`*WgEb.ۨ5\mٙ(+/}ܽПqIn|zz ZɊ%$&X4M _-8CXy -GBߠޡq^;(0nɌ6P\5{;BGg91d{+GD+aȮ~- -MTV@1y/R{\TtvQ|Q`6-y,>01q%Q `WO<bwxڕ?phD<[8Rp 21mTZcE8/yѸޚٌ@Yv{c /hs5 g>>LL㸻@fh;jmp^xkH05t+){g۶{Usˋ6k8s4* {!XS"9ZgIG㽁rkZlP,TޔΜ3ֶ2EFq `ع2ltsGv5O>X\x7ܖ Y<I;Š -Bn%v4ʯ a bQq Rd }j]H$un~NlVuEk-Zp8ⱴbCI )QsyT;D8JSGs5y2Q_ڮC?aձkdQWB z*[DDmy)YSD5u/`h]%?D^&r@7^\s֊XӲ=8pE9G݋w~l<" 9g~5.NDqji6}F闫kFE 34RYidܚ P ѴIJ YU{ZE cj,؂?J(|=3֖}0>nN5m1y$μY'N6 \Z:'N#>kRA]eUE%`]S? IyH{ҧ_j6NGKDeNQ>TVryL@[D1/Y5! c0D*7P-)$Do"9 h&桯qa%!rN^i:wx?˖q_\뇡Om1MkOE Flێ :&"~\z7- u%+L4FjRpjWh)`"E}MtFy3Lʹ>7mR5XM}e\-#~^m4PD#'T!HROa7ӢGLQ#;@$(jӴZz3QC =n>[kdXԂH1QF}Q{_2R{N\ ڮ Q0U-DsHc:j^O)MGSDklAvnjDVV9Ca .nXp -V>o4n=ޠ;Oӗܚz2e2q]s[RT@w\`눧 [kz/׊41Ei&q 2 IS1mF{ 0{S!gBjw} DI"n!{J qH"$lsY3($iEldSrk_Z}}+=7ZA4út;Ц{/8$kŸ5c Wk]?U@].%3cPkGz !3,_R\&dy҉ v8&sqm[72Q3j0{\;b<2 ,)5&adӰq y盝oe8d=BYVƬ -"}Y@:'ŸDĀp6Ȇ-{Vw9bsqyj#7]` sAZ(X(R~/,1GAlxSiC4(Xu2b\ᰗ{51Pg&pQJᵳm sJ^oclZ`Ւ={^O> 0 E@\$up^ox|ƘҼ1< gᤧTR¹ˆ/]_<_"B& yX;v>\%sޫP({BQa|G2ea*pb[?fq|(MZwW'g1~P`Q-nKrb2jϡgve{x^O>y2-4vD1k xс6"]Q.[kE Gѿ.QJIXڶ{3YddFPYW?WS@! eYp˟##FIy;bXDG"Mӡ|vc[{)%gWYYCѰ[0"g 4yu&ʼ"A iқ4S2׆du:uI1R^2s"XTgvRpQ sj)aO~XKSFi7=X냗nL%"b˶Gp ʏycZ"9(pV+r?m]RCYGkCtaqIky=.Cp֎BOmip>> 19)) & 0xffffffff; seed = ((seed + 0x165667b1) + (seed << 5)) & 0xffffffff; seed = ((seed + 0xd3a2646c) ^ (seed << 9)) & 0xffffffff; seed = ((seed + 0xfd7046c5) + (seed << 3)) & 0xffffffff; seed = ((seed ^ 0xb55a4f09) ^ (seed >>> 16)) & 0xffffffff; return (seed & 0xfffffff) / 0x10000000; }; })(); function GenerateKey() { // The benchmark framework guarantees that Math.random is // deterministic; see base.js. return Math.random(); } function CreateNewPoint() { // Insert new node with a unique key. var key; do { key = GenerateKey(); } while (splayTree.find(key) != null); var point = new Point(Math.random() * 40 - 20, Math.random() * 40 - 20, Math.random() * 40 - 20, GeneratePayloadTree(5, "" + key)); livePoints.add(point); splayTree.insert(key, point); return key; } function ModifyPointsSet() { if (livePoints.count < kNPoints) { for (var i = 0; i < kNModifications; i++) { CreateNewPoint(); } } else if (kNModifications === 20) { kNModifications = 80; kDecay = 30; } for (var i = 0; i < kNModifications; i++) { var key = CreateNewPoint(); var greatest = splayTree.findGreatestLessThan(key); if (greatest == null) { var point = splayTree.remove(key).value; } else { var point = splayTree.remove(greatest.key).value; } livePoints.remove(point); point.payload = null; dyingPoints.add(point); } } function PausePlot(width, height, size, scale) { var canvas = document.createElement("canvas"); canvas.width = this.width = width; canvas.height = this.height = height; document.body.appendChild(canvas); this.ctx = canvas.getContext('2d'); if (typeof scale !== "number") { this.autoScale = true; this.maxPause = 0; } else { this.autoScale = false; this.maxPause = scale; } this.size = size; // Initialize cyclic buffer for pauses. this.pauses = new Array(this.size); this.start = this.size; this.idx = 0; } PausePlot.prototype.addPause = function (p) { if (this.idx === this.size) { this.idx = 0; } if (this.idx === this.start) { this.start++; } if (this.start === this.size) { this.start = 0; } this.pauses[this.idx++] = p; }; PausePlot.prototype.iteratePauses = function (f) { if (this.start < this.idx) { for (var i = this.start; i < this.idx; i++) { f.call(this, i - this.start, this.pauses[i]); } } else { for (var i = this.start; i < this.size; i++) { f.call(this, i - this.start, this.pauses[i]); } var offs = this.size - this.start; for (var i = 0; i < this.idx; i++) { f.call(this, i + offs, this.pauses[i]); } } }; PausePlot.prototype.draw = function () { var first = null; if (this.autoScale) { this.iteratePauses(function (i, v) { if (first === null) { first = v; } this.maxPause = Math.max(v, this.maxPause); }); } var dx = this.width / this.size; var dy = this.height / this.maxPause; this.ctx.save(); this.ctx.clearRect(0, 0, this.width, this.height); this.ctx.beginPath(); this.ctx.moveTo(1, dy * this.pauses[this.start]); var p = first; this.iteratePauses(function (i, v) { var delta = v - p; var x = 1 + dx * i; var y = dy * v; this.ctx.lineTo(x, y); if (delta > 2 * (p / 3)) { this.ctx.font = "bold 12px sans-serif"; this.ctx.textBaseline = "bottom"; this.ctx.fillText(v + "ms", x + 2, y); } p = v; }); this.ctx.strokeStyle = "black"; this.ctx.stroke(); this.ctx.restore(); } function Scene(width, height) { var canvas = document.createElement("canvas"); canvas.width = width; canvas.height = height; document.body.appendChild(canvas); this.ctx = canvas.getContext('2d'); this.width = canvas.width; this.height = canvas.height; // Projection configuration. this.x0 = canvas.width / 2; this.y0 = canvas.height / 2; this.z0 = 100; this.f = 1000; // Focal length. // Camera is rotating around y-axis. this.angle = 0; } Scene.prototype.drawPoint = function (x, y, z, color) { // Rotate the camera around y-axis. var rx = x * Math.cos(this.angle) - z * Math.sin(this.angle); var ry = y; var rz = x * Math.sin(this.angle) + z * Math.cos(this.angle); // Perform perspective projection. var px = (this.f * rx) / (rz - this.z0) + this.x0; var py = (this.f * ry) / (rz - this.z0) + this.y0; this.ctx.save(); this.ctx.fillStyle = color this.ctx.beginPath(); this.ctx.arc(px, py, kPointRadius, 0, 2 * Math.PI, true); this.ctx.fill(); this.ctx.restore(); }; Scene.prototype.drawDyingPoints = function () { var point_next = null; for (var point = dyingPoints.head; point !== null; point = point_next) { // Rotate the scene around y-axis. scene.drawPoint(point.x, point.y, point.z, point.color()); point_next = point.next; // Decay the current point and remove it from the list // if it's life-force ran out. if (point.decay()) { dyingPoints.remove(point); } } }; Scene.prototype.draw = function () { this.ctx.save(); this.ctx.clearRect(0, 0, this.width, this.height); this.drawDyingPoints(); this.ctx.restore(); this.angle += Math.PI / 90.0; }; function updateStats(pause) { numberOfFrames++; if (pause > 20) { sumOfSquaredPauses += (pause - 20) * (pause - 20); } pauseDistribution[Math.floor(pause / 10)] |= 0; pauseDistribution[Math.floor(pause / 10)]++; } function renderStats() { var msg = document.createElement("p"); msg.innerHTML = "Score " + Math.round(numberOfFrames * 1000 / sumOfSquaredPauses); var table = document.createElement("table"); table.align = "center"; for (var i = 0; i < pauseDistribution.length; i++) { if (pauseDistribution[i] > 0) { var row = document.createElement("tr"); var time = document.createElement("td"); var count = document.createElement("td"); time.innerHTML = i*10 + "-" + (i+1)*10 + "ms"; count.innerHTML = " => " + pauseDistribution[i]; row.appendChild(time); row.appendChild(count); table.appendChild(row); } } div.appendChild(msg); div.appendChild(table); } function render() { if (typeof renderingStartTime === 'undefined') { renderingStartTime = Date.now(); benchmarkStartTime = renderingStartTime; } ModifyPointsSet(); scene.draw(); var renderingEndTime = Date.now(); var pause = renderingEndTime - renderingStartTime; pausePlot.addPause(pause); renderingStartTime = renderingEndTime; pausePlot.draw(); updateStats(pause); div.innerHTML = livePoints.count + "/" + dyingPoints.count + " " + pause + "(max = " + pausePlot.maxPause + ") ms " + numberOfFrames + " frames"; if (renderingEndTime < benchmarkStartTime + benchmarkTimeLimit) { // Schedule next frame. requestAnimationFrame(render); } else { renderStats(); } } function Form() { function create(tag) { return document.createElement(tag); } function text(value) { return document.createTextNode(value); } this.form = create("form"); this.form.setAttribute("action", "javascript:start()"); var table = create("table"); table.setAttribute("style", "margin-left: auto; margin-right: auto;"); function col(a) { var td = create("td"); td.appendChild(a); return td; } function row(a, b) { var tr = create("tr"); tr.appendChild(col(a)); tr.appendChild(col(b)); return tr; } this.timelimit = create("input"); this.timelimit.setAttribute("value", "60"); table.appendChild(row(text("Time limit in seconds"), this.timelimit)); this.autoscale = create("input"); this.autoscale.setAttribute("type", "checkbox"); this.autoscale.setAttribute("checked", "true"); table.appendChild(row(text("Autoscale pauses plot"), this.autoscale)); var button = create("input"); button.setAttribute("type", "submit"); button.setAttribute("value", "Start"); this.form.appendChild(table); this.form.appendChild(button); document.body.appendChild(this.form); } Form.prototype.remove = function () { document.body.removeChild(this.form); }; function init() { livePoints = new PointsList; dyingPoints = new PointsList; splayTree = new SplayTree(); scene = new Scene(640, 480); div = document.createElement("div"); document.body.appendChild(div); pausePlot = new PausePlot(480, autoScale ? 240 : 500, 160, autoScale ? void 0 : 500); } function start() { benchmarkTimeLimit = form.timelimit.value * 1000; autoScale = form.autoscale.checked; form.remove(); init(); render(); } var form = new Form(); node-v0.10.25~dfsg2/deps/v8/benchmarks/spinning-balls/splay-tree.js0000644000000000000000000002130312270121457023564 0ustar rootroot// Copyright 2011 the V8 project authors. All rights reserved. // Redistribution and use in source and binary forms, with or without // modification, are permitted provided that the following conditions are // met: // // * Redistributions of source code must retain the above copyright // notice, this list of conditions and the following disclaimer. // * Redistributions in binary form must reproduce the above // copyright notice, this list of conditions and the following // disclaimer in the documentation and/or other materials provided // with the distribution. // * Neither the name of Google Inc. nor the names of its // contributors may be used to endorse or promote products derived // from this software without specific prior written permission. // // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS // "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT // LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR // A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT // OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, // SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT // LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, // DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY // THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT // (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE // OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. /** * Constructs a Splay tree. A splay tree is a self-balancing binary * search tree with the additional property that recently accessed * elements are quick to access again. It performs basic operations * such as insertion, look-up and removal in O(log(n)) amortized time. * * @constructor */ function SplayTree() { }; /** * Pointer to the root node of the tree. * * @type {SplayTree.Node} * @private */ SplayTree.prototype.root_ = null; /** * @return {boolean} Whether the tree is empty. */ SplayTree.prototype.isEmpty = function() { return !this.root_; }; /** * Inserts a node into the tree with the specified key and value if * the tree does not already contain a node with the specified key. If * the value is inserted, it becomes the root of the tree. * * @param {number} key Key to insert into the tree. * @param {*} value Value to insert into the tree. */ SplayTree.prototype.insert = function(key, value) { if (this.isEmpty()) { this.root_ = new SplayTree.Node(key, value); return; } // Splay on the key to move the last node on the search path for // the key to the root of the tree. this.splay_(key); if (this.root_.key == key) { return; } var node = new SplayTree.Node(key, value); if (key > this.root_.key) { node.left = this.root_; node.right = this.root_.right; this.root_.right = null; } else { node.right = this.root_; node.left = this.root_.left; this.root_.left = null; } this.root_ = node; }; /** * Removes a node with the specified key from the tree if the tree * contains a node with this key. The removed node is returned. If the * key is not found, an exception is thrown. * * @param {number} key Key to find and remove from the tree. * @return {SplayTree.Node} The removed node. */ SplayTree.prototype.remove = function(key) { if (this.isEmpty()) { throw Error('Key not found: ' + key); } this.splay_(key); if (this.root_.key != key) { throw Error('Key not found: ' + key); } var removed = this.root_; if (!this.root_.left) { this.root_ = this.root_.right; } else { var right = this.root_.right; this.root_ = this.root_.left; // Splay to make sure that the new root has an empty right child. this.splay_(key); // Insert the original right child as the right child of the new // root. this.root_.right = right; } return removed; }; /** * Returns the node having the specified key or null if the tree doesn't contain * a node with the specified key. * * @param {number} key Key to find in the tree. * @return {SplayTree.Node} Node having the specified key. */ SplayTree.prototype.find = function(key) { if (this.isEmpty()) { return null; } this.splay_(key); return this.root_.key == key ? this.root_ : null; }; /** * @return {SplayTree.Node} Node having the maximum key value. */ SplayTree.prototype.findMax = function(opt_startNode) { if (this.isEmpty()) { return null; } var current = opt_startNode || this.root_; while (current.right) { current = current.right; } return current; }; /** * @return {SplayTree.Node} Node having the maximum key value that * is less than the specified key value. */ SplayTree.prototype.findGreatestLessThan = function(key) { if (this.isEmpty()) { return null; } // Splay on the key to move the node with the given key or the last // node on the search path to the top of the tree. this.splay_(key); // Now the result is either the root node or the greatest node in // the left subtree. if (this.root_.key < key) { return this.root_; } else if (this.root_.left) { return this.findMax(this.root_.left); } else { return null; } }; /** * @return {Array<*>} An array containing all the keys of tree's nodes. */ SplayTree.prototype.exportKeys = function() { var result = []; if (!this.isEmpty()) { this.root_.traverse_(function(node) { result.push(node.key); }); } return result; }; /** * Perform the splay operation for the given key. Moves the node with * the given key to the top of the tree. If no node has the given * key, the last node on the search path is moved to the top of the * tree. This is the simplified top-down splaying algorithm from: * "Self-adjusting Binary Search Trees" by Sleator and Tarjan * * @param {number} key Key to splay the tree on. * @private */ SplayTree.prototype.splay_ = function(key) { if (this.isEmpty()) { return; } // Create a dummy node. The use of the dummy node is a bit // counter-intuitive: The right child of the dummy node will hold // the L tree of the algorithm. The left child of the dummy node // will hold the R tree of the algorithm. Using a dummy node, left // and right will always be nodes and we avoid special cases. var dummy, left, right; dummy = left = right = new SplayTree.Node(null, null); var current = this.root_; while (true) { if (key < current.key) { if (!current.left) { break; } if (key < current.left.key) { // Rotate right. var tmp = current.left; current.left = tmp.right; tmp.right = current; current = tmp; if (!current.left) { break; } } // Link right. right.left = current; right = current; current = current.left; } else if (key > current.key) { if (!current.right) { break; } if (key > current.right.key) { // Rotate left. var tmp = current.right; current.right = tmp.left; tmp.left = current; current = tmp; if (!current.right) { break; } } // Link left. left.right = current; left = current; current = current.right; } else { break; } } // Assemble. left.right = current.left; right.left = current.right; current.left = dummy.right; current.right = dummy.left; this.root_ = current; }; /** * Constructs a Splay tree node. * * @param {number} key Key. * @param {*} value Value. */ SplayTree.Node = function(key, value) { this.key = key; this.value = value; }; /** * @type {SplayTree.Node} */ SplayTree.Node.prototype.left = null; /** * @type {SplayTree.Node} */ SplayTree.Node.prototype.right = null; /** * Performs an ordered traversal of the subtree starting at * this SplayTree.Node. * * @param {function(SplayTree.Node)} f Visitor function. * @private */ SplayTree.Node.prototype.traverse_ = function(f) { var current = this; while (current) { var left = current.left; if (left) left.traverse_(f); f(current); current = current.right; } }; SplayTree.prototype.traverseBreadthFirst = function (f) { if (f(this.root_.value)) return; var stack = [this.root_]; var length = 1; while (length > 0) { var new_stack = new Array(stack.length * 2); var new_length = 0; for (var i = 0; i < length; i++) { var n = stack[i]; var l = n.left; var r = n.right; if (l) { if (f(l.value)) return; new_stack[new_length++] = l; } if (r) { if (f(r.value)) return; new_stack[new_length++] = r; } } stack = new_stack; length = new_length; } }; node-v0.10.25~dfsg2/deps/v8/benchmarks/spinning-balls/index.html0000644000000000000000000000033012270121457023133 0ustar rootroot node-v0.10.25~dfsg2/deps/v8/benchmarks/earley-boyer.js0000644000000000000000000057517212270121457021200 0ustar rootroot// This file is automatically generated by scheme2js, except for the // benchmark harness code at the beginning and end of the file. var EarleyBoyer = new BenchmarkSuite('EarleyBoyer', 666463, [ new Benchmark("Earley", function () { BgL_earleyzd2benchmarkzd2(); }), new Benchmark("Boyer", function () { BgL_nboyerzd2benchmarkzd2(); }) ]); /************* GENERATED FILE - DO NOT EDIT *************/ /************* GENERATED FILE - DO NOT EDIT *************/ /************* GENERATED FILE - DO NOT EDIT *************/ /************* GENERATED FILE - DO NOT EDIT *************/ /************* GENERATED FILE - DO NOT EDIT *************/ /************* GENERATED FILE - DO NOT EDIT *************/ /************* GENERATED FILE - DO NOT EDIT *************/ /************* GENERATED FILE - DO NOT EDIT *************/ /* * To use write/prints/... the default-output port has to be set first. * Simply setting SC_DEFAULT_OUT and SC_ERROR_OUT to the desired values * should do the trick. * In the following example the std-out and error-port are redirected to * a DIV. function initRuntime() { function escapeHTML(s) { var tmp = s; tmp = tmp.replace(/&/g, "&"); tmp = tmp.replace(//g, ">"); tmp = tmp.replace(/ /g, " "); tmp = tmp.replace(/\n/g, "
    "); tmp = tmp.replace(/\t/g, "    "); return tmp; } document.write("
    "); SC_DEFAULT_OUT = new sc_GenericOutputPort( function(s) { var stdout = document.getElementById('stdout'); stdout.innerHTML = stdout.innerHTML + escapeHTML(s); }); SC_ERROR_OUT = SC_DEFAULT_OUT; } */ function sc_print_debug() { sc_print.apply(null, arguments); } /*** META ((export *js*)) */ var sc_JS_GLOBALS = this; var __sc_LINE=-1; var __sc_FILE=""; /*** META ((export #t)) */ function sc_alert() { var len = arguments.length; var s = ""; var i; for( i = 0; i < len; i++ ) { s += sc_toDisplayString(arguments[ i ]); } return alert( s ); } /*** META ((export #t)) */ function sc_typeof( x ) { return typeof x; } /*** META ((export #t)) */ function sc_error() { var a = [sc_jsstring2symbol("*error*")]; for (var i = 0; i < arguments.length; i++) { a[i+1] = arguments[i]; } throw a; } /*** META ((export #t) (peephole (prefix "throw "))) */ function sc_raise(obj) { throw obj; } /*** META ((export with-handler-lambda)) */ function sc_withHandlerLambda(handler, body) { try { return body(); } catch(e) { if (!e._internalException) return handler(e); else throw e; } } var sc_properties = new Object(); /*** META ((export #t)) */ function sc_putpropBang(sym, key, val) { var ht = sc_properties[sym]; if (!ht) { ht = new Object(); sc_properties[sym] = ht; } ht[key] = val; } /*** META ((export #t)) */ function sc_getprop(sym, key) { var ht = sc_properties[sym]; if (ht) { if (key in ht) return ht[key]; else return false; } else return false; } /*** META ((export #t)) */ function sc_rempropBang(sym, key) { var ht = sc_properties[sym]; if (ht) delete ht[key]; } /*** META ((export #t)) */ function sc_any2String(o) { return jsstring2string(sc_toDisplayString(o)); } /*** META ((export #t) (peephole (infix 2 2 "===")) (type bool)) */ function sc_isEqv(o1, o2) { return (o1 === o2); } /*** META ((export #t) (peephole (infix 2 2 "===")) (type bool)) */ function sc_isEq(o1, o2) { return (o1 === o2); } /*** META ((export #t) (type bool)) */ function sc_isNumber(n) { return (typeof n === "number"); } /*** META ((export #t) (type bool)) */ function sc_isComplex(n) { return sc_isNumber(n); } /*** META ((export #t) (type bool)) */ function sc_isReal(n) { return sc_isNumber(n); } /*** META ((export #t) (type bool)) */ function sc_isRational(n) { return sc_isReal(n); } /*** META ((export #t) (type bool)) */ function sc_isInteger(n) { return (parseInt(n) === n); } /*** META ((export #t) (type bool) (peephole (postfix ", false"))) */ // we don't have exact numbers... function sc_isExact(n) { return false; } /*** META ((export #t) (peephole (postfix ", true")) (type bool)) */ function sc_isInexact(n) { return true; } /*** META ((export = =fx =fl) (type bool) (peephole (infix 2 2 "==="))) */ function sc_equal(x) { for (var i = 1; i < arguments.length; i++) if (x !== arguments[i]) return false; return true; } /*** META ((export < = arguments[i]) return false; x = arguments[i]; } return true; } /*** META ((export > >fx >fl) (type bool) (peephole (infix 2 2 ">"))) */ function sc_greater(x, y) { for (var i = 1; i < arguments.length; i++) { if (x <= arguments[i]) return false; x = arguments[i]; } return true; } /*** META ((export <= <=fx <=fl) (type bool) (peephole (infix 2 2 "<="))) */ function sc_lessEqual(x, y) { for (var i = 1; i < arguments.length; i++) { if (x > arguments[i]) return false; x = arguments[i]; } return true; } /*** META ((export >= >=fl >=fx) (type bool) (peephole (infix 2 2 ">="))) */ function sc_greaterEqual(x, y) { for (var i = 1; i < arguments.length; i++) { if (x < arguments[i]) return false; x = arguments[i]; } return true; } /*** META ((export #t) (type bool) (peephole (postfix "=== 0"))) */ function sc_isZero(x) { return (x === 0); } /*** META ((export #t) (type bool) (peephole (postfix "> 0"))) */ function sc_isPositive(x) { return (x > 0); } /*** META ((export #t) (type bool) (peephole (postfix "< 0"))) */ function sc_isNegative(x) { return (x < 0); } /*** META ((export #t) (type bool) (peephole (postfix "%2===1"))) */ function sc_isOdd(x) { return (x % 2 === 1); } /*** META ((export #t) (type bool) (peephole (postfix "%2===0"))) */ function sc_isEven(x) { return (x % 2 === 0); } /*** META ((export #t)) */ var sc_max = Math.max; /*** META ((export #t)) */ var sc_min = Math.min; /*** META ((export + +fx +fl) (peephole (infix 0 #f "+" "0"))) */ function sc_plus() { var sum = 0; for (var i = 0; i < arguments.length; i++) sum += arguments[i]; return sum; } /*** META ((export * *fx *fl) (peephole (infix 0 #f "*" "1"))) */ function sc_multi() { var product = 1; for (var i = 0; i < arguments.length; i++) product *= arguments[i]; return product; } /*** META ((export - -fx -fl) (peephole (minus))) */ function sc_minus(x) { if (arguments.length === 1) return -x; else { var res = x; for (var i = 1; i < arguments.length; i++) res -= arguments[i]; return res; } } /*** META ((export / /fl) (peephole (div))) */ function sc_div(x) { if (arguments.length === 1) return 1/x; else { var res = x; for (var i = 1; i < arguments.length; i++) res /= arguments[i]; return res; } } /*** META ((export #t)) */ var sc_abs = Math.abs; /*** META ((export quotient /fx) (peephole (hole 2 "parseInt(" x "/" y ")"))) */ function sc_quotient(x, y) { return parseInt(x / y); } /*** META ((export #t) (peephole (infix 2 2 "%"))) */ function sc_remainder(x, y) { return x % y; } /*** META ((export #t) (peephole (modulo))) */ function sc_modulo(x, y) { var remainder = x % y; // if they don't have the same sign if ((remainder * y) < 0) return remainder + y; else return remainder; } function sc_euclid_gcd(a, b) { var temp; if (a === 0) return b; if (b === 0) return a; if (a < 0) {a = -a;}; if (b < 0) {b = -b;}; if (b > a) {temp = a; a = b; b = temp;}; while (true) { a %= b; if(a === 0) {return b;}; b %= a; if(b === 0) {return a;}; }; return b; } /*** META ((export #t)) */ function sc_gcd() { var gcd = 0; for (var i = 0; i < arguments.length; i++) gcd = sc_euclid_gcd(gcd, arguments[i]); return gcd; } /*** META ((export #t)) */ function sc_lcm() { var lcm = 1; for (var i = 0; i < arguments.length; i++) { var f = Math.round(arguments[i] / sc_euclid_gcd(arguments[i], lcm)); lcm *= Math.abs(f); } return lcm; } // LIMITATION: numerator and denominator don't make sense in floating point world. //var SC_MAX_DECIMALS = 1000000 // // function sc_numerator(x) { // var rounded = Math.round(x * SC_MAX_DECIMALS); // return Math.round(rounded / sc_euclid_gcd(rounded, SC_MAX_DECIMALS)); // } // function sc_denominator(x) { // var rounded = Math.round(x * SC_MAX_DECIMALS); // return Math.round(SC_MAX_DECIMALS / sc_euclid_gcd(rounded, SC_MAX_DECIMALS)); // } /*** META ((export #t)) */ var sc_floor = Math.floor; /*** META ((export #t)) */ var sc_ceiling = Math.ceil; /*** META ((export #t)) */ var sc_truncate = parseInt; /*** META ((export #t)) */ var sc_round = Math.round; // LIMITATION: sc_rationalize doesn't make sense in a floating point world. /*** META ((export #t)) */ var sc_exp = Math.exp; /*** META ((export #t)) */ var sc_log = Math.log; /*** META ((export #t)) */ var sc_sin = Math.sin; /*** META ((export #t)) */ var sc_cos = Math.cos; /*** META ((export #t)) */ var sc_tan = Math.tan; /*** META ((export #t)) */ var sc_asin = Math.asin; /*** META ((export #t)) */ var sc_acos = Math.acos; /*** META ((export #t)) */ var sc_atan = Math.atan; /*** META ((export #t)) */ var sc_sqrt = Math.sqrt; /*** META ((export #t)) */ var sc_expt = Math.pow; // LIMITATION: we don't have complex numbers. // LIMITATION: the following functions are hence not implemented. // LIMITATION: make-rectangular, make-polar, real-part, imag-part, magnitude, angle // LIMITATION: 2 argument atan /*** META ((export #t) (peephole (id))) */ function sc_exact2inexact(x) { return x; } /*** META ((export #t) (peephole (id))) */ function sc_inexact2exact(x) { return x; } function sc_number2jsstring(x, radix) { if (radix) return x.toString(radix); else return x.toString(); } function sc_jsstring2number(s, radix) { if (s === "") return false; if (radix) { var t = parseInt(s, radix); if (!t && t !== 0) return false; // verify that each char is in range. (parseInt ignores leading // white and trailing chars) var allowedChars = "01234567890abcdefghijklmnopqrstuvwxyz".substring(0, radix+1); if ((new RegExp("^["+allowedChars+"]*$", "i")).test(s)) return t; else return false; } else { var t = +s; // does not ignore trailing chars. if (!t && t !== 0) return false; // simply verify that first char is not whitespace. var c = s.charAt(0); // if +c is 0, but the char is not "0", then we have a whitespace. if (+c === 0 && c !== "0") return false; return t; } } /*** META ((export #t) (type bool) (peephole (not))) */ function sc_not(b) { return b === false; } /*** META ((export #t) (type bool)) */ function sc_isBoolean(b) { return (b === true) || (b === false); } function sc_Pair(car, cdr) { this.car = car; this.cdr = cdr; } sc_Pair.prototype.toString = function() { return sc_toDisplayString(this); }; sc_Pair.prototype.sc_toWriteOrDisplayString = function(writeOrDisplay) { var current = this; var res = "("; while(true) { res += writeOrDisplay(current.car); if (sc_isPair(current.cdr)) { res += " "; current = current.cdr; } else if (current.cdr !== null) { res += " . " + writeOrDisplay(current.cdr); break; } else // current.cdr == null break; } res += ")"; return res; }; sc_Pair.prototype.sc_toDisplayString = function() { return this.sc_toWriteOrDisplayString(sc_toDisplayString); }; sc_Pair.prototype.sc_toWriteString = function() { return this.sc_toWriteOrDisplayString(sc_toWriteString); }; // sc_Pair.prototype.sc_toWriteCircleString in IO.js /*** META ((export #t) (type bool) (peephole (postfix " instanceof sc_Pair"))) */ function sc_isPair(p) { return (p instanceof sc_Pair); } function sc_isPairEqual(p1, p2, comp) { return (comp(p1.car, p2.car) && comp(p1.cdr, p2.cdr)); } /*** META ((export #t) (peephole (hole 2 "new sc_Pair(" car ", " cdr ")"))) */ function sc_cons(car, cdr) { return new sc_Pair(car, cdr); } /*** META ((export cons*)) */ function sc_consStar() { var res = arguments[arguments.length - 1]; for (var i = arguments.length-2; i >= 0; i--) res = new sc_Pair(arguments[i], res); return res; } /*** META ((export #t) (peephole (postfix ".car"))) */ function sc_car(p) { return p.car; } /*** META ((export #t) (peephole (postfix ".cdr"))) */ function sc_cdr(p) { return p.cdr; } /*** META ((export #t) (peephole (hole 2 p ".car = " val))) */ function sc_setCarBang(p, val) { p.car = val; } /*** META ((export #t) (peephole (hole 2 p ".cdr = " val))) */ function sc_setCdrBang(p, val) { p.cdr = val; } /*** META ((export #t) (peephole (postfix ".car.car"))) */ function sc_caar(p) { return p.car.car; } /*** META ((export #t) (peephole (postfix ".cdr.car"))) */ function sc_cadr(p) { return p.cdr.car; } /*** META ((export #t) (peephole (postfix ".car.cdr"))) */ function sc_cdar(p) { return p.car.cdr; } /*** META ((export #t) (peephole (postfix ".cdr.cdr"))) */ function sc_cddr(p) { return p.cdr.cdr; } /*** META ((export #t) (peephole (postfix ".car.car.car"))) */ function sc_caaar(p) { return p.car.car.car; } /*** META ((export #t) (peephole (postfix ".car.cdr.car"))) */ function sc_cadar(p) { return p.car.cdr.car; } /*** META ((export #t) (peephole (postfix ".cdr.car.car"))) */ function sc_caadr(p) { return p.cdr.car.car; } /*** META ((export #t) (peephole (postfix ".cdr.cdr.car"))) */ function sc_caddr(p) { return p.cdr.cdr.car; } /*** META ((export #t) (peephole (postfix ".car.car.cdr"))) */ function sc_cdaar(p) { return p.car.car.cdr; } /*** META ((export #t) (peephole (postfix ".cdr.car.cdr"))) */ function sc_cdadr(p) { return p.cdr.car.cdr; } /*** META ((export #t) (peephole (postfix ".car.cdr.cdr"))) */ function sc_cddar(p) { return p.car.cdr.cdr; } /*** META ((export #t) (peephole (postfix ".cdr.cdr.cdr"))) */ function sc_cdddr(p) { return p.cdr.cdr.cdr; } /*** META ((export #t) (peephole (postfix ".car.car.car.car"))) */ function sc_caaaar(p) { return p.car.car.car.car; } /*** META ((export #t) (peephole (postfix ".car.cdr.car.car"))) */ function sc_caadar(p) { return p.car.cdr.car.car; } /*** META ((export #t) (peephole (postfix ".cdr.car.car.car"))) */ function sc_caaadr(p) { return p.cdr.car.car.car; } /*** META ((export #t) (peephole (postfix ".cdr.cdr.car.car"))) */ function sc_caaddr(p) { return p.cdr.cdr.car.car; } /*** META ((export #t) (peephole (postfix ".car.car.car.cdr"))) */ function sc_cdaaar(p) { return p.car.car.car.cdr; } /*** META ((export #t) (peephole (postfix ".car.cdr.car.cdr"))) */ function sc_cdadar(p) { return p.car.cdr.car.cdr; } /*** META ((export #t) (peephole (postfix ".cdr.car.car.cdr"))) */ function sc_cdaadr(p) { return p.cdr.car.car.cdr; } /*** META ((export #t) (peephole (postfix ".cdr.cdr.car.cdr"))) */ function sc_cdaddr(p) { return p.cdr.cdr.car.cdr; } /*** META ((export #t) (peephole (postfix ".car.car.cdr.car"))) */ function sc_cadaar(p) { return p.car.car.cdr.car; } /*** META ((export #t) (peephole (postfix ".car.cdr.cdr.car"))) */ function sc_caddar(p) { return p.car.cdr.cdr.car; } /*** META ((export #t) (peephole (postfix ".cdr.car.cdr.car"))) */ function sc_cadadr(p) { return p.cdr.car.cdr.car; } /*** META ((export #t) (peephole (postfix ".cdr.cdr.cdr.car"))) */ function sc_cadddr(p) { return p.cdr.cdr.cdr.car; } /*** META ((export #t) (peephole (postfix ".car.car.cdr.cdr"))) */ function sc_cddaar(p) { return p.car.car.cdr.cdr; } /*** META ((export #t) (peephole (postfix ".car.cdr.cdr.cdr"))) */ function sc_cdddar(p) { return p.car.cdr.cdr.cdr; } /*** META ((export #t) (peephole (postfix ".cdr.car.cdr.cdr"))) */ function sc_cddadr(p) { return p.cdr.car.cdr.cdr; } /*** META ((export #t) (peephole (postfix ".cdr.cdr.cdr.cdr"))) */ function sc_cddddr(p) { return p.cdr.cdr.cdr.cdr; } /*** META ((export #t)) */ function sc_lastPair(l) { if (!sc_isPair(l)) sc_error("sc_lastPair: pair expected"); var res = l; var cdr = l.cdr; while (sc_isPair(cdr)) { res = cdr; cdr = res.cdr; } return res; } /*** META ((export #t) (type bool) (peephole (postfix " === null"))) */ function sc_isNull(o) { return (o === null); } /*** META ((export #t) (type bool)) */ function sc_isList(o) { var rabbit; var turtle; var rabbit = o; var turtle = o; while (true) { if (rabbit === null || (rabbit instanceof sc_Pair && rabbit.cdr === null)) return true; // end of list else if ((rabbit instanceof sc_Pair) && (rabbit.cdr instanceof sc_Pair)) { rabbit = rabbit.cdr.cdr; turtle = turtle.cdr; if (rabbit === turtle) return false; // cycle } else return false; // not pair } } /*** META ((export #t)) */ function sc_list() { var res = null; var a = arguments; for (var i = a.length-1; i >= 0; i--) res = new sc_Pair(a[i], res); return res; } /*** META ((export #t)) */ function sc_iota(num, init) { var res = null; if (!init) init = 0; for (var i = num - 1; i >= 0; i--) res = new sc_Pair(i + init, res); return res; } /*** META ((export #t)) */ function sc_makeList(nbEls, fill) { var res = null; for (var i = 0; i < nbEls; i++) res = new sc_Pair(fill, res); return res; } /*** META ((export #t)) */ function sc_length(l) { var res = 0; while (l !== null) { res++; l = l.cdr; } return res; } /*** META ((export #t)) */ function sc_remq(o, l) { var dummy = { cdr : null }; var tail = dummy; while (l !== null) { if (l.car !== o) { tail.cdr = sc_cons(l.car, null); tail = tail.cdr; } l = l.cdr; } return dummy.cdr; } /*** META ((export #t)) */ function sc_remqBang(o, l) { var dummy = { cdr : null }; var tail = dummy; var needsAssig = true; while (l !== null) { if (l.car === o) { needsAssig = true; } else { if (needsAssig) { tail.cdr = l; needsAssig = false; } tail = l; } l = l.cdr; } tail.cdr = null; return dummy.cdr; } /*** META ((export #t)) */ function sc_delete(o, l) { var dummy = { cdr : null }; var tail = dummy; while (l !== null) { if (!sc_isEqual(l.car, o)) { tail.cdr = sc_cons(l.car, null); tail = tail.cdr; } l = l.cdr; } return dummy.cdr; } /*** META ((export #t)) */ function sc_deleteBang(o, l) { var dummy = { cdr : null }; var tail = dummy; var needsAssig = true; while (l !== null) { if (sc_isEqual(l.car, o)) { needsAssig = true; } else { if (needsAssig) { tail.cdr = l; needsAssig = false; } tail = l; } l = l.cdr; } tail.cdr = null; return dummy.cdr; } function sc_reverseAppendBang(l1, l2) { var res = l2; while (l1 !== null) { var tmp = res; res = l1; l1 = l1.cdr; res.cdr = tmp; } return res; } function sc_dualAppend(l1, l2) { if (l1 === null) return l2; if (l2 === null) return l1; var rev = sc_reverse(l1); return sc_reverseAppendBang(rev, l2); } /*** META ((export #t)) */ function sc_append() { if (arguments.length === 0) return null; var res = arguments[arguments.length - 1]; for (var i = arguments.length - 2; i >= 0; i--) res = sc_dualAppend(arguments[i], res); return res; } function sc_dualAppendBang(l1, l2) { if (l1 === null) return l2; if (l2 === null) return l1; var tmp = l1; while (tmp.cdr !== null) tmp=tmp.cdr; tmp.cdr = l2; return l1; } /*** META ((export #t)) */ function sc_appendBang() { var res = null; for (var i = 0; i < arguments.length; i++) res = sc_dualAppendBang(res, arguments[i]); return res; } /*** META ((export #t)) */ function sc_reverse(l1) { var res = null; while (l1 !== null) { res = sc_cons(l1.car, res); l1 = l1.cdr; } return res; } /*** META ((export #t)) */ function sc_reverseBang(l) { return sc_reverseAppendBang(l, null); } /*** META ((export #t)) */ function sc_listTail(l, k) { var res = l; for (var i = 0; i < k; i++) { res = res.cdr; } return res; } /*** META ((export #t)) */ function sc_listRef(l, k) { return sc_listTail(l, k).car; } /* // unoptimized generic versions function sc_memX(o, l, comp) { while (l != null) { if (comp(l.car, o)) return l; l = l.cdr; } return false; } function sc_memq(o, l) { return sc_memX(o, l, sc_isEq); } function sc_memv(o, l) { return sc_memX(o, l, sc_isEqv); } function sc_member(o, l) { return sc_memX(o, l, sc_isEqual); } */ /* optimized versions */ /*** META ((export #t)) */ function sc_memq(o, l) { while (l !== null) { if (l.car === o) return l; l = l.cdr; } return false; } /*** META ((export #t)) */ function sc_memv(o, l) { while (l !== null) { if (l.car === o) return l; l = l.cdr; } return false; } /*** META ((export #t)) */ function sc_member(o, l) { while (l !== null) { if (sc_isEqual(l.car,o)) return l; l = l.cdr; } return false; } /* // generic unoptimized versions function sc_assX(o, al, comp) { while (al != null) { if (comp(al.car.car, o)) return al.car; al = al.cdr; } return false; } function sc_assq(o, al) { return sc_assX(o, al, sc_isEq); } function sc_assv(o, al) { return sc_assX(o, al, sc_isEqv); } function sc_assoc(o, al) { return sc_assX(o, al, sc_isEqual); } */ // optimized versions /*** META ((export #t)) */ function sc_assq(o, al) { while (al !== null) { if (al.car.car === o) return al.car; al = al.cdr; } return false; } /*** META ((export #t)) */ function sc_assv(o, al) { while (al !== null) { if (al.car.car === o) return al.car; al = al.cdr; } return false; } /*** META ((export #t)) */ function sc_assoc(o, al) { while (al !== null) { if (sc_isEqual(al.car.car, o)) return al.car; al = al.cdr; } return false; } /* can be used for mutable strings and characters */ function sc_isCharStringEqual(cs1, cs2) { return cs1.val === cs2.val; } function sc_isCharStringLess(cs1, cs2) { return cs1.val < cs2.val; } function sc_isCharStringGreater(cs1, cs2) { return cs1.val > cs2.val; } function sc_isCharStringLessEqual(cs1, cs2) { return cs1.val <= cs2.val; } function sc_isCharStringGreaterEqual(cs1, cs2) { return cs1.val >= cs2.val; } function sc_isCharStringCIEqual(cs1, cs2) { return cs1.val.toLowerCase() === cs2.val.toLowerCase(); } function sc_isCharStringCILess(cs1, cs2) { return cs1.val.toLowerCase() < cs2.val.toLowerCase(); } function sc_isCharStringCIGreater(cs1, cs2) { return cs1.val.toLowerCase() > cs2.val.toLowerCase(); } function sc_isCharStringCILessEqual(cs1, cs2) { return cs1.val.toLowerCase() <= cs2.val.toLowerCase(); } function sc_isCharStringCIGreaterEqual(cs1, cs2) { return cs1.val.toLowerCase() >= cs2.val.toLowerCase(); } function sc_Char(c) { var cached = sc_Char.lazy[c]; if (cached) return cached; this.val = c; sc_Char.lazy[c] = this; // add return, so FF does not complain. return undefined; } sc_Char.lazy = new Object(); // thanks to Eric sc_Char.char2readable = { "\000": "#\\null", "\007": "#\\bell", "\010": "#\\backspace", "\011": "#\\tab", "\012": "#\\newline", "\014": "#\\page", "\015": "#\\return", "\033": "#\\escape", "\040": "#\\space", "\177": "#\\delete", /* poeticless names */ "\001": "#\\soh", "\002": "#\\stx", "\003": "#\\etx", "\004": "#\\eot", "\005": "#\\enq", "\006": "#\\ack", "\013": "#\\vt", "\016": "#\\so", "\017": "#\\si", "\020": "#\\dle", "\021": "#\\dc1", "\022": "#\\dc2", "\023": "#\\dc3", "\024": "#\\dc4", "\025": "#\\nak", "\026": "#\\syn", "\027": "#\\etb", "\030": "#\\can", "\031": "#\\em", "\032": "#\\sub", "\033": "#\\esc", "\034": "#\\fs", "\035": "#\\gs", "\036": "#\\rs", "\037": "#\\us"}; sc_Char.readable2char = { "null": "\000", "bell": "\007", "backspace": "\010", "tab": "\011", "newline": "\012", "page": "\014", "return": "\015", "escape": "\033", "space": "\040", "delete": "\000", "soh": "\001", "stx": "\002", "etx": "\003", "eot": "\004", "enq": "\005", "ack": "\006", "bel": "\007", "bs": "\010", "ht": "\011", "nl": "\012", "vt": "\013", "np": "\014", "cr": "\015", "so": "\016", "si": "\017", "dle": "\020", "dc1": "\021", "dc2": "\022", "dc3": "\023", "dc4": "\024", "nak": "\025", "syn": "\026", "etb": "\027", "can": "\030", "em": "\031", "sub": "\032", "esc": "\033", "fs": "\034", "gs": "\035", "rs": "\036", "us": "\037", "sp": "\040", "del": "\177"}; sc_Char.prototype.toString = function() { return this.val; }; // sc_toDisplayString == toString sc_Char.prototype.sc_toWriteString = function() { var entry = sc_Char.char2readable[this.val]; if (entry) return entry; else return "#\\" + this.val; }; /*** META ((export #t) (type bool) (peephole (postfix "instanceof sc_Char"))) */ function sc_isChar(c) { return (c instanceof sc_Char); } /*** META ((export char=?) (type bool) (peephole (hole 2 c1 ".val === " c2 ".val"))) */ var sc_isCharEqual = sc_isCharStringEqual; /*** META ((export char?) (type bool) (peephole (hole 2 c1 ".val > " c2 ".val"))) */ var sc_isCharGreater = sc_isCharStringGreater; /*** META ((export char<=?) (type bool) (peephole (hole 2 c1 ".val <= " c2 ".val"))) */ var sc_isCharLessEqual = sc_isCharStringLessEqual; /*** META ((export char>=?) (type bool) (peephole (hole 2 c1 ".val >= " c2 ".val"))) */ var sc_isCharGreaterEqual = sc_isCharStringGreaterEqual; /*** META ((export char-ci=?) (type bool) (peephole (hole 2 c1 ".val.toLowerCase() === " c2 ".val.toLowerCase()"))) */ var sc_isCharCIEqual = sc_isCharStringCIEqual; /*** META ((export char-ci?) (type bool) (peephole (hole 2 c1 ".val.toLowerCase() > " c2 ".val.toLowerCase()"))) */ var sc_isCharCIGreater = sc_isCharStringCIGreater; /*** META ((export char-ci<=?) (type bool) (peephole (hole 2 c1 ".val.toLowerCase() <= " c2 ".val.toLowerCase()"))) */ var sc_isCharCILessEqual = sc_isCharStringCILessEqual; /*** META ((export char-ci>=?) (type bool) (peephole (hole 2 c1 ".val.toLowerCase() >= " c2 ".val.toLowerCase()"))) */ var sc_isCharCIGreaterEqual = sc_isCharStringCIGreaterEqual; var SC_NUMBER_CLASS = "0123456789"; var SC_WHITESPACE_CLASS = ' \r\n\t\f'; var SC_LOWER_CLASS = 'abcdefghijklmnopqrstuvwxyz'; var SC_UPPER_CLASS = 'ABCDEFGHIJKLMNOPQRSTUVWXYZ'; function sc_isCharOfClass(c, cl) { return (cl.indexOf(c) != -1); } /*** META ((export #t) (type bool)) */ function sc_isCharAlphabetic(c) { return sc_isCharOfClass(c.val, SC_LOWER_CLASS) || sc_isCharOfClass(c.val, SC_UPPER_CLASS); } /*** META ((export #t) (type bool) (peephole (hole 1 "SC_NUMBER_CLASS.indexOf(" c ".val) != -1"))) */ function sc_isCharNumeric(c) { return sc_isCharOfClass(c.val, SC_NUMBER_CLASS); } /*** META ((export #t) (type bool)) */ function sc_isCharWhitespace(c) { var tmp = c.val; return tmp === " " || tmp === "\r" || tmp === "\n" || tmp === "\t" || tmp === "\f"; } /*** META ((export #t) (type bool) (peephole (hole 1 "SC_UPPER_CLASS.indexOf(" c ".val) != -1"))) */ function sc_isCharUpperCase(c) { return sc_isCharOfClass(c.val, SC_UPPER_CLASS); } /*** META ((export #t) (type bool) (peephole (hole 1 "SC_LOWER_CLASS.indexOf(" c ".val) != -1"))) */ function sc_isCharLowerCase(c) { return sc_isCharOfClass(c.val, SC_LOWER_CLASS); } /*** META ((export #t) (peephole (postfix ".val.charCodeAt(0)"))) */ function sc_char2integer(c) { return c.val.charCodeAt(0); } /*** META ((export #t) (peephole (hole 1 "new sc_Char(String.fromCharCode(" n "))"))) */ function sc_integer2char(n) { return new sc_Char(String.fromCharCode(n)); } /*** META ((export #t) (peephole (hole 1 "new sc_Char(" c ".val.toUpperCase())"))) */ function sc_charUpcase(c) { return new sc_Char(c.val.toUpperCase()); } /*** META ((export #t) (peephole (hole 1 "new sc_Char(" c ".val.toLowerCase())"))) */ function sc_charDowncase(c) { return new sc_Char(c.val.toLowerCase()); } function sc_makeJSStringOfLength(k, c) { var fill; if (c === undefined) fill = " "; else fill = c; var res = ""; var len = 1; // every round doubles the size of fill. while (k >= len) { if (k & len) res = res.concat(fill); fill = fill.concat(fill); len *= 2; } return res; } function sc_makejsString(k, c) { var fill; if (c) fill = c.val; else fill = " "; return sc_makeJSStringOfLength(k, fill); } function sc_jsstring2list(s) { var res = null; for (var i = s.length - 1; i >= 0; i--) res = sc_cons(new sc_Char(s.charAt(i)), res); return res; } function sc_list2jsstring(l) { var a = new Array(); while(l !== null) { a.push(l.car.val); l = l.cdr; } return "".concat.apply("", a); } var sc_Vector = Array; sc_Vector.prototype.sc_toWriteOrDisplayString = function(writeOrDisplay) { if (this.length === 0) return "#()"; var res = "#(" + writeOrDisplay(this[0]); for (var i = 1; i < this.length; i++) res += " " + writeOrDisplay(this[i]); res += ")"; return res; }; sc_Vector.prototype.sc_toDisplayString = function() { return this.sc_toWriteOrDisplayString(sc_toDisplayString); }; sc_Vector.prototype.sc_toWriteString = function() { return this.sc_toWriteOrDisplayString(sc_toWriteString); }; /*** META ((export vector? array?) (type bool) (peephole (postfix " instanceof sc_Vector"))) */ function sc_isVector(v) { return (v instanceof sc_Vector); } // only applies to vectors function sc_isVectorEqual(v1, v2, comp) { if (v1.length !== v2.length) return false; for (var i = 0; i < v1.length; i++) if (!comp(v1[i], v2[i])) return false; return true; } /*** META ((export make-vector make-array)) */ function sc_makeVector(size, fill) { var a = new sc_Vector(size); if (fill !== undefined) sc_vectorFillBang(a, fill); return a; } /*** META ((export vector array) (peephole (vector))) */ function sc_vector() { var a = new sc_Vector(); for (var i = 0; i < arguments.length; i++) a.push(arguments[i]); return a; } /*** META ((export vector-length array-length) (peephole (postfix ".length"))) */ function sc_vectorLength(v) { return v.length; } /*** META ((export vector-ref array-ref) (peephole (hole 2 v "[" pos "]"))) */ function sc_vectorRef(v, pos) { return v[pos]; } /*** META ((export vector-set! array-set!) (peephole (hole 3 v "[" pos "] = " val))) */ function sc_vectorSetBang(v, pos, val) { v[pos] = val; } /*** META ((export vector->list array->list)) */ function sc_vector2list(a) { var res = null; for (var i = a.length-1; i >= 0; i--) res = sc_cons(a[i], res); return res; } /*** META ((export list->vector list->array)) */ function sc_list2vector(l) { var a = new sc_Vector(); while(l !== null) { a.push(l.car); l = l.cdr; } return a; } /*** META ((export vector-fill! array-fill!)) */ function sc_vectorFillBang(a, fill) { for (var i = 0; i < a.length; i++) a[i] = fill; } /*** META ((export #t)) */ function sc_copyVector(a, len) { if (len <= a.length) return a.slice(0, len); else { var tmp = a.concat(); tmp.length = len; return tmp; } } /*** META ((export #t) (peephole (hole 3 a ".slice(" start "," end ")"))) */ function sc_vectorCopy(a, start, end) { return a.slice(start, end); } /*** META ((export #t)) */ function sc_vectorCopyBang(target, tstart, source, sstart, send) { if (!sstart) sstart = 0; if (!send) send = source.length; // if target == source we don't want to overwrite not yet copied elements. if (tstart <= sstart) { for (var i = tstart, j = sstart; j < send; i++, j++) { target[i] = source[j]; } } else { var diff = send - sstart; for (var i = tstart + diff - 1, j = send - 1; j >= sstart; i--, j--) { target[i] = source[j]; } } return target; } /*** META ((export #t) (type bool) (peephole (hole 1 "typeof " o " === 'function'"))) */ function sc_isProcedure(o) { return (typeof o === "function"); } /*** META ((export #t)) */ function sc_apply(proc) { var args = new Array(); // first part of arguments are not in list-form. for (var i = 1; i < arguments.length - 1; i++) args.push(arguments[i]); var l = arguments[arguments.length - 1]; while (l !== null) { args.push(l.car); l = l.cdr; } return proc.apply(null, args); } /*** META ((export #t)) */ function sc_map(proc, l1) { if (l1 === undefined) return null; // else var nbApplyArgs = arguments.length - 1; var applyArgs = new Array(nbApplyArgs); var revres = null; while (l1 !== null) { for (var i = 0; i < nbApplyArgs; i++) { applyArgs[i] = arguments[i + 1].car; arguments[i + 1] = arguments[i + 1].cdr; } revres = sc_cons(proc.apply(null, applyArgs), revres); } return sc_reverseAppendBang(revres, null); } /*** META ((export #t)) */ function sc_mapBang(proc, l1) { if (l1 === undefined) return null; // else var l1_orig = l1; var nbApplyArgs = arguments.length - 1; var applyArgs = new Array(nbApplyArgs); while (l1 !== null) { var tmp = l1; for (var i = 0; i < nbApplyArgs; i++) { applyArgs[i] = arguments[i + 1].car; arguments[i + 1] = arguments[i + 1].cdr; } tmp.car = proc.apply(null, applyArgs); } return l1_orig; } /*** META ((export #t)) */ function sc_forEach(proc, l1) { if (l1 === undefined) return undefined; // else var nbApplyArgs = arguments.length - 1; var applyArgs = new Array(nbApplyArgs); while (l1 !== null) { for (var i = 0; i < nbApplyArgs; i++) { applyArgs[i] = arguments[i + 1].car; arguments[i + 1] = arguments[i + 1].cdr; } proc.apply(null, applyArgs); } // add return so FF does not complain. return undefined; } /*** META ((export #t)) */ function sc_filter(proc, l1) { var dummy = { cdr : null }; var tail = dummy; while (l1 !== null) { if (proc(l1.car) !== false) { tail.cdr = sc_cons(l1.car, null); tail = tail.cdr; } l1 = l1.cdr; } return dummy.cdr; } /*** META ((export #t)) */ function sc_filterBang(proc, l1) { var head = sc_cons("dummy", l1); var it = head; var next = l1; while (next !== null) { if (proc(next.car) !== false) { it.cdr = next it = next; } next = next.cdr; } it.cdr = null; return head.cdr; } function sc_filterMap1(proc, l1) { var revres = null; while (l1 !== null) { var tmp = proc(l1.car) if (tmp !== false) revres = sc_cons(tmp, revres); l1 = l1.cdr; } return sc_reverseAppendBang(revres, null); } function sc_filterMap2(proc, l1, l2) { var revres = null; while (l1 !== null) { var tmp = proc(l1.car, l2.car); if(tmp !== false) revres = sc_cons(tmp, revres); l1 = l1.cdr; l2 = l2.cdr } return sc_reverseAppendBang(revres, null); } /*** META ((export #t)) */ function sc_filterMap(proc, l1, l2, l3) { if (l2 === undefined) return sc_filterMap1(proc, l1); else if (l3 === undefined) return sc_filterMap2(proc, l1, l2); // else var nbApplyArgs = arguments.length - 1; var applyArgs = new Array(nbApplyArgs); var revres = null; while (l1 !== null) { for (var i = 0; i < nbApplyArgs; i++) { applyArgs[i] = arguments[i + 1].car; arguments[i + 1] = arguments[i + 1].cdr; } var tmp = proc.apply(null, applyArgs); if(tmp !== false) revres = sc_cons(tmp, revres); } return sc_reverseAppendBang(revres, null); } /*** META ((export #t)) */ function sc_any(proc, l) { var revres = null; while (l !== null) { var tmp = proc(l.car); if(tmp !== false) return tmp; l = l.cdr; } return false; } /*** META ((export any?) (peephole (hole 2 "sc_any(" proc "," l ") !== false"))) */ function sc_anyPred(proc, l) { return sc_any(proc, l)!== false; } /*** META ((export #t)) */ function sc_every(proc, l) { var revres = null; var tmp = true; while (l !== null) { tmp = proc(l.car); if (tmp === false) return false; l = l.cdr; } return tmp; } /*** META ((export every?) (peephole (hole 2 "sc_every(" proc "," l ") !== false"))) */ function sc_everyPred(proc, l) { var tmp = sc_every(proc, l); if (tmp !== false) return true; return false; } /*** META ((export #t) (peephole (postfix "()"))) */ function sc_force(o) { return o(); } /*** META ((export #t)) */ function sc_makePromise(proc) { var isResultReady = false; var result = undefined; return function() { if (!isResultReady) { var tmp = proc(); if (!isResultReady) { isResultReady = true; result = tmp; } } return result; }; } function sc_Values(values) { this.values = values; } /*** META ((export #t) (peephole (values))) */ function sc_values() { if (arguments.length === 1) return arguments[0]; else return new sc_Values(arguments); } /*** META ((export #t)) */ function sc_callWithValues(producer, consumer) { var produced = producer(); if (produced instanceof sc_Values) return consumer.apply(null, produced.values); else return consumer(produced); } /*** META ((export #t)) */ function sc_dynamicWind(before, thunk, after) { before(); try { var res = thunk(); return res; } finally { after(); } } // TODO: eval/scheme-report-environment/null-environment/interaction-environment // LIMITATION: 'load' doesn't exist without files. // LIMITATION: transcript-on/transcript-off doesn't exist without files. function sc_Struct(name) { this.name = name; } sc_Struct.prototype.sc_toDisplayString = function() { return "#"; }; sc_Struct.prototype.sc_toWriteString = sc_Struct.prototype.sc_toDisplayString; /*** META ((export #t) (peephole (hole 1 "new sc_Struct(" name ")"))) */ function sc_makeStruct(name) { return new sc_Struct(name); } /*** META ((export #t) (type bool) (peephole (postfix " instanceof sc_Struct"))) */ function sc_isStruct(o) { return (o instanceof sc_Struct); } /*** META ((export #t) (type bool) (peephole (hole 2 "(" 1 " instanceof sc_Struct) && ( " 1 ".name === " 0 ")"))) */ function sc_isStructNamed(name, s) { return ((s instanceof sc_Struct) && (s.name === name)); } /*** META ((export struct-field) (peephole (hole 3 0 "[" 2 "]"))) */ function sc_getStructField(s, name, field) { return s[field]; } /*** META ((export struct-field-set!) (peephole (hole 4 0 "[" 2 "] = " 3))) */ function sc_setStructFieldBang(s, name, field, val) { s[field] = val; } /*** META ((export #t) (peephole (prefix "~"))) */ function sc_bitNot(x) { return ~x; } /*** META ((export #t) (peephole (infix 2 2 "&"))) */ function sc_bitAnd(x, y) { return x & y; } /*** META ((export #t) (peephole (infix 2 2 "|"))) */ function sc_bitOr(x, y) { return x | y; } /*** META ((export #t) (peephole (infix 2 2 "^"))) */ function sc_bitXor(x, y) { return x ^ y; } /*** META ((export #t) (peephole (infix 2 2 "<<"))) */ function sc_bitLsh(x, y) { return x << y; } /*** META ((export #t) (peephole (infix 2 2 ">>"))) */ function sc_bitRsh(x, y) { return x >> y; } /*** META ((export #t) (peephole (infix 2 2 ">>>"))) */ function sc_bitUrsh(x, y) { return x >>> y; } /*** META ((export js-field js-property) (peephole (hole 2 o "[" field "]"))) */ function sc_jsField(o, field) { return o[field]; } /*** META ((export js-field-set! js-property-set!) (peephole (hole 3 o "[" field "] = " val))) */ function sc_setJsFieldBang(o, field, val) { return o[field] = val; } /*** META ((export js-field-delete! js-property-delete!) (peephole (hole 2 "delete" o "[" field "]"))) */ function sc_deleteJsFieldBang(o, field) { delete o[field]; } /*** META ((export #t) (peephole (jsCall))) */ function sc_jsCall(o, fun) { var args = new Array(); for (var i = 2; i < arguments.length; i++) args[i-2] = arguments[i]; return fun.apply(o, args); } /*** META ((export #t) (peephole (jsMethodCall))) */ function sc_jsMethodCall(o, field) { var args = new Array(); for (var i = 2; i < arguments.length; i++) args[i-2] = arguments[i]; return o[field].apply(o, args); } /*** META ((export new js-new) (peephole (jsNew))) */ function sc_jsNew(c) { var evalStr = "new c("; evalStr +=arguments.length > 1? "arguments[1]": ""; for (var i = 2; i < arguments.length; i++) evalStr += ", arguments[" + i + "]"; evalStr +=")"; return eval(evalStr); } // ======================== RegExp ==================== /*** META ((export #t)) */ function sc_pregexp(re) { return new RegExp(sc_string2jsstring(re)); } /*** META ((export #t)) */ function sc_pregexpMatch(re, s) { var reg = (re instanceof RegExp) ? re : sc_pregexp(re); var tmp = reg.exec(sc_string2jsstring(s)); if (tmp == null) return false; var res = null; for (var i = tmp.length-1; i >= 0; i--) { if (tmp[i] !== null) { res = sc_cons(sc_jsstring2string(tmp[i]), res); } else { res = sc_cons(false, res); } } return res; } /*** META ((export #t)) */ function sc_pregexpReplace(re, s1, s2) { var reg; var jss1 = sc_string2jsstring(s1); var jss2 = sc_string2jsstring(s2); if (re instanceof RegExp) { if (re.global) reg = re; else reg = new RegExp(re.source); } else { reg = new RegExp(sc_string2jsstring(re)); } return jss1.replace(reg, jss2); } /*** META ((export pregexp-replace*)) */ function sc_pregexpReplaceAll(re, s1, s2) { var reg; var jss1 = sc_string2jsstring(s1); var jss2 = sc_string2jsstring(s2); if (re instanceof RegExp) { if (re.global) reg = re; else reg = new RegExp(re.source, "g"); } else { reg = new RegExp(sc_string2jsstring(re), "g"); } return jss1.replace(reg, jss2); } /*** META ((export #t)) */ function sc_pregexpSplit(re, s) { var reg = ((re instanceof RegExp) ? re : new RegExp(sc_string2jsstring(re))); var jss = sc_string2jsstring(s); var tmp = jss.split(reg); if (tmp == null) return false; return sc_vector2list(tmp); } /* =========================================================================== */ /* Other library stuff */ /* =========================================================================== */ /*** META ((export #t) (peephole (hole 1 "Math.floor(Math.random()*" 'n ")"))) */ function sc_random(n) { return Math.floor(Math.random()*n); } /*** META ((export current-date) (peephole (hole 0 "new Date()"))) */ function sc_currentDate() { return new Date(); } function sc_Hashtable() { } sc_Hashtable.prototype.toString = function() { return "#{%hashtable}"; }; // sc_toWriteString == sc_toDisplayString == toString function sc_HashtableElement(key, val) { this.key = key; this.val = val; } /*** META ((export #t) (peephole (hole 0 "new sc_Hashtable()"))) */ function sc_makeHashtable() { return new sc_Hashtable(); } /*** META ((export #t)) */ function sc_hashtablePutBang(ht, key, val) { var hash = sc_hash(key); ht[hash] = new sc_HashtableElement(key, val); } /*** META ((export #t)) */ function sc_hashtableGet(ht, key) { var hash = sc_hash(key); if (hash in ht) return ht[hash].val; else return false; } /*** META ((export #t)) */ function sc_hashtableForEach(ht, f) { for (var v in ht) { if (ht[v] instanceof sc_HashtableElement) f(ht[v].key, ht[v].val); } } /*** META ((export hashtable-contains?) (peephole (hole 2 "sc_hash(" 1 ") in " 0))) */ function sc_hashtableContains(ht, key) { var hash = sc_hash(key); if (hash in ht) return true; else return false; } var SC_HASH_COUNTER = 0; function sc_hash(o) { if (o === null) return "null"; else if (o === undefined) return "undefined"; else if (o === true) return "true"; else if (o === false) return "false"; else if (typeof o === "number") return "num-" + o; else if (typeof o === "string") return "jsstr-" + o; else if (o.sc_getHash) return o.sc_getHash(); else return sc_counterHash.call(o); } function sc_counterHash() { if (!this.sc_hash) { this.sc_hash = "hash-" + SC_HASH_COUNTER; SC_HASH_COUNTER++; } return this.sc_hash; } function sc_Trampoline(args, maxTailCalls) { this['__trampoline return__'] = true; this.args = args; this.MAX_TAIL_CALLs = maxTailCalls; } // TODO: call/cc stuff sc_Trampoline.prototype.restart = function() { var o = this; while (true) { // set both globals. SC_TAIL_OBJECT.calls = o.MAX_TAIL_CALLs-1; var fun = o.args.callee; var res = fun.apply(SC_TAIL_OBJECT, o.args); if (res instanceof sc_Trampoline) o = res; else return res; } } /*** META ((export bind-exit-lambda)) */ function sc_bindExitLambda(proc) { var escape_obj = new sc_BindExitException(); var escape = function(res) { escape_obj.res = res; throw escape_obj; }; try { return proc(escape); } catch(e) { if (e === escape_obj) { return e.res; } throw e; } } function sc_BindExitException() { this._internalException = true; } var SC_SCM2JS_GLOBALS = new Object(); // default tail-call depth. // normally the program should set it again. but just in case... var SC_TAIL_OBJECT = new Object(); SC_SCM2JS_GLOBALS.TAIL_OBJECT = SC_TAIL_OBJECT; // ======================== I/O ======================= /*------------------------------------------------------------------*/ function sc_EOF() { } var SC_EOF_OBJECT = new sc_EOF(); function sc_Port() { } /* --------------- Input ports -------------------------------------*/ function sc_InputPort() { } sc_InputPort.prototype = new sc_Port(); sc_InputPort.prototype.peekChar = function() { if (!("peeked" in this)) this.peeked = this.getNextChar(); return this.peeked; } sc_InputPort.prototype.readChar = function() { var tmp = this.peekChar(); delete this.peeked; return tmp; } sc_InputPort.prototype.isCharReady = function() { return true; } sc_InputPort.prototype.close = function() { // do nothing } /* .............. String port ..........................*/ function sc_ErrorInputPort() { }; sc_ErrorInputPort.prototype = new sc_InputPort(); sc_ErrorInputPort.prototype.getNextChar = function() { throw "can't read from error-port."; }; sc_ErrorInputPort.prototype.isCharReady = function() { return false; }; /* .............. String port ..........................*/ function sc_StringInputPort(jsStr) { // we are going to do some charAts on the str. // instead of recreating all the time a String-object, we // create one in the beginning. (not sure, if this is really an optim) this.str = new String(jsStr); this.pos = 0; } sc_StringInputPort.prototype = new sc_InputPort(); sc_StringInputPort.prototype.getNextChar = function() { if (this.pos >= this.str.length) return SC_EOF_OBJECT; return this.str.charAt(this.pos++); }; /* ------------- Read and other lib-funs -------------------------------*/ function sc_Token(type, val, pos) { this.type = type; this.val = val; this.pos = pos; } sc_Token.EOF = 0/*EOF*/; sc_Token.OPEN_PAR = 1/*OPEN_PAR*/; sc_Token.CLOSE_PAR = 2/*CLOSE_PAR*/; sc_Token.OPEN_BRACE = 3/*OPEN_BRACE*/; sc_Token.CLOSE_BRACE = 4/*CLOSE_BRACE*/; sc_Token.OPEN_BRACKET = 5/*OPEN_BRACKET*/; sc_Token.CLOSE_BRACKET = 6/*CLOSE_BRACKET*/; sc_Token.WHITESPACE = 7/*WHITESPACE*/; sc_Token.QUOTE = 8/*QUOTE*/; sc_Token.ID = 9/*ID*/; sc_Token.DOT = 10/*DOT*/; sc_Token.STRING = 11/*STRING*/; sc_Token.NUMBER = 12/*NUMBER*/; sc_Token.ERROR = 13/*ERROR*/; sc_Token.VECTOR_BEGIN = 14/*VECTOR_BEGIN*/; sc_Token.TRUE = 15/*TRUE*/; sc_Token.FALSE = 16/*FALSE*/; sc_Token.UNSPECIFIED = 17/*UNSPECIFIED*/; sc_Token.REFERENCE = 18/*REFERENCE*/; sc_Token.STORE = 19/*STORE*/; sc_Token.CHAR = 20/*CHAR*/; var SC_ID_CLASS = SC_LOWER_CLASS + SC_UPPER_CLASS + "!$%*+-./:<=>?@^_~"; function sc_Tokenizer(port) { this.port = port; } sc_Tokenizer.prototype.peekToken = function() { if (this.peeked) return this.peeked; var newToken = this.nextToken(); this.peeked = newToken; return newToken; }; sc_Tokenizer.prototype.readToken = function() { var tmp = this.peekToken(); delete this.peeked; return tmp; }; sc_Tokenizer.prototype.nextToken = function() { var port = this.port; function isNumberChar(c) { return (c >= "0" && c <= "9"); }; function isIdOrNumberChar(c) { return SC_ID_CLASS.indexOf(c) != -1 || // ID-char (c >= "0" && c <= "9"); } function isWhitespace(c) { return c === " " || c === "\r" || c === "\n" || c === "\t" || c === "\f"; }; function isWhitespaceOrEOF(c) { return isWhitespace(c) || c === SC_EOF_OBJECT; }; function readString() { res = ""; while (true) { var c = port.readChar(); switch (c) { case '"': return new sc_Token(11/*STRING*/, res); case "\\": var tmp = port.readChar(); switch (tmp) { case '0': res += "\0"; break; case 'a': res += "\a"; break; case 'b': res += "\b"; break; case 'f': res += "\f"; break; case 'n': res += "\n"; break; case 'r': res += "\r"; break; case 't': res += "\t"; break; case 'v': res += "\v"; break; case '"': res += '"'; break; case '\\': res += '\\'; break; case 'x': /* hexa-number */ var nb = 0; while (true) { var hexC = port.peekChar(); if (hexC >= '0' && hexC <= '9') { port.readChar(); nb = nb * 16 + hexC.charCodeAt(0) - '0'.charCodeAt(0); } else if (hexC >= 'a' && hexC <= 'f') { port.readChar(); nb = nb * 16 + hexC.charCodeAt(0) - 'a'.charCodeAt(0); } else if (hexC >= 'A' && hexC <= 'F') { port.readChar(); nb = nb * 16 + hexC.charCodeAt(0) - 'A'.charCodeAt(0); } else { // next char isn't part of hex. res += String.fromCharCode(nb); break; } } break; default: if (tmp === SC_EOF_OBJECT) { return new sc_Token(13/*ERROR*/, "unclosed string-literal" + res); } res += tmp; } break; default: if (c === SC_EOF_OBJECT) { return new sc_Token(13/*ERROR*/, "unclosed string-literal" + res); } res += c; } } }; function readIdOrNumber(firstChar) { var res = firstChar; while (isIdOrNumberChar(port.peekChar())) res += port.readChar(); if (isNaN(res)) return new sc_Token(9/*ID*/, res); else return new sc_Token(12/*NUMBER*/, res - 0); }; function skipWhitespaceAndComments() { var done = false; while (!done) { done = true; while (isWhitespace(port.peekChar())) port.readChar(); if (port.peekChar() === ';') { port.readChar(); done = false; while (true) { curChar = port.readChar(); if (curChar === SC_EOF_OBJECT || curChar === '\n') break; } } } }; function readDot() { if (isWhitespace(port.peekChar())) return new sc_Token(10/*DOT*/); else return readIdOrNumber("."); }; function readSharp() { var c = port.readChar(); if (isWhitespace(c)) return new sc_Token(13/*ERROR*/, "bad #-pattern0."); // reference if (isNumberChar(c)) { var nb = c - 0; while (isNumberChar(port.peekChar())) nb = nb*10 + (port.readChar() - 0); switch (port.readChar()) { case '#': return new sc_Token(18/*REFERENCE*/, nb); case '=': return new sc_Token(19/*STORE*/, nb); default: return new sc_Token(13/*ERROR*/, "bad #-pattern1." + nb); } } if (c === "(") return new sc_Token(14/*VECTOR_BEGIN*/); if (c === "\\") { // character var tmp = "" while (!isWhitespaceOrEOF(port.peekChar())) tmp += port.readChar(); switch (tmp.length) { case 0: // it's escaping a whitespace char: if (sc_isEOFObject(port.peekChar)) return new sc_Token(13/*ERROR*/, "bad #-pattern2."); else return new sc_Token(20/*CHAR*/, port.readChar()); case 1: return new sc_Token(20/*CHAR*/, tmp); default: var entry = sc_Char.readable2char[tmp.toLowerCase()]; if (entry) return new sc_Token(20/*CHAR*/, entry); else return new sc_Token(13/*ERROR*/, "unknown character description: #\\" + tmp); } } // some constants (#t, #f, #unspecified) var res; var needing; switch (c) { case 't': res = new sc_Token(15/*TRUE*/, true); needing = ""; break; case 'f': res = new sc_Token(16/*FALSE*/, false); needing = ""; break; case 'u': res = new sc_Token(17/*UNSPECIFIED*/, undefined); needing = "nspecified"; break; default: return new sc_Token(13/*ERROR*/, "bad #-pattern3: " + c); } while(true) { c = port.peekChar(); if ((isWhitespaceOrEOF(c) || c === ')') && needing == "") return res; else if (isWhitespace(c) || needing == "") return new sc_Token(13/*ERROR*/, "bad #-pattern4 " + c + " " + needing); else if (needing.charAt(0) == c) { port.readChar(); // consume needing = needing.slice(1); } else return new sc_Token(13/*ERROR*/, "bad #-pattern5"); } }; skipWhitespaceAndComments(); var curChar = port.readChar(); if (curChar === SC_EOF_OBJECT) return new sc_Token(0/*EOF*/, curChar); switch (curChar) { case " ": case "\n": case "\t": return readWhitespace(); case "(": return new sc_Token(1/*OPEN_PAR*/); case ")": return new sc_Token(2/*CLOSE_PAR*/); case "{": return new sc_Token(3/*OPEN_BRACE*/); case "}": return new sc_Token(4/*CLOSE_BRACE*/); case "[": return new sc_Token(5/*OPEN_BRACKET*/); case "]": return new sc_Token(6/*CLOSE_BRACKET*/); case "'": return new sc_Token(8/*QUOTE*/); case "#": return readSharp(); case ".": return readDot(); case '"': return readString(); default: if (isIdOrNumberChar(curChar)) return readIdOrNumber(curChar); throw "unexpected character: " + curChar; } }; function sc_Reader(tokenizer) { this.tokenizer = tokenizer; this.backref = new Array(); } sc_Reader.prototype.read = function() { function readList(listBeginType) { function matchesPeer(open, close) { return open === 1/*OPEN_PAR*/ && close === 2/*CLOSE_PAR*/ || open === 3/*OPEN_BRACE*/ && close === 4/*CLOSE_BRACE*/ || open === 5/*OPEN_BRACKET*/ && close === 6/*CLOSE_BRACKET*/; }; var res = null; while (true) { var token = tokenizer.peekToken(); switch (token.type) { case 2/*CLOSE_PAR*/: case 4/*CLOSE_BRACE*/: case 6/*CLOSE_BRACKET*/: if (matchesPeer(listBeginType, token.type)) { tokenizer.readToken(); // consume token return sc_reverseBang(res); } else throw "closing par doesn't match: " + listBeginType + " " + listEndType; case 0/*EOF*/: throw "unexpected end of file"; case 10/*DOT*/: tokenizer.readToken(); // consume token var cdr = this.read(); var par = tokenizer.readToken(); if (!matchesPeer(listBeginType, par.type)) throw "closing par doesn't match: " + listBeginType + " " + par.type; else return sc_reverseAppendBang(res, cdr); default: res = sc_cons(this.read(), res); } } }; function readQuote() { return sc_cons("quote", sc_cons(this.read(), null)); }; function readVector() { // opening-parenthesis is already consumed var a = new Array(); while (true) { var token = tokenizer.peekToken(); switch (token.type) { case 2/*CLOSE_PAR*/: tokenizer.readToken(); return a; default: a.push(this.read()); } } }; function storeRefence(nb) { var tmp = this.read(); this.backref[nb] = tmp; return tmp; }; function readReference(nb) { if (nb in this.backref) return this.backref[nb]; else throw "bad reference: " + nb; }; var tokenizer = this.tokenizer; var token = tokenizer.readToken(); // handle error if (token.type === 13/*ERROR*/) throw token.val; switch (token.type) { case 1/*OPEN_PAR*/: case 3/*OPEN_BRACE*/: case 5/*OPEN_BRACKET*/: return readList.call(this, token.type); case 8/*QUOTE*/: return readQuote.call(this); case 11/*STRING*/: return sc_jsstring2string(token.val); case 20/*CHAR*/: return new sc_Char(token.val); case 14/*VECTOR_BEGIN*/: return readVector.call(this); case 18/*REFERENCE*/: return readReference.call(this, token.val); case 19/*STORE*/: return storeRefence.call(this, token.val); case 9/*ID*/: return sc_jsstring2symbol(token.val); case 0/*EOF*/: case 12/*NUMBER*/: case 15/*TRUE*/: case 16/*FALSE*/: case 17/*UNSPECIFIED*/: return token.val; default: throw "unexpected token " + token.type + " " + token.val; } }; /*** META ((export #t)) */ function sc_read(port) { if (port === undefined) // we assume the port hasn't been given. port = SC_DEFAULT_IN; // THREAD: shared var... var reader = new sc_Reader(new sc_Tokenizer(port)); return reader.read(); } /*** META ((export #t)) */ function sc_readChar(port) { if (port === undefined) // we assume the port hasn't been given. port = SC_DEFAULT_IN; // THREAD: shared var... var t = port.readChar(); return t === SC_EOF_OBJECT? t: new sc_Char(t); } /*** META ((export #t)) */ function sc_peekChar(port) { if (port === undefined) // we assume the port hasn't been given. port = SC_DEFAULT_IN; // THREAD: shared var... var t = port.peekChar(); return t === SC_EOF_OBJECT? t: new sc_Char(t); } /*** META ((export #t) (type bool)) */ function sc_isCharReady(port) { if (port === undefined) // we assume the port hasn't been given. port = SC_DEFAULT_IN; // THREAD: shared var... return port.isCharReady(); } /*** META ((export #t) (peephole (postfix ".close()"))) */ function sc_closeInputPort(p) { return p.close(); } /*** META ((export #t) (type bool) (peephole (postfix " instanceof sc_InputPort"))) */ function sc_isInputPort(o) { return (o instanceof sc_InputPort); } /*** META ((export eof-object?) (type bool) (peephole (postfix " === SC_EOF_OBJECT"))) */ function sc_isEOFObject(o) { return o === SC_EOF_OBJECT; } /*** META ((export #t) (peephole (hole 0 "SC_DEFAULT_IN"))) */ function sc_currentInputPort() { return SC_DEFAULT_IN; } /* ------------ file operations are not supported -----------*/ /*** META ((export #t)) */ function sc_callWithInputFile(s, proc) { throw "can't open " + s; } /*** META ((export #t)) */ function sc_callWithOutputFile(s, proc) { throw "can't open " + s; } /*** META ((export #t)) */ function sc_withInputFromFile(s, thunk) { throw "can't open " + s; } /*** META ((export #t)) */ function sc_withOutputToFile(s, thunk) { throw "can't open " + s; } /*** META ((export #t)) */ function sc_openInputFile(s) { throw "can't open " + s; } /*** META ((export #t)) */ function sc_openOutputFile(s) { throw "can't open " + s; } /* ----------------------------------------------------------------------------*/ /*** META ((export #t)) */ function sc_basename(p) { var i = p.lastIndexOf('/'); if(i >= 0) return p.substring(i + 1, p.length); else return ''; } /*** META ((export #t)) */ function sc_dirname(p) { var i = p.lastIndexOf('/'); if(i >= 0) return p.substring(0, i); else return ''; } /* ----------------------------------------------------------------------------*/ /*** META ((export #t)) */ function sc_withInputFromPort(p, thunk) { try { var tmp = SC_DEFAULT_IN; // THREAD: shared var. SC_DEFAULT_IN = p; return thunk(); } finally { SC_DEFAULT_IN = tmp; } } /*** META ((export #t)) */ function sc_withInputFromString(s, thunk) { return sc_withInputFromPort(new sc_StringInputPort(sc_string2jsstring(s)), thunk); } /*** META ((export #t)) */ function sc_withOutputToPort(p, thunk) { try { var tmp = SC_DEFAULT_OUT; // THREAD: shared var. SC_DEFAULT_OUT = p; return thunk(); } finally { SC_DEFAULT_OUT = tmp; } } /*** META ((export #t)) */ function sc_withOutputToString(thunk) { var p = new sc_StringOutputPort(); sc_withOutputToPort(p, thunk); return p.close(); } /*** META ((export #t)) */ function sc_withOutputToProcedure(proc, thunk) { var t = function(s) { proc(sc_jsstring2string(s)); }; return sc_withOutputToPort(new sc_GenericOutputPort(t), thunk); } /*** META ((export #t) (peephole (hole 0 "new sc_StringOutputPort()"))) */ function sc_openOutputString() { return new sc_StringOutputPort(); } /*** META ((export #t)) */ function sc_openInputString(str) { return new sc_StringInputPort(sc_string2jsstring(str)); } /* ----------------------------------------------------------------------------*/ function sc_OutputPort() { } sc_OutputPort.prototype = new sc_Port(); sc_OutputPort.prototype.appendJSString = function(obj) { /* do nothing */ } sc_OutputPort.prototype.close = function() { /* do nothing */ } function sc_StringOutputPort() { this.res = ""; } sc_StringOutputPort.prototype = new sc_OutputPort(); sc_StringOutputPort.prototype.appendJSString = function(s) { this.res += s; } sc_StringOutputPort.prototype.close = function() { return sc_jsstring2string(this.res); } /*** META ((export #t)) */ function sc_getOutputString(sp) { return sc_jsstring2string(sp.res); } function sc_ErrorOutputPort() { } sc_ErrorOutputPort.prototype = new sc_OutputPort(); sc_ErrorOutputPort.prototype.appendJSString = function(s) { throw "don't write on ErrorPort!"; } sc_ErrorOutputPort.prototype.close = function() { /* do nothing */ } function sc_GenericOutputPort(appendJSString, close) { this.appendJSString = appendJSString; if (close) this.close = close; } sc_GenericOutputPort.prototype = new sc_OutputPort(); /*** META ((export #t) (type bool) (peephole (postfix " instanceof sc_OutputPort"))) */ function sc_isOutputPort(o) { return (o instanceof sc_OutputPort); } /*** META ((export #t) (peephole (postfix ".close()"))) */ function sc_closeOutputPort(p) { return p.close(); } /* ------------------ write ---------------------------------------------------*/ /*** META ((export #t)) */ function sc_write(o, p) { if (p === undefined) // we assume not given p = SC_DEFAULT_OUT; p.appendJSString(sc_toWriteString(o)); } function sc_toWriteString(o) { if (o === null) return "()"; else if (o === true) return "#t"; else if (o === false) return "#f"; else if (o === undefined) return "#unspecified"; else if (typeof o === 'function') return "#"; else if (o.sc_toWriteString) return o.sc_toWriteString(); else return o.toString(); } function sc_escapeWriteString(s) { var res = ""; var j = 0; for (i = 0; i < s.length; i++) { switch (s.charAt(i)) { case "\0": res += s.substring(j, i) + "\\0"; j = i + 1; break; case "\b": res += s.substring(j, i) + "\\b"; j = i + 1; break; case "\f": res += s.substring(j, i) + "\\f"; j = i + 1; break; case "\n": res += s.substring(j, i) + "\\n"; j = i + 1; break; case "\r": res += s.substring(j, i) + "\\r"; j = i + 1; break; case "\t": res += s.substring(j, i) + "\\t"; j = i + 1; break; case "\v": res += s.substring(j, i) + "\\v"; j = i + 1; break; case '"': res += s.substring(j, i) + '\\"'; j = i + 1; break; case "\\": res += s.substring(j, i) + "\\\\"; j = i + 1; break; default: var c = s.charAt(i); if ("\a" !== "a" && c == "\a") { res += s.substring(j, i) + "\\a"; j = i + 1; continue; } if ("\v" !== "v" && c == "\v") { res += s.substring(j, i) + "\\v"; j = i + 1; continue; } //if (s.charAt(i) < ' ' || s.charCodeAt(i) > 127) { // CARE: Manuel is this OK with HOP? if (s.charAt(i) < ' ') { /* non printable character and special chars */ res += s.substring(j, i) + "\\x" + s.charCodeAt(i).toString(16); j = i + 1; } // else just let i increase... } } res += s.substring(j, i); return res; } /* ------------------ display ---------------------------------------------------*/ /*** META ((export #t)) */ function sc_display(o, p) { if (p === undefined) // we assume not given p = SC_DEFAULT_OUT; p.appendJSString(sc_toDisplayString(o)); } function sc_toDisplayString(o) { if (o === null) return "()"; else if (o === true) return "#t"; else if (o === false) return "#f"; else if (o === undefined) return "#unspecified"; else if (typeof o === 'function') return "#"; else if (o.sc_toDisplayString) return o.sc_toDisplayString(); else return o.toString(); } /* ------------------ newline ---------------------------------------------------*/ /*** META ((export #t)) */ function sc_newline(p) { if (p === undefined) // we assume not given p = SC_DEFAULT_OUT; p.appendJSString("\n"); } /* ------------------ write-char ---------------------------------------------------*/ /*** META ((export #t)) */ function sc_writeChar(c, p) { if (p === undefined) // we assume not given p = SC_DEFAULT_OUT; p.appendJSString(c.val); } /* ------------------ write-circle ---------------------------------------------------*/ /*** META ((export #t)) */ function sc_writeCircle(o, p) { if (p === undefined) // we assume not given p = SC_DEFAULT_OUT; p.appendJSString(sc_toWriteCircleString(o)); } function sc_toWriteCircleString(o) { var symb = sc_gensym("writeCircle"); var nbPointer = new Object(); nbPointer.nb = 0; sc_prepWriteCircle(o, symb, nbPointer); return sc_genToWriteCircleString(o, symb); } function sc_prepWriteCircle(o, symb, nbPointer) { // TODO sc_Struct if (o instanceof sc_Pair || o instanceof sc_Vector) { if (o[symb] !== undefined) { // not the first visit. o[symb]++; // unless there is already a number, assign one. if (!o[symb + "nb"]) o[symb + "nb"] = nbPointer.nb++; return; } o[symb] = 0; if (o instanceof sc_Pair) { sc_prepWriteCircle(o.car, symb, nbPointer); sc_prepWriteCircle(o.cdr, symb, nbPointer); } else { for (var i = 0; i < o.length; i++) sc_prepWriteCircle(o[i], symb, nbPointer); } } } function sc_genToWriteCircleString(o, symb) { if (!(o instanceof sc_Pair || o instanceof sc_Vector)) return sc_toWriteString(o); return o.sc_toWriteCircleString(symb); } sc_Pair.prototype.sc_toWriteCircleString = function(symb, inList) { if (this[symb + "use"]) { // use-flag is set. Just use it. var nb = this[symb + "nb"]; if (this[symb]-- === 0) { // if we are the last use. remove all fields. delete this[symb]; delete this[symb + "nb"]; delete this[symb + "use"]; } if (inList) return '. #' + nb + '#'; else return '#' + nb + '#'; } if (this[symb]-- === 0) { // if we are the last use. remove all fields. delete this[symb]; delete this[symb + "nb"]; delete this[symb + "use"]; } var res = ""; if (this[symb] !== undefined) { // implies > 0 this[symb + "use"] = true; if (inList) res += '. #' + this[symb + "nb"] + '='; else res += '#' + this[symb + "nb"] + '='; inList = false; } if (!inList) res += "("; // print car res += sc_genToWriteCircleString(this.car, symb); if (sc_isPair(this.cdr)) { res += " " + this.cdr.sc_toWriteCircleString(symb, true); } else if (this.cdr !== null) { res += " . " + sc_genToWriteCircleString(this.cdr, symb); } if (!inList) res += ")"; return res; }; sc_Vector.prototype.sc_toWriteCircleString = function(symb) { if (this[symb + "use"]) { // use-flag is set. Just use it. var nb = this[symb + "nb"]; if (this[symb]-- === 0) { // if we are the last use. remove all fields. delete this[symb]; delete this[symb + "nb"]; delete this[symb + "use"]; } return '#' + nb + '#'; } if (this[symb]-- === 0) { // if we are the last use. remove all fields. delete this[symb]; delete this[symb + "nb"]; delete this[symb + "use"]; } var res = ""; if (this[symb] !== undefined) { // implies > 0 this[symb + "use"] = true; res += '#' + this[symb + "nb"] + '='; } res += "#("; for (var i = 0; i < this.length; i++) { res += sc_genToWriteCircleString(this[i], symb); if (i < this.length - 1) res += " "; } res += ")"; return res; }; /* ------------------ print ---------------------------------------------------*/ /*** META ((export #t)) */ function sc_print(s) { if (arguments.length === 1) { sc_display(s); sc_newline(); } else { for (var i = 0; i < arguments.length; i++) sc_display(arguments[i]); sc_newline(); } } /* ------------------ format ---------------------------------------------------*/ /*** META ((export #t)) */ function sc_format(s, args) { var len = s.length; var p = new sc_StringOutputPort(); var i = 0, j = 1; while( i < len ) { var i2 = s.indexOf("~", i); if (i2 == -1) { p.appendJSString( s.substring( i, len ) ); return p.close(); } else { if (i2 > i) { if (i2 == (len - 1)) { p.appendJSString(s.substring(i, len)); return p.close(); } else { p.appendJSString(s.substring(i, i2)); i = i2; } } switch(s.charCodeAt(i2 + 1)) { case 65: case 97: // a sc_display(arguments[j], p); i += 2; j++; break; case 83: case 115: // s sc_write(arguments[j], p); i += 2; j++; break; case 86: case 118: // v sc_display(arguments[j], p); p.appendJSString("\n"); i += 2; j++; break; case 67: case 99: // c p.appendJSString(String.fromCharCode(arguments[j])); i += 2; j++; break; case 88: case 120: // x p.appendJSString(arguments[j].toString(6)); i += 2; j++; break; case 79: case 111: // o p.appendJSString(arguments[j].toString(8)); i += 2; j++; break; case 66: case 98: // b p.appendJSString(arguments[j].toString(2)); i += 2; j++; break; case 37: case 110: // %, n p.appendJSString("\n"); i += 2; break; case 114: // r p.appendJSString("\r"); i += 2; break; case 126: // ~ p.appendJSString("~"); i += 2; break; default: sc_error( "format: illegal ~" + String.fromCharCode(s.charCodeAt(i2 + 1)) + " sequence" ); return ""; } } } return p.close(); } /* ------------------ global ports ---------------------------------------------------*/ var SC_DEFAULT_IN = new sc_ErrorInputPort(); var SC_DEFAULT_OUT = new sc_ErrorOutputPort(); var SC_ERROR_OUT = new sc_ErrorOutputPort(); var sc_SYMBOL_PREFIX = "\u1E9C"; var sc_KEYWORD_PREFIX = "\u1E9D"; /*** META ((export #t) (peephole (id))) */ function sc_jsstring2string(s) { return s; } /*** META ((export #t) (peephole (prefix "'\\u1E9C' +"))) */ function sc_jsstring2symbol(s) { return sc_SYMBOL_PREFIX + s; } /*** META ((export #t) (peephole (id))) */ function sc_string2jsstring(s) { return s; } /*** META ((export #t) (peephole (symbol2jsstring_immutable))) */ function sc_symbol2jsstring(s) { return s.slice(1); } /*** META ((export #t) (peephole (postfix ".slice(1)"))) */ function sc_keyword2jsstring(k) { return k.slice(1); } /*** META ((export #t) (peephole (prefix "'\\u1E9D' +"))) */ function sc_jsstring2keyword(s) { return sc_KEYWORD_PREFIX + s; } /*** META ((export #t) (type bool)) */ function sc_isKeyword(s) { return (typeof s === "string") && (s.charAt(0) === sc_KEYWORD_PREFIX); } /*** META ((export #t)) */ var sc_gensym = function() { var counter = 1000; return function(sym) { counter++; if (!sym) sym = sc_SYMBOL_PREFIX; return sym + "s" + counter + "~" + "^sC-GeNsYm "; }; }(); /*** META ((export #t) (type bool)) */ function sc_isEqual(o1, o2) { return ((o1 === o2) || (sc_isPair(o1) && sc_isPair(o2) && sc_isPairEqual(o1, o2, sc_isEqual)) || (sc_isVector(o1) && sc_isVector(o2) && sc_isVectorEqual(o1, o2, sc_isEqual))); } /*** META ((export number->symbol integer->symbol)) */ function sc_number2symbol(x, radix) { return sc_SYMBOL_PREFIX + sc_number2jsstring(x, radix); } /*** META ((export number->string integer->string)) */ var sc_number2string = sc_number2jsstring; /*** META ((export #t)) */ function sc_symbol2number(s, radix) { return sc_jsstring2number(s.slice(1), radix); } /*** META ((export #t)) */ var sc_string2number = sc_jsstring2number; /*** META ((export #t) (peephole (prefix "+" s))) ;; peephole will only apply if no radix is given. */ function sc_string2integer(s, radix) { if (!radix) return +s; return parseInt(s, radix); } /*** META ((export #t) (peephole (prefix "+"))) */ function sc_string2real(s) { return +s; } /*** META ((export #t) (type bool)) */ function sc_isSymbol(s) { return (typeof s === "string") && (s.charAt(0) === sc_SYMBOL_PREFIX); } /*** META ((export #t) (peephole (symbol2string_immutable))) */ function sc_symbol2string(s) { return s.slice(1); } /*** META ((export #t) (peephole (prefix "'\\u1E9C' +"))) */ function sc_string2symbol(s) { return sc_SYMBOL_PREFIX + s; } /*** META ((export symbol-append) (peephole (symbolAppend_immutable))) */ function sc_symbolAppend() { var res = sc_SYMBOL_PREFIX; for (var i = 0; i < arguments.length; i++) res += arguments[i].slice(1); return res; } /*** META ((export #t) (peephole (postfix ".val"))) */ function sc_char2string(c) { return c.val; } /*** META ((export #t) (peephole (hole 1 "'\\u1E9C' + " c ".val"))) */ function sc_char2symbol(c) { return sc_SYMBOL_PREFIX + c.val; } /*** META ((export #t) (type bool)) */ function sc_isString(s) { return (typeof s === "string") && (s.charAt(0) !== sc_SYMBOL_PREFIX); } /*** META ((export #t)) */ var sc_makeString = sc_makejsString; /*** META ((export #t)) */ function sc_string() { for (var i = 0; i < arguments.length; i++) arguments[i] = arguments[i].val; return "".concat.apply("", arguments); } /*** META ((export #t) (peephole (postfix ".length"))) */ function sc_stringLength(s) { return s.length; } /*** META ((export #t)) */ function sc_stringRef(s, k) { return new sc_Char(s.charAt(k)); } /* there's no stringSet in the immutable version function sc_stringSet(s, k, c) */ /*** META ((export string=?) (type bool) (peephole (hole 2 str1 " === " str2))) */ function sc_isStringEqual(s1, s2) { return s1 === s2; } /*** META ((export string?) (type bool) (peephole (hole 2 str1 " > " str2))) */ function sc_isStringGreater(s1, s2) { return s1 > s2; } /*** META ((export string<=?) (type bool) (peephole (hole 2 str1 " <= " str2))) */ function sc_isStringLessEqual(s1, s2) { return s1 <= s2; } /*** META ((export string>=?) (type bool) (peephole (hole 2 str1 " >= " str2))) */ function sc_isStringGreaterEqual(s1, s2) { return s1 >= s2; } /*** META ((export string-ci=?) (type bool) (peephole (hole 2 str1 ".toLowerCase() === " str2 ".toLowerCase()"))) */ function sc_isStringCIEqual(s1, s2) { return s1.toLowerCase() === s2.toLowerCase(); } /*** META ((export string-ci?) (type bool) (peephole (hole 2 str1 ".toLowerCase() > " str2 ".toLowerCase()"))) */ function sc_isStringCIGreater(s1, s2) { return s1.toLowerCase() > s2.toLowerCase(); } /*** META ((export string-ci<=?) (type bool) (peephole (hole 2 str1 ".toLowerCase() <= " str2 ".toLowerCase()"))) */ function sc_isStringCILessEqual(s1, s2) { return s1.toLowerCase() <= s2.toLowerCase(); } /*** META ((export string-ci>=?) (type bool) (peephole (hole 2 str1 ".toLowerCase() >= " str2 ".toLowerCase()"))) */ function sc_isStringCIGreaterEqual(s1, s2) { return s1.toLowerCase() >= s2.toLowerCase(); } /*** META ((export #t) (peephole (hole 3 s ".substring(" start ", " end ")"))) */ function sc_substring(s, start, end) { return s.substring(start, end); } /*** META ((export #t)) */ function sc_isSubstring_at(s1, s2, i) { return s2 == s1.substring(i, i+ s2.length); } /*** META ((export #t) (peephole (infix 0 #f "+" "''"))) */ function sc_stringAppend() { return "".concat.apply("", arguments); } /*** META ((export #t)) */ var sc_string2list = sc_jsstring2list; /*** META ((export #t)) */ var sc_list2string = sc_list2jsstring; /*** META ((export #t) (peephole (id))) */ function sc_stringCopy(s) { return s; } /* there's no string-fill in the immutable version function sc_stringFill(s, c) */ /*** META ((export #t) (peephole (postfix ".slice(1)"))) */ function sc_keyword2string(o) { return o.slice(1); } /*** META ((export #t) (peephole (prefix "'\\u1E9D' +"))) */ function sc_string2keyword(o) { return sc_KEYWORD_PREFIX + o; } String.prototype.sc_toDisplayString = function() { if (this.charAt(0) === sc_SYMBOL_PREFIX) // TODO: care for symbols with spaces (escape-chars symbols). return this.slice(1); else if (this.charAt(0) === sc_KEYWORD_PREFIX) return ":" + this.slice(1); else return this.toString(); }; String.prototype.sc_toWriteString = function() { if (this.charAt(0) === sc_SYMBOL_PREFIX) // TODO: care for symbols with spaces (escape-chars symbols). return this.slice(1); else if (this.charAt(0) === sc_KEYWORD_PREFIX) return ":" + this.slice(1); else return '"' + sc_escapeWriteString(this) + '"'; }; /* Exported Variables */ var BgL_testzd2boyerzd2; var BgL_nboyerzd2benchmarkzd2; var BgL_setupzd2boyerzd2; /* End Exports */ var translate_term_nboyer; var translate_args_nboyer; var untranslate_term_nboyer; var BgL_sc_symbolzd2ze3symbolzd2record_1ze3_nboyer; var BgL_sc_za2symbolzd2recordszd2alistza2_2z00_nboyer; var translate_alist_nboyer; var apply_subst_nboyer; var apply_subst_lst_nboyer; var tautologyp_nboyer; var if_constructor_nboyer; var rewrite_count_nboyer; var rewrite_nboyer; var rewrite_args_nboyer; var unify_subst_nboyer; var one_way_unify1_nboyer; var false_term_nboyer; var true_term_nboyer; var trans_of_implies1_nboyer; var is_term_equal_nboyer; var is_term_member_nboyer; var const_nboyer; var sc_const_3_nboyer; var sc_const_4_nboyer; { (sc_const_4_nboyer = (new sc_Pair("\u1E9Cimplies",(new sc_Pair((new sc_Pair("\u1E9Cand",(new sc_Pair((new sc_Pair("\u1E9Cimplies",(new sc_Pair("\u1E9Cx",(new sc_Pair("\u1E9Cy",null)))))),(new sc_Pair((new sc_Pair("\u1E9Cand",(new sc_Pair((new sc_Pair("\u1E9Cimplies",(new sc_Pair("\u1E9Cy",(new sc_Pair("\u1E9Cz",null)))))),(new sc_Pair((new sc_Pair("\u1E9Cand",(new sc_Pair((new sc_Pair("\u1E9Cimplies",(new sc_Pair("\u1E9Cz",(new sc_Pair("\u1E9Cu",null)))))),(new sc_Pair((new sc_Pair("\u1E9Cimplies",(new sc_Pair("\u1E9Cu",(new sc_Pair("\u1E9Cw",null)))))),null)))))),null)))))),null)))))),(new sc_Pair((new sc_Pair("\u1E9Cimplies",(new sc_Pair("\u1E9Cx",(new sc_Pair("\u1E9Cw",null)))))),null))))))); (sc_const_3_nboyer = sc_list((new sc_Pair("\u1E9Cequal",(new sc_Pair((new sc_Pair("\u1E9Ccompile",(new sc_Pair("\u1E9Cform",null)))),(new sc_Pair((new sc_Pair("\u1E9Creverse",(new sc_Pair((new sc_Pair("\u1E9Ccodegen",(new sc_Pair((new sc_Pair("\u1E9Coptimize",(new sc_Pair("\u1E9Cform",null)))),(new sc_Pair((new sc_Pair("\u1E9Cnil",null)),null)))))),null)))),null)))))), (new sc_Pair("\u1E9Cequal",(new sc_Pair((new sc_Pair("\u1E9Ceqp",(new sc_Pair("\u1E9Cx",(new sc_Pair("\u1E9Cy",null)))))),(new sc_Pair((new sc_Pair("\u1E9Cequal",(new sc_Pair((new sc_Pair("\u1E9Cfix",(new sc_Pair("\u1E9Cx",null)))),(new sc_Pair((new sc_Pair("\u1E9Cfix",(new sc_Pair("\u1E9Cy",null)))),null)))))),null)))))), (new sc_Pair("\u1E9Cequal",(new sc_Pair((new sc_Pair("\u1E9Cgreaterp",(new sc_Pair("\u1E9Cx",(new sc_Pair("\u1E9Cy",null)))))),(new sc_Pair((new sc_Pair("\u1E9Clessp",(new sc_Pair("\u1E9Cy",(new sc_Pair("\u1E9Cx",null)))))),null)))))), (new sc_Pair("\u1E9Cequal",(new sc_Pair((new sc_Pair("\u1E9Clesseqp",(new sc_Pair("\u1E9Cx",(new sc_Pair("\u1E9Cy",null)))))),(new sc_Pair((new sc_Pair("\u1E9Cnot",(new sc_Pair((new sc_Pair("\u1E9Clessp",(new sc_Pair("\u1E9Cy",(new sc_Pair("\u1E9Cx",null)))))),null)))),null)))))), (new sc_Pair("\u1E9Cequal",(new sc_Pair((new sc_Pair("\u1E9Cgreatereqp",(new sc_Pair("\u1E9Cx",(new sc_Pair("\u1E9Cy",null)))))),(new sc_Pair((new sc_Pair("\u1E9Cnot",(new sc_Pair((new sc_Pair("\u1E9Clessp",(new sc_Pair("\u1E9Cx",(new sc_Pair("\u1E9Cy",null)))))),null)))),null)))))), (new sc_Pair("\u1E9Cequal",(new sc_Pair((new sc_Pair("\u1E9Cboolean",(new sc_Pair("\u1E9Cx",null)))),(new sc_Pair((new sc_Pair("\u1E9Cor",(new sc_Pair((new sc_Pair("\u1E9Cequal",(new sc_Pair("\u1E9Cx",(new sc_Pair((new sc_Pair("\u1E9Ct",null)),null)))))),(new sc_Pair((new sc_Pair("\u1E9Cequal",(new sc_Pair("\u1E9Cx",(new sc_Pair((new sc_Pair("\u1E9Cf",null)),null)))))),null)))))),null)))))), (new sc_Pair("\u1E9Cequal",(new sc_Pair((new sc_Pair("\u1E9Ciff",(new sc_Pair("\u1E9Cx",(new sc_Pair("\u1E9Cy",null)))))),(new sc_Pair((new sc_Pair("\u1E9Cand",(new sc_Pair((new sc_Pair("\u1E9Cimplies",(new sc_Pair("\u1E9Cx",(new sc_Pair("\u1E9Cy",null)))))),(new sc_Pair((new sc_Pair("\u1E9Cimplies",(new sc_Pair("\u1E9Cy",(new sc_Pair("\u1E9Cx",null)))))),null)))))),null)))))), (new sc_Pair("\u1E9Cequal",(new sc_Pair((new sc_Pair("\u1E9Ceven1",(new sc_Pair("\u1E9Cx",null)))),(new sc_Pair((new sc_Pair("\u1E9Cif",(new sc_Pair((new sc_Pair("\u1E9Czerop",(new sc_Pair("\u1E9Cx",null)))),(new sc_Pair((new sc_Pair("\u1E9Ct",null)),(new sc_Pair((new sc_Pair("\u1E9Codd",(new sc_Pair((new sc_Pair("\u1E9Csub1",(new sc_Pair("\u1E9Cx",null)))),null)))),null)))))))),null)))))), (new sc_Pair("\u1E9Cequal",(new sc_Pair((new sc_Pair("\u1E9Ccountps-",(new sc_Pair("\u1E9Cl",(new sc_Pair("\u1E9Cpred",null)))))),(new sc_Pair((new sc_Pair("\u1E9Ccountps-loop",(new sc_Pair("\u1E9Cl",(new sc_Pair("\u1E9Cpred",(new sc_Pair((new sc_Pair("\u1E9Czero",null)),null)))))))),null)))))), (new sc_Pair("\u1E9Cequal",(new sc_Pair((new sc_Pair("\u1E9Cfact-",(new sc_Pair("\u1E9Ci",null)))),(new sc_Pair((new sc_Pair("\u1E9Cfact-loop",(new sc_Pair("\u1E9Ci",(new sc_Pair((1),null)))))),null)))))), (new sc_Pair("\u1E9Cequal",(new sc_Pair((new sc_Pair("\u1E9Creverse-",(new sc_Pair("\u1E9Cx",null)))),(new sc_Pair((new sc_Pair("\u1E9Creverse-loop",(new sc_Pair("\u1E9Cx",(new sc_Pair((new sc_Pair("\u1E9Cnil",null)),null)))))),null)))))), (new sc_Pair("\u1E9Cequal",(new sc_Pair((new sc_Pair("\u1E9Cdivides",(new sc_Pair("\u1E9Cx",(new sc_Pair("\u1E9Cy",null)))))),(new sc_Pair((new sc_Pair("\u1E9Czerop",(new sc_Pair((new sc_Pair("\u1E9Cremainder",(new sc_Pair("\u1E9Cy",(new sc_Pair("\u1E9Cx",null)))))),null)))),null)))))), (new sc_Pair("\u1E9Cequal",(new sc_Pair((new sc_Pair("\u1E9Cassume-true",(new sc_Pair("\u1E9Cvar",(new sc_Pair("\u1E9Calist",null)))))),(new sc_Pair((new sc_Pair("\u1E9Ccons",(new sc_Pair((new sc_Pair("\u1E9Ccons",(new sc_Pair("\u1E9Cvar",(new sc_Pair((new sc_Pair("\u1E9Ct",null)),null)))))),(new sc_Pair("\u1E9Calist",null)))))),null)))))), (new sc_Pair("\u1E9Cequal",(new sc_Pair((new sc_Pair("\u1E9Cassume-false",(new sc_Pair("\u1E9Cvar",(new sc_Pair("\u1E9Calist",null)))))),(new sc_Pair((new sc_Pair("\u1E9Ccons",(new sc_Pair((new sc_Pair("\u1E9Ccons",(new sc_Pair("\u1E9Cvar",(new sc_Pair((new sc_Pair("\u1E9Cf",null)),null)))))),(new sc_Pair("\u1E9Calist",null)))))),null)))))), (new sc_Pair("\u1E9Cequal",(new sc_Pair((new sc_Pair("\u1E9Ctautology-checker",(new sc_Pair("\u1E9Cx",null)))),(new sc_Pair((new sc_Pair("\u1E9Ctautologyp",(new sc_Pair((new sc_Pair("\u1E9Cnormalize",(new sc_Pair("\u1E9Cx",null)))),(new sc_Pair((new sc_Pair("\u1E9Cnil",null)),null)))))),null)))))), (new sc_Pair("\u1E9Cequal",(new sc_Pair((new sc_Pair("\u1E9Cfalsify",(new sc_Pair("\u1E9Cx",null)))),(new sc_Pair((new sc_Pair("\u1E9Cfalsify1",(new sc_Pair((new sc_Pair("\u1E9Cnormalize",(new sc_Pair("\u1E9Cx",null)))),(new sc_Pair((new sc_Pair("\u1E9Cnil",null)),null)))))),null)))))), (new sc_Pair("\u1E9Cequal",(new sc_Pair((new sc_Pair("\u1E9Cprime",(new sc_Pair("\u1E9Cx",null)))),(new sc_Pair((new sc_Pair("\u1E9Cand",(new sc_Pair((new sc_Pair("\u1E9Cnot",(new sc_Pair((new sc_Pair("\u1E9Czerop",(new sc_Pair("\u1E9Cx",null)))),null)))),(new sc_Pair((new sc_Pair("\u1E9Cnot",(new sc_Pair((new sc_Pair("\u1E9Cequal",(new sc_Pair("\u1E9Cx",(new sc_Pair((new sc_Pair("\u1E9Cadd1",(new sc_Pair((new sc_Pair("\u1E9Czero",null)),null)))),null)))))),null)))),(new sc_Pair((new sc_Pair("\u1E9Cprime1",(new sc_Pair("\u1E9Cx",(new sc_Pair((new sc_Pair("\u1E9Csub1",(new sc_Pair("\u1E9Cx",null)))),null)))))),null)))))))),null)))))), (new sc_Pair("\u1E9Cequal",(new sc_Pair((new sc_Pair("\u1E9Cand",(new sc_Pair("\u1E9Cp",(new sc_Pair("\u1E9Cq",null)))))),(new sc_Pair((new sc_Pair("\u1E9Cif",(new sc_Pair("\u1E9Cp",(new sc_Pair((new sc_Pair("\u1E9Cif",(new sc_Pair("\u1E9Cq",(new sc_Pair((new sc_Pair("\u1E9Ct",null)),(new sc_Pair((new sc_Pair("\u1E9Cf",null)),null)))))))),(new sc_Pair((new sc_Pair("\u1E9Cf",null)),null)))))))),null)))))), (new sc_Pair("\u1E9Cequal",(new sc_Pair((new sc_Pair("\u1E9Cor",(new sc_Pair("\u1E9Cp",(new sc_Pair("\u1E9Cq",null)))))),(new sc_Pair((new sc_Pair("\u1E9Cif",(new sc_Pair("\u1E9Cp",(new sc_Pair((new sc_Pair("\u1E9Ct",null)),(new sc_Pair((new sc_Pair("\u1E9Cif",(new sc_Pair("\u1E9Cq",(new sc_Pair((new sc_Pair("\u1E9Ct",null)),(new sc_Pair((new sc_Pair("\u1E9Cf",null)),null)))))))),null)))))))),null)))))), (new sc_Pair("\u1E9Cequal",(new sc_Pair((new sc_Pair("\u1E9Cnot",(new sc_Pair("\u1E9Cp",null)))),(new sc_Pair((new sc_Pair("\u1E9Cif",(new sc_Pair("\u1E9Cp",(new sc_Pair((new sc_Pair("\u1E9Cf",null)),(new sc_Pair((new sc_Pair("\u1E9Ct",null)),null)))))))),null)))))), (new sc_Pair("\u1E9Cequal",(new sc_Pair((new sc_Pair("\u1E9Cimplies",(new sc_Pair("\u1E9Cp",(new sc_Pair("\u1E9Cq",null)))))),(new sc_Pair((new sc_Pair("\u1E9Cif",(new sc_Pair("\u1E9Cp",(new sc_Pair((new sc_Pair("\u1E9Cif",(new sc_Pair("\u1E9Cq",(new sc_Pair((new sc_Pair("\u1E9Ct",null)),(new sc_Pair((new sc_Pair("\u1E9Cf",null)),null)))))))),(new sc_Pair((new sc_Pair("\u1E9Ct",null)),null)))))))),null)))))), (new sc_Pair("\u1E9Cequal",(new sc_Pair((new sc_Pair("\u1E9Cfix",(new sc_Pair("\u1E9Cx",null)))),(new sc_Pair((new sc_Pair("\u1E9Cif",(new sc_Pair((new sc_Pair("\u1E9Cnumberp",(new sc_Pair("\u1E9Cx",null)))),(new sc_Pair("\u1E9Cx",(new sc_Pair((new sc_Pair("\u1E9Czero",null)),null)))))))),null)))))), (new sc_Pair("\u1E9Cequal",(new sc_Pair((new sc_Pair("\u1E9Cif",(new sc_Pair((new sc_Pair("\u1E9Cif",(new sc_Pair("\u1E9Ca",(new sc_Pair("\u1E9Cb",(new sc_Pair("\u1E9Cc",null)))))))),(new sc_Pair("\u1E9Cd",(new sc_Pair("\u1E9Ce",null)))))))),(new sc_Pair((new sc_Pair("\u1E9Cif",(new sc_Pair("\u1E9Ca",(new sc_Pair((new sc_Pair("\u1E9Cif",(new sc_Pair("\u1E9Cb",(new sc_Pair("\u1E9Cd",(new sc_Pair("\u1E9Ce",null)))))))),(new sc_Pair((new sc_Pair("\u1E9Cif",(new sc_Pair("\u1E9Cc",(new sc_Pair("\u1E9Cd",(new sc_Pair("\u1E9Ce",null)))))))),null)))))))),null)))))), (new sc_Pair("\u1E9Cequal",(new sc_Pair((new sc_Pair("\u1E9Czerop",(new sc_Pair("\u1E9Cx",null)))),(new sc_Pair((new sc_Pair("\u1E9Cor",(new sc_Pair((new sc_Pair("\u1E9Cequal",(new sc_Pair("\u1E9Cx",(new sc_Pair((new sc_Pair("\u1E9Czero",null)),null)))))),(new sc_Pair((new sc_Pair("\u1E9Cnot",(new sc_Pair((new sc_Pair("\u1E9Cnumberp",(new sc_Pair("\u1E9Cx",null)))),null)))),null)))))),null)))))), (new sc_Pair("\u1E9Cequal",(new sc_Pair((new sc_Pair("\u1E9Cplus",(new sc_Pair((new sc_Pair("\u1E9Cplus",(new sc_Pair("\u1E9Cx",(new sc_Pair("\u1E9Cy",null)))))),(new sc_Pair("\u1E9Cz",null)))))),(new sc_Pair((new sc_Pair("\u1E9Cplus",(new sc_Pair("\u1E9Cx",(new sc_Pair((new sc_Pair("\u1E9Cplus",(new sc_Pair("\u1E9Cy",(new sc_Pair("\u1E9Cz",null)))))),null)))))),null)))))), (new sc_Pair("\u1E9Cequal",(new sc_Pair((new sc_Pair("\u1E9Cequal",(new sc_Pair((new sc_Pair("\u1E9Cplus",(new sc_Pair("\u1E9Ca",(new sc_Pair("\u1E9Cb",null)))))),(new sc_Pair((new sc_Pair("\u1E9Czero",null)),null)))))),(new sc_Pair((new sc_Pair("\u1E9Cand",(new sc_Pair((new sc_Pair("\u1E9Czerop",(new sc_Pair("\u1E9Ca",null)))),(new sc_Pair((new sc_Pair("\u1E9Czerop",(new sc_Pair("\u1E9Cb",null)))),null)))))),null)))))), (new sc_Pair("\u1E9Cequal",(new sc_Pair((new sc_Pair("\u1E9Cdifference",(new sc_Pair("\u1E9Cx",(new sc_Pair("\u1E9Cx",null)))))),(new sc_Pair((new sc_Pair("\u1E9Czero",null)),null)))))), (new sc_Pair("\u1E9Cequal",(new sc_Pair((new sc_Pair("\u1E9Cequal",(new sc_Pair((new sc_Pair("\u1E9Cplus",(new sc_Pair("\u1E9Ca",(new sc_Pair("\u1E9Cb",null)))))),(new sc_Pair((new sc_Pair("\u1E9Cplus",(new sc_Pair("\u1E9Ca",(new sc_Pair("\u1E9Cc",null)))))),null)))))),(new sc_Pair((new sc_Pair("\u1E9Cequal",(new sc_Pair((new sc_Pair("\u1E9Cfix",(new sc_Pair("\u1E9Cb",null)))),(new sc_Pair((new sc_Pair("\u1E9Cfix",(new sc_Pair("\u1E9Cc",null)))),null)))))),null)))))), (new sc_Pair("\u1E9Cequal",(new sc_Pair((new sc_Pair("\u1E9Cequal",(new sc_Pair((new sc_Pair("\u1E9Czero",null)),(new sc_Pair((new sc_Pair("\u1E9Cdifference",(new sc_Pair("\u1E9Cx",(new sc_Pair("\u1E9Cy",null)))))),null)))))),(new sc_Pair((new sc_Pair("\u1E9Cnot",(new sc_Pair((new sc_Pair("\u1E9Clessp",(new sc_Pair("\u1E9Cy",(new sc_Pair("\u1E9Cx",null)))))),null)))),null)))))), (new sc_Pair("\u1E9Cequal",(new sc_Pair((new sc_Pair("\u1E9Cequal",(new sc_Pair("\u1E9Cx",(new sc_Pair((new sc_Pair("\u1E9Cdifference",(new sc_Pair("\u1E9Cx",(new sc_Pair("\u1E9Cy",null)))))),null)))))),(new sc_Pair((new sc_Pair("\u1E9Cand",(new sc_Pair((new sc_Pair("\u1E9Cnumberp",(new sc_Pair("\u1E9Cx",null)))),(new sc_Pair((new sc_Pair("\u1E9Cor",(new sc_Pair((new sc_Pair("\u1E9Cequal",(new sc_Pair("\u1E9Cx",(new sc_Pair((new sc_Pair("\u1E9Czero",null)),null)))))),(new sc_Pair((new sc_Pair("\u1E9Czerop",(new sc_Pair("\u1E9Cy",null)))),null)))))),null)))))),null)))))), (new sc_Pair("\u1E9Cequal",(new sc_Pair((new sc_Pair("\u1E9Cmeaning",(new sc_Pair((new sc_Pair("\u1E9Cplus-tree",(new sc_Pair((new sc_Pair("\u1E9Cappend",(new sc_Pair("\u1E9Cx",(new sc_Pair("\u1E9Cy",null)))))),null)))),(new sc_Pair("\u1E9Ca",null)))))),(new sc_Pair((new sc_Pair("\u1E9Cplus",(new sc_Pair((new sc_Pair("\u1E9Cmeaning",(new sc_Pair((new sc_Pair("\u1E9Cplus-tree",(new sc_Pair("\u1E9Cx",null)))),(new sc_Pair("\u1E9Ca",null)))))),(new sc_Pair((new sc_Pair("\u1E9Cmeaning",(new sc_Pair((new sc_Pair("\u1E9Cplus-tree",(new sc_Pair("\u1E9Cy",null)))),(new sc_Pair("\u1E9Ca",null)))))),null)))))),null)))))), (new sc_Pair("\u1E9Cequal",(new sc_Pair((new sc_Pair("\u1E9Cmeaning",(new sc_Pair((new sc_Pair("\u1E9Cplus-tree",(new sc_Pair((new sc_Pair("\u1E9Cplus-fringe",(new sc_Pair("\u1E9Cx",null)))),null)))),(new sc_Pair("\u1E9Ca",null)))))),(new sc_Pair((new sc_Pair("\u1E9Cfix",(new sc_Pair((new sc_Pair("\u1E9Cmeaning",(new sc_Pair("\u1E9Cx",(new sc_Pair("\u1E9Ca",null)))))),null)))),null)))))), (new sc_Pair("\u1E9Cequal",(new sc_Pair((new sc_Pair("\u1E9Cappend",(new sc_Pair((new sc_Pair("\u1E9Cappend",(new sc_Pair("\u1E9Cx",(new sc_Pair("\u1E9Cy",null)))))),(new sc_Pair("\u1E9Cz",null)))))),(new sc_Pair((new sc_Pair("\u1E9Cappend",(new sc_Pair("\u1E9Cx",(new sc_Pair((new sc_Pair("\u1E9Cappend",(new sc_Pair("\u1E9Cy",(new sc_Pair("\u1E9Cz",null)))))),null)))))),null)))))), (new sc_Pair("\u1E9Cequal",(new sc_Pair((new sc_Pair("\u1E9Creverse",(new sc_Pair((new sc_Pair("\u1E9Cappend",(new sc_Pair("\u1E9Ca",(new sc_Pair("\u1E9Cb",null)))))),null)))),(new sc_Pair((new sc_Pair("\u1E9Cappend",(new sc_Pair((new sc_Pair("\u1E9Creverse",(new sc_Pair("\u1E9Cb",null)))),(new sc_Pair((new sc_Pair("\u1E9Creverse",(new sc_Pair("\u1E9Ca",null)))),null)))))),null)))))), (new sc_Pair("\u1E9Cequal",(new sc_Pair((new sc_Pair("\u1E9Ctimes",(new sc_Pair("\u1E9Cx",(new sc_Pair((new sc_Pair("\u1E9Cplus",(new sc_Pair("\u1E9Cy",(new sc_Pair("\u1E9Cz",null)))))),null)))))),(new sc_Pair((new sc_Pair("\u1E9Cplus",(new sc_Pair((new sc_Pair("\u1E9Ctimes",(new sc_Pair("\u1E9Cx",(new sc_Pair("\u1E9Cy",null)))))),(new sc_Pair((new sc_Pair("\u1E9Ctimes",(new sc_Pair("\u1E9Cx",(new sc_Pair("\u1E9Cz",null)))))),null)))))),null)))))), (new sc_Pair("\u1E9Cequal",(new sc_Pair((new sc_Pair("\u1E9Ctimes",(new sc_Pair((new sc_Pair("\u1E9Ctimes",(new sc_Pair("\u1E9Cx",(new sc_Pair("\u1E9Cy",null)))))),(new sc_Pair("\u1E9Cz",null)))))),(new sc_Pair((new sc_Pair("\u1E9Ctimes",(new sc_Pair("\u1E9Cx",(new sc_Pair((new sc_Pair("\u1E9Ctimes",(new sc_Pair("\u1E9Cy",(new sc_Pair("\u1E9Cz",null)))))),null)))))),null)))))), (new sc_Pair("\u1E9Cequal",(new sc_Pair((new sc_Pair("\u1E9Cequal",(new sc_Pair((new sc_Pair("\u1E9Ctimes",(new sc_Pair("\u1E9Cx",(new sc_Pair("\u1E9Cy",null)))))),(new sc_Pair((new sc_Pair("\u1E9Czero",null)),null)))))),(new sc_Pair((new sc_Pair("\u1E9Cor",(new sc_Pair((new sc_Pair("\u1E9Czerop",(new sc_Pair("\u1E9Cx",null)))),(new sc_Pair((new sc_Pair("\u1E9Czerop",(new sc_Pair("\u1E9Cy",null)))),null)))))),null)))))), (new sc_Pair("\u1E9Cequal",(new sc_Pair((new sc_Pair("\u1E9Cexec",(new sc_Pair((new sc_Pair("\u1E9Cappend",(new sc_Pair("\u1E9Cx",(new sc_Pair("\u1E9Cy",null)))))),(new sc_Pair("\u1E9Cpds",(new sc_Pair("\u1E9Cenvrn",null)))))))),(new sc_Pair((new sc_Pair("\u1E9Cexec",(new sc_Pair("\u1E9Cy",(new sc_Pair((new sc_Pair("\u1E9Cexec",(new sc_Pair("\u1E9Cx",(new sc_Pair("\u1E9Cpds",(new sc_Pair("\u1E9Cenvrn",null)))))))),(new sc_Pair("\u1E9Cenvrn",null)))))))),null)))))), (new sc_Pair("\u1E9Cequal",(new sc_Pair((new sc_Pair("\u1E9Cmc-flatten",(new sc_Pair("\u1E9Cx",(new sc_Pair("\u1E9Cy",null)))))),(new sc_Pair((new sc_Pair("\u1E9Cappend",(new sc_Pair((new sc_Pair("\u1E9Cflatten",(new sc_Pair("\u1E9Cx",null)))),(new sc_Pair("\u1E9Cy",null)))))),null)))))), (new sc_Pair("\u1E9Cequal",(new sc_Pair((new sc_Pair("\u1E9Cmember",(new sc_Pair("\u1E9Cx",(new sc_Pair((new sc_Pair("\u1E9Cappend",(new sc_Pair("\u1E9Ca",(new sc_Pair("\u1E9Cb",null)))))),null)))))),(new sc_Pair((new sc_Pair("\u1E9Cor",(new sc_Pair((new sc_Pair("\u1E9Cmember",(new sc_Pair("\u1E9Cx",(new sc_Pair("\u1E9Ca",null)))))),(new sc_Pair((new sc_Pair("\u1E9Cmember",(new sc_Pair("\u1E9Cx",(new sc_Pair("\u1E9Cb",null)))))),null)))))),null)))))), (new sc_Pair("\u1E9Cequal",(new sc_Pair((new sc_Pair("\u1E9Cmember",(new sc_Pair("\u1E9Cx",(new sc_Pair((new sc_Pair("\u1E9Creverse",(new sc_Pair("\u1E9Cy",null)))),null)))))),(new sc_Pair((new sc_Pair("\u1E9Cmember",(new sc_Pair("\u1E9Cx",(new sc_Pair("\u1E9Cy",null)))))),null)))))), (new sc_Pair("\u1E9Cequal",(new sc_Pair((new sc_Pair("\u1E9Clength",(new sc_Pair((new sc_Pair("\u1E9Creverse",(new sc_Pair("\u1E9Cx",null)))),null)))),(new sc_Pair((new sc_Pair("\u1E9Clength",(new sc_Pair("\u1E9Cx",null)))),null)))))), (new sc_Pair("\u1E9Cequal",(new sc_Pair((new sc_Pair("\u1E9Cmember",(new sc_Pair("\u1E9Ca",(new sc_Pair((new sc_Pair("\u1E9Cintersect",(new sc_Pair("\u1E9Cb",(new sc_Pair("\u1E9Cc",null)))))),null)))))),(new sc_Pair((new sc_Pair("\u1E9Cand",(new sc_Pair((new sc_Pair("\u1E9Cmember",(new sc_Pair("\u1E9Ca",(new sc_Pair("\u1E9Cb",null)))))),(new sc_Pair((new sc_Pair("\u1E9Cmember",(new sc_Pair("\u1E9Ca",(new sc_Pair("\u1E9Cc",null)))))),null)))))),null)))))), (new sc_Pair("\u1E9Cequal",(new sc_Pair((new sc_Pair("\u1E9Cnth",(new sc_Pair((new sc_Pair("\u1E9Czero",null)),(new sc_Pair("\u1E9Ci",null)))))),(new sc_Pair((new sc_Pair("\u1E9Czero",null)),null)))))), (new sc_Pair("\u1E9Cequal",(new sc_Pair((new sc_Pair("\u1E9Cexp",(new sc_Pair("\u1E9Ci",(new sc_Pair((new sc_Pair("\u1E9Cplus",(new sc_Pair("\u1E9Cj",(new sc_Pair("\u1E9Ck",null)))))),null)))))),(new sc_Pair((new sc_Pair("\u1E9Ctimes",(new sc_Pair((new sc_Pair("\u1E9Cexp",(new sc_Pair("\u1E9Ci",(new sc_Pair("\u1E9Cj",null)))))),(new sc_Pair((new sc_Pair("\u1E9Cexp",(new sc_Pair("\u1E9Ci",(new sc_Pair("\u1E9Ck",null)))))),null)))))),null)))))), (new sc_Pair("\u1E9Cequal",(new sc_Pair((new sc_Pair("\u1E9Cexp",(new sc_Pair("\u1E9Ci",(new sc_Pair((new sc_Pair("\u1E9Ctimes",(new sc_Pair("\u1E9Cj",(new sc_Pair("\u1E9Ck",null)))))),null)))))),(new sc_Pair((new sc_Pair("\u1E9Cexp",(new sc_Pair((new sc_Pair("\u1E9Cexp",(new sc_Pair("\u1E9Ci",(new sc_Pair("\u1E9Cj",null)))))),(new sc_Pair("\u1E9Ck",null)))))),null)))))), (new sc_Pair("\u1E9Cequal",(new sc_Pair((new sc_Pair("\u1E9Creverse-loop",(new sc_Pair("\u1E9Cx",(new sc_Pair("\u1E9Cy",null)))))),(new sc_Pair((new sc_Pair("\u1E9Cappend",(new sc_Pair((new sc_Pair("\u1E9Creverse",(new sc_Pair("\u1E9Cx",null)))),(new sc_Pair("\u1E9Cy",null)))))),null)))))), (new sc_Pair("\u1E9Cequal",(new sc_Pair((new sc_Pair("\u1E9Creverse-loop",(new sc_Pair("\u1E9Cx",(new sc_Pair((new sc_Pair("\u1E9Cnil",null)),null)))))),(new sc_Pair((new sc_Pair("\u1E9Creverse",(new sc_Pair("\u1E9Cx",null)))),null)))))), (new sc_Pair("\u1E9Cequal",(new sc_Pair((new sc_Pair("\u1E9Ccount-list",(new sc_Pair("\u1E9Cz",(new sc_Pair((new sc_Pair("\u1E9Csort-lp",(new sc_Pair("\u1E9Cx",(new sc_Pair("\u1E9Cy",null)))))),null)))))),(new sc_Pair((new sc_Pair("\u1E9Cplus",(new sc_Pair((new sc_Pair("\u1E9Ccount-list",(new sc_Pair("\u1E9Cz",(new sc_Pair("\u1E9Cx",null)))))),(new sc_Pair((new sc_Pair("\u1E9Ccount-list",(new sc_Pair("\u1E9Cz",(new sc_Pair("\u1E9Cy",null)))))),null)))))),null)))))), (new sc_Pair("\u1E9Cequal",(new sc_Pair((new sc_Pair("\u1E9Cequal",(new sc_Pair((new sc_Pair("\u1E9Cappend",(new sc_Pair("\u1E9Ca",(new sc_Pair("\u1E9Cb",null)))))),(new sc_Pair((new sc_Pair("\u1E9Cappend",(new sc_Pair("\u1E9Ca",(new sc_Pair("\u1E9Cc",null)))))),null)))))),(new sc_Pair((new sc_Pair("\u1E9Cequal",(new sc_Pair("\u1E9Cb",(new sc_Pair("\u1E9Cc",null)))))),null)))))), (new sc_Pair("\u1E9Cequal",(new sc_Pair((new sc_Pair("\u1E9Cplus",(new sc_Pair((new sc_Pair("\u1E9Cremainder",(new sc_Pair("\u1E9Cx",(new sc_Pair("\u1E9Cy",null)))))),(new sc_Pair((new sc_Pair("\u1E9Ctimes",(new sc_Pair("\u1E9Cy",(new sc_Pair((new sc_Pair("\u1E9Cquotient",(new sc_Pair("\u1E9Cx",(new sc_Pair("\u1E9Cy",null)))))),null)))))),null)))))),(new sc_Pair((new sc_Pair("\u1E9Cfix",(new sc_Pair("\u1E9Cx",null)))),null)))))), (new sc_Pair("\u1E9Cequal",(new sc_Pair((new sc_Pair("\u1E9Cpower-eval",(new sc_Pair((new sc_Pair("\u1E9Cbig-plus1",(new sc_Pair("\u1E9Cl",(new sc_Pair("\u1E9Ci",(new sc_Pair("\u1E9Cbase",null)))))))),(new sc_Pair("\u1E9Cbase",null)))))),(new sc_Pair((new sc_Pair("\u1E9Cplus",(new sc_Pair((new sc_Pair("\u1E9Cpower-eval",(new sc_Pair("\u1E9Cl",(new sc_Pair("\u1E9Cbase",null)))))),(new sc_Pair("\u1E9Ci",null)))))),null)))))), (new sc_Pair("\u1E9Cequal",(new sc_Pair((new sc_Pair("\u1E9Cpower-eval",(new sc_Pair((new sc_Pair("\u1E9Cbig-plus",(new sc_Pair("\u1E9Cx",(new sc_Pair("\u1E9Cy",(new sc_Pair("\u1E9Ci",(new sc_Pair("\u1E9Cbase",null)))))))))),(new sc_Pair("\u1E9Cbase",null)))))),(new sc_Pair((new sc_Pair("\u1E9Cplus",(new sc_Pair("\u1E9Ci",(new sc_Pair((new sc_Pair("\u1E9Cplus",(new sc_Pair((new sc_Pair("\u1E9Cpower-eval",(new sc_Pair("\u1E9Cx",(new sc_Pair("\u1E9Cbase",null)))))),(new sc_Pair((new sc_Pair("\u1E9Cpower-eval",(new sc_Pair("\u1E9Cy",(new sc_Pair("\u1E9Cbase",null)))))),null)))))),null)))))),null)))))), (new sc_Pair("\u1E9Cequal",(new sc_Pair((new sc_Pair("\u1E9Cremainder",(new sc_Pair("\u1E9Cy",(new sc_Pair((1),null)))))),(new sc_Pair((new sc_Pair("\u1E9Czero",null)),null)))))), (new sc_Pair("\u1E9Cequal",(new sc_Pair((new sc_Pair("\u1E9Clessp",(new sc_Pair((new sc_Pair("\u1E9Cremainder",(new sc_Pair("\u1E9Cx",(new sc_Pair("\u1E9Cy",null)))))),(new sc_Pair("\u1E9Cy",null)))))),(new sc_Pair((new sc_Pair("\u1E9Cnot",(new sc_Pair((new sc_Pair("\u1E9Czerop",(new sc_Pair("\u1E9Cy",null)))),null)))),null)))))), (new sc_Pair("\u1E9Cequal",(new sc_Pair((new sc_Pair("\u1E9Cremainder",(new sc_Pair("\u1E9Cx",(new sc_Pair("\u1E9Cx",null)))))),(new sc_Pair((new sc_Pair("\u1E9Czero",null)),null)))))), (new sc_Pair("\u1E9Cequal",(new sc_Pair((new sc_Pair("\u1E9Clessp",(new sc_Pair((new sc_Pair("\u1E9Cquotient",(new sc_Pair("\u1E9Ci",(new sc_Pair("\u1E9Cj",null)))))),(new sc_Pair("\u1E9Ci",null)))))),(new sc_Pair((new sc_Pair("\u1E9Cand",(new sc_Pair((new sc_Pair("\u1E9Cnot",(new sc_Pair((new sc_Pair("\u1E9Czerop",(new sc_Pair("\u1E9Ci",null)))),null)))),(new sc_Pair((new sc_Pair("\u1E9Cor",(new sc_Pair((new sc_Pair("\u1E9Czerop",(new sc_Pair("\u1E9Cj",null)))),(new sc_Pair((new sc_Pair("\u1E9Cnot",(new sc_Pair((new sc_Pair("\u1E9Cequal",(new sc_Pair("\u1E9Cj",(new sc_Pair((1),null)))))),null)))),null)))))),null)))))),null)))))), (new sc_Pair("\u1E9Cequal",(new sc_Pair((new sc_Pair("\u1E9Clessp",(new sc_Pair((new sc_Pair("\u1E9Cremainder",(new sc_Pair("\u1E9Cx",(new sc_Pair("\u1E9Cy",null)))))),(new sc_Pair("\u1E9Cx",null)))))),(new sc_Pair((new sc_Pair("\u1E9Cand",(new sc_Pair((new sc_Pair("\u1E9Cnot",(new sc_Pair((new sc_Pair("\u1E9Czerop",(new sc_Pair("\u1E9Cy",null)))),null)))),(new sc_Pair((new sc_Pair("\u1E9Cnot",(new sc_Pair((new sc_Pair("\u1E9Czerop",(new sc_Pair("\u1E9Cx",null)))),null)))),(new sc_Pair((new sc_Pair("\u1E9Cnot",(new sc_Pair((new sc_Pair("\u1E9Clessp",(new sc_Pair("\u1E9Cx",(new sc_Pair("\u1E9Cy",null)))))),null)))),null)))))))),null)))))), (new sc_Pair("\u1E9Cequal",(new sc_Pair((new sc_Pair("\u1E9Cpower-eval",(new sc_Pair((new sc_Pair("\u1E9Cpower-rep",(new sc_Pair("\u1E9Ci",(new sc_Pair("\u1E9Cbase",null)))))),(new sc_Pair("\u1E9Cbase",null)))))),(new sc_Pair((new sc_Pair("\u1E9Cfix",(new sc_Pair("\u1E9Ci",null)))),null)))))), (new sc_Pair("\u1E9Cequal",(new sc_Pair((new sc_Pair("\u1E9Cpower-eval",(new sc_Pair((new sc_Pair("\u1E9Cbig-plus",(new sc_Pair((new sc_Pair("\u1E9Cpower-rep",(new sc_Pair("\u1E9Ci",(new sc_Pair("\u1E9Cbase",null)))))),(new sc_Pair((new sc_Pair("\u1E9Cpower-rep",(new sc_Pair("\u1E9Cj",(new sc_Pair("\u1E9Cbase",null)))))),(new sc_Pair((new sc_Pair("\u1E9Czero",null)),(new sc_Pair("\u1E9Cbase",null)))))))))),(new sc_Pair("\u1E9Cbase",null)))))),(new sc_Pair((new sc_Pair("\u1E9Cplus",(new sc_Pair("\u1E9Ci",(new sc_Pair("\u1E9Cj",null)))))),null)))))), (new sc_Pair("\u1E9Cequal",(new sc_Pair((new sc_Pair("\u1E9Cgcd",(new sc_Pair("\u1E9Cx",(new sc_Pair("\u1E9Cy",null)))))),(new sc_Pair((new sc_Pair("\u1E9Cgcd",(new sc_Pair("\u1E9Cy",(new sc_Pair("\u1E9Cx",null)))))),null)))))), (new sc_Pair("\u1E9Cequal",(new sc_Pair((new sc_Pair("\u1E9Cnth",(new sc_Pair((new sc_Pair("\u1E9Cappend",(new sc_Pair("\u1E9Ca",(new sc_Pair("\u1E9Cb",null)))))),(new sc_Pair("\u1E9Ci",null)))))),(new sc_Pair((new sc_Pair("\u1E9Cappend",(new sc_Pair((new sc_Pair("\u1E9Cnth",(new sc_Pair("\u1E9Ca",(new sc_Pair("\u1E9Ci",null)))))),(new sc_Pair((new sc_Pair("\u1E9Cnth",(new sc_Pair("\u1E9Cb",(new sc_Pair((new sc_Pair("\u1E9Cdifference",(new sc_Pair("\u1E9Ci",(new sc_Pair((new sc_Pair("\u1E9Clength",(new sc_Pair("\u1E9Ca",null)))),null)))))),null)))))),null)))))),null)))))), (new sc_Pair("\u1E9Cequal",(new sc_Pair((new sc_Pair("\u1E9Cdifference",(new sc_Pair((new sc_Pair("\u1E9Cplus",(new sc_Pair("\u1E9Cx",(new sc_Pair("\u1E9Cy",null)))))),(new sc_Pair("\u1E9Cx",null)))))),(new sc_Pair((new sc_Pair("\u1E9Cfix",(new sc_Pair("\u1E9Cy",null)))),null)))))), (new sc_Pair("\u1E9Cequal",(new sc_Pair((new sc_Pair("\u1E9Cdifference",(new sc_Pair((new sc_Pair("\u1E9Cplus",(new sc_Pair("\u1E9Cy",(new sc_Pair("\u1E9Cx",null)))))),(new sc_Pair("\u1E9Cx",null)))))),(new sc_Pair((new sc_Pair("\u1E9Cfix",(new sc_Pair("\u1E9Cy",null)))),null)))))), (new sc_Pair("\u1E9Cequal",(new sc_Pair((new sc_Pair("\u1E9Cdifference",(new sc_Pair((new sc_Pair("\u1E9Cplus",(new sc_Pair("\u1E9Cx",(new sc_Pair("\u1E9Cy",null)))))),(new sc_Pair((new sc_Pair("\u1E9Cplus",(new sc_Pair("\u1E9Cx",(new sc_Pair("\u1E9Cz",null)))))),null)))))),(new sc_Pair((new sc_Pair("\u1E9Cdifference",(new sc_Pair("\u1E9Cy",(new sc_Pair("\u1E9Cz",null)))))),null)))))), (new sc_Pair("\u1E9Cequal",(new sc_Pair((new sc_Pair("\u1E9Ctimes",(new sc_Pair("\u1E9Cx",(new sc_Pair((new sc_Pair("\u1E9Cdifference",(new sc_Pair("\u1E9Cc",(new sc_Pair("\u1E9Cw",null)))))),null)))))),(new sc_Pair((new sc_Pair("\u1E9Cdifference",(new sc_Pair((new sc_Pair("\u1E9Ctimes",(new sc_Pair("\u1E9Cc",(new sc_Pair("\u1E9Cx",null)))))),(new sc_Pair((new sc_Pair("\u1E9Ctimes",(new sc_Pair("\u1E9Cw",(new sc_Pair("\u1E9Cx",null)))))),null)))))),null)))))), (new sc_Pair("\u1E9Cequal",(new sc_Pair((new sc_Pair("\u1E9Cremainder",(new sc_Pair((new sc_Pair("\u1E9Ctimes",(new sc_Pair("\u1E9Cx",(new sc_Pair("\u1E9Cz",null)))))),(new sc_Pair("\u1E9Cz",null)))))),(new sc_Pair((new sc_Pair("\u1E9Czero",null)),null)))))), (new sc_Pair("\u1E9Cequal",(new sc_Pair((new sc_Pair("\u1E9Cdifference",(new sc_Pair((new sc_Pair("\u1E9Cplus",(new sc_Pair("\u1E9Cb",(new sc_Pair((new sc_Pair("\u1E9Cplus",(new sc_Pair("\u1E9Ca",(new sc_Pair("\u1E9Cc",null)))))),null)))))),(new sc_Pair("\u1E9Ca",null)))))),(new sc_Pair((new sc_Pair("\u1E9Cplus",(new sc_Pair("\u1E9Cb",(new sc_Pair("\u1E9Cc",null)))))),null)))))), (new sc_Pair("\u1E9Cequal",(new sc_Pair((new sc_Pair("\u1E9Cdifference",(new sc_Pair((new sc_Pair("\u1E9Cadd1",(new sc_Pair((new sc_Pair("\u1E9Cplus",(new sc_Pair("\u1E9Cy",(new sc_Pair("\u1E9Cz",null)))))),null)))),(new sc_Pair("\u1E9Cz",null)))))),(new sc_Pair((new sc_Pair("\u1E9Cadd1",(new sc_Pair("\u1E9Cy",null)))),null)))))), (new sc_Pair("\u1E9Cequal",(new sc_Pair((new sc_Pair("\u1E9Clessp",(new sc_Pair((new sc_Pair("\u1E9Cplus",(new sc_Pair("\u1E9Cx",(new sc_Pair("\u1E9Cy",null)))))),(new sc_Pair((new sc_Pair("\u1E9Cplus",(new sc_Pair("\u1E9Cx",(new sc_Pair("\u1E9Cz",null)))))),null)))))),(new sc_Pair((new sc_Pair("\u1E9Clessp",(new sc_Pair("\u1E9Cy",(new sc_Pair("\u1E9Cz",null)))))),null)))))), (new sc_Pair("\u1E9Cequal",(new sc_Pair((new sc_Pair("\u1E9Clessp",(new sc_Pair((new sc_Pair("\u1E9Ctimes",(new sc_Pair("\u1E9Cx",(new sc_Pair("\u1E9Cz",null)))))),(new sc_Pair((new sc_Pair("\u1E9Ctimes",(new sc_Pair("\u1E9Cy",(new sc_Pair("\u1E9Cz",null)))))),null)))))),(new sc_Pair((new sc_Pair("\u1E9Cand",(new sc_Pair((new sc_Pair("\u1E9Cnot",(new sc_Pair((new sc_Pair("\u1E9Czerop",(new sc_Pair("\u1E9Cz",null)))),null)))),(new sc_Pair((new sc_Pair("\u1E9Clessp",(new sc_Pair("\u1E9Cx",(new sc_Pair("\u1E9Cy",null)))))),null)))))),null)))))), (new sc_Pair("\u1E9Cequal",(new sc_Pair((new sc_Pair("\u1E9Clessp",(new sc_Pair("\u1E9Cy",(new sc_Pair((new sc_Pair("\u1E9Cplus",(new sc_Pair("\u1E9Cx",(new sc_Pair("\u1E9Cy",null)))))),null)))))),(new sc_Pair((new sc_Pair("\u1E9Cnot",(new sc_Pair((new sc_Pair("\u1E9Czerop",(new sc_Pair("\u1E9Cx",null)))),null)))),null)))))), (new sc_Pair("\u1E9Cequal",(new sc_Pair((new sc_Pair("\u1E9Cgcd",(new sc_Pair((new sc_Pair("\u1E9Ctimes",(new sc_Pair("\u1E9Cx",(new sc_Pair("\u1E9Cz",null)))))),(new sc_Pair((new sc_Pair("\u1E9Ctimes",(new sc_Pair("\u1E9Cy",(new sc_Pair("\u1E9Cz",null)))))),null)))))),(new sc_Pair((new sc_Pair("\u1E9Ctimes",(new sc_Pair("\u1E9Cz",(new sc_Pair((new sc_Pair("\u1E9Cgcd",(new sc_Pair("\u1E9Cx",(new sc_Pair("\u1E9Cy",null)))))),null)))))),null)))))), (new sc_Pair("\u1E9Cequal",(new sc_Pair((new sc_Pair("\u1E9Cvalue",(new sc_Pair((new sc_Pair("\u1E9Cnormalize",(new sc_Pair("\u1E9Cx",null)))),(new sc_Pair("\u1E9Ca",null)))))),(new sc_Pair((new sc_Pair("\u1E9Cvalue",(new sc_Pair("\u1E9Cx",(new sc_Pair("\u1E9Ca",null)))))),null)))))), (new sc_Pair("\u1E9Cequal",(new sc_Pair((new sc_Pair("\u1E9Cequal",(new sc_Pair((new sc_Pair("\u1E9Cflatten",(new sc_Pair("\u1E9Cx",null)))),(new sc_Pair((new sc_Pair("\u1E9Ccons",(new sc_Pair("\u1E9Cy",(new sc_Pair((new sc_Pair("\u1E9Cnil",null)),null)))))),null)))))),(new sc_Pair((new sc_Pair("\u1E9Cand",(new sc_Pair((new sc_Pair("\u1E9Cnlistp",(new sc_Pair("\u1E9Cx",null)))),(new sc_Pair((new sc_Pair("\u1E9Cequal",(new sc_Pair("\u1E9Cx",(new sc_Pair("\u1E9Cy",null)))))),null)))))),null)))))), (new sc_Pair("\u1E9Cequal",(new sc_Pair((new sc_Pair("\u1E9Clistp",(new sc_Pair((new sc_Pair("\u1E9Cgopher",(new sc_Pair("\u1E9Cx",null)))),null)))),(new sc_Pair((new sc_Pair("\u1E9Clistp",(new sc_Pair("\u1E9Cx",null)))),null)))))), (new sc_Pair("\u1E9Cequal",(new sc_Pair((new sc_Pair("\u1E9Csamefringe",(new sc_Pair("\u1E9Cx",(new sc_Pair("\u1E9Cy",null)))))),(new sc_Pair((new sc_Pair("\u1E9Cequal",(new sc_Pair((new sc_Pair("\u1E9Cflatten",(new sc_Pair("\u1E9Cx",null)))),(new sc_Pair((new sc_Pair("\u1E9Cflatten",(new sc_Pair("\u1E9Cy",null)))),null)))))),null)))))), (new sc_Pair("\u1E9Cequal",(new sc_Pair((new sc_Pair("\u1E9Cequal",(new sc_Pair((new sc_Pair("\u1E9Cgreatest-factor",(new sc_Pair("\u1E9Cx",(new sc_Pair("\u1E9Cy",null)))))),(new sc_Pair((new sc_Pair("\u1E9Czero",null)),null)))))),(new sc_Pair((new sc_Pair("\u1E9Cand",(new sc_Pair((new sc_Pair("\u1E9Cor",(new sc_Pair((new sc_Pair("\u1E9Czerop",(new sc_Pair("\u1E9Cy",null)))),(new sc_Pair((new sc_Pair("\u1E9Cequal",(new sc_Pair("\u1E9Cy",(new sc_Pair((1),null)))))),null)))))),(new sc_Pair((new sc_Pair("\u1E9Cequal",(new sc_Pair("\u1E9Cx",(new sc_Pair((new sc_Pair("\u1E9Czero",null)),null)))))),null)))))),null)))))), (new sc_Pair("\u1E9Cequal",(new sc_Pair((new sc_Pair("\u1E9Cequal",(new sc_Pair((new sc_Pair("\u1E9Cgreatest-factor",(new sc_Pair("\u1E9Cx",(new sc_Pair("\u1E9Cy",null)))))),(new sc_Pair((1),null)))))),(new sc_Pair((new sc_Pair("\u1E9Cequal",(new sc_Pair("\u1E9Cx",(new sc_Pair((1),null)))))),null)))))), (new sc_Pair("\u1E9Cequal",(new sc_Pair((new sc_Pair("\u1E9Cnumberp",(new sc_Pair((new sc_Pair("\u1E9Cgreatest-factor",(new sc_Pair("\u1E9Cx",(new sc_Pair("\u1E9Cy",null)))))),null)))),(new sc_Pair((new sc_Pair("\u1E9Cnot",(new sc_Pair((new sc_Pair("\u1E9Cand",(new sc_Pair((new sc_Pair("\u1E9Cor",(new sc_Pair((new sc_Pair("\u1E9Czerop",(new sc_Pair("\u1E9Cy",null)))),(new sc_Pair((new sc_Pair("\u1E9Cequal",(new sc_Pair("\u1E9Cy",(new sc_Pair((1),null)))))),null)))))),(new sc_Pair((new sc_Pair("\u1E9Cnot",(new sc_Pair((new sc_Pair("\u1E9Cnumberp",(new sc_Pair("\u1E9Cx",null)))),null)))),null)))))),null)))),null)))))), (new sc_Pair("\u1E9Cequal",(new sc_Pair((new sc_Pair("\u1E9Ctimes-list",(new sc_Pair((new sc_Pair("\u1E9Cappend",(new sc_Pair("\u1E9Cx",(new sc_Pair("\u1E9Cy",null)))))),null)))),(new sc_Pair((new sc_Pair("\u1E9Ctimes",(new sc_Pair((new sc_Pair("\u1E9Ctimes-list",(new sc_Pair("\u1E9Cx",null)))),(new sc_Pair((new sc_Pair("\u1E9Ctimes-list",(new sc_Pair("\u1E9Cy",null)))),null)))))),null)))))), (new sc_Pair("\u1E9Cequal",(new sc_Pair((new sc_Pair("\u1E9Cprime-list",(new sc_Pair((new sc_Pair("\u1E9Cappend",(new sc_Pair("\u1E9Cx",(new sc_Pair("\u1E9Cy",null)))))),null)))),(new sc_Pair((new sc_Pair("\u1E9Cand",(new sc_Pair((new sc_Pair("\u1E9Cprime-list",(new sc_Pair("\u1E9Cx",null)))),(new sc_Pair((new sc_Pair("\u1E9Cprime-list",(new sc_Pair("\u1E9Cy",null)))),null)))))),null)))))), (new sc_Pair("\u1E9Cequal",(new sc_Pair((new sc_Pair("\u1E9Cequal",(new sc_Pair("\u1E9Cz",(new sc_Pair((new sc_Pair("\u1E9Ctimes",(new sc_Pair("\u1E9Cw",(new sc_Pair("\u1E9Cz",null)))))),null)))))),(new sc_Pair((new sc_Pair("\u1E9Cand",(new sc_Pair((new sc_Pair("\u1E9Cnumberp",(new sc_Pair("\u1E9Cz",null)))),(new sc_Pair((new sc_Pair("\u1E9Cor",(new sc_Pair((new sc_Pair("\u1E9Cequal",(new sc_Pair("\u1E9Cz",(new sc_Pair((new sc_Pair("\u1E9Czero",null)),null)))))),(new sc_Pair((new sc_Pair("\u1E9Cequal",(new sc_Pair("\u1E9Cw",(new sc_Pair((1),null)))))),null)))))),null)))))),null)))))), (new sc_Pair("\u1E9Cequal",(new sc_Pair((new sc_Pair("\u1E9Cgreatereqp",(new sc_Pair("\u1E9Cx",(new sc_Pair("\u1E9Cy",null)))))),(new sc_Pair((new sc_Pair("\u1E9Cnot",(new sc_Pair((new sc_Pair("\u1E9Clessp",(new sc_Pair("\u1E9Cx",(new sc_Pair("\u1E9Cy",null)))))),null)))),null)))))), (new sc_Pair("\u1E9Cequal",(new sc_Pair((new sc_Pair("\u1E9Cequal",(new sc_Pair("\u1E9Cx",(new sc_Pair((new sc_Pair("\u1E9Ctimes",(new sc_Pair("\u1E9Cx",(new sc_Pair("\u1E9Cy",null)))))),null)))))),(new sc_Pair((new sc_Pair("\u1E9Cor",(new sc_Pair((new sc_Pair("\u1E9Cequal",(new sc_Pair("\u1E9Cx",(new sc_Pair((new sc_Pair("\u1E9Czero",null)),null)))))),(new sc_Pair((new sc_Pair("\u1E9Cand",(new sc_Pair((new sc_Pair("\u1E9Cnumberp",(new sc_Pair("\u1E9Cx",null)))),(new sc_Pair((new sc_Pair("\u1E9Cequal",(new sc_Pair("\u1E9Cy",(new sc_Pair((1),null)))))),null)))))),null)))))),null)))))), (new sc_Pair("\u1E9Cequal",(new sc_Pair((new sc_Pair("\u1E9Cremainder",(new sc_Pair((new sc_Pair("\u1E9Ctimes",(new sc_Pair("\u1E9Cy",(new sc_Pair("\u1E9Cx",null)))))),(new sc_Pair("\u1E9Cy",null)))))),(new sc_Pair((new sc_Pair("\u1E9Czero",null)),null)))))), (new sc_Pair("\u1E9Cequal",(new sc_Pair((new sc_Pair("\u1E9Cequal",(new sc_Pair((new sc_Pair("\u1E9Ctimes",(new sc_Pair("\u1E9Ca",(new sc_Pair("\u1E9Cb",null)))))),(new sc_Pair((1),null)))))),(new sc_Pair(sc_list("\u1E9Cand", (new sc_Pair("\u1E9Cnot",(new sc_Pair((new sc_Pair("\u1E9Cequal",(new sc_Pair("\u1E9Ca",(new sc_Pair((new sc_Pair("\u1E9Czero",null)),null)))))),null)))), (new sc_Pair("\u1E9Cnot",(new sc_Pair((new sc_Pair("\u1E9Cequal",(new sc_Pair("\u1E9Cb",(new sc_Pair((new sc_Pair("\u1E9Czero",null)),null)))))),null)))), (new sc_Pair("\u1E9Cnumberp",(new sc_Pair("\u1E9Ca",null)))), (new sc_Pair("\u1E9Cnumberp",(new sc_Pair("\u1E9Cb",null)))), (new sc_Pair("\u1E9Cequal",(new sc_Pair((new sc_Pair("\u1E9Csub1",(new sc_Pair("\u1E9Ca",null)))),(new sc_Pair((new sc_Pair("\u1E9Czero",null)),null)))))), (new sc_Pair("\u1E9Cequal",(new sc_Pair((new sc_Pair("\u1E9Csub1",(new sc_Pair("\u1E9Cb",null)))),(new sc_Pair((new sc_Pair("\u1E9Czero",null)),null))))))),null)))))), (new sc_Pair("\u1E9Cequal",(new sc_Pair((new sc_Pair("\u1E9Clessp",(new sc_Pair((new sc_Pair("\u1E9Clength",(new sc_Pair((new sc_Pair("\u1E9Cdelete",(new sc_Pair("\u1E9Cx",(new sc_Pair("\u1E9Cl",null)))))),null)))),(new sc_Pair((new sc_Pair("\u1E9Clength",(new sc_Pair("\u1E9Cl",null)))),null)))))),(new sc_Pair((new sc_Pair("\u1E9Cmember",(new sc_Pair("\u1E9Cx",(new sc_Pair("\u1E9Cl",null)))))),null)))))), (new sc_Pair("\u1E9Cequal",(new sc_Pair((new sc_Pair("\u1E9Csort2",(new sc_Pair((new sc_Pair("\u1E9Cdelete",(new sc_Pair("\u1E9Cx",(new sc_Pair("\u1E9Cl",null)))))),null)))),(new sc_Pair((new sc_Pair("\u1E9Cdelete",(new sc_Pair("\u1E9Cx",(new sc_Pair((new sc_Pair("\u1E9Csort2",(new sc_Pair("\u1E9Cl",null)))),null)))))),null)))))), (new sc_Pair("\u1E9Cequal",(new sc_Pair((new sc_Pair("\u1E9Cdsort",(new sc_Pair("\u1E9Cx",null)))),(new sc_Pair((new sc_Pair("\u1E9Csort2",(new sc_Pair("\u1E9Cx",null)))),null)))))), (new sc_Pair("\u1E9Cequal",(new sc_Pair((new sc_Pair("\u1E9Clength",(new sc_Pair((new sc_Pair("\u1E9Ccons",(new sc_Pair("\u1E9Cx1",(new sc_Pair((new sc_Pair("\u1E9Ccons",(new sc_Pair("\u1E9Cx2",(new sc_Pair((new sc_Pair("\u1E9Ccons",(new sc_Pair("\u1E9Cx3",(new sc_Pair((new sc_Pair("\u1E9Ccons",(new sc_Pair("\u1E9Cx4",(new sc_Pair((new sc_Pair("\u1E9Ccons",(new sc_Pair("\u1E9Cx5",(new sc_Pair((new sc_Pair("\u1E9Ccons",(new sc_Pair("\u1E9Cx6",(new sc_Pair("\u1E9Cx7",null)))))),null)))))),null)))))),null)))))),null)))))),null)))))),null)))),(new sc_Pair((new sc_Pair("\u1E9Cplus",(new sc_Pair((6),(new sc_Pair((new sc_Pair("\u1E9Clength",(new sc_Pair("\u1E9Cx7",null)))),null)))))),null)))))), (new sc_Pair("\u1E9Cequal",(new sc_Pair((new sc_Pair("\u1E9Cdifference",(new sc_Pair((new sc_Pair("\u1E9Cadd1",(new sc_Pair((new sc_Pair("\u1E9Cadd1",(new sc_Pair("\u1E9Cx",null)))),null)))),(new sc_Pair((2),null)))))),(new sc_Pair((new sc_Pair("\u1E9Cfix",(new sc_Pair("\u1E9Cx",null)))),null)))))), (new sc_Pair("\u1E9Cequal",(new sc_Pair((new sc_Pair("\u1E9Cquotient",(new sc_Pair((new sc_Pair("\u1E9Cplus",(new sc_Pair("\u1E9Cx",(new sc_Pair((new sc_Pair("\u1E9Cplus",(new sc_Pair("\u1E9Cx",(new sc_Pair("\u1E9Cy",null)))))),null)))))),(new sc_Pair((2),null)))))),(new sc_Pair((new sc_Pair("\u1E9Cplus",(new sc_Pair("\u1E9Cx",(new sc_Pair((new sc_Pair("\u1E9Cquotient",(new sc_Pair("\u1E9Cy",(new sc_Pair((2),null)))))),null)))))),null)))))), (new sc_Pair("\u1E9Cequal",(new sc_Pair((new sc_Pair("\u1E9Csigma",(new sc_Pair((new sc_Pair("\u1E9Czero",null)),(new sc_Pair("\u1E9Ci",null)))))),(new sc_Pair((new sc_Pair("\u1E9Cquotient",(new sc_Pair((new sc_Pair("\u1E9Ctimes",(new sc_Pair("\u1E9Ci",(new sc_Pair((new sc_Pair("\u1E9Cadd1",(new sc_Pair("\u1E9Ci",null)))),null)))))),(new sc_Pair((2),null)))))),null)))))), (new sc_Pair("\u1E9Cequal",(new sc_Pair((new sc_Pair("\u1E9Cplus",(new sc_Pair("\u1E9Cx",(new sc_Pair((new sc_Pair("\u1E9Cadd1",(new sc_Pair("\u1E9Cy",null)))),null)))))),(new sc_Pair((new sc_Pair("\u1E9Cif",(new sc_Pair((new sc_Pair("\u1E9Cnumberp",(new sc_Pair("\u1E9Cy",null)))),(new sc_Pair((new sc_Pair("\u1E9Cadd1",(new sc_Pair((new sc_Pair("\u1E9Cplus",(new sc_Pair("\u1E9Cx",(new sc_Pair("\u1E9Cy",null)))))),null)))),(new sc_Pair((new sc_Pair("\u1E9Cadd1",(new sc_Pair("\u1E9Cx",null)))),null)))))))),null)))))), (new sc_Pair("\u1E9Cequal",(new sc_Pair((new sc_Pair("\u1E9Cequal",(new sc_Pair((new sc_Pair("\u1E9Cdifference",(new sc_Pair("\u1E9Cx",(new sc_Pair("\u1E9Cy",null)))))),(new sc_Pair((new sc_Pair("\u1E9Cdifference",(new sc_Pair("\u1E9Cz",(new sc_Pair("\u1E9Cy",null)))))),null)))))),(new sc_Pair((new sc_Pair("\u1E9Cif",(new sc_Pair((new sc_Pair("\u1E9Clessp",(new sc_Pair("\u1E9Cx",(new sc_Pair("\u1E9Cy",null)))))),(new sc_Pair((new sc_Pair("\u1E9Cnot",(new sc_Pair((new sc_Pair("\u1E9Clessp",(new sc_Pair("\u1E9Cy",(new sc_Pair("\u1E9Cz",null)))))),null)))),(new sc_Pair((new sc_Pair("\u1E9Cif",(new sc_Pair((new sc_Pair("\u1E9Clessp",(new sc_Pair("\u1E9Cz",(new sc_Pair("\u1E9Cy",null)))))),(new sc_Pair((new sc_Pair("\u1E9Cnot",(new sc_Pair((new sc_Pair("\u1E9Clessp",(new sc_Pair("\u1E9Cy",(new sc_Pair("\u1E9Cx",null)))))),null)))),(new sc_Pair((new sc_Pair("\u1E9Cequal",(new sc_Pair((new sc_Pair("\u1E9Cfix",(new sc_Pair("\u1E9Cx",null)))),(new sc_Pair((new sc_Pair("\u1E9Cfix",(new sc_Pair("\u1E9Cz",null)))),null)))))),null)))))))),null)))))))),null)))))), (new sc_Pair("\u1E9Cequal",(new sc_Pair((new sc_Pair("\u1E9Cmeaning",(new sc_Pair((new sc_Pair("\u1E9Cplus-tree",(new sc_Pair((new sc_Pair("\u1E9Cdelete",(new sc_Pair("\u1E9Cx",(new sc_Pair("\u1E9Cy",null)))))),null)))),(new sc_Pair("\u1E9Ca",null)))))),(new sc_Pair((new sc_Pair("\u1E9Cif",(new sc_Pair((new sc_Pair("\u1E9Cmember",(new sc_Pair("\u1E9Cx",(new sc_Pair("\u1E9Cy",null)))))),(new sc_Pair((new sc_Pair("\u1E9Cdifference",(new sc_Pair((new sc_Pair("\u1E9Cmeaning",(new sc_Pair((new sc_Pair("\u1E9Cplus-tree",(new sc_Pair("\u1E9Cy",null)))),(new sc_Pair("\u1E9Ca",null)))))),(new sc_Pair((new sc_Pair("\u1E9Cmeaning",(new sc_Pair("\u1E9Cx",(new sc_Pair("\u1E9Ca",null)))))),null)))))),(new sc_Pair((new sc_Pair("\u1E9Cmeaning",(new sc_Pair((new sc_Pair("\u1E9Cplus-tree",(new sc_Pair("\u1E9Cy",null)))),(new sc_Pair("\u1E9Ca",null)))))),null)))))))),null)))))), (new sc_Pair("\u1E9Cequal",(new sc_Pair((new sc_Pair("\u1E9Ctimes",(new sc_Pair("\u1E9Cx",(new sc_Pair((new sc_Pair("\u1E9Cadd1",(new sc_Pair("\u1E9Cy",null)))),null)))))),(new sc_Pair((new sc_Pair("\u1E9Cif",(new sc_Pair((new sc_Pair("\u1E9Cnumberp",(new sc_Pair("\u1E9Cy",null)))),(new sc_Pair((new sc_Pair("\u1E9Cplus",(new sc_Pair("\u1E9Cx",(new sc_Pair((new sc_Pair("\u1E9Ctimes",(new sc_Pair("\u1E9Cx",(new sc_Pair("\u1E9Cy",null)))))),null)))))),(new sc_Pair((new sc_Pair("\u1E9Cfix",(new sc_Pair("\u1E9Cx",null)))),null)))))))),null)))))), (new sc_Pair("\u1E9Cequal",(new sc_Pair((new sc_Pair("\u1E9Cnth",(new sc_Pair((new sc_Pair("\u1E9Cnil",null)),(new sc_Pair("\u1E9Ci",null)))))),(new sc_Pair((new sc_Pair("\u1E9Cif",(new sc_Pair((new sc_Pair("\u1E9Czerop",(new sc_Pair("\u1E9Ci",null)))),(new sc_Pair((new sc_Pair("\u1E9Cnil",null)),(new sc_Pair((new sc_Pair("\u1E9Czero",null)),null)))))))),null)))))), (new sc_Pair("\u1E9Cequal",(new sc_Pair((new sc_Pair("\u1E9Clast",(new sc_Pair((new sc_Pair("\u1E9Cappend",(new sc_Pair("\u1E9Ca",(new sc_Pair("\u1E9Cb",null)))))),null)))),(new sc_Pair((new sc_Pair("\u1E9Cif",(new sc_Pair((new sc_Pair("\u1E9Clistp",(new sc_Pair("\u1E9Cb",null)))),(new sc_Pair((new sc_Pair("\u1E9Clast",(new sc_Pair("\u1E9Cb",null)))),(new sc_Pair((new sc_Pair("\u1E9Cif",(new sc_Pair((new sc_Pair("\u1E9Clistp",(new sc_Pair("\u1E9Ca",null)))),(new sc_Pair((new sc_Pair("\u1E9Ccons",(new sc_Pair((new sc_Pair("\u1E9Ccar",(new sc_Pair((new sc_Pair("\u1E9Clast",(new sc_Pair("\u1E9Ca",null)))),null)))),(new sc_Pair("\u1E9Cb",null)))))),(new sc_Pair("\u1E9Cb",null)))))))),null)))))))),null)))))), (new sc_Pair("\u1E9Cequal",(new sc_Pair((new sc_Pair("\u1E9Cequal",(new sc_Pair((new sc_Pair("\u1E9Clessp",(new sc_Pair("\u1E9Cx",(new sc_Pair("\u1E9Cy",null)))))),(new sc_Pair("\u1E9Cz",null)))))),(new sc_Pair((new sc_Pair("\u1E9Cif",(new sc_Pair((new sc_Pair("\u1E9Clessp",(new sc_Pair("\u1E9Cx",(new sc_Pair("\u1E9Cy",null)))))),(new sc_Pair((new sc_Pair("\u1E9Cequal",(new sc_Pair((new sc_Pair("\u1E9Ct",null)),(new sc_Pair("\u1E9Cz",null)))))),(new sc_Pair((new sc_Pair("\u1E9Cequal",(new sc_Pair((new sc_Pair("\u1E9Cf",null)),(new sc_Pair("\u1E9Cz",null)))))),null)))))))),null)))))), (new sc_Pair("\u1E9Cequal",(new sc_Pair((new sc_Pair("\u1E9Cassignment",(new sc_Pair("\u1E9Cx",(new sc_Pair((new sc_Pair("\u1E9Cappend",(new sc_Pair("\u1E9Ca",(new sc_Pair("\u1E9Cb",null)))))),null)))))),(new sc_Pair((new sc_Pair("\u1E9Cif",(new sc_Pair((new sc_Pair("\u1E9Cassignedp",(new sc_Pair("\u1E9Cx",(new sc_Pair("\u1E9Ca",null)))))),(new sc_Pair((new sc_Pair("\u1E9Cassignment",(new sc_Pair("\u1E9Cx",(new sc_Pair("\u1E9Ca",null)))))),(new sc_Pair((new sc_Pair("\u1E9Cassignment",(new sc_Pair("\u1E9Cx",(new sc_Pair("\u1E9Cb",null)))))),null)))))))),null)))))), (new sc_Pair("\u1E9Cequal",(new sc_Pair((new sc_Pair("\u1E9Ccar",(new sc_Pair((new sc_Pair("\u1E9Cgopher",(new sc_Pair("\u1E9Cx",null)))),null)))),(new sc_Pair((new sc_Pair("\u1E9Cif",(new sc_Pair((new sc_Pair("\u1E9Clistp",(new sc_Pair("\u1E9Cx",null)))),(new sc_Pair((new sc_Pair("\u1E9Ccar",(new sc_Pair((new sc_Pair("\u1E9Cflatten",(new sc_Pair("\u1E9Cx",null)))),null)))),(new sc_Pair((new sc_Pair("\u1E9Czero",null)),null)))))))),null)))))), (new sc_Pair("\u1E9Cequal",(new sc_Pair((new sc_Pair("\u1E9Cflatten",(new sc_Pair((new sc_Pair("\u1E9Ccdr",(new sc_Pair((new sc_Pair("\u1E9Cgopher",(new sc_Pair("\u1E9Cx",null)))),null)))),null)))),(new sc_Pair((new sc_Pair("\u1E9Cif",(new sc_Pair((new sc_Pair("\u1E9Clistp",(new sc_Pair("\u1E9Cx",null)))),(new sc_Pair((new sc_Pair("\u1E9Ccdr",(new sc_Pair((new sc_Pair("\u1E9Cflatten",(new sc_Pair("\u1E9Cx",null)))),null)))),(new sc_Pair((new sc_Pair("\u1E9Ccons",(new sc_Pair((new sc_Pair("\u1E9Czero",null)),(new sc_Pair((new sc_Pair("\u1E9Cnil",null)),null)))))),null)))))))),null)))))), (new sc_Pair("\u1E9Cequal",(new sc_Pair((new sc_Pair("\u1E9Cquotient",(new sc_Pair((new sc_Pair("\u1E9Ctimes",(new sc_Pair("\u1E9Cy",(new sc_Pair("\u1E9Cx",null)))))),(new sc_Pair("\u1E9Cy",null)))))),(new sc_Pair((new sc_Pair("\u1E9Cif",(new sc_Pair((new sc_Pair("\u1E9Czerop",(new sc_Pair("\u1E9Cy",null)))),(new sc_Pair((new sc_Pair("\u1E9Czero",null)),(new sc_Pair((new sc_Pair("\u1E9Cfix",(new sc_Pair("\u1E9Cx",null)))),null)))))))),null)))))), (new sc_Pair("\u1E9Cequal",(new sc_Pair((new sc_Pair("\u1E9Cget",(new sc_Pair("\u1E9Cj",(new sc_Pair((new sc_Pair("\u1E9Cset",(new sc_Pair("\u1E9Ci",(new sc_Pair("\u1E9Cval",(new sc_Pair("\u1E9Cmem",null)))))))),null)))))),(new sc_Pair((new sc_Pair("\u1E9Cif",(new sc_Pair((new sc_Pair("\u1E9Ceqp",(new sc_Pair("\u1E9Cj",(new sc_Pair("\u1E9Ci",null)))))),(new sc_Pair("\u1E9Cval",(new sc_Pair((new sc_Pair("\u1E9Cget",(new sc_Pair("\u1E9Cj",(new sc_Pair("\u1E9Cmem",null)))))),null)))))))),null)))))))); (const_nboyer = (new sc_Pair((new sc_Pair("\u1E9Cx",(new sc_Pair("\u1E9Cf",(new sc_Pair((new sc_Pair("\u1E9Cplus",(new sc_Pair((new sc_Pair("\u1E9Cplus",(new sc_Pair("\u1E9Ca",(new sc_Pair("\u1E9Cb",null)))))),(new sc_Pair((new sc_Pair("\u1E9Cplus",(new sc_Pair("\u1E9Cc",(new sc_Pair((new sc_Pair("\u1E9Czero",null)),null)))))),null)))))),null)))))),(new sc_Pair((new sc_Pair("\u1E9Cy",(new sc_Pair("\u1E9Cf",(new sc_Pair((new sc_Pair("\u1E9Ctimes",(new sc_Pair((new sc_Pair("\u1E9Ctimes",(new sc_Pair("\u1E9Ca",(new sc_Pair("\u1E9Cb",null)))))),(new sc_Pair((new sc_Pair("\u1E9Cplus",(new sc_Pair("\u1E9Cc",(new sc_Pair("\u1E9Cd",null)))))),null)))))),null)))))),(new sc_Pair((new sc_Pair("\u1E9Cz",(new sc_Pair("\u1E9Cf",(new sc_Pair((new sc_Pair("\u1E9Creverse",(new sc_Pair((new sc_Pair("\u1E9Cappend",(new sc_Pair((new sc_Pair("\u1E9Cappend",(new sc_Pair("\u1E9Ca",(new sc_Pair("\u1E9Cb",null)))))),(new sc_Pair((new sc_Pair("\u1E9Cnil",null)),null)))))),null)))),null)))))),(new sc_Pair((new sc_Pair("\u1E9Cu",(new sc_Pair("\u1E9Cequal",(new sc_Pair((new sc_Pair("\u1E9Cplus",(new sc_Pair("\u1E9Ca",(new sc_Pair("\u1E9Cb",null)))))),(new sc_Pair((new sc_Pair("\u1E9Cdifference",(new sc_Pair("\u1E9Cx",(new sc_Pair("\u1E9Cy",null)))))),null)))))))),(new sc_Pair((new sc_Pair("\u1E9Cw",(new sc_Pair("\u1E9Clessp",(new sc_Pair((new sc_Pair("\u1E9Cremainder",(new sc_Pair("\u1E9Ca",(new sc_Pair("\u1E9Cb",null)))))),(new sc_Pair((new sc_Pair("\u1E9Cmember",(new sc_Pair("\u1E9Ca",(new sc_Pair((new sc_Pair("\u1E9Clength",(new sc_Pair("\u1E9Cb",null)))),null)))))),null)))))))),null))))))))))); BgL_nboyerzd2benchmarkzd2 = function() { var args = null; for (var sc_tmp = arguments.length - 1; sc_tmp >= 0; sc_tmp--) { args = sc_cons(arguments[sc_tmp], args); } var n; return ((n = ((args === null)?(0):(args.car))), (BgL_setupzd2boyerzd2()), (BgL_runzd2benchmarkzd2(("nboyer"+(sc_number2string(n))), (1), function() { return (BgL_testzd2boyerzd2(n)); }, function(rewrites) { if ((sc_isNumber(rewrites))) switch (n) { case (0): return (rewrites===(95024)); break; case (1): return (rewrites===(591777)); break; case (2): return (rewrites===(1813975)); break; case (3): return (rewrites===(5375678)); break; case (4): return (rewrites===(16445406)); break; case (5): return (rewrites===(51507739)); break; default: return true; break; } else return false; }))); }; BgL_setupzd2boyerzd2 = function() { return true; }; BgL_testzd2boyerzd2 = function() { return true; }; translate_term_nboyer = function(term) { var lst; return (!(term instanceof sc_Pair)?term:(new sc_Pair((BgL_sc_symbolzd2ze3symbolzd2record_1ze3_nboyer((term.car))), ((lst = (term.cdr)), ((lst === null)?null:(new sc_Pair((translate_term_nboyer((lst.car))), (translate_args_nboyer((lst.cdr)))))))))); }; translate_args_nboyer = function(lst) { var sc_lst_5; var term; return ((lst === null)?null:(new sc_Pair(((term = (lst.car)), (!(term instanceof sc_Pair)?term:(new sc_Pair((BgL_sc_symbolzd2ze3symbolzd2record_1ze3_nboyer((term.car))), (translate_args_nboyer((term.cdr))))))), ((sc_lst_5 = (lst.cdr)), ((sc_lst_5 === null)?null:(new sc_Pair((translate_term_nboyer((sc_lst_5.car))), (translate_args_nboyer((sc_lst_5.cdr)))))))))); }; untranslate_term_nboyer = function(term) { var optrOpnd; var tail1131; var L1127; var falseHead1130; var symbol_record; if (!(term instanceof sc_Pair)) return term; else { (falseHead1130 = (new sc_Pair(null, null))); (L1127 = (term.cdr)); (tail1131 = falseHead1130); while (!(L1127 === null)) { { (tail1131.cdr = (new sc_Pair((untranslate_term_nboyer((L1127.car))), null))); (tail1131 = (tail1131.cdr)); (L1127 = (L1127.cdr)); } } (optrOpnd = (falseHead1130.cdr)); return (new sc_Pair(((symbol_record = (term.car)), (symbol_record[(0)])), optrOpnd)); } }; BgL_sc_symbolzd2ze3symbolzd2record_1ze3_nboyer = function(sym) { var r; var x; return ((x = (sc_assq(sym, BgL_sc_za2symbolzd2recordszd2alistza2_2z00_nboyer))), ((x!== false)?(x.cdr):((r = [sym, null]), (BgL_sc_za2symbolzd2recordszd2alistza2_2z00_nboyer = (new sc_Pair((new sc_Pair(sym, r)), BgL_sc_za2symbolzd2recordszd2alistza2_2z00_nboyer))), r))); }; (BgL_sc_za2symbolzd2recordszd2alistza2_2z00_nboyer = null); translate_alist_nboyer = function(alist) { var sc_alist_6; var term; return ((alist === null)?null:(new sc_Pair((new sc_Pair((alist.car.car), ((term = (alist.car.cdr)), (!(term instanceof sc_Pair)?term:(new sc_Pair((BgL_sc_symbolzd2ze3symbolzd2record_1ze3_nboyer((term.car))), (translate_args_nboyer((term.cdr))))))))), ((sc_alist_6 = (alist.cdr)), ((sc_alist_6 === null)?null:(new sc_Pair((new sc_Pair((sc_alist_6.car.car), (translate_term_nboyer((sc_alist_6.car.cdr))))), (translate_alist_nboyer((sc_alist_6.cdr)))))))))); }; apply_subst_nboyer = function(alist, term) { var lst; var temp_temp; return (!(term instanceof sc_Pair)?((temp_temp = (sc_assq(term, alist))), ((temp_temp!== false)?(temp_temp.cdr):term)):(new sc_Pair((term.car), ((lst = (term.cdr)), ((lst === null)?null:(new sc_Pair((apply_subst_nboyer(alist, (lst.car))), (apply_subst_lst_nboyer(alist, (lst.cdr)))))))))); }; apply_subst_lst_nboyer = function(alist, lst) { var sc_lst_7; return ((lst === null)?null:(new sc_Pair((apply_subst_nboyer(alist, (lst.car))), ((sc_lst_7 = (lst.cdr)), ((sc_lst_7 === null)?null:(new sc_Pair((apply_subst_nboyer(alist, (sc_lst_7.car))), (apply_subst_lst_nboyer(alist, (sc_lst_7.cdr)))))))))); }; tautologyp_nboyer = function(sc_x_11, true_lst, false_lst) { var tmp1125; var x; var tmp1126; var sc_x_8; var sc_tmp1125_9; var sc_tmp1126_10; var sc_x_11; var true_lst; var false_lst; while (true) { if ((((sc_tmp1126_10 = (is_term_equal_nboyer(sc_x_11, true_term_nboyer))), ((sc_tmp1126_10!== false)?sc_tmp1126_10:(is_term_member_nboyer(sc_x_11, true_lst))))!== false)) return true; else if ((((sc_tmp1125_9 = (is_term_equal_nboyer(sc_x_11, false_term_nboyer))), ((sc_tmp1125_9!== false)?sc_tmp1125_9:(is_term_member_nboyer(sc_x_11, false_lst))))!== false)) return false; else if (!(sc_x_11 instanceof sc_Pair)) return false; else if (((sc_x_11.car)===if_constructor_nboyer)) if ((((sc_x_8 = (sc_x_11.cdr.car)), (tmp1126 = (is_term_equal_nboyer(sc_x_8, true_term_nboyer))), ((tmp1126!== false)?tmp1126:(is_term_member_nboyer(sc_x_8, true_lst))))!== false)) (sc_x_11 = (sc_x_11.cdr.cdr.car)); else if ((((x = (sc_x_11.cdr.car)), (tmp1125 = (is_term_equal_nboyer(x, false_term_nboyer))), ((tmp1125!== false)?tmp1125:(is_term_member_nboyer(x, false_lst))))!== false)) (sc_x_11 = (sc_x_11.cdr.cdr.cdr.car)); else if (((tautologyp_nboyer((sc_x_11.cdr.cdr.car), (new sc_Pair((sc_x_11.cdr.car), true_lst)), false_lst))!== false)) { (false_lst = (new sc_Pair((sc_x_11.cdr.car), false_lst))); (sc_x_11 = (sc_x_11.cdr.cdr.cdr.car)); } else return false; else return false; } }; (if_constructor_nboyer = "\u1E9C*"); (rewrite_count_nboyer = (0)); rewrite_nboyer = function(term) { var term2; var sc_term_12; var lst; var symbol_record; var sc_lst_13; { (++rewrite_count_nboyer); if (!(term instanceof sc_Pair)) return term; else { (sc_term_12 = (new sc_Pair((term.car), ((sc_lst_13 = (term.cdr)), ((sc_lst_13 === null)?null:(new sc_Pair((rewrite_nboyer((sc_lst_13.car))), (rewrite_args_nboyer((sc_lst_13.cdr)))))))))); (lst = ((symbol_record = (term.car)), (symbol_record[(1)]))); while (true) { if ((lst === null)) return sc_term_12; else if ((((term2 = ((lst.car).cdr.car)), (unify_subst_nboyer = null), (one_way_unify1_nboyer(sc_term_12, term2)))!== false)) return (rewrite_nboyer((apply_subst_nboyer(unify_subst_nboyer, ((lst.car).cdr.cdr.car))))); else (lst = (lst.cdr)); } } } }; rewrite_args_nboyer = function(lst) { var sc_lst_14; return ((lst === null)?null:(new sc_Pair((rewrite_nboyer((lst.car))), ((sc_lst_14 = (lst.cdr)), ((sc_lst_14 === null)?null:(new sc_Pair((rewrite_nboyer((sc_lst_14.car))), (rewrite_args_nboyer((sc_lst_14.cdr)))))))))); }; (unify_subst_nboyer = "\u1E9C*"); one_way_unify1_nboyer = function(term1, term2) { var lst1; var lst2; var temp_temp; if (!(term2 instanceof sc_Pair)) { (temp_temp = (sc_assq(term2, unify_subst_nboyer))); if ((temp_temp!== false)) return (is_term_equal_nboyer(term1, (temp_temp.cdr))); else if ((sc_isNumber(term2))) return (sc_isEqual(term1, term2)); else { (unify_subst_nboyer = (new sc_Pair((new sc_Pair(term2, term1)), unify_subst_nboyer))); return true; } } else if (!(term1 instanceof sc_Pair)) return false; else if (((term1.car)===(term2.car))) { (lst1 = (term1.cdr)); (lst2 = (term2.cdr)); while (true) { if ((lst1 === null)) return (lst2 === null); else if ((lst2 === null)) return false; else if (((one_way_unify1_nboyer((lst1.car), (lst2.car)))!== false)) { (lst1 = (lst1.cdr)); (lst2 = (lst2.cdr)); } else return false; } } else return false; }; (false_term_nboyer = "\u1E9C*"); (true_term_nboyer = "\u1E9C*"); trans_of_implies1_nboyer = function(n) { var sc_n_15; return ((sc_isEqual(n, (1)))?(sc_list("\u1E9Cimplies", (0), (1))):(sc_list("\u1E9Cand", (sc_list("\u1E9Cimplies", (n-(1)), n)), ((sc_n_15 = (n-(1))), ((sc_isEqual(sc_n_15, (1)))?(sc_list("\u1E9Cimplies", (0), (1))):(sc_list("\u1E9Cand", (sc_list("\u1E9Cimplies", (sc_n_15-(1)), sc_n_15)), (trans_of_implies1_nboyer((sc_n_15-(1))))))))))); }; is_term_equal_nboyer = function(x, y) { var lst1; var lst2; var r2; var r1; if ((x instanceof sc_Pair)) if ((y instanceof sc_Pair)) if ((((r1 = (x.car)), (r2 = (y.car)), (r1===r2))!== false)) { (lst1 = (x.cdr)); (lst2 = (y.cdr)); while (true) { if ((lst1 === null)) return (lst2 === null); else if ((lst2 === null)) return false; else if (((is_term_equal_nboyer((lst1.car), (lst2.car)))!== false)) { (lst1 = (lst1.cdr)); (lst2 = (lst2.cdr)); } else return false; } } else return false; else return false; else return (sc_isEqual(x, y)); }; is_term_member_nboyer = function(x, lst) { var x; var lst; while (true) { if ((lst === null)) return false; else if (((is_term_equal_nboyer(x, (lst.car)))!== false)) return true; else (lst = (lst.cdr)); } }; BgL_setupzd2boyerzd2 = function() { var symbol_record; var value; var BgL_sc_symbolzd2record_16zd2; var sym; var sc_sym_17; var term; var lst; var sc_term_18; var sc_term_19; { (BgL_sc_za2symbolzd2recordszd2alistza2_2z00_nboyer = null); (if_constructor_nboyer = (BgL_sc_symbolzd2ze3symbolzd2record_1ze3_nboyer("\u1E9Cif"))); (false_term_nboyer = ((sc_term_19 = (new sc_Pair("\u1E9Cf",null))), (!(sc_term_19 instanceof sc_Pair)?sc_term_19:(new sc_Pair((BgL_sc_symbolzd2ze3symbolzd2record_1ze3_nboyer((sc_term_19.car))), (translate_args_nboyer((sc_term_19.cdr)))))))); (true_term_nboyer = ((sc_term_18 = (new sc_Pair("\u1E9Ct",null))), (!(sc_term_18 instanceof sc_Pair)?sc_term_18:(new sc_Pair((BgL_sc_symbolzd2ze3symbolzd2record_1ze3_nboyer((sc_term_18.car))), (translate_args_nboyer((sc_term_18.cdr)))))))); (lst = sc_const_3_nboyer); while (!(lst === null)) { { (term = (lst.car)); if (((term instanceof sc_Pair)&&(((term.car)==="\u1E9Cequal")&&((term.cdr.car) instanceof sc_Pair)))) { (sc_sym_17 = ((term.cdr.car).car)); (value = (new sc_Pair((!(term instanceof sc_Pair)?term:(new sc_Pair((BgL_sc_symbolzd2ze3symbolzd2record_1ze3_nboyer((term.car))), (translate_args_nboyer((term.cdr)))))), ((sym = ((term.cdr.car).car)), (BgL_sc_symbolzd2record_16zd2 = (BgL_sc_symbolzd2ze3symbolzd2record_1ze3_nboyer(sym))), (BgL_sc_symbolzd2record_16zd2[(1)]))))); (symbol_record = (BgL_sc_symbolzd2ze3symbolzd2record_1ze3_nboyer(sc_sym_17))); (symbol_record[(1)] = value); } else (sc_error("ADD-LEMMA did not like term: ", term)); (lst = (lst.cdr)); } } return true; } }; BgL_testzd2boyerzd2 = function(n) { var optrOpnd; var term; var sc_n_20; var answer; var sc_term_21; var sc_term_22; { (rewrite_count_nboyer = (0)); (term = sc_const_4_nboyer); (sc_n_20 = n); while (!(sc_n_20=== 0)) { { (term = (sc_list("\u1E9Cor", term, (new sc_Pair("\u1E9Cf",null))))); (--sc_n_20); } } (sc_term_22 = term); if (!(sc_term_22 instanceof sc_Pair)) (optrOpnd = sc_term_22); else (optrOpnd = (new sc_Pair((BgL_sc_symbolzd2ze3symbolzd2record_1ze3_nboyer((sc_term_22.car))), (translate_args_nboyer((sc_term_22.cdr)))))); (sc_term_21 = (apply_subst_nboyer(((const_nboyer === null)?null:(new sc_Pair((new sc_Pair((const_nboyer.car.car), (translate_term_nboyer((const_nboyer.car.cdr))))), (translate_alist_nboyer((const_nboyer.cdr)))))), optrOpnd))); (answer = (tautologyp_nboyer((rewrite_nboyer(sc_term_21)), null, null))); (sc_write(rewrite_count_nboyer)); (sc_display(" rewrites")); (sc_newline()); if ((answer!== false)) return rewrite_count_nboyer; else return false; } }; } /* Exported Variables */ var BgL_parsezd2ze3nbzd2treesze3; var BgL_earleyzd2benchmarkzd2; var BgL_parsezd2ze3parsedzf3zc2; var test; var BgL_parsezd2ze3treesz31; var BgL_makezd2parserzd2; /* End Exports */ var const_earley; { (const_earley = (new sc_Pair((new sc_Pair("\u1E9Cs",(new sc_Pair((new sc_Pair("\u1E9Ca",null)),(new sc_Pair((new sc_Pair("\u1E9Cs",(new sc_Pair("\u1E9Cs",null)))),null)))))),null))); BgL_makezd2parserzd2 = function(grammar, lexer) { var i; var parser_descr; var def_loop; var nb_nts; var names; var steps; var predictors; var enders; var starters; var nts; var sc_names_1; var sc_steps_2; var sc_predictors_3; var sc_enders_4; var sc_starters_5; var nb_confs; var BgL_sc_defzd2loop_6zd2; var BgL_sc_nbzd2nts_7zd2; var sc_nts_8; var BgL_sc_defzd2loop_9zd2; var ind; { ind = function(nt, sc_nts_10) { var i; { (i = ((sc_nts_10.length)-(1))); while (true) { if ((i>=(0))) if ((sc_isEqual((sc_nts_10[i]), nt))) return i; else (--i); else return false; } } }; (sc_nts_8 = ((BgL_sc_defzd2loop_9zd2 = function(defs, sc_nts_11) { var rule_loop; var head; var def; return ((defs instanceof sc_Pair)?((def = (defs.car)), (head = (def.car)), (rule_loop = function(rules, sc_nts_12) { var nt; var l; var sc_nts_13; var rule; if ((rules instanceof sc_Pair)) { (rule = (rules.car)); (l = rule); (sc_nts_13 = sc_nts_12); while ((l instanceof sc_Pair)) { { (nt = (l.car)); (l = (l.cdr)); (sc_nts_13 = (((sc_member(nt, sc_nts_13))!== false)?sc_nts_13:(new sc_Pair(nt, sc_nts_13)))); } } return (rule_loop((rules.cdr), sc_nts_13)); } else return (BgL_sc_defzd2loop_9zd2((defs.cdr), sc_nts_12)); }), (rule_loop((def.cdr), (((sc_member(head, sc_nts_11))!== false)?sc_nts_11:(new sc_Pair(head, sc_nts_11)))))):(sc_list2vector((sc_reverse(sc_nts_11))))); }), (BgL_sc_defzd2loop_9zd2(grammar, null)))); (BgL_sc_nbzd2nts_7zd2 = (sc_nts_8.length)); (nb_confs = (((BgL_sc_defzd2loop_6zd2 = function(defs, BgL_sc_nbzd2confs_14zd2) { var rule_loop; var def; return ((defs instanceof sc_Pair)?((def = (defs.car)), (rule_loop = function(rules, BgL_sc_nbzd2confs_15zd2) { var l; var BgL_sc_nbzd2confs_16zd2; var rule; if ((rules instanceof sc_Pair)) { (rule = (rules.car)); (l = rule); (BgL_sc_nbzd2confs_16zd2 = BgL_sc_nbzd2confs_15zd2); while ((l instanceof sc_Pair)) { { (l = (l.cdr)); (++BgL_sc_nbzd2confs_16zd2); } } return (rule_loop((rules.cdr), (BgL_sc_nbzd2confs_16zd2+(1)))); } else return (BgL_sc_defzd2loop_6zd2((defs.cdr), BgL_sc_nbzd2confs_15zd2)); }), (rule_loop((def.cdr), BgL_sc_nbzd2confs_14zd2))):BgL_sc_nbzd2confs_14zd2); }), (BgL_sc_defzd2loop_6zd2(grammar, (0))))+BgL_sc_nbzd2nts_7zd2)); (sc_starters_5 = (sc_makeVector(BgL_sc_nbzd2nts_7zd2, null))); (sc_enders_4 = (sc_makeVector(BgL_sc_nbzd2nts_7zd2, null))); (sc_predictors_3 = (sc_makeVector(BgL_sc_nbzd2nts_7zd2, null))); (sc_steps_2 = (sc_makeVector(nb_confs, false))); (sc_names_1 = (sc_makeVector(nb_confs, false))); (nts = sc_nts_8); (starters = sc_starters_5); (enders = sc_enders_4); (predictors = sc_predictors_3); (steps = sc_steps_2); (names = sc_names_1); (nb_nts = (sc_nts_8.length)); (i = (nb_nts-(1))); while ((i>=(0))) { { (sc_steps_2[i] = (i-nb_nts)); (sc_names_1[i] = (sc_list((sc_nts_8[i]), (0)))); (sc_enders_4[i] = (sc_list(i))); (--i); } } def_loop = function(defs, conf) { var rule_loop; var head; var def; return ((defs instanceof sc_Pair)?((def = (defs.car)), (head = (def.car)), (rule_loop = function(rules, conf, rule_num) { var i; var sc_i_17; var nt; var l; var sc_conf_18; var sc_i_19; var rule; if ((rules instanceof sc_Pair)) { (rule = (rules.car)); (names[conf] = (sc_list(head, rule_num))); (sc_i_19 = (ind(head, nts))); (starters[sc_i_19] = (new sc_Pair(conf, (starters[sc_i_19])))); (l = rule); (sc_conf_18 = conf); while ((l instanceof sc_Pair)) { { (nt = (l.car)); (steps[sc_conf_18] = (ind(nt, nts))); (sc_i_17 = (ind(nt, nts))); (predictors[sc_i_17] = (new sc_Pair(sc_conf_18, (predictors[sc_i_17])))); (l = (l.cdr)); (++sc_conf_18); } } (steps[sc_conf_18] = ((ind(head, nts))-nb_nts)); (i = (ind(head, nts))); (enders[i] = (new sc_Pair(sc_conf_18, (enders[i])))); return (rule_loop((rules.cdr), (sc_conf_18+(1)), (rule_num+(1)))); } else return (def_loop((defs.cdr), conf)); }), (rule_loop((def.cdr), conf, (1)))):undefined); }; (def_loop(grammar, (sc_nts_8.length))); (parser_descr = [lexer, sc_nts_8, sc_starters_5, sc_enders_4, sc_predictors_3, sc_steps_2, sc_names_1]); return function(input) { var optrOpnd; var sc_optrOpnd_20; var sc_optrOpnd_21; var sc_optrOpnd_22; var loop1; var BgL_sc_stateza2_23za2; var toks; var BgL_sc_nbzd2nts_24zd2; var sc_steps_25; var sc_enders_26; var state_num; var BgL_sc_statesza2_27za2; var states; var i; var conf; var l; var tok_nts; var sc_i_28; var sc_i_29; var l1; var l2; var tok; var tail1129; var L1125; var goal_enders; var BgL_sc_statesza2_30za2; var BgL_sc_nbzd2nts_31zd2; var BgL_sc_nbzd2confs_32zd2; var nb_toks; var goal_starters; var sc_states_33; var BgL_sc_nbzd2confs_34zd2; var BgL_sc_nbzd2toks_35zd2; var sc_toks_36; var falseHead1128; var sc_names_37; var sc_steps_38; var sc_predictors_39; var sc_enders_40; var sc_starters_41; var sc_nts_42; var lexer; var sc_ind_43; var make_states; var BgL_sc_confzd2setzd2getza2_44za2; var conf_set_merge_new_bang; var conf_set_adjoin; var BgL_sc_confzd2setzd2adjoinza2_45za2; var BgL_sc_confzd2setzd2adjoinza2za2_46z00; var conf_set_union; var forw; var is_parsed; var deriv_trees; var BgL_sc_derivzd2treesza2_47z70; var nb_deriv_trees; var BgL_sc_nbzd2derivzd2treesza2_48za2; { sc_ind_43 = function(nt, sc_nts_49) { var i; { (i = ((sc_nts_49.length)-(1))); while (true) { if ((i>=(0))) if ((sc_isEqual((sc_nts_49[i]), nt))) return i; else (--i); else return false; } } }; make_states = function(BgL_sc_nbzd2toks_50zd2, BgL_sc_nbzd2confs_51zd2) { var v; var i; var sc_states_52; { (sc_states_52 = (sc_makeVector((BgL_sc_nbzd2toks_50zd2+(1)), false))); (i = BgL_sc_nbzd2toks_50zd2); while ((i>=(0))) { { (v = (sc_makeVector((BgL_sc_nbzd2confs_51zd2+(1)), false))); (v[(0)] = (-1)); (sc_states_52[i] = v); (--i); } } return sc_states_52; } }; BgL_sc_confzd2setzd2getza2_44za2 = function(state, BgL_sc_statezd2num_53zd2, sc_conf_54) { var conf_set; var BgL_sc_confzd2set_55zd2; return ((BgL_sc_confzd2set_55zd2 = (state[(sc_conf_54+(1))])), ((BgL_sc_confzd2set_55zd2!== false)?BgL_sc_confzd2set_55zd2:((conf_set = (sc_makeVector((BgL_sc_statezd2num_53zd2+(6)), false))), (conf_set[(1)] = (-3)), (conf_set[(2)] = (-1)), (conf_set[(3)] = (-1)), (conf_set[(4)] = (-1)), (state[(sc_conf_54+(1))] = conf_set), conf_set))); }; conf_set_merge_new_bang = function(conf_set) { return ((conf_set[((conf_set[(1)])+(5))] = (conf_set[(4)])), (conf_set[(1)] = (conf_set[(3)])), (conf_set[(3)] = (-1)), (conf_set[(4)] = (-1))); }; conf_set_adjoin = function(state, conf_set, sc_conf_56, i) { var tail; return ((tail = (conf_set[(3)])), (conf_set[(i+(5))] = (-1)), (conf_set[(tail+(5))] = i), (conf_set[(3)] = i), ((tail<(0))?((conf_set[(0)] = (state[(0)])), (state[(0)] = sc_conf_56)):undefined)); }; BgL_sc_confzd2setzd2adjoinza2_45za2 = function(sc_states_57, BgL_sc_statezd2num_58zd2, l, i) { var conf_set; var sc_conf_59; var l1; var state; { (state = (sc_states_57[BgL_sc_statezd2num_58zd2])); (l1 = l); while ((l1 instanceof sc_Pair)) { { (sc_conf_59 = (l1.car)); (conf_set = (BgL_sc_confzd2setzd2getza2_44za2(state, BgL_sc_statezd2num_58zd2, sc_conf_59))); if (((conf_set[(i+(5))])=== false)) { (conf_set_adjoin(state, conf_set, sc_conf_59, i)); (l1 = (l1.cdr)); } else (l1 = (l1.cdr)); } } return undefined; } }; BgL_sc_confzd2setzd2adjoinza2za2_46z00 = function(sc_states_60, BgL_sc_statesza2_61za2, BgL_sc_statezd2num_62zd2, sc_conf_63, i) { var BgL_sc_confzd2setza2_64z70; var BgL_sc_stateza2_65za2; var conf_set; var state; return ((state = (sc_states_60[BgL_sc_statezd2num_62zd2])), ((((conf_set = (state[(sc_conf_63+(1))])), ((conf_set!== false)?(conf_set[(i+(5))]):false))!== false)?((BgL_sc_stateza2_65za2 = (BgL_sc_statesza2_61za2[BgL_sc_statezd2num_62zd2])), (BgL_sc_confzd2setza2_64z70 = (BgL_sc_confzd2setzd2getza2_44za2(BgL_sc_stateza2_65za2, BgL_sc_statezd2num_62zd2, sc_conf_63))), (((BgL_sc_confzd2setza2_64z70[(i+(5))])=== false)?(conf_set_adjoin(BgL_sc_stateza2_65za2, BgL_sc_confzd2setza2_64z70, sc_conf_63, i)):undefined), true):false)); }; conf_set_union = function(state, conf_set, sc_conf_66, other_set) { var i; { (i = (other_set[(2)])); while ((i>=(0))) { if (((conf_set[(i+(5))])=== false)) { (conf_set_adjoin(state, conf_set, sc_conf_66, i)); (i = (other_set[(i+(5))])); } else (i = (other_set[(i+(5))])); } return undefined; } }; forw = function(sc_states_67, BgL_sc_statezd2num_68zd2, sc_starters_69, sc_enders_70, sc_predictors_71, sc_steps_72, sc_nts_73) { var next_set; var next; var conf_set; var ender; var l; var starter_set; var starter; var sc_l_74; var sc_loop1_75; var head; var BgL_sc_confzd2set_76zd2; var BgL_sc_statezd2num_77zd2; var state; var sc_states_78; var preds; var BgL_sc_confzd2set_79zd2; var step; var sc_conf_80; var BgL_sc_nbzd2nts_81zd2; var sc_state_82; { (sc_state_82 = (sc_states_67[BgL_sc_statezd2num_68zd2])); (BgL_sc_nbzd2nts_81zd2 = (sc_nts_73.length)); while (true) { { (sc_conf_80 = (sc_state_82[(0)])); if ((sc_conf_80>=(0))) { (step = (sc_steps_72[sc_conf_80])); (BgL_sc_confzd2set_79zd2 = (sc_state_82[(sc_conf_80+(1))])); (head = (BgL_sc_confzd2set_79zd2[(4)])); (sc_state_82[(0)] = (BgL_sc_confzd2set_79zd2[(0)])); (conf_set_merge_new_bang(BgL_sc_confzd2set_79zd2)); if ((step>=(0))) { (sc_l_74 = (sc_starters_69[step])); while ((sc_l_74 instanceof sc_Pair)) { { (starter = (sc_l_74.car)); (starter_set = (BgL_sc_confzd2setzd2getza2_44za2(sc_state_82, BgL_sc_statezd2num_68zd2, starter))); if (((starter_set[(BgL_sc_statezd2num_68zd2+(5))])=== false)) { (conf_set_adjoin(sc_state_82, starter_set, starter, BgL_sc_statezd2num_68zd2)); (sc_l_74 = (sc_l_74.cdr)); } else (sc_l_74 = (sc_l_74.cdr)); } } (l = (sc_enders_70[step])); while ((l instanceof sc_Pair)) { { (ender = (l.car)); if ((((conf_set = (sc_state_82[(ender+(1))])), ((conf_set!== false)?(conf_set[(BgL_sc_statezd2num_68zd2+(5))]):false))!== false)) { (next = (sc_conf_80+(1))); (next_set = (BgL_sc_confzd2setzd2getza2_44za2(sc_state_82, BgL_sc_statezd2num_68zd2, next))); (conf_set_union(sc_state_82, next_set, next, BgL_sc_confzd2set_79zd2)); (l = (l.cdr)); } else (l = (l.cdr)); } } } else { (preds = (sc_predictors_71[(step+BgL_sc_nbzd2nts_81zd2)])); (sc_states_78 = sc_states_67); (state = sc_state_82); (BgL_sc_statezd2num_77zd2 = BgL_sc_statezd2num_68zd2); (BgL_sc_confzd2set_76zd2 = BgL_sc_confzd2set_79zd2); sc_loop1_75 = function(l) { var sc_state_83; var BgL_sc_nextzd2set_84zd2; var sc_next_85; var pred_set; var i; var pred; if ((l instanceof sc_Pair)) { (pred = (l.car)); (i = head); while ((i>=(0))) { { (pred_set = ((sc_state_83 = (sc_states_78[i])), (sc_state_83[(pred+(1))]))); if ((pred_set!== false)) { (sc_next_85 = (pred+(1))); (BgL_sc_nextzd2set_84zd2 = (BgL_sc_confzd2setzd2getza2_44za2(state, BgL_sc_statezd2num_77zd2, sc_next_85))); (conf_set_union(state, BgL_sc_nextzd2set_84zd2, sc_next_85, pred_set)); } (i = (BgL_sc_confzd2set_76zd2[(i+(5))])); } } return (sc_loop1_75((l.cdr))); } else return undefined; }; (sc_loop1_75(preds)); } } else return undefined; } } } }; is_parsed = function(nt, i, j, sc_nts_86, sc_enders_87, sc_states_88) { var conf_set; var state; var sc_conf_89; var l; var BgL_sc_ntza2_90za2; { (BgL_sc_ntza2_90za2 = (sc_ind_43(nt, sc_nts_86))); if ((BgL_sc_ntza2_90za2!== false)) { (sc_nts_86.length); (l = (sc_enders_87[BgL_sc_ntza2_90za2])); while (true) { if ((l instanceof sc_Pair)) { (sc_conf_89 = (l.car)); if ((((state = (sc_states_88[j])), (conf_set = (state[(sc_conf_89+(1))])), ((conf_set!== false)?(conf_set[(i+(5))]):false))!== false)) return true; else (l = (l.cdr)); } else return false; } } else return false; } }; deriv_trees = function(sc_conf_91, i, j, sc_enders_92, sc_steps_93, sc_names_94, sc_toks_95, sc_states_96, BgL_sc_nbzd2nts_97zd2) { var sc_loop1_98; var prev; var name; return ((name = (sc_names_94[sc_conf_91])), ((name!== false)?((sc_conf_91=(0))) if (((k>=i)&&(((sc_state_99 = (sc_states_96[k])), (conf_set = (sc_state_99[(prev+(1))])), ((conf_set!== false)?(conf_set[(i+(5))]):false))!== false))) { (prev_trees = (deriv_trees(prev, i, k, sc_enders_92, sc_steps_93, sc_names_94, sc_toks_95, sc_states_96, BgL_sc_nbzd2nts_97zd2))); (ender_trees = (deriv_trees(ender, k, j, sc_enders_92, sc_steps_93, sc_names_94, sc_toks_95, sc_states_96, BgL_sc_nbzd2nts_97zd2))); loop3 = function(l3, l2) { var l4; var sc_l2_100; var ender_tree; if ((l3 instanceof sc_Pair)) { (ender_tree = (sc_list((l3.car)))); (l4 = prev_trees); (sc_l2_100 = l2); while ((l4 instanceof sc_Pair)) { { (sc_l2_100 = (new sc_Pair((sc_append((l4.car), ender_tree)), sc_l2_100))); (l4 = (l4.cdr)); } } return (loop3((l3.cdr), sc_l2_100)); } else return (loop2((ender_set[(k+(5))]), l2)); }; return (loop3(ender_trees, l2)); } else (k = (ender_set[(k+(5))])); else return (sc_loop1_98((l1.cdr), l2)); } }; return (loop2((ender_set[(2)]), l2)); } else (l1 = (l1.cdr)); } else return l2; } }), (sc_loop1_98((sc_enders_92[(sc_steps_93[prev])]), null))))); }; BgL_sc_derivzd2treesza2_47z70 = function(nt, i, j, sc_nts_101, sc_enders_102, sc_steps_103, sc_names_104, sc_toks_105, sc_states_106) { var conf_set; var state; var sc_conf_107; var l; var trees; var BgL_sc_nbzd2nts_108zd2; var BgL_sc_ntza2_109za2; { (BgL_sc_ntza2_109za2 = (sc_ind_43(nt, sc_nts_101))); if ((BgL_sc_ntza2_109za2!== false)) { (BgL_sc_nbzd2nts_108zd2 = (sc_nts_101.length)); (l = (sc_enders_102[BgL_sc_ntza2_109za2])); (trees = null); while ((l instanceof sc_Pair)) { { (sc_conf_107 = (l.car)); if ((((state = (sc_states_106[j])), (conf_set = (state[(sc_conf_107+(1))])), ((conf_set!== false)?(conf_set[(i+(5))]):false))!== false)) { (l = (l.cdr)); (trees = (sc_append((deriv_trees(sc_conf_107, i, j, sc_enders_102, sc_steps_103, sc_names_104, sc_toks_105, sc_states_106, BgL_sc_nbzd2nts_108zd2)), trees))); } else (l = (l.cdr)); } } return trees; } else return false; } }; nb_deriv_trees = function(sc_conf_110, i, j, sc_enders_111, sc_steps_112, sc_toks_113, sc_states_114, BgL_sc_nbzd2nts_115zd2) { var sc_loop1_116; var tmp1124; var prev; return ((prev = (sc_conf_110-(1))), ((((tmp1124 = (sc_conf_110=(0))) { if (((k>=i)&&(((state = (sc_states_114[k])), (conf_set = (state[(prev+(1))])), ((conf_set!== false)?(conf_set[(i+(5))]):false))!== false))) { (nb_prev_trees = (nb_deriv_trees(prev, i, k, sc_enders_111, sc_steps_112, sc_toks_113, sc_states_114, BgL_sc_nbzd2nts_115zd2))); (nb_ender_trees = (nb_deriv_trees(ender, k, j, sc_enders_111, sc_steps_112, sc_toks_113, sc_states_114, BgL_sc_nbzd2nts_115zd2))); (k = (ender_set[(k+(5))])); (n +=(nb_prev_trees*nb_ender_trees)); } else (k = (ender_set[(k+(5))])); } return (sc_loop1_116((l.cdr), n)); } else (l = (l.cdr)); } else return sc_n_118; } }), (sc_loop1_116((sc_enders_111[(sc_steps_112[prev])]), (0)))))); }; BgL_sc_nbzd2derivzd2treesza2_48za2 = function(nt, i, j, sc_nts_119, sc_enders_120, sc_steps_121, sc_toks_122, sc_states_123) { var conf_set; var state; var sc_conf_124; var l; var nb_trees; var BgL_sc_nbzd2nts_125zd2; var BgL_sc_ntza2_126za2; { (BgL_sc_ntza2_126za2 = (sc_ind_43(nt, sc_nts_119))); if ((BgL_sc_ntza2_126za2!== false)) { (BgL_sc_nbzd2nts_125zd2 = (sc_nts_119.length)); (l = (sc_enders_120[BgL_sc_ntza2_126za2])); (nb_trees = (0)); while ((l instanceof sc_Pair)) { { (sc_conf_124 = (l.car)); if ((((state = (sc_states_123[j])), (conf_set = (state[(sc_conf_124+(1))])), ((conf_set!== false)?(conf_set[(i+(5))]):false))!== false)) { (l = (l.cdr)); (nb_trees = ((nb_deriv_trees(sc_conf_124, i, j, sc_enders_120, sc_steps_121, sc_toks_122, sc_states_123, BgL_sc_nbzd2nts_125zd2))+nb_trees)); } else (l = (l.cdr)); } } return nb_trees; } else return false; } }; (lexer = (parser_descr[(0)])); (sc_nts_42 = (parser_descr[(1)])); (sc_starters_41 = (parser_descr[(2)])); (sc_enders_40 = (parser_descr[(3)])); (sc_predictors_39 = (parser_descr[(4)])); (sc_steps_38 = (parser_descr[(5)])); (sc_names_37 = (parser_descr[(6)])); (falseHead1128 = (new sc_Pair(null, null))); (L1125 = (lexer(input))); (tail1129 = falseHead1128); while (!(L1125 === null)) { { (tok = (L1125.car)); (l1 = (tok.cdr)); (l2 = null); while ((l1 instanceof sc_Pair)) { { (sc_i_29 = (sc_ind_43((l1.car), sc_nts_42))); if ((sc_i_29!== false)) { (l1 = (l1.cdr)); (l2 = (new sc_Pair(sc_i_29, l2))); } else (l1 = (l1.cdr)); } } (sc_optrOpnd_22 = (new sc_Pair((tok.car), (sc_reverse(l2))))); (sc_optrOpnd_21 = (new sc_Pair(sc_optrOpnd_22, null))); (tail1129.cdr = sc_optrOpnd_21); (tail1129 = (tail1129.cdr)); (L1125 = (L1125.cdr)); } } (sc_optrOpnd_20 = (falseHead1128.cdr)); (sc_toks_36 = (sc_list2vector(sc_optrOpnd_20))); (BgL_sc_nbzd2toks_35zd2 = (sc_toks_36.length)); (BgL_sc_nbzd2confs_34zd2 = (sc_steps_38.length)); (sc_states_33 = (make_states(BgL_sc_nbzd2toks_35zd2, BgL_sc_nbzd2confs_34zd2))); (goal_starters = (sc_starters_41[(0)])); (BgL_sc_confzd2setzd2adjoinza2_45za2(sc_states_33, (0), goal_starters, (0))); (forw(sc_states_33, (0), sc_starters_41, sc_enders_40, sc_predictors_39, sc_steps_38, sc_nts_42)); (sc_i_28 = (0)); while ((sc_i_28=(0))) { { (states = sc_states_33); (BgL_sc_statesza2_27za2 = BgL_sc_statesza2_30za2); (state_num = i); (sc_enders_26 = sc_enders_40); (sc_steps_25 = sc_steps_38); (BgL_sc_nbzd2nts_24zd2 = BgL_sc_nbzd2nts_31zd2); (toks = sc_toks_36); (BgL_sc_stateza2_23za2 = (BgL_sc_statesza2_30za2[i])); loop1 = function() { var sc_loop1_127; var prev; var BgL_sc_statesza2_128za2; var sc_states_129; var j; var i; var sc_i_130; var head; var conf_set; var sc_conf_131; { (sc_conf_131 = (BgL_sc_stateza2_23za2[(0)])); if ((sc_conf_131>=(0))) { (conf_set = (BgL_sc_stateza2_23za2[(sc_conf_131+(1))])); (head = (conf_set[(4)])); (BgL_sc_stateza2_23za2[(0)] = (conf_set[(0)])); (conf_set_merge_new_bang(conf_set)); (sc_i_130 = head); while ((sc_i_130>=(0))) { { (i = sc_i_130); (j = state_num); (sc_states_129 = states); (BgL_sc_statesza2_128za2 = BgL_sc_statesza2_27za2); (prev = (sc_conf_131-(1))); if (((sc_conf_131>=BgL_sc_nbzd2nts_24zd2)&&((sc_steps_25[prev])>=(0)))) { sc_loop1_127 = function(l) { var k; var ender_set; var state; var ender; var l; while (true) { if ((l instanceof sc_Pair)) { (ender = (l.car)); (ender_set = ((state = (sc_states_129[j])), (state[(ender+(1))]))); if ((ender_set!== false)) { (k = (ender_set[(2)])); while ((k>=(0))) { { if ((k>=i)) if (((BgL_sc_confzd2setzd2adjoinza2za2_46z00(sc_states_129, BgL_sc_statesza2_128za2, k, prev, i))!== false)) (BgL_sc_confzd2setzd2adjoinza2za2_46z00(sc_states_129, BgL_sc_statesza2_128za2, j, ender, k)); (k = (ender_set[(k+(5))])); } } return (sc_loop1_127((l.cdr))); } else (l = (l.cdr)); } else return undefined; } }; (sc_loop1_127((sc_enders_26[(sc_steps_25[prev])]))); } (sc_i_130 = (conf_set[(sc_i_130+(5))])); } } return (loop1()); } else return undefined; } }; (loop1()); (--i); } } (optrOpnd = BgL_sc_statesza2_30za2); return [sc_nts_42, sc_starters_41, sc_enders_40, sc_predictors_39, sc_steps_38, sc_names_37, sc_toks_36, optrOpnd, is_parsed, BgL_sc_derivzd2treesza2_47z70, BgL_sc_nbzd2derivzd2treesza2_48za2]; } }; } }; BgL_parsezd2ze3parsedzf3zc2 = function(parse, nt, i, j) { var is_parsed; var states; var enders; var nts; return ((nts = (parse[(0)])), (enders = (parse[(2)])), (states = (parse[(7)])), (is_parsed = (parse[(8)])), (is_parsed(nt, i, j, nts, enders, states))); }; BgL_parsezd2ze3treesz31 = function(parse, nt, i, j) { var BgL_sc_derivzd2treesza2_132z70; var states; var toks; var names; var steps; var enders; var nts; return ((nts = (parse[(0)])), (enders = (parse[(2)])), (steps = (parse[(4)])), (names = (parse[(5)])), (toks = (parse[(6)])), (states = (parse[(7)])), (BgL_sc_derivzd2treesza2_132z70 = (parse[(9)])), (BgL_sc_derivzd2treesza2_132z70(nt, i, j, nts, enders, steps, names, toks, states))); }; BgL_parsezd2ze3nbzd2treesze3 = function(parse, nt, i, j) { var BgL_sc_nbzd2derivzd2treesza2_133za2; var states; var toks; var steps; var enders; var nts; return ((nts = (parse[(0)])), (enders = (parse[(2)])), (steps = (parse[(4)])), (toks = (parse[(6)])), (states = (parse[(7)])), (BgL_sc_nbzd2derivzd2treesza2_133za2 = (parse[(10)])), (BgL_sc_nbzd2derivzd2treesza2_133za2(nt, i, j, nts, enders, steps, toks, states))); }; test = function(k) { var x; var p; return ((p = (BgL_makezd2parserzd2(const_earley, function(l) { var sc_x_134; var tail1134; var L1130; var falseHead1133; { (falseHead1133 = (new sc_Pair(null, null))); (tail1134 = falseHead1133); (L1130 = l); while (!(L1130 === null)) { { (tail1134.cdr = (new sc_Pair(((sc_x_134 = (L1130.car)), (sc_list(sc_x_134, sc_x_134))), null))); (tail1134 = (tail1134.cdr)); (L1130 = (L1130.cdr)); } } return (falseHead1133.cdr); } }))), (x = (p((sc_vector2list((sc_makeVector(k, "\u1E9Ca"))))))), (sc_length((BgL_parsezd2ze3treesz31(x, "\u1E9Cs", (0), k))))); }; BgL_earleyzd2benchmarkzd2 = function() { var args = null; for (var sc_tmp = arguments.length - 1; sc_tmp >= 0; sc_tmp--) { args = sc_cons(arguments[sc_tmp], args); } var k; return ((k = ((args === null)?(7):(args.car))), (BgL_runzd2benchmarkzd2("earley", (1), function() { return (test(k)); }, function(result) { return ((sc_display(result)), (sc_newline()), result == 132); }))); }; } /************* END OF GENERATED CODE *************/ // Invoke this function to run a benchmark. // The first argument is a string identifying the benchmark. // The second argument is the number of times to run the benchmark. // The third argument is a function that runs the benchmark. // The fourth argument is a unary function that warns if the result // returned by the benchmark is incorrect. // // Example: // RunBenchmark("new Array()", // 1, // function () { new Array(1000000); } // function (v) { // return (v instanceof Array) && (v.length == 1000000); // }); SC_DEFAULT_OUT = new sc_GenericOutputPort(function(s) {}); SC_ERROR_OUT = SC_DEFAULT_OUT; function RunBenchmark(name, count, run, warn) { for (var n = 0; n < count; ++n) { result = run(); if (!warn(result)) { throw new Error("Earley or Boyer did incorrect number of rewrites"); } } } var BgL_runzd2benchmarkzd2 = RunBenchmark; node-v0.10.25~dfsg2/deps/v8/preparser/0000755000000000000000000000000012270121457016110 5ustar rootrootnode-v0.10.25~dfsg2/deps/v8/preparser/SConscript0000644000000000000000000000352212270121457020124 0ustar rootroot# Copyright 2011 the V8 project authors. All rights reserved. # Redistribution and use in source and binary forms, with or without # modification, are permitted provided that the following conditions are # met: # # * Redistributions of source code must retain the above copyright # notice, this list of conditions and the following disclaimer. # * Redistributions in binary form must reproduce the above # copyright notice, this list of conditions and the following # disclaimer in the documentation and/or other materials provided # with the distribution. # * Neither the name of Google Inc. nor the names of its # contributors may be used to endorse or promote products derived # from this software without specific prior written permission. # # THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS # "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT # LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR # A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT # OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, # SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT # LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, # DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY # THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT # (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE # OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. from os.path import join Import('context tools') def ConfigureObjectFiles(): env = Environment(tools=tools) env.Replace(**context.flags['preparser']) context.ApplyEnvOverrides(env) return env.Object('preparser-process.cc') preparser_object = ConfigureObjectFiles() Return('preparser_object') node-v0.10.25~dfsg2/deps/v8/preparser/preparser.gyp0000644000000000000000000000347112270121457020641 0ustar rootroot# Copyright 2011 the V8 project authors. All rights reserved. # Redistribution and use in source and binary forms, with or without # modification, are permitted provided that the following conditions are # met: # # * Redistributions of source code must retain the above copyright # notice, this list of conditions and the following disclaimer. # * Redistributions in binary form must reproduce the above # copyright notice, this list of conditions and the following # disclaimer in the documentation and/or other materials provided # with the distribution. # * Neither the name of Google Inc. nor the names of its # contributors may be used to endorse or promote products derived # from this software without specific prior written permission. # # THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS # "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT # LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR # A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT # OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, # SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT # LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, # DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY # THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT # (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE # OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. { 'includes': ['../build/common.gypi'], 'targets': [ { 'target_name': 'preparser', 'type': 'executable', 'dependencies': [ '../tools/gyp/v8.gyp:preparser_lib', ], 'sources': [ 'preparser-process.cc', ], }, ], } node-v0.10.25~dfsg2/deps/v8/preparser/preparser-process.cc0000644000000000000000000002631312270121457022103 0ustar rootroot// Copyright 2012 the V8 project authors. All rights reserved. // Redistribution and use in source and binary forms, with or without // modification, are permitted provided that the following conditions are // met: // // * Redistributions of source code must retain the above copyright // notice, this list of conditions and the following disclaimer. // * Redistributions in binary form must reproduce the above // copyright notice, this list of conditions and the following // disclaimer in the documentation and/or other materials provided // with the distribution. // * Neither the name of Google Inc. nor the names of its // contributors may be used to endorse or promote products derived // from this software without specific prior written permission. // // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS // "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT // LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR // A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT // OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, // SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT // LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, // DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY // THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT // (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE // OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. #include #include #include #include #include "../include/v8stdint.h" #include "../include/v8-preparser.h" #include "../src/preparse-data-format.h" namespace i = v8::internal; // This file is only used for testing the stand-alone preparser // library. // The first argument must be the path of a JavaScript source file, or // the flags "-e" and the next argument is then the source of a JavaScript // program. // Optionally this can be followed by the word "throws" (case sensitive), // which signals that the parsing is expected to throw - the default is // to expect the parsing to not throw. // The command line can further be followed by a message text (the // *type* of the exception to throw), and even more optionally, the // start and end position reported with the exception. // // This source file is preparsed and tested against the expectations, and if // successful, the resulting preparser data is written to stdout. // Diagnostic output is output on stderr. // The source file must contain only ASCII characters (UTF-8 isn't supported). // The file is read into memory, so it should have a reasonable size. // Adapts an ASCII string to the UnicodeInputStream interface. class AsciiInputStream : public v8::UnicodeInputStream { public: AsciiInputStream(const uint8_t* buffer, size_t length) : buffer_(buffer), end_offset_(static_cast(length)), offset_(0) { } virtual ~AsciiInputStream() { } virtual void PushBack(int32_t ch) { offset_--; #ifdef DEBUG if (offset_ < 0 || (ch != ((offset_ >= end_offset_) ? -1 : buffer_[offset_]))) { fprintf(stderr, "Invalid pushback: '%c' at offset %d.", ch, offset_); exit(1); } #endif } virtual int32_t Next() { if (offset_ >= end_offset_) { offset_++; // Increment anyway to allow symmetric pushbacks. return -1; } uint8_t next_char = buffer_[offset_]; #ifdef DEBUG if (next_char > 0x7fu) { fprintf(stderr, "Non-ASCII character in input: '%c'.", next_char); exit(1); } #endif offset_++; return static_cast(next_char); } private: const uint8_t* buffer_; const int end_offset_; int offset_; }; bool ReadBuffer(FILE* source, void* buffer, size_t length) { size_t actually_read = fread(buffer, 1, length, source); return (actually_read == length); } bool WriteBuffer(FILE* dest, const void* buffer, size_t length) { size_t actually_written = fwrite(buffer, 1, length, dest); return (actually_written == length); } class PreparseDataInterpreter { public: PreparseDataInterpreter(const uint8_t* data, int length) : data_(data), length_(length), message_(NULL) { } ~PreparseDataInterpreter() { if (message_ != NULL) delete[] message_; } bool valid() { int header_length = i::PreparseDataConstants::kHeaderSize * sizeof(int); // NOLINT return length_ >= header_length; } bool throws() { return valid() && word(i::PreparseDataConstants::kHasErrorOffset) != 0; } const char* message() { if (message_ != NULL) return message_; if (!throws()) return NULL; int text_pos = i::PreparseDataConstants::kHeaderSize + i::PreparseDataConstants::kMessageTextPos; int length = word(text_pos); char* buffer = new char[length + 1]; for (int i = 1; i <= length; i++) { int character = word(text_pos + i); buffer[i - 1] = character; } buffer[length] = '\0'; message_ = buffer; return buffer; } int beg_pos() { if (!throws()) return -1; return word(i::PreparseDataConstants::kHeaderSize + i::PreparseDataConstants::kMessageStartPos); } int end_pos() { if (!throws()) return -1; return word(i::PreparseDataConstants::kHeaderSize + i::PreparseDataConstants::kMessageEndPos); } private: int word(int offset) { const int* word_data = reinterpret_cast(data_); if (word_data + offset < reinterpret_cast(data_ + length_)) { return word_data[offset]; } return -1; } const uint8_t* const data_; const int length_; const char* message_; }; template class ScopedPointer { public: explicit ScopedPointer() : pointer_(NULL) {} explicit ScopedPointer(T* pointer) : pointer_(pointer) {} ~ScopedPointer() { if (pointer_ != NULL) delete[] pointer_; } T& operator[](int index) { return pointer_[index]; } T* operator*() { return pointer_ ;} T* operator=(T* new_value) { if (pointer_ != NULL) delete[] pointer_; pointer_ = new_value; return new_value; } private: T* pointer_; }; void fail(v8::PreParserData* data, const char* message, ...) { va_list args; va_start(args, message); vfprintf(stderr, message, args); va_end(args); fflush(stderr); if (data != NULL) { // Print preparser data to stdout. uint32_t size = static_cast(data->size()); fprintf(stderr, "LOG: data size: %u\n", size); if (!WriteBuffer(stdout, data->data(), size)) { perror("ERROR: Writing data"); fflush(stderr); } } exit(EXIT_FAILURE); } bool IsFlag(const char* arg) { // Anything starting with '-' is considered a flag. // It's summarily ignored for now. return arg[0] == '-'; } struct ExceptionExpectation { ExceptionExpectation() : throws(false), type(NULL), beg_pos(-1), end_pos(-1) { } bool throws; const char* type; int beg_pos; int end_pos; }; void CheckException(v8::PreParserData* data, ExceptionExpectation* expects) { PreparseDataInterpreter reader(data->data(), static_cast(data->size())); if (expects->throws) { if (!reader.throws()) { if (expects->type == NULL) { fail(data, "Didn't throw as expected\n"); } else { fail(data, "Didn't throw \"%s\" as expected\n", expects->type); } } if (expects->type != NULL) { const char* actual_message = reader.message(); if (strcmp(expects->type, actual_message)) { fail(data, "Wrong error message. Expected <%s>, found <%s> at %d..%d\n", expects->type, actual_message, reader.beg_pos(), reader.end_pos()); } } if (expects->beg_pos >= 0) { if (expects->beg_pos != reader.beg_pos()) { fail(data, "Wrong error start position: Expected %i, found %i\n", expects->beg_pos, reader.beg_pos()); } } if (expects->end_pos >= 0) { if (expects->end_pos != reader.end_pos()) { fail(data, "Wrong error end position: Expected %i, found %i\n", expects->end_pos, reader.end_pos()); } } } else if (reader.throws()) { const char* message = reader.message(); fail(data, "Throws unexpectedly with message: %s at location %d-%d\n", message, reader.beg_pos(), reader.end_pos()); } } ExceptionExpectation ParseExpectation(int argc, const char* argv[]) { // Parse ["throws" [ [ []]]]. ExceptionExpectation expects; int arg_index = 0; while (argc > arg_index && strncmp("throws", argv[arg_index], 7)) { arg_index++; } if (argc > arg_index) { expects.throws = true; arg_index++; if (argc > arg_index && !IsFlag(argv[arg_index])) { expects.type = argv[arg_index]; arg_index++; if (argc > arg_index && !IsFlag(argv[arg_index])) { expects.beg_pos = atoi(argv[arg_index]); // NOLINT arg_index++; if (argc > arg_index && !IsFlag(argv[arg_index])) { expects.end_pos = atoi(argv[arg_index]); // NOLINT } } } } return expects; } int main(int argc, const char* argv[]) { // Parse command line. // Format: preparser ( | -e "") // ["throws" [ [ []]]] // Any flags (except an initial -e) are ignored. // Flags must not separate "throws" and its arguments. // Check for mandatory filename argument. int arg_index = 1; if (argc <= arg_index) { fail(NULL, "ERROR: No filename on command line.\n"); } const uint8_t* source = NULL; const char* filename = argv[arg_index]; if (!strcmp(filename, "-e")) { arg_index++; if (argc <= arg_index) { fail(NULL, "ERROR: No source after -e on command line.\n"); } source = reinterpret_cast(argv[arg_index]); } // Check remainder of command line for exception expectations. arg_index++; ExceptionExpectation expects = ParseExpectation(argc - arg_index, argv + arg_index); ScopedPointer buffer; size_t length; if (source == NULL) { // Open JS file. FILE* input = fopen(filename, "rb"); if (input == NULL) { perror("ERROR: Error opening file"); fflush(stderr); return EXIT_FAILURE; } // Find length of JS file. if (fseek(input, 0, SEEK_END) != 0) { perror("ERROR: Error during seek"); fflush(stderr); return EXIT_FAILURE; } length = static_cast(ftell(input)); rewind(input); // Read JS file into memory buffer. buffer = new uint8_t[length]; if (!ReadBuffer(input, *buffer, length)) { perror("ERROR: Reading file"); fflush(stderr); return EXIT_FAILURE; } fclose(input); source = *buffer; } else { length = strlen(reinterpret_cast(source)); } // Preparse input file. AsciiInputStream input_buffer(source, length); size_t kMaxStackSize = 64 * 1024 * sizeof(void*); // NOLINT v8::PreParserData data = v8::Preparse(&input_buffer, kMaxStackSize); // Fail if stack overflow. if (data.stack_overflow()) { fail(&data, "ERROR: Stack overflow\n"); } // Check that the expected exception is thrown, if an exception is // expected. CheckException(&data, &expects); return EXIT_SUCCESS; } node-v0.10.25~dfsg2/deps/v8/LICENSE.v80000644000000000000000000000276712270121457015462 0ustar rootrootCopyright 2006-2011, the V8 project authors. All rights reserved. Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: * Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. * Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution. * Neither the name of Google Inc. nor the names of its contributors may be used to endorse or promote products derived from this software without specific prior written permission. THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. node-v0.10.25~dfsg2/deps/v8/ChangeLog0000644000000000000000000041244412270121457015670 0ustar rootroot2012-10-22: Version 3.14.5 Killed off the SCons based build. Added a faster API for creating v8::Integer objects. Speeded up function deoptimization by avoiding quadratic pass over optimized function list. (Chromium issue 155270) Always invoke the default Array.sort functions from builtin functions. (issue 2372) Reverted recent CPU profiler changes because they broke --prof. (issue 2364) Switched code flushing to use different JSFunction field. (issue 1609) Performance and stability improvements on all platforms. 2012-10-15: Version 3.14.4 Allow evals for debugger even if they are prohibited in the debugee context. (Chromium issue 154733) Enabled --verify-heap in release mode (issue 2120) Performance and stability improvements on all platforms. 2012-10-11: Version 3.14.3 Use native context to retrieve ErrorMessageForCodeGenerationFromStrings (Chromium issue 155076). Bumped variable limit further to 2^17 (Chromium issue 151625). Performance and stability improvements on all platforms. 2012-10-10: Version 3.14.2 ARM: allowed VFP3 instructions when hardfloat is enabled. (Chromium issue 152506) Fixed instance_descriptors() and PushStackTraceAndDie regressions. (Chromium issue 151749) Made GDBJIT interface compile again. (issue 1804) Fixed Accessors::FunctionGetPrototype's proto chain traversal. (Chromium issue 143967) Made sure that names of temporaries do not clash with real variables. (issue 2322) Rejected local module declarations. (Chromium issue 150628) Rejected uses of lexical for-loop variable on the RHS. (issue 2322) Fixed slot recording of code target patches. (Chromium issue 152615,chromium:144230) Changed the Android makefile to use GCC 4.6 instead of GCC 4.4.3. Performance and stability improvements on all platforms. 2012-10-01: Version 3.14.1 Don't set -m32 flag when compiling with Android ARM compiler. (Chromium issue 143889) Restore the descriptor array before returning allocation failure. (Chromium issue 151750) Lowered kMaxVirtualRegisters (v8 issue 2139, Chromium issues 123822 and 128252). Pull more recent gyp in 'make dependencies'. Made sure that the generic KeyedStoreIC changes length and element_kind atomically (issue 2346). Bumped number of allowed variables per scope to 65535, to address GWT. (Chromium issue 151625) Support sourceURL for dynamically inserted scripts (issue 2342). Performance and stability improvements on all platforms. 2012-09-20: Version 3.14.0 Fixed missing slot recording during clearing of CallICs. (Chromium issue 144230) Fixed LBoundsCheck on x64 to handle (stack slot + constant) correctly. (Chromium issue 150729) Fixed minus zero test. (Issue 2133) Fixed setting array length to zero for slow elements. (Chromium issue 146910) Fixed lost arguments dropping in HLeaveInlined. (Chromium issue 150545) Fixed casting error for receiver of interceptors. (Chromium issue 149912) Throw a more descriptive exception when blocking 'eval' via CSP. (Chromium issue 140191) Fixed debugger's eval when close to stack overflow. (issue 2318) Added checks to live edit. (issue 2297) Switched on code compaction on incremental GCs. Fixed caching of optimized code for OSR. (issue 2326) Not mask exception thrown by toString in String::UtfValue etc. (issue 2317) Fixed API check for length of external arrays. (Chromium issue 148896) Ensure correct enumeration indices in the dict (Chromium issue 148376) Correctly initialize regexp global cache. (Chromium issue 148378) Fixed arguments object materialization during deopt. (issue 2261) Introduced new API to expose external string resource regardless of encoding. Fixed CHECK failure in LCodeGen::DoWrapReceiver when --deopt-every-n-times flag is present (Chromium issue 148389) Fixed edge case of extension with NULL as source string. (Chromium issue 144649) Fixed array index dehoisting. (Chromium issue 141395) Performance and stability improvements on all platforms. 2012-09-11: Version 3.13.7 Enable/disable LiveEdit using the (C++) debug API. Performance and stability improvements on all platforms. 2012-09-06: Version 3.13.6 Added validity checking to API functions and calls. Disabled accessor inlining (Chromium issue 134609). Fixed bug in Math.min/max in optimized code (Chromium issue 145961). Directly use %ObjectKeys in json stringify (Chromium issue 2312). Fixed VS2005 build (issue 2313). Activated fixed ES5 readonly semantics by default. Added hardfp flag to the Makefile. Performance and stability improvements on all platforms. 2012-08-29: Version 3.13.5 Release stack trace data after firing Error.stack accessor. (issue 2308) Added a new API V8::SetJitCodeEventHandler to push code name and location to users such as profilers. Allocate block-scoped global bindings to global context. Performance and stability improvements on all platforms. 2012-08-28: Version 3.13.4 Print reason for disabling optimization. Kill --trace-bailout flag. Provided option to disable full DEBUG build on Android. Introduced global contexts to represent lexical global scope(s). Fixed rounding in Uint8ClampedArray setter. (issue 2294) Performance and stability improvements on all platforms. 2012-08-21: Version 3.13.3 Performance and stability improvements on all platforms. 2012-08-20: Version 3.13.2 Performance and stability improvements on all platforms. 2012-08-16: Version 3.13.1 Performance and stability improvements on all platforms. 2012-08-10: Version 3.13.0 Added histograms for total allocated/live heap size, as well as allocated size and percentage of total for map and cell space. Fixed parseInt's octal parsing behavior (ECMA-262 Annex E 15.1.2.2). (issue 1645) Added checks for interceptors to negative lookup code in Crankshaft. (Chromium issue 140473) Made incremental marking clear ICs and type feedback cells. Performance and stability improvements on all platforms. 2012-08-01: Version 3.12.19 Performance and stability improvements on all platforms. 2012-07-30: Version 3.12.18 Forced using bit-pattern for signed zero double. (issue 2239) Made sure double to int conversion is correct. (issue 2260) Performance and stability improvements on all platforms. 2012-07-27: Version 3.12.17 Always set the callee's context when calling a function from optimized code. (Chromium issue 138887) Fixed building with GCC 3.x (issue 2016, 2017) Improved API calls that return empty handles. (issue 2245) Performance and stability improvements on all platforms. 2012-07-25: Version 3.12.16 Performance and stability improvements on all platforms. 2012-07-24: Version 3.12.15 Added PRESERVE_ASCII_NULL option to String::WriteAscii. (issue 2252) Added dependency to HLoadKeyed* instructions to prevent invalid hoisting. (Chromium issue 137768) Enabled building d8 for Android on Mac. Interpret negative hexadecimal literals as NaN. (issue 2240) Expose counters in javascript when using --track-gc-object-stats. Enabled building and testing V8 on Android IA. Added --trace-parse flag to parser. Performance and stability improvements on all platforms. 2012-07-18: Version 3.12.14 Deactivated optimization of packed arrays. (Chromium issue 137768) Fixed broken accessor transition. (Chromium issue 137689) Performance and stability improvements on all platforms. 2012-07-17: Version 3.12.13 Fixed missing tagging of stack value in finally block. (Chromium issue 137496) Added more support for heap analysis. Performance and stability improvements on all platforms. 2012-07-16: Version 3.12.12 Added an option to the tickprocessor to specify the directory for lib lookup. Fixed ICs for slow objects with native accessor (Chromium issue 137002). Fixed transcendental cache on ARM in optimized code (issue 2234). New heap inspection tools: counters for object sizes and counts, histograms for external fragmentation. Incorporated constness into inferred interfaces (in preparation for handling imports) (issue 1569). Performance and stability improvements on all platforms. 2012-07-12: Version 3.12.11 Renamed "mips" arch to "mipsel" in the GYP build. Fixed computation of call targets on prototypes in Crankshaft. (Chromium issue 125148) Removed use of __lookupGetter__ when generating stack trace. (issue 1591) Turned on ES 5.2 globals semantics by default. (issue 1991, Chromium issue 80591) Synced preparser and parser wrt syntax error in switch..case. (issue 2210) Fixed reporting of octal literals in strict mode when preparsing. (issue 2220) Fixed inline constructors for Harmony Proxy prototypes. (issue 2225) Performance and stability improvements on all platforms. 2012-07-10: Version 3.12.10 Re-enabled and fixed issue with array bounds check elimination (Chromium issue 132114). Fixed Debug::Break crash. (Chromium issue 131642) Added optimizing compiler support for JavaScript getters. Performance and stability improvements on all platforms. 2012-07-06: Version 3.12.9 Correctly advance the scanner when scanning unicode regexp flag. (Chromium issue 136084) Fixed unhandlified code calling Harmony Proxy traps. (issue 2219) Performance and stability improvements on all platforms. 2012-07-05: Version 3.12.8 Implemented TypedArray.set and ArrayBuffer.slice in d8. Performance and stability improvements on all platforms. 2012-07-03: Version 3.12.7 Fixed lazy compilation for strict eval scopes. (Chromium issue 135066) Made MACOSX_DEPLOYMENT_TARGET configurable in GYP. (issue 2151) Report "hidden properties" in heap profiler for properties case. (issue 2212) Activated optimization of packed arrays by default. Performance and stability improvements on all platforms. 2012-06-29: Version 3.12.6 Cleaned up hardfp ABI detection for ARM (V8 issue 2140). Extended TypedArray support in d8. 2012-06-28: Version 3.12.5 Fixed lazy parsing heuristics to respect outer scope. (Chromium issue 135008) Allow using test-wrapper-gypbuild.py on Windows when no python interpreter is registered. Performance and stability improvements on all platforms. 2012-06-27: Version 3.12.4 Removed -fomit-frame-pointer flag from Release builds to make the stack walkable by TCMalloc (Chromium issue 133723). Ported r7868 (constant masking) to x64 (issue 1374). Expose more detailed memory statistics (issue 2201). Fixed Harmony Maps and WeakMaps for undefined values (Chromium issue 132744). Correctly throw reference error in strict mode with ICs disabled (issue 2119). Performance and stability improvements on all platforms. 2012-06-25: Version 3.12.3 Reverted r11835 'Unify promotion and allocation limit computation' due to V8 Splay performance regression on Mac. (Chromium issue 134183) Fixed sharing of literal boilerplates for optimized code. (issue 2193) Performance and stability improvements on all platforms. 2012-06-22: Version 3.12.2 Made near-jump check more strict in LoadNamedFieldPolymorphic on ia32/x64. (Chromium issue 134055) Fixed lazy sweeping heuristics to prevent old-space expansion. (issue 2194) Performance and stability improvements on all platforms. 2012-06-21: Version 3.12.1 Performance and stability improvements on all platforms. 2012-06-20: Version 3.12.0 Fixed Chromium issues: 115100, 129628, 131994, 132727, 132741, 132742, 133211 Fixed V8 issues: 915, 1914, 2034, 2087, 2094, 2134, 2156, 2166, 2172, 2177, 2179, 2185 Added --extra-code flag to mksnapshot to load JS code into the VM before creating the snapshot. Support 'restart call frame' command in the debugger. Performance and stability improvements on all platforms. 2012-06-13: Version 3.11.10 Implemented heap profiler memory usage reporting. Preserved error message during finally block in try..finally. (Chromium issue 129171) Fixed EnsureCanContainElements to properly handle double values. (issue 2170) Improved heuristics to keep objects in fast mode with inherited constructors. Performance and stability improvements on all platforms. 2012-06-06: Version 3.11.9 Implemented ES5-conformant semantics for inherited setters and read-only properties. Currently behind --es5_readonly flag, because it breaks WebKit bindings. Exposed last seen heap object id via v8 public api. Performance and stability improvements on all platforms. 2012-05-31: Version 3.11.8 Avoid overdeep recursion in regexp where a guarded expression with a minimum repetition count is inside another quantifier. (Chromium issue 129926) Fixed missing write barrier in store field stub. (issues 2143, 1465, Chromium issue 129355) Proxies: Fixed receiver for setters inherited from proxies. Proxies: Fixed ToStringArray function so that it does not reject some keys. (issue 1543) Performance and stability improvements on all platforms. 2012-05-29: Version 3.11.7 Get better function names in stack traces. Performance and stability improvements on all platforms. 2012-05-24: Version 3.11.6 Fixed RegExp.prototype.toString for incompatible receivers (issue 1981). Performance and stability improvements on all platforms. 2012-05-23: Version 3.11.5 Performance and stability improvements on all platforms. 2012-05-22: Version 3.11.4 Some cleanup to common.gypi. This fixes some host/target combinations that weren't working in the Make build on Mac. Handle EINTR in socket functions and continue incomplete sends. (issue 2098) Fixed python deprecations. (issue 1391) Made socket send and receive more robust and return 0 on failure. (Chromium issue 15719) Fixed GCC 4.7 (C++11) compilation. (issue 2136) Set '-m32' option for host and target platforms Performance and stability improvements on all platforms. 2012-05-18: Version 3.11.3 Disable optimization for functions that have scopes that cannot be reconstructed from the context chain. (issue 2071) Define V8_EXPORT to nothing for clients of v8. (Chromium issue 90078) Correctly check for native error objects. (Chromium issue 2138) Performance and stability improvements on all platforms. 2012-05-16: Version 3.11.2 Revert r11496. (Chromium issue 128146) Implement map collection for incremental marking. (issue 1465) Add toString method to CallSite (which describes a frame of the stack trace). 2012-05-15: Version 3.11.1 Added a readbuffer function to d8 that reads a file into an ArrayBuffer. Fix freebsd build. (V8 issue 2126) Performance and stability improvements on all platforms. 2012-05-11: Version 3.11.0 Fixed compose-discard crasher from r11524 (issue 2123). Activated new global semantics by default. Global variables can now shadow properties of the global object (ES5.1 erratum). Properly set ElementsKind of empty FAST_DOUBLE_ELEMENTS arrays when transitioning (Chromium issue 117409). Made Error.prototype.name writable again, as required by the spec and the web (Chromium issue 69187). Implemented map collection with incremental marking (issue 1465). Regexp: Fixed overflow in min-match-length calculation (Chromium issue 126412). MIPS: Fixed illegal instruction use on Loongson in code for Math.random() (issue 2115). Fixed crash bug in VisitChoice (Chromium issue 126272). Fixed unsigned-Smi check in MappedArgumentsLookup (Chromium issue 126414). Fixed LiveEdit for function with no locals (issue 825). Fixed register clobbering in LoadIC for interceptors (Chromium issue 125988). Implemented clearing of CompareICs (issue 2102). Performance and stability improvements on all platforms. 2012-05-03: Version 3.10.8 Enabled MIPS cross-compilation. Ensured reload of elements pointer in StoreFastDoubleElement stub. (Chromium issue 125515) Fixed corner cases in truncation behavior when storing to TypedArrays. (issue 2110) Fixed failure to properly recognize and report out-of-memory conditions when allocating code space pages. (Chromium issue 118625) Fixed idle notifications to perform a round of incremental GCs after context disposal. (issue 2107) Fixed preparser for try statement. (issue 2109) Performance and stability improvements on all platforms. 2012-04-30: Version 3.10.7 Performance and stability improvements on all platforms. 2012-04-26: Version 3.10.6 Fixed some bugs in accessing details of the last regexp match. Fixed source property of empty RegExp objects. (issue 1982) Enabled inlining some V8 API functions. Performance and stability improvements on all platforms. 2012-04-23: Version 3.10.5 Put new global var semantics behind a flag until WebKit tests are cleaned up. Enabled stepping into callback passed to builtins. (Chromium issue 109564) Performance and stability improvements on all platforms. 2012-04-19: Version 3.10.4 Fixed issues when stressing compaction with WeakMaps. Fixed missing GVN flag for new-space promotion. (Chromium issue 123919) Simplify invocation sequence at monomorphic function invocation sites. (issue 2079) Performance and stability improvements on all platforms. 2012-04-17: Version 3.10.3 Fixed several bugs in heap profiles (including issue 2078). Throw syntax errors on illegal escape sequences. Implemented rudimentary module linking (behind --harmony flag) Implemented ES5 erratum: Global declarations should shadow inherited properties. Made handling of const more consistent when combined with 'eval' and 'with'. Fixed V8 on MinGW-x64 (issue 2026). Performance and stability improvements on all platforms. 2012-04-13: Version 3.10.2 Fixed native ARM build (issues 1744, 539) Return LOOKUP variable instead of CONTEXT for non-context allocated outer scope parameters (Chromium issue 119609). Fixed regular and ElementsKind transitions interfering with each other (Chromium issue 122271). Improved performance of keyed loads/stores which have a HeapNumber index (issues 1388, 1295). Fixed WeakMap processing for evacuation candidates (issue 2060). Bailout on possible direct eval calls (Chromium issue 122681). Do not assume that names of function expressions are context-allocated (issue 2051). Performance and stability improvements on all platforms. 2012-04-10: Version 3.10.1 Fixed bug with arguments object in inlined functions (issue 2045). Fixed performance bug with lazy initialization (Chromium issue 118686). Added suppport for Mac OS X 64bit builds with GYP. (Patch contributed by Filipe David Manana ) Fixed bug with hidden properties (issue 2034). Fixed a performance bug when reloading pages (Chromium issue 117767, V8 issue 1902). Fixed bug when optimizing throw in top-level code (issue 2054). Fixed two bugs with array literals (issue 2055, Chromium issue 121407). Fixed bug with Math.min/Math.max with NaN inputs (issue 2056). Fixed a bug with the new runtime profiler (Chromium issue 121147). Fixed compilation of V8 using uClibc. Optimized boot-up memory use. Optimized regular expressions. 2012-03-30: Version 3.10.0 Fixed store IC writability check in strict mode (Chromium issue 120099). Resynchronize timers if the Windows system time was changed. (Chromium issue 119815) Removed "-mfloat-abi=hard" from host compiler cflags when building for hardfp ARM (https://code.google.com/p/chrome-os-partner/issues/detail?id=8539) Fixed edge case for case independent regexp character classes (issue 2032). Reset function info counters after context disposal. (Chromium issue 117767, V8 issue 1902) Fixed missing write barrier in CopyObjectToObjectElements. (Chromium issue 119926) Fixed missing bounds check in HasElementImpl. (Chromium issue 119925) Performance and stability improvements on all platforms. 2012-03-23: Version 3.9.24 Activated count-based profiler for ARM. Fixed use of proxies as f.prototype properties. (issue 2021) Enabled snapshots on MIPS. Performance and stability improvements on all platforms. 2012-03-21: Version 3.9.23 Use correct arguments adaptation environment when inlining function containing arguments. (Issue 2014) Performance and stability improvements on all platforms. 2012-03-20: Version 3.9.22 Enabled count-based profiler by default. Implemented a hash based look-up to speed up address checks in large object space (issue 853). Performance and stability improvements on all platforms. 2012-03-19: Version 3.9.21 Fixed push-to-trunk script (and re-push). Added API call that identifies strings that are guaranteed only to contain ASCII characters. 2012-03-19: Version 3.9.20 Fixed declarations escaping global strict eval. (Issue 1624) Fixed wrapping of receiver for non-strict callbacks. (Issue 1973) Fixed function declarations overwriting read-only global properties. (Chromium issue 115452) Fixed --use-strict flag in combination with --harmony[-scoping]. Debugger: naive implementation of "step into Function.prototype.bind". Debugger: added ability to set script source from within OnBeforeCompile Added flag to always call DebugBreak on abort. Re-enabled constructor inlining and inline === comparison with boolean constants. (Issue 2009) Don't use an explicit s0 in ClampDoubleToUint8. (Issue 2004) Performance and stability improvements on all platforms. 2012-03-14: Version 3.9.19 Ensure there is a smi check of the receiver for global load and call ICs (Chromium issue 117794). Performance and stability improvements on all platforms. 2012-03-13: Version 3.9.18 Ensure consistency of Math.sqrt on Intel platforms. Remove static initializers in v8. (issue 1859) Add explicit dependency on v8_base in the GYP-based build. Performance and stability improvements on all platforms. 2012-03-12: Version 3.9.17 Fixed VFP detection through compiler defines. (issue 1996) Add Code-related fields to postmortem metadata. Performance and stability improvements on all platforms. 2012-03-09: Version 3.9.16 Added basic interface inference for modules (behind the --harmony flag). Added Object.is, Number.isFinite, Number.isNaN. Updated the Unicode tables to Unicode version 6.1.0. Performance and stability improvements on all platforms. 2012-03-06: Version 3.9.15 Fix the heap profiler crash caused by memory layout changes between passes. Fix Error.prototype.toString to throw TypeError. (issue 1980) Fix double-rounding in strtod for MinGW. (issue 1062) Fix corrupted snapshot serializaton on ia32. (Chromium issue v8/1985) Performance and stability improvements on all platforms. 2012-03-01: Version 3.9.14 Performance and stability improvements on all platforms. 2012-02-29: Version 3.9.13 Added code kind check before preparing for OSR. (issue 1900, 115073) Fixed issue 1802: Pass zone explicitly to zone-allocation on x64 and ARM. Ported string construct stub to x64. (issue 849) Performance and stability improvements on all platforms. 2012-02-28: Version 3.9.12 Fixed the negative lookup stub to handle deleted entries in a dictionary. (issue 1964) Added a new API where the host can supply a callback function. The callback function can resolve the location of a return address on stack to the location where a return-address rewriting profiler stashed the original return address. Fixed Chromium issue http://crbug.com/115646: When compiling for-in pass correct context value to the increment instruction. Fixed issue 1853: Update breakpoints set with partial file name after compile. 2012-02-27: Version 3.9.11 Made 'module' a context-sensitive keyword (V8 issue 1957). 2012-02-24: Version 3.9.10 Fixed V8 issues 1322, 1772 and 1969. Conformance improvements. Performance and stability improvements on all platforms. 2012-02-23: Version 3.9.9 Supported fast case for-in in Crankshaft. Sped up heap snapshot serialization and dominators construction. Randomized allocation addresses on windows. (Chromium issue 115151) Fixed compilation with MinGW-w64. (issue 1943) Fixed incorrect value of assignments to non-extensible properties. Fixed a crash bug in generated code on ia32. Performance and stability improvements on all platforms. 2012-02-21: Version 3.9.8 Fixed memory leak and missing #include in StartupDataDecompressor (issue 1960). Renamed static methods to avoid shadowing virtual methods and fix Clang C++11 compile error. Fixed sequence of element access in array builtins (issue 1790). Performance and stability improvements on all platforms. 2012-02-16: Version 3.9.7 Fixed V8 issues 1322, 1878, 1942, 1945 and Chromium issue 113924. Fixed GCC-4.7 warnings. Added Navier-Stokes benchmark. Performance and stability improvements on all platforms. 2012-02-14: Version 3.9.6 Fixed template-related linker error. (issue 1936) Allowed inlining of functions containing object literals. (issue 1322) Added --call-graph-size option to tickprocessor. (issue 1937) Heap Snapshot maximum size limit is too low for really big apps. At the moment the limit is 256MB. (Chromium issue 113015) Performance and stability improvements on all platforms. 2012-02-09: Version 3.9.5 Removed unused command line flags. Performance and stability improvements on all platforms. 2012-02-08: Version 3.9.4 Properly initialize element-transitioning array literals on ARM. (issue 1930) Bug fixes on all platforms. 2012-02-07: Version 3.9.3 When rethrowing an exception, print the stack trace of its original site instead of rethrow site (Chromium issue 60240). Increased size of small stacks from 32k to 64k to avoid hitting limits in Chromium (Chromium issue 112843). 2012-02-06: Version 3.9.2 Added timestamp to --trace-gc output. (issue 1932) Heap profiler reports implicit references. Optionally export metadata with libv8 to enable debuggers to inspect V8 state. 2012-02-02: Version 3.9.1 Fixed memory leak in NativeObjectsExplorer::FindOrAddGroupInfo (Chromium issue 112315). Fixed a crash in dev tools (Chromium issue 107996). Added 'dependencies_traverse': 1 to v8 GYP target. Performance and stability improvements on all platforms. 2012-02-01: Version 3.9.0 Reduced memory use immediately after starting V8. Stability fixes and performance improvements on all platforms. 2012-01-26: Version 3.8.9 Flush number string cache on GC (issue 1605). Provide access to function inferred name with v8::Function::GetInferredName in V8 public API. Fix building with Clang (issue 1912). Reduce the space used by the stack for the profiling thread. Fix misleading documentation of v8::Locker (issue 542). Introduce readbinary function in d8 to read binary files. Performance and stability improvements on all platforms. 2012-01-23: Version 3.8.8 Limited number of loop iterations in Heap::ReserveSpace (Chromium issue 99027). Fixed solaris build (VirtualMemory) (issue 1761). Fixed strict vs. non-strict handling of function proxies in higher-order array and string methods. Enabled asynchronous remote debugging with d8 (issue 1691). Stability and performance improvements on all platforms. 2012-01-19: Version 3.8.7 Ensure that LRandom restores rsi after call to the C function on x64. (Chromium issue http://crbug.com/110509) Fixing include issues on *bsd when building with scons. (issue 1897) Provide a switch to specify -fno-strict-aliasing (issue 1887) Move WIN32 define from standalone.gypi to common.gypi (issue 1760) Fix corner-case in heap size estimation. (issue 1893) Fix and enable NEW_NON_STRICT_FAST ArgumentsAccess stub on x64. (issue 1903) Performance improvements and bug fixes. 2012-01-16: Version 3.8.6 Add primitive WebGL array support to d8. Improve heap size estimation (issue 1893). Hash collision DOS workaround extended from string keys to numeric keys. Provide an API for iterating through all external strings referenced from the JS heap. Adjust position recorded for call expressions. http://crbug.com/109195 Fix GC crash related to instanceof. http://crbug.com/109448 Performance improvements and bug fixes. 2012-01-05: Version 3.8.5 Fix broken test that assumes that no GC can clear the regexp cache (GC can happen at any time due to Crankshaft). Fix handling of bogus receivers for Harmony collections. (issue 1884) Add netbsd support to gyp build. Determine page size at runtime on posix platforms. Ensure that store buffer filtering hash sets are cleared after StoreBuffer::Filter. Randomize the seed used for string hashing. This helps guard against CPU-eating DOS attacks against node.js servers. Based on code from Bert Belder. This version only solves the issue for those that compile V8 themselves or those that do not use snapshots. A snapshot-based precompiled V8 will still have predictable string hash codes. Implement callback when script finishes running in V8 API. Improve performance of Math.min and Math.max for the case of two arguments. (issue 1325) 2012-01-02: Version 3.8.4 Performance improvements for large Smi-only arrays. Fixed InternalArrays construction. (issue 1878) 2011-12-27: Version 3.8.3 Avoid embedding new space objects into code objects in the lithium gap resolver. (chromium:108296) Bug fixes and performance optimizations on all platforms. 2011-12-21: Version 3.8.2 Add max optimization flag to v8 gyp build to ensure V8 is always built fully optimized in Chrome. MIPS: Bring MIPS to parity with other platforms. Optimizations and stability improvements on all platforms. 2011-12-19: Version 3.8.1 Fixed GCC 4.7 warnings. Patch from Tobias Burnus. Stability improvements on all platforms. 2011-12-13: Version 3.8.0 Fixed handling of arrays in DefineOwnProperty. (issue 1756) Sync parser and preparser on do-while and return statements. (issue 1856) Fixed another corner case for DefineOwnProperty on arrays (issue 1756). Stability and performance improvements on all platforms. 2011-12-01: Version 3.7.12 Increase tick interval for the android platform. Fix a bug in the register allocator. (chromium:105112) Fix handling of recompiling code. (chromium:105375, v8:1782) Start incremental marking on idle notification. (v8:1458) Build fixes for various platforms. Various performance improvements. 2011-11-29: Version 3.7.11 Fixed bug when generating padding to ensure space for lazy deoptimization. (issue 1846) Further reduced pause times due to GC. Stability and performance improvements on all platforms. 2011-11-23: Version 3.7.10 Set maximum length of FixedArray in terms of elements instead an absolute number of bytes. (Chromium issue 103103) Stability and performance improvements on all platforms. 2011-11-21: Version 3.7.9 Removed exit-time destructors. Stability and performance improvements on all platforms. 2011-11-17: Version 3.7.8 Removed hidden prototype from builtins, i.e., deleting an overridden function on builtins will not make the original function reappear. Added NetBSD support for scons build. Performance improvements on all platforms. 2011-11-14: Version 3.7.7 Fix missing fast property accessors in heap snapshots. (issue 1818) 2011-11-11: Version 3.7.6 Fixed filtering of store buffer for large object pages. (issue 1817) Fixed generated hash function on all platforms. (issue 1808) Fixed Heap::Shrink to ensure that it does not free pages that are still in use. (Chromium issue 100414) Stability and performance improvements on all platforms. 2011-11-10: Version 3.7.5 Added initial gyp infrastructure for MIPS. Implemented performance improvements to the incremental garbage collector. Added optimizations and stability improvements on all platforms. 2011-11-07: Version 3.7.4 Proper "libv8.so.3.7.4" SONAME for Linux shared library (issue 1786). Fix Harmony sets and maps to allow null and undefined as keys (still hidden behind --harmony flag) (issue 1622). Implement VirtualMemory on FreeBSD to fix build (issue 1807). Enable VFP instructions for Android. Fix error handling in Date.prototype.toISOString (issue 1792). Bug fixes and performance improvements for all platforms. Not officially supported but noteworthy: Crankshaft for MIPS :-) 2011-10-28: Version 3.7.3 Slight deoptimization as a workaround for issue with jslint: Issue 1789. 2011-10-27: Version 3.7.2 Fix bug in deoptimization. Known issue with jslint: Issue 1789. 2011-10-26: Version 3.7.1 Achieved 33% speedup in debug-mode tests. Removed special casing of calls to RegExp test and exec methods with no argument. Now matches new JSC behaviour. crbug.com/75740. Return the empty string on cyclic references in toString (ES5 conformance). Fixed bug triggered by JSBeautifier. crbug.com/100409. Made Math.random state per-context instead of per-process (issue 864). Fixed stack traces to skip native functions. Make snapshots (new contexts) smaller and faster. Fixed handling of Function.apply for non-array arguments. Fixed evaluation order in defineProperties to match FireFox. Fixed handling of non-object receivers for array builtins, crbug.com/100702. Multiple fixes to improve compliance with test262. Fixed compatibility with older Android releases. Fixed compilation with gcc-4.5.3. Improved performance of WriteUtf8, issue 1665. Made native syntax an early error in the preparser. Fixed issues 793 and 893 relating to Function.prototype.bind. Improved let, const, Set and Map support and other Harmony features (behind the --harmony flag). Changed evaluation order for > and <= to match ES5 instead of ES3. Bug fixes and performance improvements on all platforms. 2011-10-13: Version 3.7.0 Fixed array handling for Object.defineOwnProperty (ES5 conformance). Fixed issue 1757 (string slices of external strings). Fixed issue 1759 (ARM). Added flag --noclever-optimizations to disable some things that caused trouble in the past. Added flag --stress-compaction for testing. Added flag --harmony to activate all experimental Harmony features. 2011-10-10: Version 3.6.6 Added a GC pause visualization tool. Added presubmit=no and werror=no flags to Makefile. ES5/Test262 conformance improvements. Fixed compilation issues with GCC 4.5.x (issue 1743). Bug fixes and performance improvements on all platforms. 2011-10-05: Version 3.6.5 New incremental garbage collector. Removed the hard heap size limit (soft heap size limit is still 700/1400Mbytes by default). Implemented ES5 generic Array.prototype.toString (Issue 1361). V8 now allows surrogate pair codes in decodeURIComponent (Issue 1415). Fixed x64 RegExp start-of-string bug (Issues 1746, 1748). Fixed propertyIsEnumerable for numeric properties (Issue 1692). Fixed the MinGW and Windows 2000 builds. Fixed "Prototype chain is not searched if named property handler does not set a property" (Issue 1636). Made the RegExp.prototype object be a RegExp object (Issue 1217). Disallowed future reserved words as labels in strict mode. Fixed string split to correctly coerce the separator to a string (Issue 1711). API: Added an optional source length field to the Extension constructor. API: Added Debug::DisableAgent to match existing Debug::EnableAgent (Issue 1573). Added "native" target to Makefile for the benefit of Linux distros. Fixed: debugger stops stepping outside evaluate (Issue 1639). More work on ES-Harmony proxies. Still hidden behind a flag. Bug fixes and performance improvements on all platforms. 2011-09-15: Version 3.6.4 Fixed d8's broken readline history. Removed the need for code delete events in CPU profiler (Issue 1466). Fixed debugger stepping next with trycatch recursion (Issue 1639). Fixing parallel execution in d8 (with -p) and some memory leaks. Support for precise stepping in functions compiled before debugging was started (step 1). 2011-09-13: Version 3.6.3 Implemented better support of typed arrays in the d8 shell. Bug fixes and performance improvements on all platforms. 2011-09-08: Version 3.6.2 Added "dependencies" target to top-level Makefile. Added ability to turn profiler on/off in d8. Added "soname_version" parameter to common.gypi, v8.gyp, and Makefile. Fixed several crash bugs. 2011-09-07: Version 3.6.1 Fixed a bug in abrupt exit from with or catch inside finally. Fixed possible crash in FixedDoubleArray::Initialize() (Chromium issue 95113). Fixed a bug in Page::GetRegionMaskForSpan (Chromium issue 94425). Fixed a few clang warnings (which -Werror treated as errors). Performance improvements on all platforms. 2011-09-05: Version 3.6.0 Fixed a bug when optimizing named function expression (issue 1647). Fixed a bug when optimizing f.call.apply (issue 1650). Made arguments and caller always be null on native functions (issues 1548 and 1643). Fixed issue 1648 (cross-compiling x64 targeting ia32). Fixed issue 371 (d8 printing of strings containing \0). Fixed order of evaluation in arguments to parseInt (issue 1649). Fixed a problem with large heap snapshots in Chrome DevTools (issue 1658, chromium issue 89268). Upped default maximum heap size from 512M to 700M. 2011-08-31: Version 3.5.10 Added dependency of v8_base on WinSocket2 Windows library in the GYP-build. Various bugfixes. 2011-08-29: Version 3.5.9 Made FromPropertyDescriptor not trigger inherited setters. Fixed .gyp files to work on the ARM simulator. Fixed shared library build warnings for MSVS. 2011-08-24: Version 3.5.8 Added V8EXPORT attributes for v8::Array::CheckCast and v8::Number::CheckCast. Made a slight API change enabling opting out from null termination in String::Write*(). Fixed arm build for gcc-4.6. 2011-08-22: Version 3.5.7 Make scanner handle invalid unicode escapes in identifiers correctly. Make regexp flag parsing stricter. Fix several memory leaks. 2011-08-17: Version 3.5.6 Fixed issue that could cause crashes when running with --heap-stats. Fixed compilation on Linux 2.6.9 and older. Fixed live-object-list to work with isolates. Fixed memory leaks in zones and isolates. Fixed a performance regression for TypedArrays on x64. Stability improvements on all platforms. 2011-08-15: Version 3.5.5 Fixed bugs involving negative zero and the optimizing compiler. Fixed optimized version of Function.apply(x, arguments). (issue 1592) Eliminated uses of deprecated ARM instructions. Sped up Math.floor by using SSE 4.1 roundsd instruction on ia32. Removed restriction on the size of disassembled code that is printed. 2011-08-10: Version 3.5.4 Added a preliminary implementation of ES Harmony weak maps. Weak maps can be enabled by the flag --harmony-weakmaps. Introduced a toplevel Makefile to support GYP-based building. GYP can be obtained from http://gyp.googlecode.com. Fixed a bug in the length property of functions created by Function.prototype.bind. Reduced malloc heap allocation on process startup. Several important code generation bug fixes. Performance improvements on all platforms. 2011-08-03: Version 3.5.3 MIPS: Port of fix to ClassOf check from ARM. Patch from Paul Lind . Stopped using mprotect on Cygwin. Avoided uninitialized member warning on gcc 4.3.4 Both patches by Bert Belder. Bug fixes and performance improvements on all platforms. 2011-08-01: Version 3.5.2 Performance improvements on all platforms. 2011-07-28: Version 3.5.1 Fixed setting the readonly flag on the prototype property using the API call FunctionTemplate::SetPrototypeAttributes (issue 1539). Changed the tools/test.py script to use d8 instead of shell for testing. Fixed crash in ToBooleanStub when GC happens during invocation. Enabled automatic unboxing of double arrays. Performance improvements on all platforms. 2011-07-25: Version 3.5.0 Implemented Object.prototype.{hasOwnProperty, propertyIsEnumerable} for proxies. Removed logging to memory support. Bugfixes and performance work. 2011-07-20: Version 3.4.14 Fix the debugger for strict-mode functions. (Chromium issue 89236) Add GetPropertyAttribute method for Object in the API. (Patch by Peter Varga) Fix -Wunused-but-set-variable for gcc-4.6 on x64. (Issue 1291) 2011-07-18: Version 3.4.13 Improved debugger support to allow inspection of optimized frames (issue 1140). Fixed a bug in prototype transitions cache clearing introduced by r8165. Fixed shortcutting bug in HInferRepresentation. Patch by Andy Wingo. Fixed a memory leak in sample/shell.cc (dispose semaphores). Simplified HClampToUint8. Patch by Andy Wingo. Exposed APIs for detecting boxed primitives, native errors. Patch by Luke Zarko. Added map check for COW elements to crankshaft array handling code (issue 1560). Sample shell and (a light version of) D8 links against a shared library now. Fixed bug in array filter and reduce functions (issue 1559). Avoid TLS load in AstNode constructor. Introduced a random entropy source which can optionally be provided at initialization. (Chromium issue 89462). 2011-07-13: Version 3.4.12 Added --prof profiling option to d8 shell. Fixed a bug where reading a directory in d8 shell hangs (issue 1533). Fixed a potential assertion failure in const declarations. Fixed an assertion failure in descriptor arrays (issue 1526). Enabled fast thread-local storage by default on supported platforms. Improved reporting of source position for global variable loads (issue 1527). 2011-07-11: Version 3.4.11 Fixed MinGW32 build. Fixed a GC bug with RegExp code flushing. Implemented Object.defineProperty for proxies. Fixed a bug in for/in iteration of arguments objects (issue 1531). Added debugger support for inspecting optimized frames (issue 1140). Allowed JSObject::PreventExtensions to work for arguments objects. Bugfixes and performance work. 2011-07-06: Version 3.4.10 Fixed debugger not breaking on certain "if" statements (issue 1523). Fixed assertion failure in runtime profiler when running on IA32 without snapshot (issue 1522). Fixed ABI for API calls on IA32 (for clang compatibility). Introduced code flushing of RegExp code to free memory used by RegExps sooner. Fixed linux-tick-processor built wrong version of v8 (issue 1532). Fixed assertion failure in v8::TryCache::StackTrace (issue 1529). Performance improvements on all platforms. 2011-07-04: Version 3.4.9 Added support for debugger inspection of locals in optimized frames (issue 1140). Fixed SConstruct to pass correct defines to samples/preparser when building with library=shared. Made date parser handle ES5 Date Time Strings correctly (issue 1498). Fixed a bug in Object.defineProperty on the arguments object. Performance improvements on all platforms. 2011-06-29: Version 3.4.8 Ensure 16-byte stack alignment on Solaris (issue 1505). Fix "illegal access" when calling parseInt with a radix that is not a smi. (issue 1246). 2011-06-27: Version 3.4.7 Fixed 64-bit build on FreeBSD. Added API to set the property attributes for the prototype property on functions created from FunctionTemplates. Bugfixes and performance work. 2011-06-22: Version 3.4.6 Lowered limit on code space for systems with low memory supply. Allowed compiling v8_shell with the 'host' toolset (issue 82437). Extended setBreakpoint API to accept partial script name (issue 1418). Made multi-line comments not count when deciding whether the '-->' comment starter is first on a line. This matches Safari. Made handling of non-array recievers in Array length setter correct (issue 1491). Added ability to heap profiler to iterate over snapshot's node (issue 1481). 2011-06-20: Version 3.4.5 Fixed issues 794, 1097, 1215(partial), 1417, 1435, 1472, 1473, 1476, and 1477. Improved code generation for !0 and !1. Reduced memory usage for regular expressions with nested qualifiers. (issue 1472) Fixed V8 to count line terminators in multi-line comments. (Chromium issue 86431) Fixed disassembler=on option for release-mode builds. (issue 1473) Performance improvements on all platforms. 2011-06-15: Version 3.4.4 Added snapshot compression support and --stress-opt flag to d8. Improved performance of try/catch. Several GYP-related changes: Added support for building Xcode project files. Make the ARM simulator build with GYP again. Generate Makefiles for all architectures on Linux. Fixed Array.prototype.{reduce,reduceRight} to pass undefined as the receiver for strict mode callbacks. (issue 1436) Fixed a bug where an array load was incorrectly hoisted by GVN. Handle 'undefined' correctly when === has been specialized for doubles. (issue 1434) Corrected the limit of local variables in an optimized function from 64 to 63. Correctly set ReadOnly flag on indexed properties when using the API Set method. (issue 1470) Give the correct error message when Object.isExtensible is called on a non-object. (issue 1452) Added GetOwnPropertyNames method for Object in the API. Patch by Peter Varga. Do not redefine properties unneccesarily in seal and freeze. (issue 1447) IsExecutionTerminating has an Isolate parameter now. Distinguish keyed loads with a symbol key from fast elements loads, avoiding some useless deoptimizations. (issue 1471) 2011-06-08: Version 3.4.3 Clear the global thread table when an isolate is disposed (issue 1433). Converted time zone name to UTF8 on Windows (issue 1290). Limited the number of arguments in a function call to 32766 (issue 1413). Compress sources of JS libraries in addition to the snapshot. Fixed a bug in Lithium environment iteration. Performance improvements on all platforms. 2011-06-06: Version 3.4.2 More work on ES-Harmony proxies. Still hidden behind a flag. Fixed some crash bugs and improved performance. Fixed building with gdb debugging support. Do not install SIGPROF handler until it is needed. Added DateTimeFormat to i18n API. Fixed compilation on OpenBSD. Take the ulimit into account when sizing the heap. OpenBSD users may still have to increase the default ulimit to run heavy pages in the browser. 2011-06-01: Version 3.4.1 Fixed JSON stringify issue with arrays. Changed calls to JS builtins to be passed undefined when called with implicit receiver. Implemented the set trap for Harmony proxies. Proxies still need to be enabled with the --harmony-proxies flag. 2011-05-30: Version 3.4.0 Changed calls to undefined property setters to not throw (issue 1355). Made RegExp objects not callable. Fixed issues on special case large JSON strings in new json parser (issues http://crbug.com/83877 and http://crbug.com/84186). Performance improvements on all platforms. 2011-05-25: Version 3.3.10 Fixed calls of strict mode function with an implicit receiver. Fixed fast handling of arrays to properly deal with changes to the Object prototype (issue 1403). Changed strict mode poison pill to be the same type error function (issue 1387). Fixed a debug crash in arguments object handling (issue 1227). Fixed a bug in deoptimization on x64 (issue 1404). Performance improvements and bug fixes on all platforms. 2011-05-23: Version 3.3.9 Added DateTimeFormat class to experimental i18n API. Extended preparser to give early errors for some strict mode restrictions. Removed legacy execScript function from V8. Extended isolate API with the ability to add embedder-specific data to an isolate. Added basic support for polymorphic loads from JS and external arrays. Fixed bug in handling of switch statements in the optimizing compiler. 2011-05-18: Version 3.3.8 Added MarkIndependent to the persistent handle API. Independent handles are independent of all other persistent handles and can be garbage collected more frequently. Implemented the get trap for Harmony proxies. Proxies are enabled with the --harmony-proxies flag. Performance improvements and bug fixes on all platforms. 2011-05-16: Version 3.3.7 Updated MIPS infrastructure files. Performance improvements and bug fixes on all platforms. 2011-05-11: Version 3.3.6 Updated MIPS infrastructure files. Added method IsCallable for Object to the API. Patch by Peter Varga. 2011-05-09: Version 3.3.5 Fixed build on FreeBSD. Patch by Akinori MUSHA. Added check that receiver is JSObject on API calls. Implemented CallAsConstructor method for Object in the API (Issue 1348). Patch by Peter Varga. Added CallAsFunction method to the Object class in the API (Issue 1336). Patch by Peter Varga. Added per-isolate locking and unlocking. Fixed bug in x64 >>> operator (Issue 1359). 2011-05-04: Version 3.3.4 Implemented API to disallow code generation from strings for a context (issue 1258). Fixed bug with whitespaces in parseInt (issue 955). Fixed bug with == comparison of Date objects (issue 1356). Added GYP variables for ARM code generation: v8_can_use_vfp_instructions, v8_can_use_unaligned_accesses and v8_use_arm_eabi_hardfloat. 2011-05-02: Version 3.3.3 Added support for generating Visual Studio solution and project files using GYP. Implemented support for ARM EABI calling convention variation where floating-point arguments are passed in registers (hardfloat). Added Object::HasOwnProperty() to the API. Added support for compressing startup data to reduce binary size. This includes build time support and an API for the embedder to decompress the startup data before initializing V8. Reduced the profiling hooks overhead from >400% to 25% when using ll_prof. Performance improvements and bug fixes on all platforms. 2011-04-27: Version 3.3.2 Fixed crash bug on ARM with no VFP3 hardware. Fixed compilation of V8 without debugger support. Improved performance on JSLint. Added support Float64 WebGL arrays. Fixed crash bug in regexp replace. 2011-04-20: Version 3.3.1 Reduced V8 binary size by removing virtual functions from hydrogen. Fixed crash bug on x64. Performance improvements on ARM and IA32. 2011-04-18: Version 3.3.0 Fixed bug in floating point rounding in Crankshaft on ARM (issue 958) Fixed a number of issues with running without VFPv3 support on ARM (issue 1315) Introduced v8Locale.Collator, a partial implementation of Collator per last ECMAScript meeting + mailing list. Minor performance improvements and bug fixes. 2011-04-13: Version 3.2.10 Fixed bug in external float arrays on ARM (issue 1323). Minor performance improvements and bug fixes. 2011-04-11: Version 3.2.9 Removed support for ABI prior to EABI on ARM. Fixed multiple crash bugs. Added GCMole to the repository, a simple static analysis tool that searches for GC-unsafe evaluation order dependent callsites. Made preparser API be exported in shared libraries. Fixed multiple issues in EcmaScript 5 strict mode implementation. Fixed mutable __proto__ property if object is not extensible (Issue 1309). Fixed auto suspension of the sampler thread. 2011-04-06: Version 3.2.8 Exposed WebGL typed array constructors in the shell sample. Performance improvements on all platforms. 2011-04-04: Version 3.2.7 Disabled the original 'classic' V8 code generator. Crankshaft is now the default on all platforms. Changed the heap profiler to use more descriptive names. Performance and stability improvements to isolates on all platforms. 2011-03-30: Version 3.2.6 Fixed xcode build warning in shell.cc (out of order initialization). Fixed null-pointer dereference in the compiler when running without SSE3 support (Chromium issue 77654). Fixed x64 compilation error due to some dead code. (Issue 1286) Introduced scons target to build the preparser stand-alone example. Made FreeBSD build and pass all tests. 2011-03-28: Version 3.2.5 Fixed build with Irregexp interpreter (issue 1266). Added Crankshaft support for external arrays. Fixed two potential crash bugs. 2011-03-23: Version 3.2.4 Added isolates which allows several V8 instances in the same process. This is controlled through the new Isolate class in the API. Implemented more of EcmaScript 5 strict mode. Reduced the time it takes to make detailed heap snapshot. Added a number of commands to the ARM simulator and enhanced the ARM disassembler. 2011-03-17: Version 3.2.3 Fixed a number of crash bugs. Fixed Array::New(length) to return an array with a length (issue 1256). Fixed FreeBSD build. Changed __defineGetter__ to not throw (matching the behavior of Safari). Implemented more of EcmaScript 5 strict mode. Improved Crankshaft performance on all platforms. 2011-03-14: Version 3.2.2 Fixed a number of crash and correctness bugs. Improved Crankshaft performance on all platforms. Fixed Crankshaft on Solaris/Illumos. 2011-03-10: Version 3.2.1 Fixed a number of crash bugs. Improved Crankshaft for x64 and ARM. Implemented more of EcmaScript 5 strict mode. 2011-03-07: Version 3.2.0 Fixed a number of crash bugs. Turned on Crankshaft by default on x64 and ARM. Improved Crankshaft for x64 and ARM. Implemented more of EcmaScript 5 strict mode. 2011-03-02: Version 3.1.8 Fixed a number of crash bugs. Improved Crankshaft for x64 and ARM. Implemented more of EcmaScript 5 strict mode. Fixed issue with unaligned reads and writes on ARM. Improved heap profiler support. 2011-02-28: Version 3.1.7 Fixed a number of crash bugs. Improved Crankshaft for x64 and ARM. Fixed implementation of indexOf/lastIndexOf for sparse arrays (http://crbug.com/73940). Fixed bug in map space compaction (http://crbug.com/59688). Added support for direct getter accessors calls on ARM. 2011-02-24: Version 3.1.6 Fixed a number of crash bugs. Added support for Cygwin (issue 64). Improved Crankshaft for x64 and ARM. Added Crankshaft support for stores to pixel arrays. Fixed issue in CPU profiler with Crankshaft. 2011-02-16: Version 3.1.5 Change RegExp parsing to disallow /(*)/. Added GDB JIT support for ARM. Fixed several crash bugs. Performance improvements on the IA32 platform. 2011-02-14: Version 3.1.4 Fixed incorrect compare of prototypes of the global object (issue 1082). Fixed a bug in optimizing calls to global functions (issue 1106). Made optimized Function.prototype.apply safe for non-JSObject first arguments (issue 1128). Fixed an error related to element accessors on Object.prototype and parser errors (issue 1130). Fixed a bug in sorting an array with large array indices (issue 1131). Properly treat exceptions thrown while compiling (issue 1132). Fixed bug in register requirements for function.apply (issue 1133). Fixed a representation change bug in the Hydrogen graph construction (issue 1134). Fixed the semantics of delete on parameters (issue 1136). Fixed a optimizer bug related to moving instructions with side effects (issue 1138). Added support for the global object in Object.keys (issue 1150). Fixed incorrect value for Math.LOG10E (issue http://code.google.com/p/chromium/issues/detail?id=72555) Performance improvements on the IA32 platform. Implement assignment to undefined reference in ES5 Strict Mode. 2011-02-09: Version 3.1.3 Fixed a bug triggered by functions with huge numbers of declared arguments. Fixed zap value aliasing a real object - debug mode only (issue 866). Fixed issue where Array.prototype.__proto__ had been set to null (issue 1121). Fixed stability bugs in Crankshaft for x86. 2011-02-07: Version 3.1.2 Added better security checks when accessing properties via Object.getOwnPropertyDescriptor. Fixed bug in Object.defineProperty and related access bugs (issues 992, 1083 and 1092). Added LICENSE.v8, LICENSE.strongtalk and LICENSE.valgrind to ease copyright notice generation for embedders. 2011-02-02: Version 3.1.1 Perform security checks before fetching the value in Object.getOwnPropertyDescriptor. Fixed a bug in Array.prototype.splice triggered by passing no arguments. Fixed bugs in -0 in arithmetic and in Math.pow. Fixed bugs in the register allocator and in switching from optimized to unoptimized code. 2011-01-31: Version 3.1.0 Performance improvements on all platforms. 2011-01-28: Version 3.0.12 Added support for strict mode parameter and object property validation. Fixed a couple of crash bugs. 2011-01-25: Version 3.0.11 Fixed a bug in deletion of lookup slots that could cause global variables to be accidentally deleted (http://crbug.com/70066). Added support for strict mode octal literal verification. Fixed a couple of crash bugs (issues 1070 and 1071). 2011-01-24: Version 3.0.10 Fixed External::Wrap for 64-bit addresses (issue 1037). Fixed incorrect .arguments variable proxy handling in the full code generator (issue 1060). Introduced partial strict mode support. Changed formatting of recursive error messages to match Firefox and Safari (issue http://crbug.com/70334). Fixed incorrect rounding for float-to-integer conversions for external array types, which implement the Typed Array spec (issue http://crbug.com/50972). Performance improvements on the IA32 platform. 2011-01-19: Version 3.0.9 Added basic GDB JIT Interface integration. Make invalid break/continue statements a syntax error instead of a runtime error. 2011-01-17: Version 3.0.8 Exposed heap size limit to the heap statistics gathered by the GetHeapStatistics API. Wrapped external pointers more carefully (issue 1037). Hardened the implementation of error objects to avoid setters intercepting the properties set then throwing an error. Avoided trashing the FPSCR when calculating Math.floor on ARM. Performance improvements on the IA32 platform. 2011-01-10: Version 3.0.7 Stopped calling inherited setters when creating object literals (issue 1015). Changed interpretation of malformed \c? escapes in RegExp to match JSC. Enhanced the command-line debugger interface and fixed some minor bugs in the debugger. Performance improvements on the IA32 platform. 2011-01-05: Version 3.0.6 Allowed getters and setters on JSArray elements (issue 900). Stopped JSON objects from hitting inherited setters (part of issue 1015). Allowed numbers and strings as names of getters/setters in object initializer (issue 820). Added use_system_v8 option to gyp (off by default), to make it easier for Linux distributions to ship with system-provided V8 library. Exported external array data accessors (issue 1016). Added labelled thread names to help with debugging (on Linux). 2011-01-03: Version 3.0.5 Fixed a couple of cast errors for gcc-3.4.3. Performance improvements in GC and IA32 code generator. 2010-12-21: Version 3.0.4 Added Date::ResetCache() to the API so that the cached values in the Date object can be reset to allow live DST / timezone changes. Extended existing support for printing (while debugging) the contents of objects. Added support for printing objects from release builds. Fixed V8 issues 989, 1006, and 1007. 2010-12-17: Version 3.0.3 Reapplied all changes for version 3.0.1. Improved debugger protocol for remote debugging. Added experimental support for using gyp to generate build files for V8. Fixed implementation of String::Write in the API (issue 975). 2010-12-15: Version 3.0.2 Revert version 3.0.1 and patch 3.0.1.1. 2010-12-13: Version 3.0.1 Added support for an experimental internationalization API as an extension. This extension is disabled by default but can be enabled when building V8. The ECMAScript internationalization strawman is at http://wiki.ecmascript.org/doku.php?id=strawman:i18n_api. Made RegExp character class parsing stricter. This mirrors a change to RegExp parsing in WebKit. Fixed a bug in Object.defineProperty when used to change attributes of an existing property. It incorrectly set the property value to undefined (issue 965). Fixed several different compilation failures on various platforms caused by the 3.0.0 release. Optimized Math.pow so it can work on unboxed doubles. Sped up quoting of JSON strings by removing one traversal of the string. 2010-12-07: Version 3.0.0 Improved performance by (partially) addressing issue 957 on IA-32. Still needs more work for the other architectures. 2010-11-29: Version 2.5.9 Fixed crashes during GC caused by partially initialize heap objects. Fixed bug in process sample that caused memory leaks. Improved performance on ARM by implementing missing stubs and inlining. Improved heap profiler support. Added separate seeding on Windows of the random number generator used internally by the compiler (issue 936). Exposed API for getting the name of the function used to construct an object. Fixed date parser to handle one and two digit millisecond values (issue 944). Fixed number parsing to disallow space between sign and digits (issue 946). 2010-11-23: Version 2.5.8 Removed dependency on Gay's dtoa. Improved heap profiler precision and speed. Reduced overhead of callback invocations on ARM. 2010-11-18: Version 2.5.7 Fixed obscure evaluation order bug (issue 931). Split the random number state between JavaScript and the private API. Fixed performance bug causing GCs when generating stack traces on code from very large scripts. Fixed bug in parser that allowed (foo):42 as a labelled statement (issue 918). Provide more accurate results about used heap size via GetHeapStatistics. Allow build-time customization of the max semispace size. Made String.prototype.split honor limit when separator is empty (issue 929). Added missing failure check after expecting an identifier in preparser (Chromium issue 62639). 2010-11-10: Version 2.5.6 Added support for VFP rounding modes to the ARM simulator. Fixed multiplication overflow bug (issue 927). Added a limit for the amount of executable memory (issue 925). 2010-11-08: Version 2.5.5 Added more aggressive GC of external objects in near out-of-memory situations. Fixed a bug that gave the incorrect result for String.split called on the empty string (issue 924). 2010-11-03: Version 2.5.4 Improved V8 VFPv3 runtime detection to address issue 914. 2010-11-01: Version 2.5.3 Fixed a bug that prevents constants from overwriting function values in object literals (issue 907). Fixed a bug with reporting of impossible nested calls of DOM functions (issue http://crbug.com/60753). 2010-10-27: Version 2.5.2 Improved sampler resolution on Linux. Allowed forcing the use of a simulator from the build script independently of the host architecture. Fixed FreeBSD port (issue 912). Made windows-tick-processor respect D8_PATH. Implemented --noinline-new flag fully on IA32, X64 and ARM platforms. 2010-10-20: Version 2.5.1 Fixed bug causing spurious out of memory exceptions (issue http://crbug.com/54580). Fixed compilation error on Solaris platform (issue 901). Fixed error in strtod (string to floating point number conversion) due to glibc's use of 80-bit floats in the FPU on 32-bit linux. Adjusted randomized allocations of executable memory to have 64k granularity (issue http://crbug.com/56036). Supported profiling using kernel perf_events on linux. Added ll_prof script to tools and --ll-prof flag to V8. 2010-10-18: Version 2.5.0 Fixed bug in cache handling of lastIndex on global regexps (issue http://crbug.com/58740). Added USE_SIMULATOR macro that explicitly indicates that we wish to use the simulator as the execution engine (by Mark Lam from Hewlett-Packard Development Company, LP). Fixed compilation error on ARM with gcc 4.4 (issue 894). 2010-10-13: Version 2.4.9 Fixed a bug in the handling of conditional expressions in test contexts in compiler for top-level code. Added "//@ sourceURL" information to the StackTrace API. Exposed RegExp construction through the API. 2010-10-04: Version 2.4.8 Fixed a bug in ResumeProfilerEx causing it to not always write out the whole snapshot (issue 868). Performance improvements on all platforms. 2010-09-30: Version 2.4.7 Changed the command-line flag --max-new-space-size to be in kB and the flag --max-old-space-size to be in MB (previously they were in bytes). Added Debug::CancelDebugBreak to the debugger API. Fixed a bug in getters for negative numeric property names (https://bugs.webkit.org/show_bug.cgi?id=46689). Performance improvements on all platforms. 2010-09-27: Version 2.4.6 Fixed assertion failure related to copy-on-write arrays (issue 876). Fixed build failure of 64-bit V8 on Windows. Fixed a bug in RegExp (issue http://crbug.com/52801). Improved the profiler's coverage to cover more functions (issue 858). Fixed error in shift operators on 64-bit V8 (issue http://crbug.com/54521). 2010-09-22: Version 2.4.5 Changed the RegExp benchmark to exercise the regexp engine on different inputs by scrambling the input strings. Fixed a bug in keyed loads on strings. Fixed a bug with loading global function prototypes. Fixed a bug with profiling RegExp calls (issue http://crbug.com/55999). Performance improvements on all platforms. 2010-09-15: Version 2.4.4 Fixed bug with hangs on very large sparse arrays. Now tries harder to free up memory when running out of space. Added heap snapshots to JSON format to API. Recalibrated benchmarks. 2010-09-13: Version 2.4.3 Made Date.parse properly handle TZ offsets (issue 857). Performance improvements on all platforms. 2010-09-08: Version 2.4.2 Fixed GC crash bug. Fixed stack corruption bug. Fixed compilation for newer C++ compilers that found Operand(0) ambiguous. 2010-09-06: Version 2.4.1 Added the ability for an embedding application to receive a callback when V8 allocates (V8::AddMemoryAllocationCallback) or deallocates (V8::RemoveMemoryAllocationCallback) from the OS. Fixed several JSON bugs (including issue 855). Fixed memory overrun crash bug triggered during V8's tick-based profiling. Performance improvements on all platforms. 2010-09-01: Version 2.4.0 Fixed bug in Object.freeze and Object.seal when Array.prototype or Object.prototype are changed (issue 842). Updated Array.splice to follow Safari and Firefox when called with zero arguments. Fixed a missing live register when breaking at keyed loads on ARM. Performance improvements on all platforms. 2010-08-25: Version 2.3.11 Fixed bug in RegExp related to copy-on-write arrays. Refactored tools/test.py script, including the introduction of VARIANT_FLAGS that allows specification of sets of flags with which all tests should be run. Fixed a bug in the handling of debug breaks in CallIC. Performance improvements on all platforms. 2010-08-23: Version 2.3.10 Fixed bug in bitops on ARM. Build fixes for unusual compilers. Track high water mark for RWX memory. Performance improvements on all platforms. 2010-08-18: Version 2.3.9 Fixed compilation for ARMv4 on OpenBSD/FreeBSD. Removed specialized handling of GCC 4.4 (issue 830). Fixed DST cache to take into account the suspension of DST in Egypt during the 2010 Ramadan (issue http://crbug.com/51855). Performance improvements on all platforms. 2010-08-16: Version 2.3.8 Fixed build with strict aliasing on GCC 4.4 (issue 463). Fixed issue with incorrect handling of custom valueOf methods on string wrappers (issue 760). Fixed compilation for ARMv4 (issue 590). Improved performance. 2010-08-11: Version 2.3.7 Reduced size of heap snapshots produced by heap profiler (issue 783). Introduced v8::Value::IsRegExp method. Fixed CPU profiler crash in start / stop sequence when non-existent name is passed (issue http://crbug.com/51594). Introduced new indexed property query callbacks API (issue 816). This API is guarded by USE_NEW_QUERY_CALLBACK define and is disabled by default. Removed support for object literal get/set with number/string property name. Fixed handling of JSObject::elements in CalculateNetworkSize (issue 822). Allowed compiling with strict aliasing enabled on GCC 4.4 (issue 463). 2010-08-09: Version 2.3.6 RegExp literals create a new object every time they are evaluated (issue 704). Object.seal and Object.freeze return the modified object (issue 809). Fixed building using GCC 4.4.4. 2010-08-04: Version 2.3.5 Added support for ES5 property names. Object initialisers and dot-notation property access now allows keywords. Also allowed non-identifiers after "get" or "set" in an object initialiser. Randomized the addresses of allocated executable memory on Windows. 2010-08-02: Version 2.3.4 Fixed problems in implementation of ES5 function.prototype.bind. Fixed error when using apply with arguments object on ARM (issue 784). Added setting of global flags to debugger protocol. Fixed an error affecting cached results of sin and cos (issue 792). Removed memory leak from a boundary case where V8 is not initialized. Fixed issue where debugger could set breakpoints outside the body of a function. Fixed issue in debugger when using both live edit and step in features. Added Number-letter (Nl) category to Unicode tables. These characters can now be used in identifiers. Fixed an assert failure on X64 (issue 806). Performance improvements on all platforms. 2010-07-26: Version 2.3.3 Fixed error when building the d8 shell in a fresh checkout. Implemented Function.prototype.bind (ES5 15.3.4.5). Fixed an error in inlined stores on ia32. Fixed an error when setting a breakpoint at the end of a function that does not end with a newline character. Performance improvements on all platforms. 2010-07-21: Version 2.3.2 Fixed compiler warnings when building with LLVM. Fixed a bug with for-in applied to strings (issue 785). Performance improvements on all platforms. 2010-07-19: Version 2.3.1 Fixed compilation and linking with V8_INTERPRETED_REGEXP flag. Fixed bug related to code flushing while compiling a lazy compilable function (issue http://crbug.com/49099). Performance improvements on all platforms. 2010-07-15: Version 2.3.0 Added ES5 Object.seal and Object.isSealed. Added debugger API for scheduling debugger commands from a separate thread. 2010-07-14: Version 2.2.24 Added API for capturing stack traces for uncaught exceptions. Fixed crash bug when preparsing from a non-external V8 string (issue 775). Fixed JSON.parse bug causing input not to be converted to string (issue 764). Added ES5 Object.freeze and Object.isFrozen. Performance improvements on all platforms. 2010-07-07: Version 2.2.23 API change: Convert Unicode code points outside the basic multilingual plane to the replacement character. Previous behavior was to silently truncate the value to 16 bits. Fixed crash: handle all flat string types in regexp replace. Prevent invalid pre-parsing data passed in through the API from crashing V8. Performance improvements on all platforms. 2010-07-05: Version 2.2.22 Added ES5 Object.isExtensible and Object.preventExtensions. Enabled building V8 as a DLL. Fixed a bug in date code where -0 was not interpreted as 0 (issue 736). Performance improvements on all platforms. 2010-06-30: Version 2.2.21 Fixed bug in externalizing some ASCII strings (Chromium issue 47824). Updated JSON.stringify to floor the space parameter (issue 753). Updated the Mozilla test expectations to the newest version. Updated the ES5 Conformance Test expectations to the latest version. Updated the V8 benchmark suite. Provide actual breakpoints locations in response to setBreakpoint and listBreakpoints requests. 2010-06-28: Version 2.2.20 Fixed bug with for-in on x64 platform (issue 748). Fixed crash bug on x64 platform (issue 756). Fixed bug in Object.getOwnPropertyNames. (chromium issue 41243). Fixed a bug on ARM that caused the result of 1 << x to be miscalculated for some inputs. Performance improvements on all platforms. 2010-06-23: Version 2.2.19 Fixed bug that causes the build to break when profillingsupport=off (issue 738). Added expose-externalize-string flag for testing extensions. Resolve linker issues with using V8 as a DLL causing a number of problems with unresolved symbols. Fixed build failure for cctests when ENABLE_DEBUGGER_SUPPORT is not defined. Performance improvements on all platforms. 2010-06-16: Version 2.2.18 Added API functions to retrieve information on indexed properties managed by the embedding layer. Fixes bug 737. Made ES5 Object.defineProperty support array elements. Fixes bug 619. Added heap profiling to the API. Removed old named property query from the API. Incremental performance improvements. 2010-06-14: Version 2.2.17 Improved debugger support for stepping out of functions. Incremental performance improvements. 2010-06-09: Version 2.2.16 Removed the SetExternalStringDiposeCallback API. Changed the disposal of external string resources to call a virtual Dispose method on the resource. Added support for more precise break points when debugging and stepping. Memory usage improvements on all platforms. 2010-06-07: Version 2.2.15 Added an API to control the disposal of external string resources. Added missing initialization of a couple of variables which makes some compilers complaint when compiling with -Werror. Improved performance on all platforms. 2010-06-02: Version 2.2.14 Fixed a crash in code generated for String.charCodeAt. Fixed a compilation issue with some GCC versions (issue 727). Performance optimizations on x64 and ARM platforms. 2010-05-31: Version 2.2.13 Implemented Object.getOwnPropertyDescriptor for element indices and strings (issue 599). Fixed bug for windows 64 bit C calls from generated code. Added new scons flag unalignedaccesses for arm builds. Performance improvements on all platforms. 2010-05-26: Version 2.2.12 Allowed accessors to be defined on objects rather than just object templates. Changed the ScriptData API. 2010-05-21: Version 2.2.11 Fixed crash bug in liveedit on 64 bit. Use 'full compiler' when debugging is active. This should increase the density of possible break points, making single step more fine grained. This will only take effect for functions compiled after debugging has been started, so recompilation of all functions is required to get the full effect. IA32 and x64 only for now. Misc. fixes to the Solaris build. Added new flags --print-cumulative-gc-stat and --trace-gc-nvp. Added filtering of CPU profiles by security context. Fixed crash bug on ARM when running without VFP2 or VFP3. Incremental performance improvements in all backends. 2010-05-17: Version 2.2.10 Performance improvements in the x64 and ARM backends. 2010-05-10: Version 2.2.9 Allowed Object.create to be called with a function (issue 697). Fixed bug with Date.parse returning a non-NaN value when called on a non date string (issue 696). Allowed unaligned memory accesses on ARM targets that support it (by Subrato K De of CodeAurora ). C++ API for retrieving JavaScript stack trace information. 2010-05-05: Version 2.2.8 Performance improvements in the x64 and ARM backends. 2010-05-03: Version 2.2.7 Added support for ES5 date time string format to Date.parse. Performance improvements in the x64 backend. 2010-04-28: Version 2.2.6 Added "amd64" as recognized architecture in scons build script (by Ryan Dahl ). Fixed bug in String search and replace with very simple RegExps. Fixed bug in RegExp containing "\b^". Performance improvements on all platforms. 2010-04-26: Version 2.2.5 Various performance improvements (especially for ARM and x64) Fixed bug in CPU profiling (http://crbug.com/42137) Fixed a bug with the natives cache. Fixed two bugs in the ARM code generator that can cause wrong calculations. Fixed a bug that may cause a wrong result for shift operations. 2010-04-21: Version 2.2.4 Fixed warnings on arm on newer GCC versions. Fixed a number of minor bugs. Performance improvements on all platforms. 2010-04-14: Version 2.2.3 Added stack command and mem command to ARM simulator debugger. Fixed scons snapshot and ARM build, and Windows X64 build issues. Performance improvements on all platforms. 2010-04-12: Version 2.2.2 Introduced new profiler API. Fixed random number generator to produce full 32 random bits. 2010-04-06: Version 2.2.1 Debugger improvements. Fixed minor bugs. 2010-03-29: Version 2.2.0 Fixed a few minor bugs. Performance improvements for string operations. 2010-03-26: Version 2.1.10 Fixed scons build issues. Fixed a couple of minor bugs. 2010-03-25: Version 2.1.9 Added API support for reattaching a global object to a context. Extended debugger API with access to the internal debugger context. Fixed Chromium crashes (issues http://crbug.com/39128 and http://crbug.com/39160) 2010-03-24: Version 2.1.8 Added fine-grained garbage collection callbacks to the API. Performance improvements on all platforms. 2010-03-22: Version 2.1.7 Fixed issue 650. Fixed a bug where __proto__ was sometimes enumerated (issue 646). Performance improvements for arithmetic operations. Performance improvements for string operations. Print script name and line number information in stack trace. 2010-03-17: Version 2.1.6 Performance improvements for arithmetic operations. Performance improvements for string operations. 2010-03-10: Version 2.1.4 Fixed code cache lookup for keyed IC's (issue http://crbug.com/37853). Performance improvements on all platforms. 2010-03-10: Version 2.1.3 Added API method for context-disposal notifications. Added API method for accessing elements by integer index. Added missing implementation of Uint32::Value and Value::IsUint32 API methods. Added IsExecutionTerminating API method. Disabled strict aliasing for GCC 4.4. Fixed string-concatenation bug (issue 636). Performance improvements on all platforms. 2010-02-23: Version 2.1.2 Fixed a crash bug caused by wrong assert. Fixed a bug with register names on 64-bit V8 (issue 615). Performance improvements on all platforms. 2010-02-19: Version 2.1.1 [ES5] Implemented Object.defineProperty. Improved profiler support. Added SetPrototype method in the public V8 API. Added GetScriptOrigin and GetScriptLineNumber methods to Function objects in the API. Performance improvements on all platforms. 2010-02-03: Version 2.1.0 Values are now always wrapped in objects when used as a receiver. (issue 223). [ES5] Implemented Object.getOwnPropertyNames. [ES5] Restrict JSON.parse to only accept strings that conforms to the JSON grammar. Improvement of debugger agent (issue 549 and 554). Fixed problem with skipped stack frame in profiles (issue 553). Solaris support by Erich Ocean and Ryan Dahl . Fixed a bug that Math.round() returns incorrect results for huge integers. Fixed enumeration order for objects created from some constructor functions (isue http://crbug.com/3867). Fixed arithmetic on some integer constants (issue 580). Numerous performance improvements including porting of previous IA-32 optimizations to x64 and ARM architectures. 2010-01-14: Version 2.0.6 Added ES5 Object.getPrototypeOf, GetOwnPropertyDescriptor, GetOwnProperty, FromPropertyDescriptor. Fixed Mac x64 build errors. Improved performance of some math and string operations. Improved performance of some regexp operations. Improved performance of context creation. Improved performance of hash tables. 2009-12-18: Version 2.0.5 Extended to upper limit of map space to allow for 7 times as many map to be allocated (issue 524). Improved performance of code using closures. Improved performance of some binary operations involving doubles. 2009-12-16: Version 2.0.4 Added ECMAScript 5 Object.create. Improved performance of Math.max and Math.min. Optimized adding of strings on 64-bit platforms. Improved handling of external strings by using a separate table instead of weak handles. This improves garbage collection performance and uses less memory. Changed code generation for object and array literals in toplevel code to be more compact by doing more work in the runtime. Fixed a crash bug triggered when garbage collection happened during generation of a callback load inline cache stub. Fixed crash bug sometimes triggered when local variables shadowed parameters in functions that used the arguments object. 2009-12-03: Version 2.0.3 Optimized handling and adding of strings, for-in and Array.join. Heap serialization is now non-destructive. Improved profiler support with information on time spend in C++ callbacks registered through the API. Added commands to the debugger protocol for starting/stopping profiling. Enabled the non-optimizing compiler for top-level code. Changed the API to only allow strings to be set as data objects on Contexts and scripts to avoid potentially keeping global objects around for too long (issue 528). OpenBSD support patch by Peter Valchev . Fixed bugs. 2009-11-24: Version 2.0.2 Improved profiler support. Fixed bug that broke compilation of d8 with readline support. 2009-11-20: Version 2.0.1 Fixed crash bug in String.prototype.replace. Reverted a change which caused Chromium interactive ui test failures. 2009-11-18: Version 2.0.0 Added support for VFP on ARM. Added TryCatch::ReThrow method to the API. Reduced the size of snapshots and improved the snapshot load time. Improved heap profiler support. 64-bit version now supported on Windows. Fixed a number of debugger issues. Fixed bugs. 2009-10-29: Version 1.3.18 Reverted a change which caused crashes in RegExp replace. Reverted a change which caused Chromium ui_tests failure. 2009-10-28: Version 1.3.17 Added API method to get simple heap statistics. Improved heap profiler support. Fixed the implementation of the resource constraint API so it works when using snapshots. Fixed a number of issues in the Windows 64-bit version. Optimized calls to API getters. Added valgrind notification on code modification to the 64-bit version. Fixed issue where we logged shared library addresses on Windows at startup and never used them. 2009-10-16: Version 1.3.16 X64: Convert smis to holding 32 bits of payload. Introduced v8::Integer::NewFromUnsigned method. Added missing null check in Context::GetCurrent. Added trim, trimLeft and trimRight methods to String Patch by Jan de Mooij Implement ES5 Array.isArray Patch by Jan de Mooij Skip access checks for hidden properties. Added String::Concat(Handle left, Handle right) to the V8 API. Fixed GYP-based builds of V8. 2009-10-07: Version 1.3.15 Expanded the maximum size of the code space to 512MB for 64-bit mode. Fixed a crash bug happening when starting profiling (issue http://crbug.com/23768). 2009-10-07: Version 1.3.14 Added GetRealNamedProperty to the API to lookup real properties located on the object or in the prototype chain skipping any interceptors. Fixed the stack limits setting API to work correctly with threads. The stack limit now needs to be set to each thread thich is used with V8. Removed the high-priority flag from IdleNotification() Ensure V8 is initialized before locking and unlocking threads. Implemented a new JavaScript minifier for compressing the source of the built-in JavaScript. This removes non-Open Source code from Douglas Crockford from the project. Added a missing optimization in StringCharAt. Fixed some flaky socket tests. Change by Alexander Botero-Lowry to fix profiler sampling on FreeBSD in 64-bit mode. Fixed memory leaks in the thread management code. Fixed the result of assignment to a pixel array. The assigned value is now the result. Error reporting for invalid left-hand sides in for-in statements, pre- and postfix count expressions, and assignments now matches the JSC behavior in Safari 4. Follow the spec in disallowing function declarations without a name. Always allocate code objects within a 2 GB range. On x64 architecture this is used to use near calls (32-bit displacement) in Code objects. Optimized array construction ported to x64 and ARM architectures. [ES5] Changed Object.keys to return strings for element indices. 2009-09-23: Version 1.3.13 Fixed uninitialized memory problem. Improved heap profiler support. 2009-09-22: Version 1.3.12 Changed behavior of |function|.toString() on built-in functions to be compatible with other implementations. Patch by Jan de Mooij. Added Object::IsDirty in the API. Optimized array construction; it is now handled purely in native code. [ES5] Made properties of the arguments array enumerable. [ES5] Added test suite adapter for the es5conform test suite. [ES5] Added Object.keys function. 2009-09-15: Version 1.3.11 Fixed crash in error reporting during bootstrapping. Optimized generated IA32 math code by using SSE2 instructions when available. Implemented missing pieces of debugger infrastructure on ARM. The debugger is now fully functional on ARM. Made 'hidden' the default visibility for gcc. 2009-09-09: Version 1.3.10 Fixed profiler on Mac in 64-bit mode. Optimized creation of objects from simple constructor functions on ARM. Fixed a number of debugger issues. Reduced the amount of memory consumed by V8. 2009-09-02: Version 1.3.9 Optimized stack guard checks on ARM. Optimized API operations by inlining more in the API. Optimized creation of objects from simple constructor functions. Enabled a number of missing optimizations in the 64-bit port. Implemented native-code support for regular expressions on ARM. Stopped using the 'sahf' instruction on 64-bit machines that do not support it. Fixed a bug in the support for forceful termination of JavaScript execution. 2009-08-26: Version 1.3.8 Changed the handling of idle notifications to allow idle notifications when V8 has not yet been initialized. Fixed ARM simulator compilation problem on Windows. 2009-08-25: Version 1.3.7 Reduced the size of generated code on ARM platforms by reducing the size of constant pools. Changed build files to not include the 'ENV' user environment variable in the build environment. Changed the handling of idle notifications. 2009-08-21: Version 1.3.6 Added support for forceful termination of JavaScript execution. Added low memory notification to the API. The embedding host can signal a low memory situation to V8. Changed the handling of global handles (persistent handles in the API sense) to avoid issues regarding allocation of new global handles during weak handle callbacks. Changed the growth policy of the young space. Fixed a GC issue introduced in version 1.3.5. 2009-08-19: Version 1.3.5 Optimized initialization of some arrays in the builtins. Fixed mac-nm script to support filenames with spaces. Support for using the V8 profiler when V8 is embedded in a Windows DLL. Changed typeof RegExp from 'object' to 'function' for compatibility. Fixed bug where regexps were not callable across contexts. Added context independent script compilation to the API. Added API call to get the stack trace for an exception. Added API for getting object mirrors. Made sure that SSE3 instructions are used whenever possible even when running off a snapshot generated without using SSE3 instructions. Tweaked the handling of the initial size and growth policy of the heap. Added native code generation for RegExp to 64-bit version. Added JavaScript debugger support to 64-bit version. 2009-08-13: Version 1.3.4 Added a readline() command to the d8 shell. Fixed bug in json parsing. Added idle notification to the API and reduced memory on idle notifications. 2009-08-12: Version 1.3.3 Fixed issue 417: incorrect %t placeholder expansion. Added .gitignore file similar to Chromium's one. Fixed SConstruct file to build with new logging code for Android. API: added function to find instance of template in prototype chain. Inlined Object::IsInstanceOf. Land change to notify valgrind when we modify code on x86. Added api call to determine whether a string can be externalized. Added a write() command to d8. 2009-08-05: Version 1.3.2 Started new compiler infrastructure for two-pass compilation using a control flow graph constructed from the AST. Profiler stack sampling for X64. Safe handling of NaN to Posix platform-dependent time functions. Added a new profiler control API to unify controlling various aspects of profiling. Fixed issue 392. 2009-07-30: Version 1.3.1 Speed improvements to accessors and interceptors. Added support for capturing stack information on custom errors. Added support for morphing an object into a pixel array where its indexed properties are stored in an external byte array. Values written are always clamped to the 0..255 interval. Profiler on x64 now handles C/C++ functions from shared libraries. Changed the debugger to avoid stepping into function.call/apply if the function is a built-in. Initial implementation of constructor heap profile for JS objects. More fine grained control of profiling aspects through the API. Optimized the called as constructor check for API calls. 2009-07-27: Version 1.3.0 Allowed RegExp objects to be called as functions (issue 132). Fixed issue where global property cells would escape after detaching the global object; see http://crbug.com/16276. Added support for stepping into setters and getters in the debugger. Changed the debugger to avoid stopping in its own JavaScript code and in the code of built-in functions. Fixed issue 345 by avoiding duplicate escaping labels. Fixed ARM code generator crash in short-circuited boolean expressions and added regression tests. Added an external allocation limit to avoid issues where small V8 objects would hold on to large amounts of external memory without causing garbage collections. Finished more of the inline caching stubs for x64 targets. 2009-07-13: Version 1.2.14 Added separate paged heap space for global property cells and avoid updating the write barrier when storing into them. Improved peep-hole optimization on ARM platforms by not emitting unnecessary debug information. Re-enabled ICs for loads and calls that skip a global object during lookup through the prototype chain. Allowed access through global proxies to use ICs. Fixed issue 401. 2009-07-09: Version 1.2.13 Fixed issue 397, issue 398, and issue 399. Added support for breakpoint groups. Fixed bugs introduced with the new global object representation. Fixed a few bugs in the ARM code generator. 2009-07-06: Version 1.2.12 Added stack traces collection to Error objects accessible through the e.stack property. Changed RegExp parser to use a recursive data structure instead of stack-based recursion. Optimized Date object construction and string concatenation. Improved performance of div, mod, and mul on ARM platforms. 2009-07-02: Version 1.2.11 Improved performance on IA-32 and ARM. Fixed profiler sampler implementation on Mac OS X. Changed the representation of global objects to improve performance of adding a lot of new properties. 2009-06-29: Version 1.2.10 Improved debugger support. Fixed bug in exception message reporting (issue 390). Improved overall performance. 2009-06-23: Version 1.2.9 Improved math performance on ARM. Fixed profiler name-inference bug. Fixed handling of shared libraries in the profiler tick processor scripts. Fixed handling of tests that time out in the test scripts. Fixed compilation on MacOS X version 10.4. Fixed two bugs in the regular expression engine. Fixed a bug in the string type inference. Fixed a bug in the handling of 'constant function' properties. Improved overall performance. 2009-06-16: Version 1.2.8 Optimized math on ARM platforms. Fixed two crash bugs in the handling of getters and setters. Improved the debugger support by adding scope chain information. Improved the profiler support by compressing log data transmitted to clients. Improved overall performance. 2009-06-08: Version 1.2.7 Improved debugger and profiler support. Reduced compilation time by improving the handling of deferred code. Optimized interceptor accesses where the property is on the object on which the interceptors is attached. Fixed compilation problem on GCC 4.4 by changing the stack alignment to 16 bytes. Fixed handle creation to follow stric aliasing rules. Fixed compilation on FreeBSD. Introduced API for forcing the deletion of a property ignoring interceptors and attributes. 2009-05-29: Version 1.2.6 Added a histogram recording hit rates at different levels of the compilation cache. Added stack overflow check for the RegExp analysis phase. Previously a very long regexp graph could overflow the stack with recursive calls. Use a dynamic buffer when collecting log events in memory. Added start/stop events to the profiler log. Fixed infinite loop which could happen when setting a debug break while executing a RegExp compiled to native code. Fixed handling of lastIndexOf called with negative index (issue 351). Fixed irregular crash in profiler test (issue 358). Fixed compilation issues with some versions of gcc. 2009-05-26: Version 1.2.5 Fixed bug in initial boundary check for Boyer-Moore text search (issue 349). Fixed compilation issues with MinGW and gcc 4.3+ and added support for armv7 and cortex-a8 architectures. Patches by Lei Zhang and Craig Schlenter. Added a script cache to the debugger. Optimized compilation performance by improving internal data structures and avoiding expensive property load optimizations for code that's infrequently executed. Exposed the calling JavaScript context through the static API function Context::GetCalling(). 2009-05-18: Version 1.2.4 Improved performance of floating point number allocation for ARM platforms. Fixed crash when using the instanceof operator on functions with number values in their prototype chain (issue 341). Optimized virtual frame operations in the code generator to speed up compilation time and allocated the frames in the zone. Made the representation of virtual frames and jump targets in the code generator much more compact. Avoided linear search for non-locals in scope code when resolving variables inside with and eval scopes. Optimized lexical scanner by dealing with whitespace as part of the token scanning instead of as a separate step before it. Changed the scavenging collector so that promoted objects do not reside in the old generation while their remembered set is being swept for pointers into the young generation. Fixed numeric overflow handling when compiling count operations. 2009-05-11: Version 1.2.3 Fixed bug in reporting of out-of-memory situations. Introduced hidden prototypes on certain builtin prototype objects such as String.prototype to emulate JSC's behavior of restoring the original function when deleting functions from those prototype objects. Fixed crash bug in the register allocator. 2009-05-04: Version 1.2.2 Fixed bug in array sorting for sparse arrays (issue 326). Added support for adding a soname when building a shared library on Linux (issue 151). Fixed bug caused by morphing internal ASCII strings to external two-byte strings. Slices over ASCII strings have to forward ASCII checks to the underlying buffer string. Allowed API call-as-function handlers to be called as constructors. Fixed a crash bug where an external string was disposed but a slice of the external string survived as a symbol. 2009-04-27: Version 1.2.1 Added EcmaScript 5 JSON object. Fixed bug in preemption support on ARM. 2009-04-23: Version 1.2.0 Optimized floating-point operations on ARM. Added a number of extensions to the debugger API. Changed the enumeration order for unsigned integer keys to always be numerical order. Added a "read" extension to the shell sample. Added support for Array.prototype.reduce and Array.prototype.reduceRight. Added an option to the SCons build to control Microsoft Visual C++ link-time code generation. Fixed a number of bugs (in particular issue 315, issue 316, issue 317 and issue 318). 2009-04-15: Version 1.1.10 Fixed crash bug that occurred when loading a const variable in the presence of eval. Allowed using with and eval in registered extensions in debug mode by fixing bogus assert. Fixed the source position for function returns to enable the debugger to break there. 2009-04-14: Version 1.1.9 Made the stack traversal code in the profiler robust by avoiding to look into the heap. Added name inferencing for anonymous functions to facilitate debugging and profiling. Re-enabled stats timers in the developer shell (d8). Fixed issue 303 by avoiding to shortcut cons-symbols. 2009-04-11: Version 1.1.8 Changed test-debug/ThreadedDebugging to be non-flaky (issue 96). Fixed step-in handling for Function.prototype.apply and call in the debugger (issue 269). Fixed v8::Object::DeleteHiddenValue to not bail out when there are no hidden properties. Added workaround for crash bug, where external symbol table entries with deleted resources would lead to NPEs when looking up in the symbol table. 2009-04-07: Version 1.1.7 Added support for easily importing additional environment variables into the SCons build. Optimized strict equality checks. Fixed crash in indexed setters on objects without a corresponding getter (issue 298). Re-enabled script compilation cache. 2009-04-01: Version 1.1.6 Reverted an unsafe code generator change. 2009-04-01: Version 1.1.5 Fixed bug that caused function literals to not be optimized as much as other functions. Improved profiler support. Fixed a crash bug in connection with debugger unloading. Fixed a crash bug in the code generator caused by losing the information that a frame element was copied. Fixed an exception propagation bug that could cause non-null return values when exceptions were thrown. 2009-03-30: Version 1.1.4 Optimized String.prototype.match. Improved the stack information in profiles. Fixed bug in ARM port making it possible to compile the runtime system for thumb mode again. Implemented a number of optimizations in the code generator. Fixed a number of memory leaks in tests. Fixed crash bug in connection with script source code and external strings. 2009-03-24: Version 1.1.3 Fixed assertion failures in compilation of loop conditions. Removed STL dependency from developer shell (d8). Added infrastructure for protecting the V8 heap from corruption caused by memory modifications from the outside. 2009-03-24: Version 1.1.2 Improved frame merge code generated by the code generator. Optimized String.prototype.replace. Implemented __defineGetter__ and __defineSetter__ for properties with integer keys on non-array objects. Improved debugger and profiler support. Fixed a number of portability issues to allow compilation for smaller ARM devices. Exposed object cloning through the API. Implemented hidden properties. This is used to expose an identity hash for objects through the API. Implemented restarting of regular expressions if their input string changes representation during preemption. Fixed a code generator bug that could cause assignments in loops to be ignored if using continue to break out of the loop (issue 284). 2009-03-12: Version 1.1.1 Fixed an assertion in the new compiler to take stack overflow exceptions into account. Removed exception propagation code that could cause crashes. Fixed minor bug in debugger line number computations. 8-byte align the C stack on Linux and Windows to speed up floating point computations. 2009-03-12: Version 1.1.0 Improved code generation infrastructure by doing simple register allocation and constant folding and propagation. Optimized regular expression matching by avoiding to create intermediate string arrays and by flattening nested array representations of RegExp data. Traverse a few stack frames when recording profiler samples to include partial call graphs in the profiling output. Added support for using OProfile to profile generated code. Added remote debugging support to the D8 developer shell. Optimized creation of nested literals like JSON objects. Fixed a bug in garbage collecting unused maps and turned it on by default (--collect-maps). Added support for running tests under Valgrind. 2009-02-27: Version 1.0.3 Optimized double-to-integer conversions in bit operations by using SSE3 instructions if available. Optimized initialization sequences that store to multiple properties of the same object. Changed the D8 debugger frontend to use JSON messages. Force garbage collections when disposing contexts. Align code objects at 32-byte boundaries. 2009-02-25: Version 1.0.2 Improved profiling support by performing simple call stack sampling for ticks and by fixing a bug in the logging of code addresses. Fixed a number of debugger issues. Optimized code that uses eval. Fixed a couple of bugs in the regular expression engine. Reduced the size of generated code for certain regular expressions. Removed JSCRE completely. Fixed issue where test could not be run if there was a dot in the checkout path. 2009-02-13: Version 1.0.1 Fixed two crash-bugs in irregexp (issue 231 and 233). Fixed a number of minor bugs (issue 87, 227 and 228). Added support for morphing strings to external strings on demand to avoid having to create copies in the embedding code. Removed experimental support for external symbol callbacks. 2009-02-09: Version 1.0.0 Fixed crash-bug in the code generation for case independent 16 bit backreferences. Made shells more robust in the presence of string conversion failures (issue 224). Fixed a potential infinite loop when attempting to resolve eval (issue 221). Miscellaneous fixes to the new regular expression engine. Reduced binary by stripping unneeded text from JavaScript library and minifying some JavaScript files. 2009-01-27: Version 0.4.9 Enabled new regular expression engine. Made a number of changes to the debugger protocol. Fixed a number of bugs in the preemption support. Added -p option to the developer shell to run files in parallel using preemption. Fixed a number of minor bugs (including issues 176, 187, 189, 192, 193, 198 and 201). Fixed a number of bugs in the serialization/deserialization support for the ARM platform. 2009-01-19: Version 0.4.8.1 Minor patch to debugger support. 2009-01-16: Version 0.4.8 Fixed string length bug on ARM (issue 171). Made most methods in the API const. Optimized object literals by improving data locality. Fixed bug that caused incomplete functions to be cached in case of stack overflow exceptions. Fixed bugs that caused catch variables and variables introduced by eval to behave incorrectly when using accessors (issues 186, 190 and 191). 2009-01-06: Version 0.4.7 Minor bugfixes and optimizations. Added command line debugger to D8 shell. Fixed subtle bug that caused the wrong 'this' to be used when calling a caught function in a catch clause. Inline array loads within loops directly in the code instead of always calling a stub. 2008-12-11: Version 0.4.6 Fixed exception reporting bug where certain exceptions were incorrectly reported as uncaught. Improved the memory allocation strategy used during compilation to make running out of memory when compiling huge scripts less likely. Optimized String.replace by avoiding the construction of certain sub strings. Fixed bug in code generation for large switch statements on ARM. Fixed bug that caused V8 to change the global object template passed in by the user. Changed the API for creating object groups used during garbage collection. Entire object groups are now passed to V8 instead of individual members of the groups. 2008-12-03: Version 0.4.5 Added experimental API support for allocating V8 symbols as external strings. Fixed bugs in debugging support on ARM. Changed eval implementation to correctly detect whether or not a call to eval is aliased. Fixed bug caused by a combination of the compilation cache and dictionary probing in native code. The bug caused us to sometimes call functions that had not yet been compiled. Added platform support for FreeBSD. Added support for building V8 on Windows with either the shared or static version of MSVCRT Added the v8::jscre namespace around the jscre functions to avoid link errors (duplicate symbols) when building Google Chrome. Added support for calling a JavaScript function with the current debugger execution context as its argument to the debugger interface. Changed the type of names of counters from wchar_t to char. Changed the Windows system call used to compute daylight savings time. The system call that we used to use became four times slower on WinXP SP3. Added support in the d8 developer shell for memory-mapped counters and added a stats-viewer tool. Fixed bug in upper/lower case mappings (issue 149). 2008-11-17: Version 0.4.4 Reduced code size by using shorter instruction encoding when possible. Added a --help option to the shell sample and to the d8 shell. Added visual studio project files for building the ARM simulator. Fixed a number of ARM simulator issues. Fixed bug in out-of-memory handling on ARM. Implemented shell support for passing arguments to a script from the command line. Fixed bug in date code that made certain date functions return -0 instead of 0 for dates before the epoch. Restricted applications of eval so it can only be used in the context of the associated global object. Treat byte-order marks as whitespace characters. 2008-11-04: Version 0.4.3 Added support for API accessors that prohibit overwriting by accessors defined in JavaScript code by using __defineGetter__ and __defineSetter__. Improved handling of conditionals in test status files. Introduced access control in propertyIsEnumerable. Improved performance of some string operations by caching information about the type of the string between operations. Fixed bug in fast-case code for switch statements that only have integer labels. 2008-10-30: Version 0.4.2 Improved performance of Array.prototype.concat by moving the implementation to C++ (issue 123). Fixed heap growth policy to avoid growing old space to its maximum capacity before doing a garbage collection and fixed issue that would lead to artificial out of memory situations (issue 129). Fixed Date.prototype.toLocaleDateString to return the date in the same format as WebKit. Added missing initialization checks to debugger API. Added removing of unused maps during GC. 2008-10-28: Version 0.4.1 Added caching of RegExp data in compilation cache. Added Visual Studio project file for d8 shell. Fixed function call performance regression introduced in version 0.4.0 when splitting the global object in two parts (issue 120). Fixed issue 131 by checking for empty handles before throwing and reporting exceptions. 2008-10-23: Version 0.4.0 Split the global object into two parts: The state holding global object and the global object proxy. Fixed bug that affected the value of an assignment to an element in certain cases (issue 116). Added GetPropertyNames functionality (issue 33) and extra Date functions (issue 77) to the API. Changed WeakReferenceCallback to take a Persistent instead of a Persistent (issue 101). Fixed issues with message reporting for exceptions in try-finally blocks (issues 73 and 75). Optimized flattening of strings and string equality checking. Improved Boyer-Moore implementation for faster indexOf operations. Added development shell (d8) which includes counters and completion support. Fixed problem with the receiver passed to functions called from eval (issue 124). 2008-10-16: Version 0.3.5 Improved string hash-code distribution by excluding bit-field bits from the hash-code. Changed string search algorithm used in indexOf from KMP to Boyer-Moore. Improved the generated code for the instanceof operator. Improved performance of slow-case string equality checks by specializing the code based on the string representation. Improve the handling of out-of-memory situations (issue 70). Improved performance of strict equality checks. Improved profiler output to make it easier to see anonymous functions. Improved performance of slow-case keyed loads. Improved property access performance by allocating a number of properties in the front object. Changed the toString behavior on the built-in object constructors to print [native code] instead of the actual source. Some web applications do not like constructors with complex toString results. 2008-10-06: Version 0.3.4 Changed Array.prototype.sort to use quick sort. Fixed code generation issue where leaving a finally block with break or continue would accumulate elements on the expression stack (issue 86). Made sure that the name accessor on functions returns the expected names for builtin JavaScript functions and C++ callback functions. Added fast case code for extending the property storage array of JavaScript objects. Ported switch statement optimizations introduced in version 0.3.3 to the ARM code generator. Allowed GCC to use strict-aliasing rules when compiling. Improved performance of arguments object allocation by taking care of arguments adaptor frames in the generated code. Updated the V8 benchmark suite to version 2. 2008-09-25: Version 0.3.3 Improved handling of relocation information to enable more peep-hole optimizations. Optimized switch statements where all labels are constant small integers. Optimized String.prototype.indexOf for common cases. Fixed more build issues (issue 80). Fixed a couple of profiler issues. Fixed bug where the body of a function created using the Function constructor was not allowed to end with a single-line comment (issue 85). Improved handling of object literals by canonicalizing object literal maps. This will allow JSON objects with the same set of properties to share the same map making inline caching work better for JSON objects. 2008-09-17: Version 0.3.2 Generalized the EvalCache into a CompilationCache and enabled it for scripts too. The current strategy is to retire all entries whenever a mark-sweep collection is started. Fixed bug where switch statements containing only a default case would lead to an unbalanced stack (issue 69). Fixed bug that made access to the function in a named function expression impossible in certain situations (issue 24). Fixed even more build issues. Optimized calling conventions on ARM. The conventions on ARM and IA-32 now match. Removed static initializers for flags and counters. Improved inline caching behavior for uncommon cases where lazily loading Date and RegExp code could force certain code paths go megamorphic. Removed arguments adaption for builtins written in C++. This makes Array.prototype.push and Array.prototype.pop slightly faster. 2008-09-11: Version 0.3.1 Fixed a number of build issues. Fixed problem with missing I-cache flusing on ARM. Changed space layout in memory management by splitting up code space into old data space and code space. Added utf-8 conversion support to the API (issue 57). Optimized repeated calls to eval with the same strings. These repeated calls are common in web applications. Added Xcode project file. Optimized a couple of Array operation. Fixed parser bug by checking for end-of-string when parsing break and continue (issue 35). Fixed problem where asian characters were not categorized as letters. Fixed bug that disallowed calling functions fetched from an array using a string as an array index (issue 32). Fixed bug where the internal field count on object templates were sometimes ignored (issue 54). Added -f option to the shell sample for compatibility with other engines (issue 18). Added source info to TryCatches in the API. Fixed problem where the seed for the random number generator was clipped in a double to unsigned int conversion. Fixed bug where cons string symbols were sometimes converted to non-symbol flat strings during GC. Fixed bug in error reporting when attempting to convert null to an object. 2008-09-04: Version 0.3.0 Added support for running tests on the ARM simulator. Fixed bug in the 'in' operator where negative indices were not treated correctly. Fixed build issues on gcc-4.3.1. Changed Date.prototype.toLocaleTimeString to not print the timezone part of the time. Renamed debug.h to v8-debug.h to reduce the risk of name conflicts with user code. 2008-09-02: Version 0.2.5 Renamed the top level directory 'public' to 'include'. Added 'env' option to the SCons build scripts to support overriding the ENV part of the build environment. This is mostly to support Windows builds in cases where SCons cannot find the correct paths to the Windows SDK, as these paths cannot be passed through shell environment variables. Enabled "Buffer Security Check" on for the Windows SCons build and added the linker option /OPT:ICF as an optimization. Added the V8 benchmark suite to the repository. 2008-09-01: Version 0.2.4 Included mjsunit JavaScript test suite and C++ unit tests. Changed the shell sample to not print the result of executing a script provided on the command line. Fixed issue when building samples on Windows using a shared V8 library. Added visibility option on Linux build which makes the generated library 18% smaller. Changed build system to accept multiple build modes in one build and generate separate objects, libraries and executables for each mode. Removed deferred negation optimization (a * -b => -(a * b)) since this visibly changes operand conversion order. Improved parsing performance by introducing stack guard in preparsing. Without a stack guard preparsing always bails out with stack overflow. Changed shell sample to take flags directly from the command-line. Added API call that implements this. Added load, quit and version functions to the shell sample so it's easier to run benchmarks and tests. Fixed issue with building samples and cctests on 64-bit machines. Fixed bug in the runtime system where the prototype chain was not always searched for a setter when setting a property that does not exist locally. 2008-08-14: Version 0.2.3 Improved performance of garbage collection by moving the function that updates pointers during compacting collection into the updating visitor. This gives the compiler a better chance to inline and avoid a function call per (potential) pointer. Extended the shell sample with a --runtime-flags option. Added Visual Studio project files for the shell.cc and process.cc samples. 2008-08-13: Version 0.2.2 Improved performance of garbage collection by changing the way we use the marking stack in the event of stack overflow during full garbage collection and by changing the way we mark roots. Cleaned up ARM version by removing top of stack caching and by introducing push/pop elimination. Cleaned up the way runtime functions are called to allow runtime calls with no arguments. Changed Windows build options to make sure that exceptions are disabled and that optimization flags are enabled. Added first version of Visual Studio project files. 2008-08-06: Version 0.2.1 Improved performance of unary addition by avoiding runtime calls. Fixed the handling of '>' and '<=' to use right-to-left conversion and left-to-right evaluation as specified by ECMA-262. Fixed a branch elimination bug on the ARM platform where incorrect code was generated because of overly aggressive branch elimination. Improved performance of code that repeatedly assigns the same function to the same property of different objects with the same map. Untangled DEBUG and ENABLE_DISASSEMBLER defines. The disassembler no longer expects DEBUG to be defined. Added platform-nullos.cc to serve as the basis for new platform implementations. 2008-07-30: Version 0.2.0 Changed all text files to have native svn:eol-style. Added a few samples and support for building them. The samples include a simple shell that can be used to benchmark and test V8. Changed V8::GetVersion to return the version as a string. Added source for lazily loaded scripts to snapshots and made serialization non-destructive. Improved ARM support by fixing the write barrier code to use aligned loads and stores and by removing premature locals optimization that relied on broken support for callee-saved registers (removed). Refactored the code for marking live objects during garbage collection and the code for allocating objects in paged spaces. Introduced an abstraction for the map word of a heap- allocated object and changed the memory allocator to allocate executable memory only for spaces that may contain code objects. Moved StringBuilder to utils.h and ScopedLock to platform.h, where they can be used by debugging and logging modules. Added thread-safe message queues for dealing with debugger events. Fixed the source code reported by toString for certain builtin empty functions and made sure that the prototype property of a function is enumerable. Improved performance of converting values to condition flags in generated code. Merged disassembler-{arch} files. 2008-07-28: Version 0.1.4 Added support for storing JavaScript stack traces in a stack allocated buffer to make it visible in shallow core dumps. Controlled by the --preallocate-message-memory flag which is disabled by default. 2008-07-25: Version 0.1.3 Fixed bug in JSObject::GetPropertyAttributePostInterceptor where map transitions would count as properties. Allowed aliased eval invocations by treating them as evals in the global context. This may change in the future. Added support for accessing the last entered context through the API and renamed Context::Current to Context::GetCurrent and Context::GetSecurityContext to Context::GetCurrentSecurityContext. Fixed bug in the debugger that would cause the debugger scripts to be recursively loaded and changed all disabling of interrupts to be block-structured. Made snapshot data read-only to allow it to be more easily shared across multiple users of V8 when linked as a shared library. 2008-07-16: Version 0.1.2 Fixed building on Mac OS X by recognizing i386 and friends as IA-32 platforms. Added propagation of stack overflow exceptions that occur while compiling nested functions. Improved debugger with support for recursive break points and handling of exceptions that occur in the debugger JavaScript code. Renamed GetInternal to GetInternalField and SetInternal to SetInternalField in the API and moved InternalFieldCount and SetInternalFieldCount from FunctionTemplate to ObjectTemplate. 2008-07-09: Version 0.1.1 Fixed bug in stack overflow check code for IA-32 targets where a non-tagged value in register eax was pushed to the stack. Fixed potential quadratic behavior when converting strings to numbers. Fixed bug where the return value from Object::SetProperty could end up being the property holder instead of the written value. Improved debugger support by allowing nested break points and by dealing with stack-overflows when compiling functions before setting break points in them. 2008-07-03: Version 0.1.0 Initial export. # Local Variables: # mode:text # End: node-v0.10.25~dfsg2/deps/v8/build/0000755000000000000000000000000012270121457015204 5ustar rootrootnode-v0.10.25~dfsg2/deps/v8/build/common.gypi0000644000000000000000000003511212270121457017370 0ustar rootroot# Copyright 2012 the V8 project authors. All rights reserved. # Redistribution and use in source and binary forms, with or without # modification, are permitted provided that the following conditions are # met: # # * Redistributions of source code must retain the above copyright # notice, this list of conditions and the following disclaimer. # * Redistributions in binary form must reproduce the above # copyright notice, this list of conditions and the following # disclaimer in the documentation and/or other materials provided # with the distribution. # * Neither the name of Google Inc. nor the names of its # contributors may be used to endorse or promote products derived # from this software without specific prior written permission. # # THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS # "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT # LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR # A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT # OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, # SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT # LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, # DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY # THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT # (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE # OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. # Shared definitions for all V8-related targets. { 'variables': { 'use_system_v8%': 0, 'msvs_use_common_release': 0, 'gcc_version%': 'unknown', 'v8_compress_startup_data%': 'off', 'v8_target_arch%': '<(target_arch)', # Setting 'v8_can_use_unaligned_accesses' to 'true' will allow the code # generated by V8 to do unaligned memory access, and setting it to 'false' # will ensure that the generated code will always do aligned memory # accesses. The default value of 'default' will try to determine the correct # setting. Note that for Intel architectures (ia32 and x64) unaligned memory # access is allowed for all CPUs. 'v8_can_use_unaligned_accesses%': 'default', # Setting 'v8_can_use_vfp2_instructions' to 'true' will enable use of ARM VFP # instructions in the V8 generated code. VFP instructions will be enabled # both for the snapshot and for the ARM target. Leaving the default value # of 'false' will avoid VFP instructions in the snapshot and use CPU feature # probing when running on the target. 'v8_can_use_vfp2_instructions%': 'false', 'v8_can_use_vfp3_instructions%': 'false', # Similar to vfp but on MIPS. 'v8_can_use_fpu_instructions%': 'true', # Setting v8_use_arm_eabi_hardfloat to true will turn on V8 support for ARM # EABI calling convention where double arguments are passed in VFP # registers. Note that the GCC flag '-mfloat-abi=hard' should be used as # well when compiling for the ARM target. 'v8_use_arm_eabi_hardfloat%': 'false', # Similar to the ARM hard float ABI but on MIPS. 'v8_use_mips_abi_hardfloat%': 'true', # Default arch variant for MIPS. 'mips_arch_variant%': 'mips32r2', 'v8_enable_debugger_support%': 1, 'v8_enable_disassembler%': 0, # Enable extra checks in API functions and other strategic places. 'v8_enable_extra_checks%': 1, 'v8_enable_gdbjit%': 0, 'v8_object_print%': 0, # Enable profiling support. Only required on Windows. 'v8_enable_prof%': 0, 'v8_enable_verify_heap%': 0, # Some versions of GCC 4.5 seem to need -fno-strict-aliasing. 'v8_no_strict_aliasing%': 0, # Chrome needs this definition unconditionally. For standalone V8 builds, # it's handled in build/standalone.gypi. 'want_separate_host_toolset%': 1, 'v8_use_snapshot%': 'true', 'host_os%': '<(OS)', 'v8_use_liveobjectlist%': 'false', 'werror%': '-Werror', # With post mortem support enabled, metadata is embedded into libv8 that # describes various parameters of the VM for use by debuggers. See # tools/gen-postmortem-metadata.py for details. 'v8_postmortem_support%': 'false', # For a shared library build, results in "libv8-<(soname_version).so". 'soname_version%': '', # Interpreted regexp engine exists as platform-independent alternative # based where the regular expression is compiled to a bytecode. 'v8_interpreted_regexp%': 0, }, 'target_defaults': { 'conditions': [ ['v8_enable_debugger_support==1', { 'defines': ['ENABLE_DEBUGGER_SUPPORT',], }], ['v8_enable_disassembler==1', { 'defines': ['ENABLE_DISASSEMBLER',], }], ['v8_enable_extra_checks==1', { 'defines': ['ENABLE_EXTRA_CHECKS',], }], ['v8_enable_gdbjit==1', { 'defines': ['ENABLE_GDB_JIT_INTERFACE',], }], ['v8_object_print==1', { 'defines': ['OBJECT_PRINT',], }], ['v8_enable_verify_heap==1', { 'defines': ['VERIFY_HEAP',], }], ['v8_interpreted_regexp==1', { 'defines': ['V8_INTERPRETED_REGEXP',], }], ['v8_target_arch=="arm"', { 'defines': [ 'V8_TARGET_ARCH_ARM', ], 'conditions': [ [ 'v8_can_use_unaligned_accesses=="true"', { 'defines': [ 'CAN_USE_UNALIGNED_ACCESSES=1', ], }], [ 'v8_can_use_unaligned_accesses=="false"', { 'defines': [ 'CAN_USE_UNALIGNED_ACCESSES=0', ], }], [ 'v8_can_use_vfp2_instructions=="true"', { 'defines': [ 'CAN_USE_VFP2_INSTRUCTIONS', ], }], [ 'v8_can_use_vfp3_instructions=="true"', { 'defines': [ 'CAN_USE_VFP3_INSTRUCTIONS', ], }], [ 'v8_use_arm_eabi_hardfloat=="true"', { 'defines': [ 'USE_EABI_HARDFLOAT=1', 'CAN_USE_VFP2_INSTRUCTIONS', ], 'target_conditions': [ ['_toolset=="target"', { 'cflags': ['-mfloat-abi=hard',], }], ], }, { 'defines': [ 'USE_EABI_HARDFLOAT=0', ], }], ], }], # v8_target_arch=="arm" ['v8_target_arch=="ia32"', { 'defines': [ 'V8_TARGET_ARCH_IA32', ], }], # v8_target_arch=="ia32" ['v8_target_arch=="mipsel"', { 'defines': [ 'V8_TARGET_ARCH_MIPS', ], 'variables': { 'mipscompiler': '&1 | grep -q "^Target: mips" && echo "yes" || echo "no")', }, 'conditions': [ ['mipscompiler=="yes"', { 'target_conditions': [ ['_toolset=="target"', { 'cflags': ['-EL'], 'ldflags': ['-EL'], 'conditions': [ [ 'v8_use_mips_abi_hardfloat=="true"', { 'cflags': ['-mhard-float'], 'ldflags': ['-mhard-float'], }, { 'cflags': ['-msoft-float'], 'ldflags': ['-msoft-float'], }], ['mips_arch_variant=="mips32r2"', { 'cflags': ['-mips32r2', '-Wa,-mips32r2'], }], ['mips_arch_variant=="mips32r1"', { 'cflags': ['-mips32', '-Wa,-mips32'], }], ['mips_arch_variant=="loongson"', { 'cflags': ['-mips3', '-Wa,-mips3'], }], ], }], ], }], [ 'v8_can_use_fpu_instructions=="true"', { 'defines': [ 'CAN_USE_FPU_INSTRUCTIONS', ], }], [ 'v8_use_mips_abi_hardfloat=="true"', { 'defines': [ '__mips_hard_float=1', 'CAN_USE_FPU_INSTRUCTIONS', ], }, { 'defines': [ '__mips_soft_float=1' ], }], ['mips_arch_variant=="mips32r2"', { 'defines': ['_MIPS_ARCH_MIPS32R2',], }], ['mips_arch_variant=="loongson"', { 'defines': ['_MIPS_ARCH_LOONGSON',], }], ], }], # v8_target_arch=="mipsel" ['v8_target_arch=="x64"', { 'defines': [ 'V8_TARGET_ARCH_X64', ], 'xcode_settings': { 'ARCHS': [ 'x86_64' ], }, 'msvs_settings': { 'VCLinkerTool': { 'StackReserveSize': '2097152', }, }, 'msvs_configuration_platform': 'x64', }], # v8_target_arch=="x64" ['v8_use_liveobjectlist=="true"', { 'defines': [ 'ENABLE_DEBUGGER_SUPPORT', 'INSPECTOR', 'OBJECT_PRINT', 'LIVEOBJECTLIST', ], }], ['v8_compress_startup_data=="bz2"', { 'defines': [ 'COMPRESS_STARTUP_DATA_BZ2', ], }], ['OS=="win"', { 'defines': [ 'WIN32', ], 'msvs_configuration_attributes': { 'OutputDirectory': '<(DEPTH)\\build\\$(ConfigurationName)', 'IntermediateDirectory': '$(OutDir)\\obj\\$(ProjectName)', 'CharacterSet': '1', }, }], ['OS=="win" and v8_enable_prof==1', { 'msvs_settings': { 'VCLinkerTool': { 'GenerateMapFile': 'true', }, }, }], ['OS=="linux" or OS=="freebsd" or OS=="openbsd" or OS=="solaris" \ or OS=="netbsd"', { 'conditions': [ [ 'v8_no_strict_aliasing==1', { 'cflags': [ '-fno-strict-aliasing' ], }], ], # conditions }], ['OS=="solaris"', { 'defines': [ '__C99FEATURES__=1' ], # isinf() etc. }], ['(OS=="linux" or OS=="freebsd" or OS=="openbsd" or OS=="solaris" \ or OS=="netbsd" or OS=="mac" or OS=="android") and \ (v8_target_arch=="arm" or v8_target_arch=="ia32" or \ v8_target_arch=="mipsel")', { # Check whether the host compiler and target compiler support the # '-m32' option and set it if so. 'target_conditions': [ ['_toolset=="host"', { 'variables': { 'm32flag': ' /dev/null 2>&1) && echo "-m32" || true)', }, 'cflags': [ '<(m32flag)' ], 'ldflags': [ '<(m32flag)' ], 'xcode_settings': { 'ARCHS': [ 'i386' ], }, }], ['_toolset=="target"', { 'variables': { 'm32flag': ' /dev/null 2>&1) && echo "-m32" || true)', 'clang%': 0, }, 'conditions': [ ['OS!="android" or clang==1', { 'cflags': [ '<(m32flag)' ], 'ldflags': [ '<(m32flag)' ], }], ], 'xcode_settings': { 'ARCHS': [ 'i386' ], }, }], ], }], ['OS=="freebsd" or OS=="openbsd"', { 'cflags': [ '-I/usr/local/include' ], }], ['OS=="netbsd"', { 'cflags': [ '-I/usr/pkg/include' ], }], ], # conditions 'configurations': { 'Debug': { 'defines': [ 'DEBUG', 'ENABLE_DISASSEMBLER', 'V8_ENABLE_CHECKS', 'OBJECT_PRINT', 'VERIFY_HEAP', ], 'msvs_settings': { 'VCCLCompilerTool': { 'Optimization': '0', 'conditions': [ ['OS=="win" and component=="shared_library"', { 'RuntimeLibrary': '3', # /MDd }, { 'RuntimeLibrary': '1', # /MTd }], ], }, 'VCLinkerTool': { 'LinkIncremental': '2', }, }, 'conditions': [ ['OS=="linux" or OS=="freebsd" or OS=="openbsd" or OS=="netbsd"', { 'cflags': [ '-Wall', '<(werror)', '-W', '-Wno-unused-parameter', '-Wnon-virtual-dtor', '-Woverloaded-virtual' ], }], ['OS=="android"', { 'variables': { 'android_full_debug%': 1, }, 'conditions': [ ['android_full_debug==0', { # Disable full debug if we want a faster v8 in a debug build. # TODO(2304): pass DISABLE_DEBUG_ASSERT instead of hiding DEBUG. 'defines!': [ 'DEBUG', ], }], ], }], ], }, # Debug 'Release': { 'conditions': [ ['OS=="linux" or OS=="freebsd" or OS=="openbsd" or OS=="netbsd" \ or OS=="android"', { 'conditions': [ [ 'gcc_version==44 and clang==0', { 'cflags': [ # Avoid crashes with gcc 4.4 in the v8 test suite. '-fno-tree-vrp', ], }], ], }], ['OS=="mac"', { 'xcode_settings': { 'GCC_OPTIMIZATION_LEVEL': '3', # -O3 # -fstrict-aliasing. Mainline gcc # enables this at -O2 and above, # but Apple gcc does not unless it # is specified explicitly. 'GCC_STRICT_ALIASING': 'YES', }, }], # OS=="mac" ['OS=="win"', { 'msvs_settings': { 'VCCLCompilerTool': { 'Optimization': '2', 'InlineFunctionExpansion': '2', 'EnableIntrinsicFunctions': 'true', 'FavorSizeOrSpeed': '0', 'StringPooling': 'true', 'conditions': [ ['OS=="win" and component=="shared_library"', { 'RuntimeLibrary': '2', #/MD }, { 'RuntimeLibrary': '0', #/MT }], ['v8_target_arch=="x64"', { # TODO(2207): remove this option once the bug is fixed. 'WholeProgramOptimization': 'true', }], ], }, 'VCLinkerTool': { 'LinkIncremental': '1', 'OptimizeReferences': '2', 'EnableCOMDATFolding': '2', }, }, }], # OS=="win" ], # conditions }, # Release }, # configurations }, # target_defaults } node-v0.10.25~dfsg2/deps/v8/build/gyp_v80000755000000000000000000001353212270121457016352 0ustar rootroot#!/usr/bin/python # # Copyright 2012 the V8 project authors. All rights reserved. # Redistribution and use in source and binary forms, with or without # modification, are permitted provided that the following conditions are # met: # # * Redistributions of source code must retain the above copyright # notice, this list of conditions and the following disclaimer. # * Redistributions in binary form must reproduce the above # copyright notice, this list of conditions and the following # disclaimer in the documentation and/or other materials provided # with the distribution. # * Neither the name of Google Inc. nor the names of its # contributors may be used to endorse or promote products derived # from this software without specific prior written permission. # # THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS # "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT # LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR # A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT # OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, # SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT # LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, # DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY # THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT # (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE # OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. # This script is wrapper for V8 that adds some support for how GYP # is invoked by V8 beyond what can be done in the gclient hooks. import glob import os import shlex import sys script_dir = os.path.dirname(__file__) v8_root = os.path.normpath(os.path.join(script_dir, os.pardir)) if __name__ == '__main__': os.chdir(v8_root) script_dir = os.path.dirname(__file__) v8_root = '.' sys.path.insert(0, os.path.join(v8_root, 'tools')) import utils sys.path.insert(0, os.path.join(v8_root, 'build', 'gyp', 'pylib')) import gyp def apply_gyp_environment(file_path=None): """ Reads in a *.gyp_env file and applies the valid keys to os.environ. """ if not file_path or not os.path.exists(file_path): return file_contents = open(file_path).read() try: file_data = eval(file_contents, {'__builtins__': None}, None) except SyntaxError, e: e.filename = os.path.abspath(file_path) raise supported_vars = ( 'V8_GYP_FILE', 'V8_GYP_SYNTAX_CHECK', 'GYP_DEFINES', 'GYP_GENERATOR_FLAGS', 'GYP_GENERATOR_OUTPUT', ) for var in supported_vars: val = file_data.get(var) if val: if var in os.environ: print 'INFO: Environment value for "%s" overrides value in %s.' % ( var, os.path.abspath(file_path) ) else: os.environ[var] = val def additional_include_files(args=[]): """ Returns a list of additional (.gypi) files to include, without duplicating ones that are already specified on the command line. """ # Determine the include files specified on the command line. # This doesn't cover all the different option formats you can use, # but it's mainly intended to avoid duplicating flags on the automatic # makefile regeneration which only uses this format. specified_includes = set() for arg in args: if arg.startswith('-I') and len(arg) > 2: specified_includes.add(os.path.realpath(arg[2:])) result = [] def AddInclude(path): if os.path.realpath(path) not in specified_includes: result.append(path) # Always include standalone.gypi AddInclude(os.path.join(v8_root, 'build', 'standalone.gypi')) # Optionally add supplemental .gypi files if present. supplements = glob.glob(os.path.join(v8_root, '*', 'supplement.gypi')) for supplement in supplements: AddInclude(supplement) return result def run_gyp(args): rc = gyp.main(args) if rc != 0: print 'Error running GYP' sys.exit(rc) if __name__ == '__main__': args = sys.argv[1:] if 'SKIP_V8_GYP_ENV' not in os.environ: # Update the environment based on v8.gyp_env gyp_env_path = os.path.join(os.path.dirname(v8_root), 'v8.gyp_env') apply_gyp_environment(gyp_env_path) # This could give false positives since it doesn't actually do real option # parsing. Oh well. gyp_file_specified = False for arg in args: if arg.endswith('.gyp'): gyp_file_specified = True break # If we didn't get a file, check an env var, and then fall back to # assuming 'all.gyp' from the same directory as the script. if not gyp_file_specified: gyp_file = os.environ.get('V8_GYP_FILE') if gyp_file: # Note that V8_GYP_FILE values can't have backslashes as # path separators even on Windows due to the use of shlex.split(). args.extend(shlex.split(gyp_file)) else: # Note that this must not start with "./" or things break. # So we rely on having done os.chdir(v8_root) above and use the # relative path. args.append(os.path.join('build', 'all.gyp')) args.extend(['-I' + i for i in additional_include_files(args)]) # There shouldn't be a circular dependency relationship between .gyp files args.append('--no-circular-check') # Set the GYP DEPTH variable to the root of the V8 project. args.append('--depth=' + v8_root) # If V8_GYP_SYNTAX_CHECK is set to 1, it will invoke gyp with --check # to enfore syntax checking. syntax_check = os.environ.get('V8_GYP_SYNTAX_CHECK') if syntax_check and int(syntax_check): args.append('--check') print 'Updating projects from gyp files...' sys.stdout.flush() # Generate for the architectures supported on the given platform. gyp_args = list(args) if utils.GuessOS() == 'linux': gyp_args.append('--generator-output=out') run_gyp(gyp_args) node-v0.10.25~dfsg2/deps/v8/build/all.gyp0000644000000000000000000000065312270121457016501 0ustar rootroot# Copyright 2011 the V8 project authors. All rights reserved. # Use of this source code is governed by a BSD-style license that can be # found in the LICENSE file. { 'targets': [ { 'target_name': 'All', 'type': 'none', 'dependencies': [ '../preparser/preparser.gyp:*', '../samples/samples.gyp:*', '../src/d8.gyp:d8', '../test/cctest/cctest.gyp:*', ], } ] } node-v0.10.25~dfsg2/deps/v8/build/android.gypi0000644000000000000000000002136112270121457017521 0ustar rootroot# Copyright 2012 the V8 project authors. All rights reserved. # Redistribution and use in source and binary forms, with or without # modification, are permitted provided that the following conditions are # met: # # * Redistributions of source code must retain the above copyright # notice, this list of conditions and the following disclaimer. # * Redistributions in binary form must reproduce the above # copyright notice, this list of conditions and the following # disclaimer in the documentation and/or other materials provided # with the distribution. # * Neither the name of Google Inc. nor the names of its # contributors may be used to endorse or promote products derived # from this software without specific prior written permission. # # THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS # "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT # LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR # A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT # OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, # SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT # LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, # DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY # THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT # (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE # OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. # Definitions for building standalone V8 binaries to run on Android. # This is mostly excerpted from: # http://src.chromium.org/viewvc/chrome/trunk/src/build/common.gypi { 'variables': { # Location of Android NDK. 'variables': { 'android_ndk_root%': ' svn co http://src.chromium.org/svn/trunk/deps/third_party/cygwin@66844 third_party/cygwin To run GYP Python is required and it is recommended to use the same version as is used by the Chromium project. This can also be checked out from the Chromium repository. From the root of the V8 project do the following: > svn co http://src.chromium.org/svn/trunk/tools/third_party/python_26@89111 third_party/python_26 Now generate Visual Studio solution and project files for the ia32 architecture: > third_party\python_26\python build/gyp_v8 Now open build\All.sln in Visual Studio. node-v0.10.25~dfsg2/deps/v8/build/standalone.gypi0000644000000000000000000002016212270121457020227 0ustar rootroot# Copyright 2012 the V8 project authors. All rights reserved. # Redistribution and use in source and binary forms, with or without # modification, are permitted provided that the following conditions are # met: # # * Redistributions of source code must retain the above copyright # notice, this list of conditions and the following disclaimer. # * Redistributions in binary form must reproduce the above # copyright notice, this list of conditions and the following # disclaimer in the documentation and/or other materials provided # with the distribution. # * Neither the name of Google Inc. nor the names of its # contributors may be used to endorse or promote products derived # from this software without specific prior written permission. # # THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS # "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT # LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR # A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT # OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, # SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT # LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, # DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY # THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT # (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE # OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. # Definitions to be used when building stand-alone V8 binaries. { 'variables': { 'library%': 'static_library', 'component%': 'static_library', 'visibility%': 'hidden', 'msvs_multi_core_compile%': '1', 'mac_deployment_target%': '10.5', 'variables': { 'variables': { 'variables': { 'conditions': [ ['OS=="linux" or OS=="freebsd" or OS=="openbsd" or \ OS=="netbsd" or OS=="mac"', { # This handles the Unix platforms we generally deal with. # Anything else gets passed through, which probably won't work # very well; such hosts should pass an explicit target_arch # to gyp. 'host_arch%': '= 4) || \ (__GNUC__ == 3 && __GNUC_MINOR__ >= 3)) && defined(V8_SHARED) #define V8EXPORT __attribute__ ((visibility("default"))) #else #define V8EXPORT #endif #endif // _WIN32 namespace v8 { // The result of preparsing is either a stack overflow error, or an opaque // blob of data that can be passed back into the parser. class V8EXPORT PreParserData { public: PreParserData(size_t size, const uint8_t* data) : data_(data), size_(size) { } // Create a PreParserData value where stack_overflow reports true. static PreParserData StackOverflow() { return PreParserData(0, NULL); } // Whether the pre-parser stopped due to a stack overflow. // If this is the case, size() and data() should not be used. bool stack_overflow() { return size_ == 0u; } // The size of the data in bytes. size_t size() const { return size_; } // Pointer to the data. const uint8_t* data() const { return data_; } private: const uint8_t* const data_; const size_t size_; }; // Interface for a stream of Unicode characters. class V8EXPORT UnicodeInputStream { // NOLINT - Thinks V8EXPORT is class name. public: virtual ~UnicodeInputStream(); // Returns the next Unicode code-point in the input, or a negative value when // there is no more input in the stream. virtual int32_t Next() = 0; }; // Preparse a JavaScript program. The source code is provided as a // UnicodeInputStream. The max_stack_size limits the amount of stack // space that the preparser is allowed to use. If the preparser uses // more stack space than the limit provided, the result's stack_overflow() // method will return true. Otherwise the result contains preparser // data that can be used by the V8 parser to speed up parsing. PreParserData V8EXPORT Preparse(UnicodeInputStream* input, size_t max_stack_size); } // namespace v8. #endif // PREPARSER_H node-v0.10.25~dfsg2/deps/v8/include/v8.h0000644000000000000000000044640112270121457016247 0ustar rootroot// Copyright 2012 the V8 project authors. All rights reserved. // Redistribution and use in source and binary forms, with or without // modification, are permitted provided that the following conditions are // met: // // * Redistributions of source code must retain the above copyright // notice, this list of conditions and the following disclaimer. // * Redistributions in binary form must reproduce the above // copyright notice, this list of conditions and the following // disclaimer in the documentation and/or other materials provided // with the distribution. // * Neither the name of Google Inc. nor the names of its // contributors may be used to endorse or promote products derived // from this software without specific prior written permission. // // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS // "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT // LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR // A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT // OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, // SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT // LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, // DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY // THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT // (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE // OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. /** \mainpage V8 API Reference Guide * * V8 is Google's open source JavaScript engine. * * This set of documents provides reference material generated from the * V8 header file, include/v8.h. * * For other documentation see http://code.google.com/apis/v8/ */ #ifndef V8_H_ #define V8_H_ #include "v8stdint.h" #ifdef _WIN32 // Setup for Windows DLL export/import. When building the V8 DLL the // BUILDING_V8_SHARED needs to be defined. When building a program which uses // the V8 DLL USING_V8_SHARED needs to be defined. When either building the V8 // static library or building a program which uses the V8 static library neither // BUILDING_V8_SHARED nor USING_V8_SHARED should be defined. #if defined(BUILDING_V8_SHARED) && defined(USING_V8_SHARED) #error both BUILDING_V8_SHARED and USING_V8_SHARED are set - please check the\ build configuration to ensure that at most one of these is set #endif #ifdef BUILDING_V8_SHARED #define V8EXPORT __declspec(dllexport) #elif USING_V8_SHARED #define V8EXPORT __declspec(dllimport) #else #define V8EXPORT #endif // BUILDING_V8_SHARED #else // _WIN32 // Setup for Linux shared library export. #if defined(__GNUC__) && ((__GNUC__ >= 4) || \ (__GNUC__ == 3 && __GNUC_MINOR__ >= 3)) && defined(V8_SHARED) #ifdef BUILDING_V8_SHARED #define V8EXPORT __attribute__ ((visibility("default"))) #else #define V8EXPORT #endif #else #define V8EXPORT #endif #endif // _WIN32 /** * The v8 JavaScript engine. */ namespace v8 { class Context; class String; class StringObject; class Value; class Utils; class Number; class NumberObject; class Object; class Array; class Int32; class Uint32; class External; class Primitive; class Boolean; class BooleanObject; class Integer; class Function; class Date; class ImplementationUtilities; class Signature; class AccessorSignature; template class Handle; template class Local; template class Persistent; class FunctionTemplate; class ObjectTemplate; class Data; class AccessorInfo; class StackTrace; class StackFrame; class Isolate; namespace internal { class Arguments; class Object; class Heap; class HeapObject; class Isolate; } // --- Weak Handles --- /** * A weak reference callback function. * * This callback should either explicitly invoke Dispose on |object| if * V8 wrapper is not needed anymore, or 'revive' it by invocation of MakeWeak. * * \param object the weak global object to be reclaimed by the garbage collector * \param parameter the value passed in when making the weak global object */ typedef void (*WeakReferenceCallback)(Persistent object, void* parameter); // --- Handles --- #define TYPE_CHECK(T, S) \ while (false) { \ *(static_cast(0)) = static_cast(0); \ } /** * An object reference managed by the v8 garbage collector. * * All objects returned from v8 have to be tracked by the garbage * collector so that it knows that the objects are still alive. Also, * because the garbage collector may move objects, it is unsafe to * point directly to an object. Instead, all objects are stored in * handles which are known by the garbage collector and updated * whenever an object moves. Handles should always be passed by value * (except in cases like out-parameters) and they should never be * allocated on the heap. * * There are two types of handles: local and persistent handles. * Local handles are light-weight and transient and typically used in * local operations. They are managed by HandleScopes. Persistent * handles can be used when storing objects across several independent * operations and have to be explicitly deallocated when they're no * longer used. * * It is safe to extract the object stored in the handle by * dereferencing the handle (for instance, to extract the Object* from * a Handle); the value will still be governed by a handle * behind the scenes and the same rules apply to these values as to * their handles. */ template class Handle { public: /** * Creates an empty handle. */ inline Handle() : val_(0) {} /** * Creates a new handle for the specified value. */ inline explicit Handle(T* val) : val_(val) {} /** * Creates a handle for the contents of the specified handle. This * constructor allows you to pass handles as arguments by value and * to assign between handles. However, if you try to assign between * incompatible handles, for instance from a Handle to a * Handle it will cause a compile-time error. Assigning * between compatible handles, for instance assigning a * Handle to a variable declared as Handle, is legal * because String is a subclass of Value. */ template inline Handle(Handle that) : val_(reinterpret_cast(*that)) { /** * This check fails when trying to convert between incompatible * handles. For example, converting from a Handle to a * Handle. */ TYPE_CHECK(T, S); } /** * Returns true if the handle is empty. */ inline bool IsEmpty() const { return val_ == 0; } /** * Sets the handle to be empty. IsEmpty() will then return true. */ inline void Clear() { val_ = 0; } inline T* operator->() const { return val_; } inline T* operator*() const { return val_; } /** * Checks whether two handles are the same. * Returns true if both are empty, or if the objects * to which they refer are identical. * The handles' references are not checked. */ template inline bool operator==(Handle that) const { internal::Object** a = reinterpret_cast(**this); internal::Object** b = reinterpret_cast(*that); if (a == 0) return b == 0; if (b == 0) return false; return *a == *b; } /** * Checks whether two handles are different. * Returns true if only one of the handles is empty, or if * the objects to which they refer are different. * The handles' references are not checked. */ template inline bool operator!=(Handle that) const { return !operator==(that); } template static inline Handle Cast(Handle that) { #ifdef V8_ENABLE_CHECKS // If we're going to perform the type check then we have to check // that the handle isn't empty before doing the checked cast. if (that.IsEmpty()) return Handle(); #endif return Handle(T::Cast(*that)); } template inline Handle As() { return Handle::Cast(*this); } private: T* val_; }; /** * A light-weight stack-allocated object handle. All operations * that return objects from within v8 return them in local handles. They * are created within HandleScopes, and all local handles allocated within a * handle scope are destroyed when the handle scope is destroyed. Hence it * is not necessary to explicitly deallocate local handles. */ template class Local : public Handle { public: inline Local(); template inline Local(Local that) : Handle(reinterpret_cast(*that)) { /** * This check fails when trying to convert between incompatible * handles. For example, converting from a Handle to a * Handle. */ TYPE_CHECK(T, S); } template inline Local(S* that) : Handle(that) { } template static inline Local Cast(Local that) { #ifdef V8_ENABLE_CHECKS // If we're going to perform the type check then we have to check // that the handle isn't empty before doing the checked cast. if (that.IsEmpty()) return Local(); #endif return Local(T::Cast(*that)); } template inline Local As() { return Local::Cast(*this); } /** Create a local handle for the content of another handle. * The referee is kept alive by the local handle even when * the original handle is destroyed/disposed. */ inline static Local New(Handle that); }; /** * An object reference that is independent of any handle scope. Where * a Local handle only lives as long as the HandleScope in which it was * allocated, a Persistent handle remains valid until it is explicitly * disposed. * * A persistent handle contains a reference to a storage cell within * the v8 engine which holds an object value and which is updated by * the garbage collector whenever the object is moved. A new storage * cell can be created using Persistent::New and existing handles can * be disposed using Persistent::Dispose. Since persistent handles * are passed by value you may have many persistent handle objects * that point to the same storage cell. For instance, if you pass a * persistent handle as an argument to a function you will not get two * different storage cells but rather two references to the same * storage cell. */ template class Persistent : public Handle { public: /** * Creates an empty persistent handle that doesn't point to any * storage cell. */ inline Persistent(); /** * Creates a persistent handle for the same storage cell as the * specified handle. This constructor allows you to pass persistent * handles as arguments by value and to assign between persistent * handles. However, attempting to assign between incompatible * persistent handles, for instance from a Persistent to a * Persistent will cause a compile-time error. Assigning * between compatible persistent handles, for instance assigning a * Persistent to a variable declared as Persistent, * is allowed as String is a subclass of Value. */ template inline Persistent(Persistent that) : Handle(reinterpret_cast(*that)) { /** * This check fails when trying to convert between incompatible * handles. For example, converting from a Handle to a * Handle. */ TYPE_CHECK(T, S); } template inline Persistent(S* that) : Handle(that) { } /** * "Casts" a plain handle which is known to be a persistent handle * to a persistent handle. */ template explicit inline Persistent(Handle that) : Handle(*that) { } template static inline Persistent Cast(Persistent that) { #ifdef V8_ENABLE_CHECKS // If we're going to perform the type check then we have to check // that the handle isn't empty before doing the checked cast. if (that.IsEmpty()) return Persistent(); #endif return Persistent(T::Cast(*that)); } template inline Persistent As() { return Persistent::Cast(*this); } /** * Creates a new persistent handle for an existing local or * persistent handle. */ inline static Persistent New(Handle that); /** * Releases the storage cell referenced by this persistent handle. * Does not remove the reference to the cell from any handles. * This handle's reference, and any other references to the storage * cell remain and IsEmpty will still return false. */ inline void Dispose(); /** * Make the reference to this object weak. When only weak handles * refer to the object, the garbage collector will perform a * callback to the given V8::WeakReferenceCallback function, passing * it the object reference and the given parameters. */ inline void MakeWeak(void* parameters, WeakReferenceCallback callback); /** Clears the weak reference to this object. */ inline void ClearWeak(); /** * Marks the reference to this object independent. Garbage collector * is free to ignore any object groups containing this object. * Weak callback for an independent handle should not * assume that it will be preceded by a global GC prologue callback * or followed by a global GC epilogue callback. */ inline void MarkIndependent(); /** Returns true if this handle was previously marked as independent. */ inline bool IsIndependent() const; /** Checks if the handle holds the only reference to an object. */ inline bool IsNearDeath() const; /** Returns true if the handle's reference is weak. */ inline bool IsWeak() const; /** * Assigns a wrapper class ID to the handle. See RetainedObjectInfo * interface description in v8-profiler.h for details. */ inline void SetWrapperClassId(uint16_t class_id); /** * Returns the class ID previously assigned to this handle or 0 if no class * ID was previously assigned. */ inline uint16_t WrapperClassId() const; private: friend class ImplementationUtilities; friend class ObjectTemplate; }; /** * A stack-allocated class that governs a number of local handles. * After a handle scope has been created, all local handles will be * allocated within that handle scope until either the handle scope is * deleted or another handle scope is created. If there is already a * handle scope and a new one is created, all allocations will take * place in the new handle scope until it is deleted. After that, * new handles will again be allocated in the original handle scope. * * After the handle scope of a local handle has been deleted the * garbage collector will no longer track the object stored in the * handle and may deallocate it. The behavior of accessing a handle * for which the handle scope has been deleted is undefined. */ class V8EXPORT HandleScope { public: HandleScope(); ~HandleScope(); /** * Closes the handle scope and returns the value as a handle in the * previous scope, which is the new current scope after the call. */ template Local Close(Handle value); /** * Counts the number of allocated handles. */ static int NumberOfHandles(); /** * Creates a new handle with the given value. */ static internal::Object** CreateHandle(internal::Object* value); // Faster version, uses HeapObject to obtain the current Isolate. static internal::Object** CreateHandle(internal::HeapObject* value); private: // Make it impossible to create heap-allocated or illegal handle // scopes by disallowing certain operations. HandleScope(const HandleScope&); void operator=(const HandleScope&); void* operator new(size_t size); void operator delete(void*, size_t); // This Data class is accessible internally as HandleScopeData through a // typedef in the ImplementationUtilities class. class V8EXPORT Data { public: internal::Object** next; internal::Object** limit; int level; inline void Initialize() { next = limit = NULL; level = 0; } }; void Leave(); internal::Isolate* isolate_; internal::Object** prev_next_; internal::Object** prev_limit_; // Allow for the active closing of HandleScopes which allows to pass a handle // from the HandleScope being closed to the next top most HandleScope. bool is_closed_; internal::Object** RawClose(internal::Object** value); friend class ImplementationUtilities; }; // --- Special objects --- /** * The superclass of values and API object templates. */ class V8EXPORT Data { private: Data(); }; /** * Pre-compilation data that can be associated with a script. This * data can be calculated for a script in advance of actually * compiling it, and can be stored between compilations. When script * data is given to the compile method compilation will be faster. */ class V8EXPORT ScriptData { // NOLINT public: virtual ~ScriptData() { } /** * Pre-compiles the specified script (context-independent). * * \param input Pointer to UTF-8 script source code. * \param length Length of UTF-8 script source code. */ static ScriptData* PreCompile(const char* input, int length); /** * Pre-compiles the specified script (context-independent). * * NOTE: Pre-compilation using this method cannot happen on another thread * without using Lockers. * * \param source Script source code. */ static ScriptData* PreCompile(Handle source); /** * Load previous pre-compilation data. * * \param data Pointer to data returned by a call to Data() of a previous * ScriptData. Ownership is not transferred. * \param length Length of data. */ static ScriptData* New(const char* data, int length); /** * Returns the length of Data(). */ virtual int Length() = 0; /** * Returns a serialized representation of this ScriptData that can later be * passed to New(). NOTE: Serialized data is platform-dependent. */ virtual const char* Data() = 0; /** * Returns true if the source code could not be parsed. */ virtual bool HasError() = 0; }; /** * The origin, within a file, of a script. */ class ScriptOrigin { public: inline ScriptOrigin( Handle resource_name, Handle resource_line_offset = Handle(), Handle resource_column_offset = Handle()) : resource_name_(resource_name), resource_line_offset_(resource_line_offset), resource_column_offset_(resource_column_offset) { } inline Handle ResourceName() const; inline Handle ResourceLineOffset() const; inline Handle ResourceColumnOffset() const; private: Handle resource_name_; Handle resource_line_offset_; Handle resource_column_offset_; }; /** * A compiled JavaScript script. */ class V8EXPORT Script { public: /** * Compiles the specified script (context-independent). * * \param source Script source code. * \param origin Script origin, owned by caller, no references are kept * when New() returns * \param pre_data Pre-parsing data, as obtained by ScriptData::PreCompile() * using pre_data speeds compilation if it's done multiple times. * Owned by caller, no references are kept when New() returns. * \param script_data Arbitrary data associated with script. Using * this has same effect as calling SetData(), but allows data to be * available to compile event handlers. * \return Compiled script object (context independent; when run it * will use the currently entered context). */ static Local