api.html 104 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180218121822183218421852186218721882189219021912192219321942195219621972198219922002201220222032204220522062207220822092210221122122213221422152216221722182219222022212222222322242225222622272228222922302231223222332234223522362237223822392240224122422243224422452246224722482249225022512252225322542255225622572258225922602261226222632264226522662267226822692270227122722273227422752276227722782279228022812282228322842285228622872288228922902291229222932294229522962297229822992300230123022303230423052306230723082309231023112312231323142315231623172318231923202321232223232324232523262327232823292330233123322333233423352336233723382339234023412342234323442345234623472348234923502351235223532354235523562357235823592360236123622363236423652366236723682369237023712372237323742375237623772378237923802381238223832384238523862387238823892390239123922393239423952396239723982399240024012402240324042405240624072408240924102411241224132414241524162417241824192420242124222423242424252426242724282429243024312432243324342435243624372438243924402441244224432444244524462447244824492450245124522453245424552456245724582459246024612462246324642465246624672468246924702471247224732474247524762477247824792480248124822483248424852486248724882489249024912492249324942495249624972498249925002501250225032504250525062507250825092510251125122513251425152516251725182519252025212522252325242525252625272528252925302531253225332534253525362537253825392540254125422543254425452546254725482549255025512552255325542555255625572558255925602561256225632564256525662567256825692570257125722573257425752576257725782579258025812582258325842585258625872588258925902591259225932594259525962597259825992600260126022603260426052606260726082609261026112612261326142615261626172618261926202621262226232624262526262627262826292630263126322633263426352636263726382639264026412642264326442645264626472648264926502651265226532654265526562657265826592660266126622663266426652666266726682669267026712672267326742675267626772678267926802681268226832684268526862687268826892690269126922693269426952696269726982699270027012702270327042705270627072708270927102711271227132714271527162717271827192720272127222723272427252726272727282729273027312732273327342735273627372738273927402741274227432744274527462747274827492750275127522753275427552756275727582759276027612762276327642765276627672768276927702771277227732774277527762777277827792780278127822783278427852786278727882789279027912792279327942795279627972798279928002801280228032804280528062807280828092810281128122813281428152816281728182819282028212822282328242825282628272828282928302831283228332834283528362837283828392840284128422843284428452846284728482849285028512852285328542855285628572858285928602861286228632864286528662867286828692870287128722873287428752876287728782879288028812882288328842885288628872888288928902891289228932894289528962897289828992900290129022903290429052906290729082909291029112912291329142915291629172918291929202921292229232924292529262927292829292930293129322933293429352936293729382939294029412942294329442945294629472948294929502951295229532954295529562957295829592960296129622963296429652966296729682969297029712972297329742975297629772978297929802981298229832984298529862987298829892990299129922993299429952996299729982999300030013002300330043005300630073008300930103011301230133014301530163017301830193020302130223023302430253026302730283029303030313032303330343035303630373038303930403041304230433044304530463047304830493050305130523053305430553056305730583059306030613062306330643065306630673068306930703071307230733074307530763077307830793080308130823083308430853086308730883089309030913092309330943095309630973098309931003101310231033104310531063107310831093110311131123113311431153116311731183119312031213122312331243125312631273128312931303131313231333134313531363137313831393140314131423143314431453146314731483149315031513152315331543155315631573158315931603161316231633164316531663167316831693170317131723173317431753176317731783179318031813182318331843185318631873188318931903191319231933194319531963197319831993200320132023203320432053206320732083209321032113212321332143215321632173218321932203221322232233224322532263227322832293230323132323233323432353236323732383239324032413242324332443245324632473248324932503251325232533254325532563257325832593260326132623263326432653266326732683269327032713272327332743275327632773278327932803281328232833284328532863287328832893290329132923293329432953296329732983299330033013302330333043305330633073308330933103311
  1. <!DOCTYPE html>
  2. <head>
  3. <meta http-equiv="Content-Type" content="text/html; charset=utf-8">
  4. <meta name='generator' value='Ronn/v0.4.1'>
  5. <title>node(1) -- evented I/O for V8 JavaScript</title>
  6. <style type='text/css'>
  7. *{
  8. margin: 0;padding: 0;
  9. }
  10. html,body
  11. {
  12. height: 100%;
  13. }
  14. body
  15. {
  16. font-family:helvetica, arial, sans serif;
  17. background:#22252a;
  18. color:#eee;
  19. font-size:16px;
  20. line-height:1.3;
  21. position:relative;
  22. min-width: 690px;
  23. }
  24. a
  25. {
  26. color:#CD5;
  27. }
  28. a:focus
  29. {
  30. outline: none;
  31. -moz-outline: none;
  32. }
  33. pre
  34. {
  35. overflow: hidden;
  36. }
  37. li
  38. {
  39. list-style: inside;
  40. }
  41. #man,#man code,#man pre,#man tt,#man kbd,#man samp
  42. {
  43. line-height:1.6;
  44. color:#eee;
  45. background:#22252a;
  46. }
  47. #man
  48. {
  49. margin: 0;
  50. position: absolute;
  51. top:0;
  52. bottom:0;
  53. left: 225px;
  54. right: 0;
  55. overflow: auto;
  56. }
  57. #man-content
  58. {
  59. padding: 0 20px;
  60. max-width: 650px;
  61. }
  62. #man h1,#man h2,#man h3
  63. {
  64. color:#DCDDDE;
  65. clear:left;
  66. }
  67. #man h1
  68. {
  69. background:url("http://nodejs.org/logo.png") no-repeat scroll center 0 transparent;
  70. height:111px;
  71. margin:15px 0 20px;
  72. text-align:center;
  73. text-indent:-2000px;
  74. }
  75. #man h2
  76. {
  77. font-size:18px;
  78. background:#000;
  79. color:#CD5;
  80. margin:10px 0;
  81. padding:5px 10px;
  82. }
  83. #man h3
  84. {
  85. font-size:16px;
  86. margin:0 0 0 0ex;
  87. }
  88. #man p,#man ul,#man ol,#man dl,#man pre
  89. {
  90. margin:0 0 18px;
  91. }
  92. #man pre
  93. {
  94. color:#CCCDCE;
  95. background:#121314;
  96. border-left:2ex solid #222;
  97. margin:0 0 20px;
  98. padding:5px 7px;
  99. }
  100. #man pre + h2,#man pre + h3
  101. {
  102. margin-top:22px;
  103. }
  104. #man h2 + pre,#man h3 + pre
  105. {
  106. margin-top:5px;
  107. }
  108. #man > p,#man > ul,#man > ol,#man > dl,#man > pre
  109. {
  110. margin-left:5%;
  111. }
  112. #man dt
  113. {
  114. clear:left;
  115. margin:0;
  116. }
  117. #man dt.flush
  118. {
  119. float:left;
  120. width:8ex;
  121. }
  122. #man dd
  123. {
  124. margin:0 0 0 9ex;
  125. }
  126. #man code,#man strong,#man b
  127. {
  128. font-weight:bold;
  129. color:#ECEDEE;
  130. }
  131. #man pre code
  132. {
  133. font-weight:normal;
  134. color:#DCDDDE;
  135. background:inherit;
  136. }
  137. #man em,var,u
  138. {
  139. font-style:normal;
  140. color:#CCCDCE;
  141. border-bottom:1px solid #999;
  142. }
  143. #man ol.man,#man ol.man li
  144. {
  145. float:left;
  146. width:33%;
  147. list-style-type:none;
  148. text-transform:uppercase;
  149. font-size:18px;
  150. color:#666;
  151. letter-spacing:1px;
  152. margin:2px 0 10px;
  153. padding:0;
  154. }
  155. #man ol.man
  156. {
  157. width:100%;
  158. }
  159. #man ol.man li.tl
  160. {
  161. text-align:left;
  162. }
  163. #man ol.man li.tc
  164. {
  165. text-align:center;
  166. letter-spacing:4px;
  167. }
  168. #man ol.man li.tr
  169. {
  170. text-align:right;
  171. }
  172. #man ol.man a
  173. {
  174. color:#666;
  175. }
  176. #man ol.man a:hover
  177. {
  178. color:#CCCDCE;
  179. }
  180. #toc
  181. {
  182. position: absolute;
  183. top:0;
  184. bottom:0;
  185. left: 0;
  186. padding-left: 30px;
  187. width: 195px;
  188. overflow: auto;
  189. overflow-x: hidden;
  190. font-size: 15px;
  191. }
  192. #toc li
  193. {
  194. text-wrap: word-wrap;
  195. }
  196. #toc a
  197. {
  198. display: inline-block;
  199. width: 100%;
  200. color: #fff;
  201. text-decoration:none;
  202. }
  203. #toc > a:hover
  204. {
  205. color: rgba(255,255,255,0.7);
  206. }
  207. #toc > ul > li
  208. {
  209. border-bottom:1px solid #0f1214;
  210. padding:5px 0 5px 5px;
  211. list-style: none;
  212. line-height: 1.3;
  213. }
  214. #toc ul ul
  215. {
  216. display: none;
  217. }
  218. #toc ul ul > li
  219. {
  220. border-top:1px solid rgba(0, 0, 0, 0.1);
  221. color:#FFFFFF;
  222. font-size:85%;
  223. line-height:1.3;
  224. list-style:disc outside none;
  225. margin-left:25px;
  226. max-width:165px;
  227. padding:3px 0 5px 5px;
  228. }
  229. #toc li.active > a
  230. {
  231. color:#CD5;
  232. }
  233. .sh_sourceCode
  234. {
  235. font-family: monospace;
  236. overflow:hidden;
  237. }
  238. #toc .toggler
  239. {
  240. -moz-user-select:none;
  241. background:none repeat scroll 0 0 #000000;
  242. color:#FFFFFF;
  243. display:inline-block;
  244. font-weight:bold;
  245. height:31px;
  246. line-height:32px;
  247. margin:-5px 8px -18px -33px;
  248. outline:medium none;
  249. padding:0;
  250. text-align:center;
  251. width:25px;
  252. }
  253. .current-section
  254. {
  255. position: fixed;
  256. top: 0;
  257. margin: 0 !important;
  258. }
  259. #toctitle
  260. {
  261. background:none repeat scroll 0 0 #000000;
  262. color:#CCDD55;
  263. font-size:18px;
  264. margin: 0 0 10px -30px;
  265. padding: 10px;
  266. }
  267. </style>
  268. <link rel="stylesheet" href="./sh_vim-dark.css" type="text/css" />
  269. </head>
  270. <body>
  271. <div id="toc">
  272. <div id="toctitle">Node v0.1.99</div>
  273. <noscript>JavaScript must be enabled in your browser to display the table of contents.</noscript>
  274. </div>
  275. <div id='man'>
  276. <div id="man-content">
  277. <h1 class='man-title'>node(1)</h1>
  278. <ol class='head man'>
  279. <li class='tl'>node(1)</li>
  280. <li class='tc'></li>
  281. <li class='tr'>node(1)</li>
  282. </ol>
  283. <h2 id='NAME'>NAME</h2>
  284. <p><code>node</code> -- evented I/O for V8 JavaScript</p>
  285. <h2 id="Synopsis">Synopsis</h2>
  286. <p>An example of a web server written with Node which responds with 'Hello
  287. World':</p>
  288. <pre><code>var sys = require('sys'),
  289. http = require('http');
  290. http.createServer(function (request, response) {
  291. response.writeHead(200, {'Content-Type': 'text/plain'});
  292. response.end('Hello World\n');
  293. }).listen(8124);
  294. sys.puts('Server running at http://127.0.0.1:8124/');
  295. </code></pre>
  296. <p>To run the server, put the code into a file called <code>example.js</code> and execute
  297. it with the node program</p>
  298. <pre><code>&gt; node example.js
  299. Server running at http://127.0.0.1:8124/
  300. </code></pre>
  301. <p>All of the examples in the documentation can be run similarly.</p>
  302. <h2 id="Standard Modules">Standard Modules</h2>
  303. <p>Node comes with a number of modules that are compiled in to the process,
  304. most of which are documented below. The most common way to use these modules
  305. is with <code>require('name')</code> and then assigning the return value to a local
  306. variable with the same name as the module.</p>
  307. <p>Example:</p>
  308. <pre><code>var sys = require('sys');
  309. </code></pre>
  310. <p>It is possible to extend node with other modules. See <code>'Modules'</code></p>
  311. <h2 id="Buffers">Buffers</h2>
  312. <p>Pure Javascript is Unicode friendly but not nice to binary data. When
  313. dealing with TCP streams or the file system, it's necessary to handle octet
  314. streams. Node has several strategies for manipulating, creating, and
  315. consuming octet streams.</p>
  316. <p>Raw data is stored in instances of the <code>Buffer</code> class. A <code>Buffer</code> is similar
  317. to an array of integers but corresponds to a raw memory allocation outside
  318. the V8 heap. A <code>Buffer</code> cannot be resized.
  319. Access the class with <code>require('buffer').Buffer</code>.</p>
  320. <p>Converting between Buffers and JavaScript string objects requires an explicit encoding
  321. method. Node supports 3 string encodings: UTF-8 (<code>'utf8'</code>), ASCII (<code>'ascii'</code>), and
  322. Binary (<code>'binary'</code>).</p>
  323. <ul>
  324. <li><p><code>'ascii'</code> - for 7 bit ASCII data only. This encoding method is very fast, and will
  325. strip the high bit if set.</p></li>
  326. <li><p><code>'binary'</code> - for 8 bit binary data such as images.</p></li>
  327. <li><p><code>'utf8'</code> - Unicode characters. Many web pages and other document formats use UTF-8.</p></li>
  328. </ul>
  329. <h3>new Buffer(size)</h3>
  330. <p>Allocates a new buffer of <code>size</code> octets.</p>
  331. <h3>new Buffer(array)</h3>
  332. <p>Allocates a new buffer using an <code>array</code> of octets.</p>
  333. <h3>new Buffer(str, encoding = 'utf8')</h3>
  334. <p>Allocates a new buffer containing the given <code>str</code>.</p>
  335. <h3>buffer.write(string, encoding, offset)</h3>
  336. <p>Writes <code>string</code> to the buffer at <code>offset</code> using the given encoding. Returns
  337. number of octets written. If <code>buffer</code> did not contain enough space to fit
  338. the entire string it will write a partial amount of the string. In the case
  339. of <code>'utf8'</code> encoding, the method will not write partial characters.</p>
  340. <p>Example: write a utf8 string into a buffer, then print it</p>
  341. <pre><code>var sys = require('sys'),
  342. Buffer = require('buffer').Buffer,
  343. buf = new Buffer(256),
  344. len;
  345. len = buf.write('\u00bd + \u00bc = \u00be', 'utf8', 0);
  346. sys.puts(len + " bytes: " + buf.toString('utf8', 0, len));
  347. // 12 bytes: ½ + ¼ = ¾
  348. </code></pre>
  349. <h3>buffer.toString(encoding, start, end)</h3>
  350. <p>Decodes and returns a string from buffer data encoded with <code>encoding</code>
  351. beginning at <code>start</code> and ending at <code>end</code>.</p>
  352. <p>See <code>buffer.write()</code> example, above.</p>
  353. <h3>buffer[index]</h3>
  354. <p>Get and set the octet at <code>index</code>. The values refer to individual bytes,
  355. so the legal range is between <code>0x00</code> and <code>0xFF</code> hex or <code>0</code> and <code>255</code>.</p>
  356. <p>Example: copy an ASCII string into a buffer, one byte at a time:</p>
  357. <pre><code>var sys = require('sys'),
  358. Buffer = require('buffer').Buffer,
  359. str = "node.js",
  360. buf = new Buffer(str.length),
  361. i;
  362. for (i = 0; i &lt; str.length ; i += 1) {
  363. buf[i] = str.charCodeAt(i);
  364. }
  365. sys.puts(buf);
  366. // node.js
  367. </code></pre>
  368. <h3>Buffer.byteLength(string, encoding)</h3>
  369. <p>Gives the actual byte length of a string. This is not the same as
  370. <code>String.prototype.length</code> since that returns the number of <em>characters</em> in a
  371. string.</p>
  372. <p>Example:</p>
  373. <pre><code>var sys = require('sys'),
  374. Buffer = require('buffer').Buffer,
  375. str = '\u00bd + \u00bc = \u00be';
  376. sys.puts(str + ": " + str.length + " characters, " +
  377. Buffer.byteLength(str, 'utf8') + " bytes");
  378. // ½ + ¼ = ¾: 9 characters, 12 bytes
  379. </code></pre>
  380. <h3>buffer.length</h3>
  381. <p>The size of the buffer in bytes. Note that this is not necessarily the size
  382. of the contents. <code>length</code> refers to the amount of memory allocated for the
  383. buffer object. It does not change when the contents of the buffer are changed.</p>
  384. <pre><code>var sys = require('sys'),
  385. Buffer = require('buffer').Buffer,
  386. buf = new Buffer(1234);
  387. sys.puts(buf.length);
  388. buf.write("some string", "ascii", 0);
  389. sys.puts(buf.length);
  390. // 1234
  391. // 1234
  392. </code></pre>
  393. <h3>buffer.copy(targetBuffer, targetStart, sourceStart, sourceEnd)</h3>
  394. <p>Does a memcpy() between buffers.</p>
  395. <p>Example: build two Buffers, then copy <code>buf1</code> from byte 16 through byte 20
  396. into <code>buf2</code>, starting at the 8th byte in <code>buf2</code>.</p>
  397. <pre><code>var sys = require('sys'),
  398. Buffer = require('buffer').Buffer,
  399. buf1 = new Buffer(26),
  400. buf2 = new Buffer(26),
  401. i;
  402. for (i = 0 ; i &lt; 26 ; i += 1) {
  403. buf1[i] = i + 97; // 97 is ASCII a
  404. buf2[i] = 33; // ASCII !
  405. }
  406. buf1.copy(buf2, 8, 16, 20);
  407. sys.puts(buf2.toString('ascii', 0, 25));
  408. // !!!!!!!!qrst!!!!!!!!!!!!!
  409. </code></pre>
  410. <h3>buffer.slice(start, end)</h3>
  411. <p>Returns a new buffer which references the
  412. same memory as the old, but offset and cropped by the <code>start</code> and <code>end</code>
  413. indexes.</p>
  414. <p><strong>Modifying the new buffer slice will modify memory in the original buffer!</strong></p>
  415. <p>Example: build a Buffer with the ASCII alphabet, take a slice, then modify one byte
  416. from the original Buffer.</p>
  417. <pre><code>var sys = require('sys'),
  418. Buffer = require('buffer').Buffer,
  419. buf1 = new Buffer(26), buf2,
  420. i;
  421. for (i = 0 ; i &lt; 26 ; i += 1) {
  422. buf1[i] = i + 97; // 97 is ASCII a
  423. }
  424. buf2 = buf1.slice(0, 3);
  425. sys.puts(buf2.toString('ascii', 0, buf2.length));
  426. buf1[0] = 33;
  427. sys.puts(buf2.toString('ascii', 0, buf2.length));
  428. // abc
  429. // !bc
  430. </code></pre>
  431. <h2 id="EventEmitter">EventEmitter</h2>
  432. <p>Many objects in Node emit events: a TCP server emits an event each time
  433. there is a stream, a child process emits an event when it exits. All
  434. objects which emit events are instances of <code>events.EventEmitter</code>.</p>
  435. <p>Events are represented by a camel-cased string. Here are some examples:
  436. <code>'stream'</code>, <code>'data'</code>, <code>'messageBegin'</code>.</p>
  437. <p>Functions can be then be attached to objects, to be executed when an event
  438. is emitted. These functions are called <em>listeners</em>.</p>
  439. <p><code>require('events').EventEmitter</code> to access the <code>EventEmitter</code> class.</p>
  440. <p>All EventEmitters emit the event <code>'newListener'</code> when new listeners are
  441. added.</p>
  442. <p>When an EventEmitter experiences an error, the typical action is to emit an
  443. <code>'error'</code> event. Error events are special--if there is no handler for them
  444. they will print a stack trace and exit the program.</p>
  445. <h3>Event: 'newListener'</h3>
  446. <p><code>function (event, listener) { }</code></p>
  447. <p>This event is made any time someone adds a new listener.</p>
  448. <h3>Event: 'error'</h3>
  449. <p><code>function (exception) { }</code></p>
  450. <p>If an error was encountered, then this event is emitted. This event is
  451. special - when there are no listeners to receive the error Node will
  452. terminate execution and display the exception's stack trace.</p>
  453. <h3>emitter.addListener(event, listener)</h3>
  454. <p>Adds a listener to the end of the listeners array for the specified event.</p>
  455. <pre><code>server.addListener('stream', function (stream) {
  456. sys.puts('someone connected!');
  457. });
  458. </code></pre>
  459. <h3>emitter.removeListener(event, listener)</h3>
  460. <p>Remove a listener from the listener array for the specified event.
  461. <strong>Caution</strong>: changes array indices in the listener array behind the listener.</p>
  462. <h3>emitter.removeAllListeners(event)</h3>
  463. <p>Removes all listeners from the listener array for the specified event.</p>
  464. <h3>emitter.listeners(event)</h3>
  465. <p>Returns an array of listeners for the specified event. This array can be
  466. manipulated, e.g. to remove listeners.</p>
  467. <h3>emitter.emit(event, arg1, arg2, ...)</h3>
  468. <p>Execute each of the listeners in order with the supplied arguments.</p>
  469. <h2 id="Streams">Streams</h2>
  470. <p>A stream is an abstract interface implemented by various objects in Node.
  471. For example a request to an HTTP server is a stream, as is stdout. Streams
  472. are readable, writable, or both. All streams are instances of <code>EventEmitter</code>.</p>
  473. <h2 id="Readable Stream">Readable Stream</h2>
  474. <p>A <strong>readable stream</strong> has the following methods, members, and events.</p>
  475. <h3>Event: 'data'</h3>
  476. <p><code>function (data) { }</code></p>
  477. <p>The <code>'data'</code> event emits either a <code>Buffer</code> (by default) or a string if
  478. <code>setEncoding()</code> was used.</p>
  479. <h3>Event: 'end'</h3>
  480. <p><code>function () { }</code></p>
  481. <p>Emitted when the stream has received an EOF (FIN in TCP terminology).
  482. Indicates that no more <code>'data'</code> events will happen. If the stream is also
  483. writable, it may be possible to continue writing.</p>
  484. <h3>Event: 'error'</h3>
  485. <p><code>function (exception) { }</code></p>
  486. <p>Emitted if there was an error receiving data.</p>
  487. <h3>Event: 'close'</h3>
  488. <p><code>function () { }</code></p>
  489. <p>Emitted when the underlying file descriptor has be closed. Not all streams
  490. will emit this. (For example, an incoming HTTP request will not emit
  491. <code>'close'</code>.)</p>
  492. <h3>stream.setEncoding(encoding)</h3>
  493. <p>Makes the data event emit a string instead of a <code>Buffer</code>. <code>encoding</code> can be
  494. <code>'utf8'</code>, <code>'ascii'</code>, or <code>'binary'</code>.</p>
  495. <h3>stream.pause()</h3>
  496. <p>Pauses the incoming <code>'data'</code> events.</p>
  497. <h3>stream.resume()</h3>
  498. <p>Resumes the incoming <code>'data'</code> events after a <code>pause()</code>.</p>
  499. <h3>stream.destroy()</h3>
  500. <p>Closes the underlying file descriptor. Stream will not emit any more events.</p>
  501. <h2 id="Writable Stream">Writable Stream</h2>
  502. <p>A <strong>writable stream</strong> has the following methods, members, and events.</p>
  503. <h3>Event: 'drain'</h3>
  504. <p><code>function () { }</code></p>
  505. <p>Emitted after a <code>write()</code> method was called that returned <code>false</code> to
  506. indicate that it is safe to write again.</p>
  507. <h3>Event: 'error'</h3>
  508. <p><code>function (exception) { }</code></p>
  509. <p>Emitted on error with the exception <code>exception</code>.</p>
  510. <h3>Event: 'close'</h3>
  511. <p><code>function () { }</code></p>
  512. <p>Emitted when the underlying file descriptor has been closed.</p>
  513. <h3>stream.write(string, encoding)</h3>
  514. <p>Writes <code>string</code> with the given <code>encoding</code> to the stream. Returns <code>true</code> if
  515. the string has been flushed to the kernel buffer. Returns <code>false</code> to
  516. indicate that the kernel buffer is full, and the data will be sent out in
  517. the future. The <code>'drain'</code> event will indicate when the kernel buffer is
  518. empty again. The <code>encoding</code> defaults to <code>'utf8'</code>.</p>
  519. <h3>stream.write(buffer)</h3>
  520. <p>Same as the above except with a raw buffer.</p>
  521. <h3>stream.end()</h3>
  522. <p>Terminates the stream with EOF or FIN.</p>
  523. <h3>stream.end(string, encoding)</h3>
  524. <p>Sends <code>string</code> with the given <code>encoding</code> and terminates the stream with EOF
  525. or FIN. This is useful to reduce the number of packets sent.</p>
  526. <h3>stream.end(buffer)</h3>
  527. <p>Same as above but with a <code>buffer</code>.</p>
  528. <h3>stream.destroy()</h3>
  529. <p>Closes the underlying file descriptor. Stream will not emit any more events.</p>
  530. <h2 id="Global Objects">Global Objects</h2>
  531. <p>These object are available in the global scope and can be accessed from anywhere.</p>
  532. <h3>global</h3>
  533. <p>The global namespace object.</p>
  534. <h3>process</h3>
  535. <p>The process object. Most stuff lives in here. See the <code>'process object'</code>
  536. section.</p>
  537. <h3>require()</h3>
  538. <p>To require modules. See the <code>'Modules'</code> section.</p>
  539. <h3>require.paths</h3>
  540. <p>An array of search paths for <code>require()</code>. This array can be modified to add custom paths.</p>
  541. <p>Example: add a new path to the beginning of the search list</p>
  542. <pre><code>var sys = require('sys');
  543. require.paths.unshift('/usr/local/node');
  544. sys.puts(require.paths);
  545. // /usr/local/node,/Users/mjr/.node_libraries
  546. </code></pre>
  547. <h3>__filename</h3>
  548. <p>The filename of the script being executed. This is the absolute path, and not necessarily
  549. the same filename passed in as a command line argument.</p>
  550. <h3>__dirname</h3>
  551. <p>The dirname of the script being executed.</p>
  552. <p>Example: running <code>node example.js</code> from <code>/Users/mjr</code></p>
  553. <pre><code>var sys = require('sys');
  554. sys.puts(__filename);
  555. sys.puts(__dirname);
  556. // /Users/mjr/example.js
  557. // /Users/mjr
  558. </code></pre>
  559. <h3>module</h3>
  560. <p>A reference to the current module (of type <code>process.Module</code>). In particular
  561. <code>module.exports</code> is the same as the <code>exports</code> object. See <code>src/process.js</code>
  562. for more information.</p>
  563. <h2 id="process">process</h2>
  564. <p>The <code>process</code> object is a global object and can be accessed from anywhere.
  565. It is an instance of <code>EventEmitter</code>.</p>
  566. <h3>Event: 'exit'</h3>
  567. <p><code>function () {}</code></p>
  568. <p>Emitted when the process is about to exit. This is a good hook to perform
  569. constant time checks of the module's state (like for unit tests). The main
  570. event loop will no longer be run after the 'exit' callback finishes, so
  571. timers may not be scheduled.</p>
  572. <p>Example of listening for <code>exit</code>:</p>
  573. <pre><code>var sys = require('sys');
  574. process.addListener('exit', function () {
  575. process.nextTick(function () {
  576. sys.puts('This will not run');
  577. });
  578. sys.puts('About to exit.');
  579. });
  580. </code></pre>
  581. <h3>Event: 'uncaughtException'</h3>
  582. <p><code>function (err) { }</code></p>
  583. <p>Emitted when an exception bubbles all the way back to the event loop. If a
  584. listener is added for this exception, the default action (which is to print
  585. a stack trace and exit) will not occur.</p>
  586. <p>Example of listening for <code>uncaughtException</code>:</p>
  587. <pre><code>var sys = require('sys');
  588. process.addListener('uncaughtException', function (err) {
  589. sys.puts('Caught exception: ' + err);
  590. });
  591. setTimeout(function () {
  592. sys.puts('This will still run.');
  593. }, 500);
  594. // Intentionally cause an exception, but don't catch it.
  595. nonexistentFunc();
  596. sys.puts('This will not run.');
  597. </code></pre>
  598. <p>Note that <code>uncaughtException</code> is a very crude mechanism for exception
  599. handling. Using try / catch in your program will give you more control over
  600. your program's flow. Especially for server programs that are designed to
  601. stay running forever, <code>uncaughtException</code> can be a useful safety mechanism.</p>
  602. <h3>Signal Events</h3>
  603. <p><code>function () {}</code></p>
  604. <p>Emitted when the processes receives a signal. See sigaction(2) for a list of
  605. standard POSIX signal names such as SIGINT, SIGUSR1, etc.</p>
  606. <p>Example of listening for <code>SIGINT</code>:</p>
  607. <pre><code>var sys = require('sys'),
  608. stdin = process.openStdin();
  609. process.addListener('SIGINT', function () {
  610. sys.puts('Got SIGINT. Press Control-D to exit.');
  611. });
  612. </code></pre>
  613. <p>An easy way to send the <code>SIGINT</code> signal is with <code>Control-C</code> in most terminal
  614. programs.</p>
  615. <h3>process.stdout</h3>
  616. <p>A writable stream to <code>stdout</code>.</p>
  617. <p>Example: the definition of <code>sys.puts</code></p>
  618. <pre><code>exports.puts = function (d) {
  619. process.stdout.write(d + '\n');
  620. };
  621. </code></pre>
  622. <h3>process.openStdin()</h3>
  623. <p>Opens the standard input stream, returns a readable stream.</p>
  624. <p>Example of opening standard input and listening for both events:</p>
  625. <pre><code>var stdin = process.openStdin();
  626. stdin.setEncoding('utf8');
  627. stdin.addListener('data', function (chunk) {
  628. process.stdout.write('data: ' + chunk);
  629. });
  630. stdin.addListener('end', function () {
  631. process.stdout.write('end');
  632. });
  633. </code></pre>
  634. <h3>process.argv</h3>
  635. <p>An array containing the command line arguments. The first element will be
  636. 'node', the second element will be the name of the JavaScript file. The
  637. next elements will be any additional command line arguments.</p>
  638. <pre><code>// print process.argv
  639. var sys = require('sys');
  640. process.argv.forEach(function (val, index, array) {
  641. sys.puts(index + ': ' + val);
  642. });
  643. </code></pre>
  644. <p>This will generate:</p>
  645. <pre><code>$ node process-2.js one two=three four
  646. 0: node
  647. 1: /Users/mjr/work/node/process-2.js
  648. 2: one
  649. 3: two=three
  650. 4: four
  651. </code></pre>
  652. <h3>process.chdir(directory)</h3>
  653. <p>Changes the current working directory of the process or throws an exception if that fails.</p>
  654. <pre><code>var sys = require('sys');
  655. sys.puts('Starting directory: ' + process.cwd());
  656. try {
  657. process.chdir('/tmp');
  658. sys.puts('New directory: ' + process.cwd());
  659. }
  660. catch (err) {
  661. sys.puts('chdir: ' + err);
  662. }
  663. </code></pre>
  664. <h3>process.compile(code, filename)</h3>
  665. <p>Similar to <code>eval</code> except that you can specify a <code>filename</code> for better
  666. error reporting and the <code>code</code> cannot see the local scope. The value of <code>filename</code>
  667. will be used as a filename if a stack trace is generated by the compiled code.</p>
  668. <p>Example of using <code>process.compile</code> and <code>eval</code> to run the same code:</p>
  669. <pre><code>var sys = require('sys'),
  670. localVar = 123,
  671. compiled, evaled;
  672. compiled = process.compile('localVar = 1;', 'myfile.js');
  673. sys.puts('localVar: ' + localVar + ', compiled: ' + compiled);
  674. evaled = eval('localVar = 1;');
  675. sys.puts('localVar: ' + localVar + ', evaled: ' + evaled);
  676. // localVar: 123, compiled: 1
  677. // localVar: 1, evaled: 1
  678. </code></pre>
  679. <p><code>process.compile</code> does not have access to the local scope, so <code>localVar</code> is unchanged.
  680. <code>eval</code> does have access to the local scope, so <code>localVar</code> is changed.</p>
  681. <p>In case of syntax error in <code>code</code>, <code>process.compile</code> exits node.</p>
  682. <p>See also: <code>Script</code></p>
  683. <h3>process.cwd()</h3>
  684. <p>Returns the current working directory of the process.</p>
  685. <pre><code>require('sys').puts('Current directory: ' + process.cwd());
  686. </code></pre>
  687. <h3>process.env</h3>
  688. <p>An object containing the user environment. See environ(7).</p>
  689. <h3>process.exit(code)</h3>
  690. <p>Ends the process with the specified <code>code</code>. If omitted, exit uses the
  691. 'success' code <code>0</code>.</p>
  692. <p>To exit with a 'failure' code:</p>
  693. <pre><code>process.exit(1);
  694. </code></pre>
  695. <p>The shell that executed node should see the exit code as 1.</p>
  696. <h3>process.getgid(), process.setgid(id)</h3>
  697. <p>Gets/sets the group identity of the process. (See setgid(2).) This is the numerical group id, not the group name.</p>
  698. <pre><code>var sys = require('sys');
  699. sys.puts('Current gid: ' + process.getgid());
  700. try {
  701. process.setgid(501);
  702. sys.puts('New gid: ' + process.getgid());
  703. }
  704. catch (err) {
  705. sys.puts('Failed to set gid: ' + err);
  706. }
  707. </code></pre>
  708. <h3>process.getuid(), process.setuid(id)</h3>
  709. <p>Gets/sets the user identity of the process. (See setuid(2).) This is the numerical userid, not the username.</p>
  710. <pre><code>var sys = require('sys');
  711. sys.puts('Current uid: ' + process.getuid());
  712. try {
  713. process.setuid(501);
  714. sys.puts('New uid: ' + process.getuid());
  715. }
  716. catch (err) {
  717. sys.puts('Failed to set uid: ' + err);
  718. }
  719. </code></pre>
  720. <h3>process.version</h3>
  721. <p>A compiled-in property that exposes <code>NODE_VERSION</code>.</p>
  722. <pre><code>require('sys').puts('Version: ' + process.version);
  723. </code></pre>
  724. <h3>process.installPrefix</h3>
  725. <p>A compiled-in property that exposes <code>NODE_PREFIX</code>.</p>
  726. <pre><code>require('sys').puts('Prefix: ' + process.installPrefix);
  727. </code></pre>
  728. <h3>process.kill(pid, signal)</h3>
  729. <p>Send a signal to a process. <code>pid</code> is the process id and <code>signal</code> is the
  730. string describing the signal to send. Signal names are strings like
  731. 'SIGINT' or 'SIGUSR1'. If omitted, the signal will be 'SIGINT'.
  732. See kill(2) for more information.</p>
  733. <p>Note that just because the name of this function is <code>process.kill</code>, it is
  734. really just a signal sender, like the <code>kill</code> system call. The signal sent
  735. may do something other than kill the target process.</p>
  736. <p>Example of sending a signal to yourself:</p>
  737. <pre><code>var sys = require('sys');
  738. process.addListener('SIGHUP', function () {
  739. sys.puts('Got SIGHUP signal.');
  740. });
  741. setTimeout(function () {
  742. sys.puts('Exiting.');
  743. process.exit(0);
  744. }, 100);
  745. process.kill(process.pid, 'SIGHUP');
  746. </code></pre>
  747. <h3>process.pid</h3>
  748. <p>The PID of the process.</p>
  749. <pre><code>require('sys').puts('This process is pid ' + process.pid);
  750. </code></pre>
  751. <h3>process.platform</h3>
  752. <p>What platform you're running on. <code>'linux2'</code>, <code>'darwin'</code>, etc.</p>
  753. <pre><code>require('sys').puts('This platform is ' + process.platform);
  754. </code></pre>
  755. <h3>process.memoryUsage()</h3>
  756. <p>Returns an object describing the memory usage of the Node process.</p>
  757. <pre><code>var sys = require('sys');
  758. sys.puts(sys.inspect(process.memoryUsage()));
  759. </code></pre>
  760. <p>This will generate:</p>
  761. <pre><code>{ rss: 4935680
  762. , vsize: 41893888
  763. , heapTotal: 1826816
  764. , heapUsed: 650472
  765. }
  766. </code></pre>
  767. <p><code>heapTotal</code> and <code>heapUsed</code> refer to V8's memory usage.</p>
  768. <h3>process.nextTick(callback)</h3>
  769. <p>On the next loop around the event loop call this callback.
  770. This is <em>not</em> a simple alias to <code>setTimeout(fn, 0)</code>, it's much more
  771. efficient.</p>
  772. <pre><code>var sys = require('sys');
  773. process.nextTick(function () {
  774. sys.puts('nextTick callback');
  775. });
  776. </code></pre>
  777. <h3>process.umask(mask)</h3>
  778. <p>Sets or read the process's file mode creation mask. Child processes inherit
  779. the mask from the parent process. Returns the old mask if <code>mask</code> argument is
  780. given, otherwise returns the current mask.</p>
  781. <pre><code>var sys = require('sys'),
  782. oldmask, newmask = 0644;
  783. oldmask = process.umask(newmask);
  784. sys.puts('Changed umask from: ' + oldmask.toString(8) +
  785. ' to ' + newmask.toString(8));
  786. </code></pre>
  787. <h2 id="sys">sys</h2>
  788. <p>These functions are in the module <code>'sys'</code>. Use <code>require('sys')</code> to access
  789. them.</p>
  790. <h3>sys.puts(string)</h3>
  791. <p>Outputs <code>string</code> and a trailing newline to <code>stdout</code>.</p>
  792. <pre><code>require('sys').puts('String with a newline');
  793. </code></pre>
  794. <h3>sys.print(string)</h3>
  795. <p>Like <code>puts()</code> but without the trailing newline.</p>
  796. <pre><code>require('sys').print('String with no newline');
  797. </code></pre>
  798. <h3>sys.debug(string)</h3>
  799. <p>A synchronous output function. Will block the process and
  800. output <code>string</code> immediately to <code>stderr</code>.</p>
  801. <pre><code>require('sys').debug('message on stderr');
  802. </code></pre>
  803. <h3>sys.log(string)</h3>
  804. <p>Output with timestamp on <code>stdout</code>.</p>
  805. <pre><code>require('sys').log('Timestmaped message.');
  806. </code></pre>
  807. <h3>sys.inspect(object, showHidden, depth)</h3>
  808. <p>Return a string representation of <code>object</code>, which is useful for debugging.</p>
  809. <p>If <code>showHidden</code> is <code>true</code>, then the object's non-enumerable properties will be
  810. shown too.</p>
  811. <p>If <code>depth</code> is provided, it tells <code>inspect</code> how many times to recurse while
  812. formatting the object. This is useful for inspecting large complicated objects.</p>
  813. <p>The default is to only recurse twice. To make it recurse indefinitely, pass
  814. in <code>null</code> for <code>depth</code>.</p>
  815. <p>Example of inspecting all properties of the <code>sys</code> object:</p>
  816. <pre><code>var sys = require('sys');
  817. sys.puts(sys.inspect(sys, true, null));
  818. </code></pre>
  819. <h2 id="Timers">Timers</h2>
  820. <h3>setTimeout(callback, delay, [arg, ...])</h3>
  821. <p>To schedule execution of <code>callback</code> after <code>delay</code> milliseconds. Returns a
  822. <code>timeoutId</code> for possible use with <code>clearTimeout()</code>.</p>
  823. <h3>clearTimeout(timeoutId)</h3>
  824. <p>Prevents a timeout from triggering.</p>
  825. <h3>setInterval(callback, delay, [arg, ...])</h3>
  826. <p>To schedule the repeated execution of <code>callback</code> every <code>delay</code> milliseconds.
  827. Returns a <code>intervalId</code> for possible use with <code>clearInterval()</code>.</p>
  828. <p>Optionally, you can also pass arguments to the callback.</p>
  829. <h3>clearInterval(intervalId)</h3>
  830. <p>Stops a interval from triggering.</p>
  831. <h2 id="Child Processes">Child Processes</h2>
  832. <p>Node provides a tri-directional <code>popen(3)</code> facility through the <code>ChildProcess</code>
  833. class.</p>
  834. <p>It is possible to stream data through the child's <code>stdin</code>, <code>stdout</code>, and
  835. <code>stderr</code> in a fully non-blocking way.</p>
  836. <p>To create a child process use <code>require('child_process').spawn()</code>.</p>
  837. <p>Child processes always have three streams associated with them. <code>child.stdin</code>,
  838. <code>child.stdout</code>, and <code>child.stderr</code>.</p>
  839. <p><code>ChildProcess</code> is an EventEmitter.</p>
  840. <h3>Event: 'exit'</h3>
  841. <p><code>function (code, signal) {}</code></p>
  842. <p>This event is emitted after the child process ends. If the process terminated
  843. normally, <code>code</code> is the final exit code of the process, otherwise <code>null</code>. If
  844. the process terminated due to receipt of a signal, <code>signal</code> is the string name
  845. of the signal, otherwise <code>null</code>.</p>
  846. <p>After this event is emitted, the <code>'output'</code> and <code>'error'</code> callbacks will no
  847. longer be made.</p>
  848. <p>See <code>waitpid(2)</code>.</p>
  849. <h3>child_process.spawn(command, args, env)</h3>
  850. <p>Launches a new process with the given <code>command</code>, command line arguments, and
  851. environment variables. If omitted, <code>args</code> defaults to an empty Array, and <code>env</code>
  852. defaults to <code>process.env</code>.</p>
  853. <p>Example of running <code>ls -lh /usr</code>, capturing <code>stdout</code>, <code>stderr</code>, and the exit code:</p>
  854. <pre><code>var sys = require('sys'),
  855. spawn = require('child_process').spawn,
  856. ls = spawn('ls', ['-lh', '/usr']);
  857. ls.stdout.addListener('data', function (data) {
  858. sys.print('stdout: ' + data);
  859. });
  860. ls.stderr.addListener('data', function (data) {
  861. sys.print('stderr: ' + data);
  862. });
  863. ls.addListener('exit', function (code) {
  864. sys.puts('child process exited with code ' + code);
  865. });
  866. </code></pre>
  867. <p>Example of checking for failed exec:</p>
  868. <pre><code>var sys = require('sys'),
  869. spawn = require('child_process').spawn,
  870. child = spawn('bad_command');
  871. child.stderr.addListener('data', function (data) {
  872. if (/^execvp\(\)/.test(data.asciiSlice(0,data.length))) {
  873. sys.puts('Failed to start child process.');
  874. }
  875. });
  876. </code></pre>
  877. <p>See also: <code>child_process.exec()</code></p>
  878. <h3>child.kill(signal)</h3>
  879. <p>Send a signal to the child process. If no argument is given, the process will
  880. be sent <code>'SIGTERM'</code>. See <code>signal(7)</code> for a list of available signals.</p>
  881. <pre><code>var sys = require('sys'),
  882. spawn = require('child_process').spawn,
  883. grep = spawn('grep', ['ssh']);
  884. grep.addListener('exit', function (code, signal) {
  885. sys.puts('child process terminated due to receipt of signal '+signal);
  886. });
  887. // send SIGHUP to process
  888. grep.kill('SIGHUP');
  889. </code></pre>
  890. <p>Note that while the function is called <code>kill</code>, the signal delivered to the child
  891. process may not actually kill it. <code>kill</code> really just sends a signal to a process.</p>
  892. <p>See <code>kill(2)</code></p>
  893. <h3>child.pid</h3>
  894. <p>The PID of the child process.</p>
  895. <p>Example:</p>
  896. <pre><code>var sys = require('sys'),
  897. spawn = require('child_process').spawn,
  898. grep = spawn('grep', ['ssh']);
  899. sys.puts('Spawned child pid: ' + grep.pid);
  900. grep.stdin.end();
  901. </code></pre>
  902. <h3>child.stdin.write(data, encoding)</h3>
  903. <p>Write data to the child process's <code>stdin</code>. The second argument is optional and
  904. specifies the encoding: possible values are <code>'utf8'</code>, <code>'ascii'</code>, and
  905. <code>'binary'</code>.</p>
  906. <p>Example: A very elaborate way to run 'ps ax | grep ssh'</p>
  907. <pre><code>var sys = require('sys'),
  908. spawn = require('child_process').spawn,
  909. ps = spawn('ps', ['ax']),
  910. grep = spawn('grep', ['ssh']);
  911. ps.stdout.addListener('data', function (data) {
  912. grep.stdin.write(data);
  913. });
  914. ps.stderr.addListener('data', function (data) {
  915. sys.print('ps stderr: ' + data);
  916. });
  917. ps.addListener('exit', function (code) {
  918. if (code !== 0) {
  919. sys.puts('ps process exited with code ' + code);
  920. }
  921. grep.stdin.end();
  922. });
  923. grep.stdout.addListener('data', function (data) {
  924. sys.print(data);
  925. });
  926. grep.stderr.addListener('data', function (data) {
  927. sys.print('grep stderr: ' + data);
  928. });
  929. grep.addListener('exit', function (code) {
  930. if (code !== 0) {
  931. sys.puts('grep process exited with code ' + code);
  932. }
  933. });
  934. </code></pre>
  935. <h3>child.stdin.end()</h3>
  936. <p>Closes the child process's <code>stdin</code> stream. This often causes the child process to terminate.</p>
  937. <p>Example:</p>
  938. <pre><code>var sys = require('sys'),
  939. spawn = require('child_process').spawn,
  940. grep = spawn('grep', ['ssh']);
  941. grep.addListener('exit', function (code) {
  942. sys.puts('child process exited with code ' + code);
  943. });
  944. grep.stdin.end();
  945. </code></pre>
  946. <h3>child_process.exec(command, [options, ] callback)</h3>
  947. <p>High-level way to execute a command as a child process, buffer the
  948. output, and return it all in a callback.</p>
  949. <pre><code>var sys = require('sys'),
  950. exec = require('child_process').exec,
  951. child;
  952. child = exec('cat *.js bad_file | wc -l',
  953. function (error, stdout, stderr) {
  954. sys.print('stdout: ' + stdout);
  955. sys.print('stderr: ' + stderr);
  956. if (error !== null) {
  957. sys.puts('exec error: ' + error);
  958. }
  959. });
  960. </code></pre>
  961. <p>The callback gets the arguments <code>(error, stdout, stderr)</code>. On success, <code>error</code>
  962. will be <code>null</code>. On error, <code>error</code> will be an instance of <code>Error</code> and <code>err.code</code>
  963. will be the exit code of the child process, and <code>err.signal</code> will be set to the
  964. signal that terminated the process.</p>
  965. <p>There is a second optional argument to specify several options. The default options are</p>
  966. <pre><code>{ encoding: 'utf8'
  967. , timeout: 0
  968. , maxBuffer: 200*1024
  969. , killSignal: 'SIGKILL'
  970. }
  971. </code></pre>
  972. <p>If <code>timeout</code> is greater than 0, then it will kill the child process
  973. if it runs longer than <code>timeout</code> milliseconds. The child process is killed with
  974. <code>killSignal</code> (default: <code>'SIGKILL'</code>). <code>maxBuffer</code> specifies the largest
  975. amount of data allowed on stdout or stderr - if this value is exceeded then
  976. the child process is killed.</p>
  977. <h2 id="Script">Script</h2>
  978. <p><code>Script</code> class compiles and runs JavaScript code. You can access this class with:</p>
  979. <pre><code>var Script = process.binding('evals').Script;
  980. </code></pre>
  981. <p>New JavaScript code can be compiled and run immediately or compiled, saved, and run later.</p>
  982. <h3>Script.runInThisContext(code, filename)</h3>
  983. <p>Similar to <code>process.compile</code>. <code>Script.runInThisContext</code> compiles <code>code</code> as if it were loaded from <code>filename</code>,
  984. runs it and returns the result. Running code does not have access to local scope. <code>filename</code> is optional.</p>
  985. <p>Example of using <code>Script.runInThisContext</code> and <code>eval</code> to run the same code:</p>
  986. <pre><code>var sys = require('sys'),
  987. localVar = 123,
  988. usingscript, evaled,
  989. Script = process.binding('evals').Script;
  990. usingscript = Script.runInThisContext('localVar = 1;',
  991. 'myfile.js');
  992. sys.puts('localVar: ' + localVar + ', usingscript: ' +
  993. usingscript);
  994. evaled = eval('localVar = 1;');
  995. sys.puts('localVar: ' + localVar + ', evaled: ' +
  996. evaled);
  997. // localVar: 123, usingscript: 1
  998. // localVar: 1, evaled: 1
  999. </code></pre>
  1000. <p><code>Script.runInThisContext</code> does not have access to the local scope, so <code>localVar</code> is unchanged.
  1001. <code>eval</code> does have access to the local scope, so <code>localVar</code> is changed.</p>
  1002. <p>In case of syntax error in <code>code</code>, <code>Script.runInThisContext</code> emits the syntax error to stderr
  1003. and throws.an exception.</p>
  1004. <h3>Script.runInNewContext(code, sandbox, filename)</h3>
  1005. <p><code>Script.runInNewContext</code> compiles <code>code</code> to run in <code>sandbox</code> as if it were loaded from <code>filename</code>,
  1006. then runs it and returns the result. Running code does not have access to local scope and
  1007. the object <code>sandbox</code> will be used as the global object for <code>code</code>.
  1008. <code>sandbox</code> and <code>filename</code> are optional.</p>
  1009. <p>Example: compile and execute code that increments a global variable and sets a new one.
  1010. These globals are contained in the sandbox.</p>
  1011. <pre><code>var sys = require('sys'),
  1012. Script = process.binding('evals').Script,
  1013. sandbox = {
  1014. animal: 'cat',
  1015. count: 2
  1016. };
  1017. Script.runInNewContext(
  1018. 'count += 1; name = "kitty"', sandbox, 'myfile.js');
  1019. sys.puts(sys.inspect(sandbox));
  1020. // { animal: 'cat', count: 3, name: 'kitty' }
  1021. </code></pre>
  1022. <p>Note that running untrusted code is a tricky business requiring great care. To prevent accidental
  1023. global variable leakage, <code>Script.runInNewContext</code> is quite useful, but safely running untrusted code
  1024. requires a separate process.</p>
  1025. <p>In case of syntax error in <code>code</code>, <code>Script.runInThisContext</code> emits the syntax error to stderr
  1026. and throws an exception.</p>
  1027. <h3>new Script(code, filename)</h3>
  1028. <p><code>new Script</code> compiles <code>code</code> as if it were loaded from <code>filename</code>,
  1029. but does not run it. Instead, it returns a <code>Script</code> object representing this compiled code.
  1030. This script can be run later many times using methods below.
  1031. The returned script is not bound to any global object.
  1032. It is bound before each run, just for that run. <code>filename</code> is optional.</p>
  1033. <p>In case of syntax error in <code>code</code>, <code>new Script</code> emits the syntax error to stderr
  1034. and throws an exception.</p>
  1035. <h3>script.runInThisContext()</h3>
  1036. <p>Similar to <code>Script.runInThisContext</code> (note capital 'S'), but now being a method of a precompiled Script object.
  1037. <code>script.runInThisContext</code> runs the code of <code>script</code> and returns the result.
  1038. Running code does not have access to local scope, but does have access to the <code>global</code> object
  1039. (v8: in actual context).</p>
  1040. <p>Example of using <code>script.runInThisContext</code> to compile code once and run it multiple times:</p>
  1041. <pre><code>var sys = require('sys'),
  1042. Script = process.binding('evals').Script,
  1043. scriptObj, i;
  1044. globalVar = 0;
  1045. scriptObj = new Script('globalVar += 1', 'myfile.js');
  1046. for (i = 0; i &lt; 1000 ; i += 1) {
  1047. scriptObj.runInThisContext();
  1048. }
  1049. sys.puts(globalVar);
  1050. // 1000
  1051. </code></pre>
  1052. <h3>script.runInNewContext(sandbox)</h3>
  1053. <p>Similar to <code>Script.runInNewContext</code> (note capital 'S'), but now being a method of a precompiled Script object.
  1054. <code>script.runInNewContext</code> runs the code of <code>script</code> with <code>sandbox</code> as the global object and returns the result.
  1055. Running code does not have access to local scope. <code>sandbox</code> is optional.</p>
  1056. <p>Example: compile code that increments a global variable and sets one, then execute this code multiple times.
  1057. These globals are contained in the sandbox.</p>
  1058. <pre><code>var sys = require('sys'),
  1059. Script = process.binding('evals').Script,
  1060. scriptObj, i,
  1061. sandbox = {
  1062. animal: 'cat',
  1063. count: 2
  1064. };
  1065. scriptObj = new Script(
  1066. 'count += 1; name = "kitty"', 'myfile.js');
  1067. for (i = 0; i &lt; 10 ; i += 1) {
  1068. scriptObj.runInNewContext(sandbox);
  1069. }
  1070. sys.puts(sys.inspect(sandbox));
  1071. // { animal: 'cat', count: 12, name: 'kitty' }
  1072. </code></pre>
  1073. <p>Note that running untrusted code is a tricky business requiring great care. To prevent accidental
  1074. global variable leakage, <code>script.runInNewContext</code> is quite useful, but safely running untrusted code
  1075. requires a separate process.</p>
  1076. <h2 id="File System">File System</h2>
  1077. <p>File I/O is provided by simple wrappers around standard POSIX functions. To
  1078. use this module do <code>require('fs')</code>. All the methods have asynchronous and
  1079. synchronous forms.</p>
  1080. <p>The asynchronous form always take a completion callback as its last argument.
  1081. The arguments passed to the completion callback depend on the method, but the
  1082. first argument is always reserved for an exception. If the operation was
  1083. completed successfully, then the first argument will be <code>null</code> or <code>undefined</code>.</p>
  1084. <p>Here is an example of the asynchronous version:</p>
  1085. <pre><code>var fs = require('fs'),
  1086. sys = require('sys');
  1087. fs.unlink('/tmp/hello', function (err) {
  1088. if (err) throw err;
  1089. sys.puts('successfully deleted /tmp/hello');
  1090. });
  1091. </code></pre>
  1092. <p>Here is the synchronous version:</p>
  1093. <pre><code>var fs = require('fs'),
  1094. sys = require('sys');
  1095. fs.unlinkSync('/tmp/hello')
  1096. sys.puts('successfully deleted /tmp/hello');
  1097. </code></pre>
  1098. <p>With the asynchronous methods there is no guaranteed ordering. So the
  1099. following is prone to error:</p>
  1100. <pre><code>fs.rename('/tmp/hello', '/tmp/world', function (err) {
  1101. if (err) throw err;
  1102. sys.puts('renamed complete');
  1103. });
  1104. fs.stat('/tmp/world', function (err, stats) {
  1105. if (err) throw err;
  1106. sys.puts('stats: ' + JSON.stringify(stats));
  1107. });
  1108. </code></pre>
  1109. <p>It could be that <code>fs.stat</code> is executed before <code>fs.rename</code>.
  1110. The correct way to do this is to chain the callbacks.</p>
  1111. <pre><code>fs.rename('/tmp/hello', '/tmp/world', function (err) {
  1112. if (err) throw err;
  1113. fs.stat('/tmp/world', function (err, stats) {
  1114. if (err) throw err;
  1115. sys.puts('stats: ' + JSON.stringify(stats));
  1116. });
  1117. });
  1118. </code></pre>
  1119. <p>In busy processes, the programmer is <em>strongly encouraged</em> to use the
  1120. asynchronous versions of these calls. The synchronous versions will block
  1121. the entire process until they complete--halting all connections.</p>
  1122. <h3>fs.rename(path1, path2, callback)</h3>
  1123. <p>Asynchronous rename(2). No arguments other than a possible exception are given to the completion callback.</p>
  1124. <h3>fs.renameSync(path1, path2)</h3>
  1125. <p>Synchronous rename(2).</p>
  1126. <h3>fs.truncate(fd, len, callback)</h3>
  1127. <p>Asynchronous ftruncate(2). No arguments other than a possible exception are given to the completion callback.</p>
  1128. <h3>fs.truncateSync(fd, len)</h3>
  1129. <p>Synchronous ftruncate(2).</p>
  1130. <h3>fs.chmod(path, mode, callback)</h3>
  1131. <p>Asynchronous chmod(2). No arguments other than a possible exception are given to the completion callback.</p>
  1132. <h3>fs.chmodSync(path, mode)</h3>
  1133. <p>Synchronous chmod(2).</p>
  1134. <h3>fs.stat(path, callback), fs.lstat(path, callback), fs.fstat(fd, callback)</h3>
  1135. <p>Asynchronous stat(2), lstat(2) or fstat(2). The callback gets two arguments <code>(err, stats)</code> where <code>stats</code> is a <code>fs.Stats</code> object. It looks like this:</p>
  1136. <pre><code>{ dev: 2049
  1137. , ino: 305352
  1138. , mode: 16877
  1139. , nlink: 12
  1140. , uid: 1000
  1141. , gid: 1000
  1142. , rdev: 0
  1143. , size: 4096
  1144. , blksize: 4096
  1145. , blocks: 8
  1146. , atime: '2009-06-29T11:11:55Z'
  1147. , mtime: '2009-06-29T11:11:40Z'
  1148. , ctime: '2009-06-29T11:11:40Z'
  1149. }
  1150. </code></pre>
  1151. <p>See the <code>fs.Stats</code> section below for more information.</p>
  1152. <h3>fs.statSync(path), fs.lstatSync(path), fs.fstatSync(fd)</h3>
  1153. <p>Synchronous stat(2), lstat(2) or fstat(2). Returns an instance of <code>fs.Stats</code>.</p>
  1154. <h3>fs.link(srcpath, dstpath, callback)</h3>
  1155. <p>Asynchronous link(2). No arguments other than a possible exception are given to the completion callback.</p>
  1156. <h3>fs.linkSync(dstpath, srcpath)</h3>
  1157. <p>Synchronous link(2).</p>
  1158. <h3>fs.symlink(linkdata, path, callback)</h3>
  1159. <p>Asynchronous symlink(2). No arguments other than a possible exception are given to the completion callback.</p>
  1160. <h3>fs.symlinkSync(linkdata, path)</h3>
  1161. <p>Synchronous symlink(2).</p>
  1162. <h3>fs.readlink(path, callback)</h3>
  1163. <p>Asynchronous readlink(2). The callback gets two arguments <code>(err, resolvedPath)</code>.</p>
  1164. <h3>fs.readlinkSync(path)</h3>
  1165. <p>Synchronous readlink(2). Returns the resolved path.</p>
  1166. <h3>fs.realpath(path, callback)</h3>
  1167. <p>Asynchronous realpath(2). The callback gets two arguments <code>(err, resolvedPath)</code>.</p>
  1168. <h3>fs.realpathSync(path)</h3>
  1169. <p>Synchronous realpath(2). Returns the resolved path.</p>
  1170. <h3>fs.unlink(path, callback)</h3>
  1171. <p>Asynchronous unlink(2). No arguments other than a possible exception are given to the completion callback.</p>
  1172. <h3>fs.unlinkSync(path)</h3>
  1173. <p>Synchronous unlink(2).</p>
  1174. <h3>fs.rmdir(path, callback)</h3>
  1175. <p>Asynchronous rmdir(2). No arguments other than a possible exception are given to the completion callback.</p>
  1176. <h3>fs.rmdirSync(path)</h3>
  1177. <p>Synchronous rmdir(2).</p>
  1178. <h3>fs.mkdir(path, mode, callback)</h3>
  1179. <p>Asynchronous mkdir(2). No arguments other than a possible exception are given to the completion callback.</p>
  1180. <h3>fs.mkdirSync(path, mode)</h3>
  1181. <p>Synchronous mkdir(2).</p>
  1182. <h3>fs.readdir(path, callback)</h3>
  1183. <p>Asynchronous readdir(3). Reads the contents of a directory.
  1184. The callback gets two arguments <code>(err, files)</code> where <code>files</code> is an array of
  1185. the names of the files in the directory excluding <code>'.'</code> and <code>'..'</code>.</p>
  1186. <h3>fs.readdirSync(path)</h3>
  1187. <p>Synchronous readdir(3). Returns an array of filenames excluding <code>'.'</code> and
  1188. <code>'..'</code>.</p>
  1189. <h3>fs.close(fd, callback)</h3>
  1190. <p>Asynchronous close(2). No arguments other than a possible exception are given to the completion callback.</p>
  1191. <h3>fs.closeSync(fd)</h3>
  1192. <p>Synchronous close(2).</p>
  1193. <h3>fs.open(path, flags, mode, callback)</h3>
  1194. <p>Asynchronous file open. See open(2). Flags can be 'r', 'r+', 'w', 'w+', 'a',
  1195. or 'a+'. The callback gets two arguments <code>(err, fd)</code>.</p>
  1196. <h3>fs.openSync(path, flags, mode)</h3>
  1197. <p>Synchronous open(2).</p>
  1198. <h3>fs.write(fd, buffer, offset, length, position, callback)</h3>
  1199. <p>Write <code>buffer</code> to the file specified by <code>fd</code>.</p>
  1200. <p><code>offset</code> and <code>length</code> determine the part of the buffer to be written.</p>
  1201. <p><code>position</code> refers to the offset from the beginning of the file where this data
  1202. should be written. If <code>position</code> is <code>null</code>, the data will be written at the
  1203. current position.
  1204. See pwrite(2).</p>
  1205. <p>The callback will be given two arguments <code>(err, written)</code> where <code>written</code>
  1206. specifies how many <em>bytes</em> were written.</p>
  1207. <h3>fs.writeSync(fd, data, position, encoding)</h3>
  1208. <p>Synchronous version of <code>fs.write()</code>. Returns the number of bytes written.</p>
  1209. <h3>fs.read(fd, buffer, offset, length, position, callback)</h3>
  1210. <p>Read data from the file specified by <code>fd</code>.</p>
  1211. <p><code>buffer</code> is the buffer that the data will be written to.</p>
  1212. <p><code>offset</code> is offset within the buffer where writing will start.</p>
  1213. <p><code>length</code> is an integer specifying the number of bytes to read.</p>
  1214. <p><code>position</code> is an integer specifying where to begin reading from in the file.
  1215. If <code>position</code> is <code>null</code>, data will be read from the current file position.</p>
  1216. <p>The callback is given the two arguments, <code>(err, bytesRead)</code>.</p>
  1217. <h3>fs.readSync(fd, buffer, offset, length, position)</h3>
  1218. <p>Synchronous version of <code>fs.read</code>. Returns the number of <code>bytesRead</code>.</p>
  1219. <h3>fs.readFile(filename, [encoding,] callback)</h3>
  1220. <p>Asynchronously reads the entire contents of a file. Example:</p>
  1221. <pre><code>fs.readFile('/etc/passwd', function (err, data) {
  1222. if (err) throw err;
  1223. sys.puts(data);
  1224. });
  1225. </code></pre>
  1226. <p>The callback is passed two arguments <code>(err, data)</code>, where <code>data</code> is the
  1227. contents of the file.</p>
  1228. <p>If no encoding is specified, then the raw buffer is returned.</p>
  1229. <h3>fs.readFileSync(filename [, encoding])</h3>
  1230. <p>Synchronous version of <code>fs.readFile</code>. Returns the contents of the <code>filename</code>.</p>
  1231. <p>If <code>encoding</code> is specified then this function returns a string. Otherwise it
  1232. returns a buffer.</p>
  1233. <h3>fs.writeFile(filename, data, encoding='utf8', callback)</h3>
  1234. <p>Asynchronously writes data to a file. Example:</p>
  1235. <pre><code>fs.writeFile('message.txt', 'Hello Node', function (err) {
  1236. if (err) throw err;
  1237. sys.puts('It\'s saved!');
  1238. });
  1239. </code></pre>
  1240. <h3>fs.writeFileSync(filename, data, encoding='utf8')</h3>
  1241. <p>The synchronous version of <code>fs.writeFile</code>.</p>
  1242. <h3>fs.watchFile(filename, [options,] listener)</h3>
  1243. <p>Watch for changes on <code>filename</code>. The callback <code>listener</code> will be called each
  1244. time the file changes.</p>
  1245. <p>The second argument is optional. The <code>options</code> if provided should be an object
  1246. containing two members a boolean, <code>persistent</code>, and <code>interval</code>, a polling
  1247. value in milliseconds. The default is <code>{persistent: true, interval: 0}</code>.</p>
  1248. <p>The <code>listener</code> gets two arguments the current stat object and the previous
  1249. stat object:</p>
  1250. <pre><code>fs.watchFile(f, function (curr, prev) {
  1251. sys.puts('the current mtime is: ' + curr.mtime);
  1252. sys.puts('the previous mtime was: ' + prev.mtime);
  1253. });
  1254. </code></pre>
  1255. <p>These stat objects are instances of <code>fs.Stat</code>.</p>
  1256. <h3>fs.unwatchFile(filename)</h3>
  1257. <p>Stop watching for changes on <code>filename</code>.</p>
  1258. <h2 id="fs.Stats">fs.Stats</h2>
  1259. <p>Objects returned from <code>fs.stat()</code> and <code>fs.lstat()</code> are of this type.</p>
  1260. <ul>
  1261. <li><code>stats.isFile()</code></li>
  1262. <li><code>stats.isDirectory()</code></li>
  1263. <li><code>stats.isBlockDevice()</code></li>
  1264. <li><code>stats.isCharacterDevice()</code></li>
  1265. <li><code>stats.isSymbolicLink()</code> (only valid with <code>fs.lstat()</code>)</li>
  1266. <li><code>stats.isFIFO()</code></li>
  1267. <li><code>stats.isSocket()</code></li>
  1268. </ul>
  1269. <h2 id="fs.ReadStream">fs.ReadStream</h2>
  1270. <p><code>ReadStream</code> is a readable stream.</p>
  1271. <h3>fs.createReadStream(path, [options])</h3>
  1272. <p>Returns a new ReadStream object.</p>
  1273. <p><code>options</code> is an object with the following defaults:</p>
  1274. <pre><code>{ 'flags': 'r'
  1275. , 'encoding': 'binary'
  1276. , 'mode': 0666
  1277. , 'bufferSize': 4 * 1024
  1278. }
  1279. </code></pre>
  1280. <h3>readStream.readable</h3>
  1281. <p>A boolean that is <code>true</code> by default, but turns <code>false</code> after an <code>'error'</code>
  1282. occured, the stream came to an <code>'end'</code>, or <code>destroy()</code> was called.</p>
  1283. <h3>readStream.pause()</h3>
  1284. <p>Stops the stream from reading further data. No <code>'data'</code> event will be fired
  1285. until the stream is resumed.</p>
  1286. <h3>readStream.resume()</h3>
  1287. <p>Resumes the stream. Together with <code>pause()</code> this useful to throttle reading.</p>
  1288. <h3>readStream.destroy()</h3>
  1289. <p>Allows to close the stream before the <code>'end'</code> is reached. No more events other
  1290. than <code>'close'</code> will be fired after this method has been called.</p>
  1291. <h2 id="fs.WriteStream">fs.WriteStream</h2>
  1292. <p><code>WriteStream</code> is a writable stream.</p>
  1293. <h3>fs.createWriteStream(path, [options])</h3>
  1294. <p>Returns a new WriteStream object.
  1295. <code>options</code> is an object with the following defaults:</p>
  1296. <pre><code>{ 'flags': 'w'
  1297. , 'encoding': 'binary'
  1298. , 'mode': 0666
  1299. }
  1300. </code></pre>
  1301. <h3>writeStream.writeable</h3>
  1302. <p>A boolean that is <code>true</code> by default, but turns <code>false</code> after an <code>'error'</code>
  1303. occurred or <code>end()</code> / <code>destroy()</code> was called.</p>
  1304. <h3>writeStream.write(data, encoding='utf8')</h3>
  1305. <p>Returns <code>true</code> if the data was flushed to the kernel, and <code>false</code> if it was
  1306. queued up for being written later. A <code>'drain'</code> will fire after all queued data
  1307. has been written.</p>
  1308. <p>The second optional parameter specifies the encoding of for the string.</p>
  1309. <h3>writeStream.end()</h3>
  1310. <p>Closes the stream right after all queued <code>write()</code> calls have finished.</p>
  1311. <h3>writeStream.destroy()</h3>
  1312. <p>Allows to close the stream regardless of its current state.</p>
  1313. <h2 id="HTTP">HTTP</h2>
  1314. <p>To use the HTTP server and client one must <code>require('http')</code>.</p>
  1315. <p>The HTTP interfaces in Node are designed to support many features
  1316. of the protocol which have been traditionally difficult to use.
  1317. In particular, large, possibly chunk-encoded, messages. The interface is
  1318. careful to never buffer entire requests or responses--the
  1319. user is able to stream data.</p>
  1320. <p>HTTP message headers are represented by an object like this:</p>
  1321. <pre><code>{ 'content-length': '123'
  1322. , 'content-type': 'text/plain'
  1323. , 'stream': 'keep-alive'
  1324. , 'accept': '*/*'
  1325. }
  1326. </code></pre>
  1327. <p>Keys are lowercased. Values are not modified.</p>
  1328. <p>In order to support the full spectrum of possible HTTP applications, Node's
  1329. HTTP API is very low-level. It deals with stream handling and message
  1330. parsing only. It parses a message into headers and body but it does not
  1331. parse the actual headers or the body.</p>
  1332. <p>HTTPS is supported if OpenSSL is available on the underlying platform.</p>
  1333. <h2 id="http.Server">http.Server</h2>
  1334. <p>This is an EventEmitter with the following events:</p>
  1335. <h3>Event: 'request'</h3>
  1336. <p><code>function (request, response) { }</code></p>
  1337. <p> <code>request</code> is an instance of <code>http.ServerRequest</code> and <code>response</code> is
  1338. an instance of <code>http.ServerResponse</code></p>
  1339. <h3>Event: 'connection'</h3>
  1340. <p><code>function (stream) { }</code></p>
  1341. <p> When a new TCP stream is established. <code>stream</code> is an object of type
  1342. <code>net.Stream</code>. Usually users will not want to access this event. The
  1343. <code>stream</code> can also be accessed at <code>request.connection</code>.</p>
  1344. <h3>Event: 'close'</h3>
  1345. <p><code>function (errno) { }</code></p>
  1346. <p> Emitted when the server closes.</p>
  1347. <h3>http.createServer(requestListener, [options])</h3>
  1348. <p>Returns a new web server object.</p>
  1349. <p>The <code>options</code> argument is optional. The
  1350. <code>options</code> argument accepts the same values as the
  1351. options argument for <code>net.Server</code>.</p>
  1352. <p>The <code>requestListener</code> is a function which is automatically
  1353. added to the <code>'request'</code> event.</p>
  1354. <h3>Event: 'request'</h3>
  1355. <p><code>function (request, response) {}</code></p>
  1356. <p>Emitted each time there is request. Note that there may be multiple requests
  1357. per connection (in the case of keep-alive connections).</p>
  1358. <h3>Event: 'upgrade'</h3>
  1359. <p><code>function (request, socket, head)</code></p>
  1360. <p>Emitted each time a client requests a http upgrade. If this event isn't
  1361. listened for, then clients requesting an upgrade will have their connections
  1362. closed.</p>
  1363. <ul>
  1364. <li><code>request</code> is the arguments for the http request, as it is in the request event.</li>
  1365. <li><code>socket</code> is the network socket between the server and client.</li>
  1366. <li><code>head</code> is an instance of Buffer, the first packet of the upgraded stream, this may be empty.</li>
  1367. </ul>
  1368. <p>After this event is emitted, the request's socket will not have a <code>data</code>
  1369. event listener, meaning you will need to bind to it in order to handle data
  1370. sent to the server on that socket.</p>
  1371. <h3>Event: 'clientError'</h3>
  1372. <p><code>function (exception) {}</code></p>
  1373. <p>If a client connection emits an 'error' event - it will forwarded here.</p>
  1374. <h3>server.listen(port, hostname=null, callback=null)</h3>
  1375. <p>Begin accepting connections on the specified port and hostname. If the
  1376. hostname is omitted, the server will accept connections directed to any
  1377. IPv4 address (<code>INADDR_ANY</code>).</p>
  1378. <p>To listen to a unix socket, supply a filename instead of port and hostname.</p>
  1379. <p>This function is asynchronous. The last parameter <code>callback</code> will be called
  1380. when the server has been bound to the port.</p>
  1381. <h3>server.listen(path, callback=null)</h3>
  1382. <p>Start a UNIX socket server listening for connections on the given <code>path</code>.</p>
  1383. <p>This function is asynchronous. The last parameter <code>callback</code> will be called
  1384. when the server has been bound.</p>
  1385. <h3>server.setSecure(credentials)</h3>
  1386. <p>Enables HTTPS support for the server, with the crypto module credentials specifying the private key and certificate of the server, and optionally the CA certificates for use in client authentication.</p>
  1387. <p>If the credentials hold one or more CA certificates, then the server will request for the client to submit a client certificate as part of the HTTPS connection handshake. The validity and content of this can be accessed via verifyPeer() and getPeerCertificate() from the server's request.connection.</p>
  1388. <h3>server.close()</h3>
  1389. <p>Stops the server from accepting new connections.</p>
  1390. <h2 id="http.ServerRequest">http.ServerRequest</h2>
  1391. <p>This object is created internally by a HTTP server--not by
  1392. the user--and passed as the first argument to a <code>'request'</code> listener.</p>
  1393. <p>This is an EventEmitter with the following events:</p>
  1394. <h3>Event: 'data'</h3>
  1395. <p><code>function (chunk) { }</code></p>
  1396. <p>Emitted when a piece of the message body is received.</p>
  1397. <p>Example: A chunk of the body is given as the single
  1398. argument. The transfer-encoding has been decoded. The
  1399. body chunk is a string. The body encoding is set with
  1400. <code>request.setBodyEncoding()</code>.</p>
  1401. <h3>Event: 'end'</h3>
  1402. <p><code>function () { }</code></p>
  1403. <p>Emitted exactly once for each message. No arguments. After
  1404. emitted no other events will be emitted on the request.</p>
  1405. <h3>request.method</h3>
  1406. <p>The request method as a string. Read only. Example:
  1407. <code>'GET'</code>, <code>'DELETE'</code>.</p>
  1408. <h3>request.url</h3>
  1409. <p>Request URL string. This contains only the URL that is
  1410. present in the actual HTTP request. If the request is:</p>
  1411. <pre><code>GET /status?name=ryan HTTP/1.1\r\n
  1412. Accept: text/plain\r\n
  1413. \r\n
  1414. </code></pre>
  1415. <p>Then <code>request.url</code> will be:</p>
  1416. <pre><code>'/status?name=ryan'
  1417. </code></pre>
  1418. <p>If you would like to parse the URL into its parts, you can use
  1419. <code>require('url').parse(request.url)</code>. Example:</p>
  1420. <pre><code>node&gt; require('url').parse('/status?name=ryan')
  1421. { href: '/status?name=ryan'
  1422. , search: '?name=ryan'
  1423. , query: 'name=ryan'
  1424. , pathname: '/status'
  1425. }
  1426. </code></pre>
  1427. <p>If you would like to extract the params from the query string,
  1428. you can use the <code>require('querystring').parse</code> function, or pass
  1429. <code>true</code> as the second argument to <code>require('url').parse</code>. Example:</p>
  1430. <pre><code>node&gt; require('url').parse('/status?name=ryan', true)
  1431. { href: '/status?name=ryan'
  1432. , search: '?name=ryan'
  1433. , query: { name: 'ryan' }
  1434. , pathname: '/status'
  1435. }
  1436. </code></pre>
  1437. <h3>request.headers</h3>
  1438. <p>Read only.</p>
  1439. <h3>request.httpVersion</h3>
  1440. <p>The HTTP protocol version as a string. Read only. Examples:
  1441. <code>'1.1'</code>, <code>'1.0'</code>.
  1442. Also <code>request.httpVersionMajor</code> is the first integer and
  1443. <code>request.httpVersionMinor</code> is the second.</p>
  1444. <h3>request.setEncoding(encoding='binary')</h3>
  1445. <p>Set the encoding for the request body. Either <code>'utf8'</code> or <code>'binary'</code>. Defaults
  1446. to <code>'binary'</code>.</p>
  1447. <h3>request.pause()</h3>
  1448. <p>Pauses request from emitting events. Useful to throttle back an upload.</p>
  1449. <h3>request.resume()</h3>
  1450. <p>Resumes a paused request.</p>
  1451. <h3>request.connection</h3>
  1452. <p>The <code>net.Stream</code> object assocated with the connection.</p>
  1453. <p>With HTTPS support, use request.connection.verifyPeer() and
  1454. request.connection.getPeerCertificate() to obtain the client's
  1455. authentication details.</p>
  1456. <h2 id="http.ServerResponse">http.ServerResponse</h2>
  1457. <p>This object is created internally by a HTTP server--not by the user. It is
  1458. passed as the second parameter to the <code>'request'</code> event. It is a writable stream.</p>
  1459. <h3>response.writeHead(statusCode[, reasonPhrase] , headers)</h3>
  1460. <p>Sends a response header to the request. The status code is a 3-digit HTTP
  1461. status code, like <code>404</code>. The last argument, <code>headers</code>, are the response headers.
  1462. Optionally one can give a human-readable <code>reasonPhrase</code> as the second
  1463. argument.</p>
  1464. <p>Example:</p>
  1465. <pre><code>var body = 'hello world';
  1466. response.writeHead(200, {
  1467. 'Content-Length': body.length,
  1468. 'Content-Type': 'text/plain'
  1469. });
  1470. </code></pre>
  1471. <p>This method must only be called once on a message and it must
  1472. be called before <code>response.end()</code> is called.</p>
  1473. <h3>response.write(chunk, encoding)</h3>
  1474. <p>This method must be called after <code>writeHead</code> was
  1475. called. It sends a chunk of the response body. This method may
  1476. be called multiple times to provide successive parts of the body.</p>
  1477. <p>If <code>chunk</code> is a string, the second parameter
  1478. specifies how to encode it into a byte stream. By default the
  1479. <code>encoding</code> is <code>'ascii'</code>.</p>
  1480. <p><strong>Note</strong>: This is the raw HTTP body and has nothing to do with
  1481. higher-level multi-part body encodings that may be used.</p>
  1482. <p>The first time <code>response.write()</code> is called, it will send the buffered
  1483. header information and the first body to the client. The second time
  1484. <code>response.write()</code> is called, Node assumes you're going to be streaming
  1485. data, and sends that separately. That is, the response is buffered up to the
  1486. first chunk of body.</p>
  1487. <h3>response.end()</h3>
  1488. <p>This method signals to the server that all of the response headers and body
  1489. has been sent; that server should consider this message complete.
  1490. The method, <code>response.end()</code>, MUST be called on each
  1491. response.</p>
  1492. <h2 id="http.Client">http.Client</h2>
  1493. <p>An HTTP client is constructed with a server address as its
  1494. argument, the returned handle is then used to issue one or more
  1495. requests. Depending on the server connected to, the client might
  1496. pipeline the requests or reestablish the stream after each
  1497. stream. <em>Currently the implementation does not pipeline requests.</em></p>
  1498. <p>Example of connecting to <code>google.com</code>:</p>
  1499. <pre><code>var sys = require('sys'),
  1500. http = require('http');
  1501. var google = http.createClient(80, 'www.google.com');
  1502. var request = google.request('GET', '/',
  1503. {'host': 'www.google.com'});
  1504. request.end();
  1505. request.addListener('response', function (response) {
  1506. sys.puts('STATUS: ' + response.statusCode);
  1507. sys.puts('HEADERS: ' + JSON.stringify(response.headers));
  1508. response.setEncoding('utf8');
  1509. response.addListener('data', function (chunk) {
  1510. sys.puts('BODY: ' + chunk);
  1511. });
  1512. });
  1513. </code></pre>
  1514. <h3>http.createClient(port, host, secure, credentials)</h3>
  1515. <p>Constructs a new HTTP client. <code>port</code> and
  1516. <code>host</code> refer to the server to be connected to. A
  1517. stream is not established until a request is issued.</p>
  1518. <p><code>secure</code> is an optional boolean flag to enable https support and <code>credentials</code> is an optional credentials object from the crypto module, which may hold the client's private key, certificate, and a list of trusted CA certificates.</p>
  1519. <p>If the connection is secure, but no explicit CA certificates are passed in the credentials, then node.js will default to the publicly trusted list of CA certificates, as given in http://mxr.mozilla.org/mozilla/source/security/nss/lib/ckfw/builtins/certdata.txt</p>
  1520. <h3>client.request([method], path, [request_headers])</h3>
  1521. <p>Issues a request; if necessary establishes stream. Returns a <code>http.ClientRequest</code> instance.</p>
  1522. <p><code>method</code> is optional and defaults to 'GET' if omitted.</p>
  1523. <p><code>request_headers</code> is optional.
  1524. Additional request headers might be added internally
  1525. by Node. Returns a <code>ClientRequest</code> object.</p>
  1526. <p>Do remember to include the <code>Content-Length</code> header if you
  1527. plan on sending a body. If you plan on streaming the body, perhaps
  1528. set <code>Transfer-Encoding: chunked</code>.</p>
  1529. <p><em>NOTE</em>: the request is not complete. This method only sends the header of
  1530. the request. One needs to call <code>request.end()</code> to finalize the request and
  1531. retrieve the response. (This sounds convoluted but it provides a chance for
  1532. the user to stream a body to the server with <code>request.write()</code>.)</p>
  1533. <h3>client.verifyPeer()</h3>
  1534. <p>Returns true or false depending on the validity of the server's certificate in the context of the defined or default list of trusted CA certificates.</p>
  1535. <h3>client.getPeerCertificate()</h3>
  1536. <p>Returns a JSON structure detailing the server's certificate, containing a dictionary with keys for the certificate 'subject', 'issuer', 'valid_from' and 'valid_to'</p>
  1537. <h2 id="http.ClientRequest">http.ClientRequest</h2>
  1538. <p>This object is created internally and returned from the <code>request()</code> method
  1539. of a <code>http.Client</code>. It represents an <em>in-progress</em> request whose header has
  1540. already been sent.</p>
  1541. <p>To get the response, add a listener for <code>'response'</code> to the request object.
  1542. <code>'response'</code> will be emitted from the request object when the response
  1543. headers have been received. The <code>'response'</code> event is executed with one
  1544. argument which is an instance of <code>http.ClientResponse</code>.</p>
  1545. <p>During the <code>'response'</code> event, one can add listeners to the
  1546. response object; particularly to listen for the <code>'data'</code> event. Note that
  1547. the <code>'response'</code> event is called before any part of the response body is received,
  1548. so there is no need to worry about racing to catch the first part of the
  1549. body. As long as a listener for <code>'data'</code> is added during the <code>'response'</code>
  1550. event, the entire body will be caught.</p>
  1551. <pre><code>// Good
  1552. request.addListener('response', function (response) {
  1553. response.addListener('data', function (chunk) {
  1554. sys.puts('BODY: ' + chunk);
  1555. });
  1556. });
  1557. // Bad - misses all or part of the body
  1558. request.addListener('response', function (response) {
  1559. setTimeout(function () {
  1560. response.addListener('data', function (chunk) {
  1561. sys.puts('BODY: ' + chunk);
  1562. });
  1563. }, 10);
  1564. });
  1565. </code></pre>
  1566. <p>This is a writable stream.</p>
  1567. <p>This is an <code>EventEmitter</code> with the following events:</p>
  1568. <h3>Event 'response'</h3>
  1569. <p><code>function (response) { }</code></p>
  1570. <p>Emitted when a response is received to this request. This event is emitted only once. The
  1571. <code>response</code> argument will be an instance of <code>http.ClientResponse</code>.</p>
  1572. <h3>request.write(chunk, encoding='ascii')</h3>
  1573. <p>Sends a chunk of the body. By calling this method
  1574. many times, the user can stream a request body to a
  1575. server--in that case it is suggested to use the
  1576. <code>['Transfer-Encoding', 'chunked']</code> header line when
  1577. creating the request.</p>
  1578. <p>The <code>chunk</code> argument should be an array of integers
  1579. or a string.</p>
  1580. <p>The <code>encoding</code> argument is optional and only
  1581. applies when <code>chunk</code> is a string. The encoding
  1582. argument should be either <code>'utf8'</code> or
  1583. <code>'ascii'</code>. By default the body uses ASCII encoding,
  1584. as it is faster.</p>
  1585. <h3>request.end()</h3>
  1586. <p>Finishes sending the request. If any parts of the body are
  1587. unsent, it will flush them to the stream. If the request is
  1588. chunked, this will send the terminating <code>'0\r\n\r\n'</code>.</p>
  1589. <h2 id="http.ClientResponse">http.ClientResponse</h2>
  1590. <p>This object is created when making a request with <code>http.Client</code>. It is
  1591. passed to the <code>'response'</code> event of the request object.</p>
  1592. <p>The response implements the <strong>readable stream</strong> interface.</p>
  1593. <h3>Event: 'data'</h3>
  1594. <p><code>function (chunk) {}</code></p>
  1595. <p>Emitted when a piece of the message body is received.</p>
  1596. <pre><code>Example: A chunk of the body is given as the single
  1597. argument. The transfer-encoding has been decoded. The
  1598. body chunk a String. The body encoding is set with
  1599. `response.setBodyEncoding()`.
  1600. </code></pre>
  1601. <h3>Event: 'end'</h3>
  1602. <p><code>function () {}</code></p>
  1603. <p>Emitted exactly once for each message. No arguments. After
  1604. emitted no other events will be emitted on the response.</p>
  1605. <h3>response.statusCode</h3>
  1606. <p>The 3-digit HTTP response status code. E.G. <code>404</code>.</p>
  1607. <h3>response.httpVersion</h3>
  1608. <p>The HTTP version of the connected-to server. Probably either
  1609. <code>'1.1'</code> or <code>'1.0'</code>.
  1610. Also <code>response.httpVersionMajor</code> is the first integer and
  1611. <code>response.httpVersionMinor</code> is the second.</p>
  1612. <h3>response.headers</h3>
  1613. <p>The response headers.</p>
  1614. <h3>response.setEncoding(encoding)</h3>
  1615. <p>Set the encoding for the response body. Either <code>'utf8'</code> or <code>'binary'</code>.
  1616. Defaults to <code>'binary'</code>.</p>
  1617. <h3>response.pause()</h3>
  1618. <p>Pauses response from emitting events. Useful to throttle back a download.</p>
  1619. <h3>response.resume()</h3>
  1620. <p>Resumes a paused response.</p>
  1621. <h3>response.client</h3>
  1622. <p>A reference to the <code>http.Client</code> that this response belongs to.</p>
  1623. <h2 id="net.Server">net.Server</h2>
  1624. <p>This class is used to create a TCP or UNIX server.</p>
  1625. <p>Here is an example of a echo server which listens for connections
  1626. on port 8124:</p>
  1627. <pre><code>var net = require('net');
  1628. var server = net.createServer(function (stream) {
  1629. stream.setEncoding('utf8');
  1630. stream.addListener('connect', function () {
  1631. stream.write('hello\r\n');
  1632. });
  1633. stream.addListener('data', function (data) {
  1634. stream.write(data);
  1635. });
  1636. stream.addListener('end', function () {
  1637. stream.write('goodbye\r\n');
  1638. stream.end();
  1639. });
  1640. });
  1641. server.listen(8124, 'localhost');
  1642. </code></pre>
  1643. <p>To listen on the socket <code>'/tmp/echo.sock'</code>, the last line would just be
  1644. changed to</p>
  1645. <pre><code>server.listen('/tmp/echo.sock');
  1646. </code></pre>
  1647. <p>This is an EventEmitter with the following events:</p>
  1648. <h3>Event: 'connection'</h3>
  1649. <p><code>function (stream) {}</code></p>
  1650. <p>Emitted when a new connection is made. <code>stream</code> is an instance of
  1651. <code>net.Stream</code>.</p>
  1652. <h3>Event: 'close'</h3>
  1653. <p><code>function () {}</code></p>
  1654. <p>Emitted when the server closes.</p>
  1655. <h3>net.createServer(connectionListener)</h3>
  1656. <p>Creates a new TCP server. The <code>connection_listener</code> argument is
  1657. automatically set as a listener for the <code>'connection'</code> event.</p>
  1658. <h3>server.listen(port, host=null, callback=null)</h3>
  1659. <p>Begin accepting connections on the specified <code>port</code> and <code>host</code>. If the
  1660. <code>host</code> is omitted, the server will accept connections directed to any
  1661. IPv4 address (<code>INADDR_ANY</code>).</p>
  1662. <p>This function is asynchronous. The last parameter <code>callback</code> will be called
  1663. when the server has been bound.</p>
  1664. <h3>server.listen(path, callback=null)</h3>
  1665. <p>Start a UNIX socket server listening for connections on the given <code>path</code>.</p>
  1666. <p>This function is asynchronous. The last parameter <code>callback</code> will be called
  1667. when the server has been bound.</p>
  1668. <h3>server.close()</h3>
  1669. <p>Stops the server from accepting new connections. This function is
  1670. asynchronous, the server is finally closed when the server emits a <code>'close'</code>
  1671. event.</p>
  1672. <h2 id="net.Stream">net.Stream</h2>
  1673. <p>This object is an abstraction of of a TCP or UNIX socket. <code>net.Stream</code>
  1674. instance implement a duplex stream interface. They can be created by the
  1675. user and used as a client (with <code>connect()</code>) or they can be created by Node
  1676. and passed to the user through the <code>'connection'</code> event of a server.</p>
  1677. <p><code>net.Stream</code> instances are an EventEmitters with the following events:</p>
  1678. <h3>Event: 'connect'</h3>
  1679. <p><code>function () { }</code></p>
  1680. <p>Emitted when a stream connection successfully is established.
  1681. See <code>connect()</code>.</p>
  1682. <h3>Event: 'secure'</h3>
  1683. <p><code>function () { }</code></p>
  1684. <p>Emitted when a stream connection successfully establishes a HTTPS handshake with its peer.</p>
  1685. <h3>Event: 'data'</h3>
  1686. <p><code>function (data) { }</code></p>
  1687. <p>Emitted when data is received. The argument <code>data</code> will be a <code>Buffer</code> or
  1688. <code>String</code>. Encoding of data is set by <code>stream.setEncoding()</code>.
  1689. (See the section on Readable Streams for more infromation.)</p>
  1690. <h3>Event: 'end'</h3>
  1691. <p><code>function () { }</code></p>
  1692. <p>Emitted when the other end of the stream sends a FIN packet. After this is
  1693. emitted the <code>readyState</code> will be <code>'writeOnly'</code>. One should probably just
  1694. call <code>stream.end()</code> when this event is emitted.</p>
  1695. <h3>Event: 'timeout'</h3>
  1696. <p><code>function () { }</code></p>
  1697. <p>Emitted if the stream times out from inactivity. This is only to notify that
  1698. the stream has been idle. The user must manually close the connection.</p>
  1699. <p>See also: <code>stream.setTimeout()</code></p>
  1700. <h3>Event: 'drain'</h3>
  1701. <p><code>function () { }</code></p>
  1702. <p>Emitted when the write buffer becomes empty. Can be used to throttle uploads.</p>
  1703. <h3>Event: 'error'</h3>
  1704. <p><code>function (exception) { }</code></p>
  1705. <p>Emitted when an error occurs. The <code>'close'</code> event will be called directly
  1706. following this event.</p>
  1707. <h3>Event: 'close'</h3>
  1708. <p><code>function () { }</code></p>
  1709. <p>Emitted once the stream is fully closed. The argument <code>had_error</code> is a boolean which says if
  1710. the stream was closed due to a transmission
  1711. error.</p>
  1712. <h3>net.createConnection(port, host='127.0.0.1')</h3>
  1713. <p>Construct a new stream object and opens a stream to the specified <code>port</code>
  1714. and <code>host</code>. If the second parameter is omitted, localhost is assumed.</p>
  1715. <p>When the stream is established the <code>'connect'</code> event will be emitted.</p>
  1716. <h3>stream.connect(port, host='127.0.0.1')</h3>
  1717. <p>Opens a stream to the specified <code>port</code> and <code>host</code>. <code>createConnection()</code>
  1718. also opens a stream; normally this method is not needed. Use this only if
  1719. a stream is closed and you want to reuse the object to connect to another
  1720. server.</p>
  1721. <p>This function is asynchronous. When the <code>'connect'</code> event is emitted the
  1722. stream is established. If there is a problem connecting, the <code>'connect'</code>
  1723. event will not be emitted, the <code>'error'</code> event will be emitted with
  1724. the exception.</p>
  1725. <h3>stream.remoteAddress</h3>
  1726. <p>The string representation of the remote IP address. For example,
  1727. <code>'74.125.127.100'</code> or <code>'2001:4860:a005::68'</code>.</p>
  1728. <p>This member is only present in server-side connections.</p>
  1729. <h3>stream.readyState</h3>
  1730. <p>Either <code>'closed'</code>, <code>'open'</code>, <code>'opening'</code>, <code>'readOnly'</code>, or <code>'writeOnly'</code>.</p>
  1731. <h3>stream.setEncoding(encoding)</h3>
  1732. <p>Sets the encoding (either <code>'ascii'</code>, <code>'utf8'</code>, or <code>'binary'</code>) for data that is
  1733. received.</p>
  1734. <h3>stream.setSecure(credentials)</h3>
  1735. <p>Enables HTTPS support for the stream, with the crypto module credentials specifying the private key and certificate of the stream, and optionally the CA certificates for use in peer authentication.</p>
  1736. <p>If the credentials hold one ore more CA certificates, then the stream will request for the peer to submit a client certificate as part of the HTTPS connection handshake. The validity and content of this can be accessed via verifyPeer() and getPeerCertificate().</p>
  1737. <h3>stream.verifyPeer()</h3>
  1738. <p>Returns true or false depending on the validity of the peers's certificate in the context of the defined or default list of trusted CA certificates.</p>
  1739. <h3>stream.getPeerCertificate()</h3>
  1740. <p>Returns a JSON structure detailing the peer's certificate, containing a dictionary with keys for the certificate 'subject', 'issuer', 'valid_from' and 'valid_to'</p>
  1741. <h3>stream.write(data, encoding='ascii')</h3>
  1742. <p>Sends data on the stream. The second parameter specifies the encoding in
  1743. the case of a string--it defaults to ASCII because encoding to UTF8 is rather
  1744. slow.</p>
  1745. <p>Returns <code>true</code> if the entire data was flushed successfully to the kernel
  1746. buffer. Returns <code>false</code> if all or part of the data was queued in user memory.
  1747. <code>'drain'</code> will be emitted when the buffer is again free.</p>
  1748. <h3>stream.end()</h3>
  1749. <p>Half-closes the stream. I.E., it sends a FIN packet. It is possible the
  1750. server will still send some data. After calling this <code>readyState</code> will be
  1751. <code>'readOnly'</code>.</p>
  1752. <h3>stream.destroy()</h3>
  1753. <p>Ensures that no more I/O activity happens on this stream. Only necessary in
  1754. case of errors (parse error or so).</p>
  1755. <h3>stream.pause()</h3>
  1756. <p>Pauses the reading of data. That is, <code>'data'</code> events will not be emitted.
  1757. Useful to throttle back an upload.</p>
  1758. <h3>stream.resume()</h3>
  1759. <p>Resumes reading after a call to <code>pause()</code>.</p>
  1760. <h3>stream.setTimeout(timeout)</h3>
  1761. <p>Sets the stream to timeout after <code>timeout</code> milliseconds of inactivity on
  1762. the stream. By default <code>net.Stream</code> do not have a timeout.</p>
  1763. <p>When an idle timeout is triggered the stream will receive a <code>'timeout'</code>
  1764. event but the connection will not be severed. The user must manually <code>end()</code>
  1765. or <code>destroy()</code> the stream.</p>
  1766. <p>If <code>timeout</code> is 0, then the existing idle timeout is disabled.</p>
  1767. <h3>stream.setNoDelay(noDelay=true)</h3>
  1768. <p>Disables the Nagle algorithm. By default TCP connections use the Nagle
  1769. algorithm, they buffer data before sending it off. Setting <code>noDelay</code> will
  1770. immediately fire off data each time <code>stream.write()</code> is called.</p>
  1771. <h3>stream.setKeepAlive(enable=false, initialDelay)</h3>
  1772. <p>Enable/disable keep-alive functionality, and optionally set the initial
  1773. delay before the first keepalive probe is sent on an idle stream.
  1774. Set <code>initialDelay</code> (in milliseconds) to set the delay between the last
  1775. data packet received and the first keepalive probe. Setting 0 for
  1776. initialDelay will leave the value unchanged from the default
  1777. (or previous) setting.</p>
  1778. <h2 id="Crypto">Crypto</h2>
  1779. <p>Use <code>require('crypto')</code> to access this module.</p>
  1780. <p>The crypto module requires OpenSSL to be available on the underlying platform. It offers a way of encapsulating secure credentials to be used as part of a secure HTTPS net or http connection.</p>
  1781. <p>It also offers a set of wrappers for OpenSSL's hash, hmac, cipher, decipher, sign and verify methods.</p>
  1782. <h3>crypto.createCredentials(details)</h3>
  1783. <p>Creates a credentials object, with the optional details being a dictionary with keys:</p>
  1784. <p><code>key</code> : a string holding the PEM encoded private key</p>
  1785. <p><code>cert</code> : a string holding the PEM encoded certificate</p>
  1786. <p><code>ca</code> : either a string or list of strings of PEM encoded CA certificates to trust.</p>
  1787. <p>If no 'ca' details are given, then node.js will use the default publicly trusted list of CAs as given in
  1788. http://mxr.mozilla.org/mozilla/source/security/nss/lib/ckfw/builtins/certdata.txt</p>
  1789. <h3>crypto.createHash(algorithm)</h3>
  1790. <p>Creates and returns a hash object, a cryptographic hash with the given algorithm which can be used to generate hash digests.</p>
  1791. <p><code>algorithm</code> is dependent on the available algorithms supported by the version of OpenSSL on the platform. Examples are sha1, md5, sha256, sha512, etc. On recent releases, <code>openssl list-message-digest-algorithms</code> will display the available digest algorithms.</p>
  1792. <h3>hash.update(data)</h3>
  1793. <p>Updates the hash content with the given <code>data</code>. This can be called many times with new data as it is streamed.</p>
  1794. <h3>hash.digest(encoding)</h3>
  1795. <p>Calculates the digest of all of the passed data to be hashed. The <code>encoding</code> can be 'hex', 'binary' or 'base64'.</p>
  1796. <h3>crypto.createHmac(algorithm, key)</h3>
  1797. <p>Creates and returns a hmac object, a cryptographic hmac with the given algorithm and key.</p>
  1798. <p><code>algorithm</code> is dependent on the available algorithms supported by OpenSSL - see createHash above.
  1799. <code>key</code> is the hmac key to be used.</p>
  1800. <h3>hmac.update(data)</h3>
  1801. <p>Update the hmac content with the given <code>data</code>. This can be called many times with new data as it is streamed.</p>
  1802. <h3>hmac.digest(encoding)</h3>
  1803. <p>Calculates the digest of all of the passed data to the hmac. The <code>encoding</code> can be 'hex', 'binary' or 'base64'.</p>
  1804. <h3>crypto.createCipher(algorithm, key)</h3>
  1805. <p>Creates and returns a cipher object, with the given algorithm and key.</p>
  1806. <p><code>algorithm</code> is dependent on OpenSSL, examples are aes192, etc. On recent releases, <code>openssl list-cipher-algorithms</code> will display the available cipher algorithms.</p>
  1807. <h3>cipher.update(data, input_encoding, output_encoding)</h3>
  1808. <p>Updates the cipher with <code>data</code>, the encoding of which is given in <code>input_encoding</code> and can be 'utf8', 'ascii' or 'binary'. The <code>output_encoding</code> specifies the output format of the enciphered data, and can be 'binary', 'base64' or 'hex'.</p>
  1809. <p>Returns the enciphered contents, and can be called many times with new data as it is streamed.</p>
  1810. <h3>cipher.final(output_encoding)</h3>
  1811. <p>Returns any remaining enciphered contents, with <code>output_encoding</code> as update above.</p>
  1812. <h3>crypto.createDecipher(algorithm, key)</h3>
  1813. <p>Creates and returns a decipher object, with the given algorithm and key. This is the mirror of the cipher object above.</p>
  1814. <h3>decipher.update(data, input_encoding, output_encoding)</h3>
  1815. <p>Updates the decipher with <code>data</code>, which is encoded in 'binary', 'base64' or 'hex'. The <code>output_decoding</code> specifies in what format to return the deciphered plaintext - either 'binary', 'ascii' or 'utf8'.</p>
  1816. <h3>decipher.final(output_encoding)</h3>
  1817. <p>Returns any remaining plaintext which is deciphered, with `output_encoding' as update above.</p>
  1818. <h3>crypto.createSign(algorithm)</h3>
  1819. <p>Creates and returns a signing object, with the given algorithm. On recent OpenSSL releases, <code>openssl list-public-key-algorithms</code> will display the available signing algorithms. Examples are 'RSA-SHA256'.</p>
  1820. <h3>signer.update(data)</h3>
  1821. <p>Updates the signer object with data. This can be called many times with new data as it is streamed.</p>
  1822. <h3>signer.sign(private_key, output_format)</h3>
  1823. <p>Calculates the signature on all the updated data passed through the signer. <code>private_key</code> is a string containing the PEM encoded private key for signing.</p>
  1824. <p>Returns the signature in <code>output_format</code> which can be 'binary', 'hex' or 'base64'</p>
  1825. <h3>crypto.createVerify(algorithm)</h3>
  1826. <p>Creates and returns a verification object, with the given algorithm. This is the mirror of the signing object above.</p>
  1827. <h3>verifier.update(data)</h3>
  1828. <p>Updates the verifyer object with data. This can be called many times with new data as it is streamed.</p>
  1829. <h3>verifier.verify(public_key, signature, signature_format)</h3>
  1830. <p>Verifies the signed data by using the <code>public_key</code> which is a string containing the PEM encoded public key, and <code>signature</code>, which is the previously calculates signature for the data, in the <code>signature_format</code> which can be 'binary', 'hex' or 'base64'.</p>
  1831. <p>Returns true or false depending on the validity of the signature for the data and public key.</p>
  1832. <h2 id="DNS">DNS</h2>
  1833. <p>Use <code>require('dns')</code> to access this module.</p>
  1834. <p>Here is an example which resolves <code>'www.google.com'</code> then reverse
  1835. resolves the IP addresses which are returned.</p>
  1836. <pre><code>var dns = require('dns'),
  1837. sys = require('sys');
  1838. dns.resolve4('www.google.com', function (err, addresses) {
  1839. if (err) throw err;
  1840. sys.puts('addresses: ' + JSON.stringify(addresses));
  1841. for (var i = 0; i &lt; addresses.length; i++) {
  1842. var a = addresses[i];
  1843. dns.reverse(a, function (err, domains) {
  1844. if (err) {
  1845. sys.puts('reverse for ' + a + ' failed: ' +
  1846. err.message);
  1847. } else {
  1848. sys.puts('reverse for ' + a + ': ' +
  1849. JSON.stringify(domains));
  1850. }
  1851. });
  1852. }
  1853. });
  1854. </code></pre>
  1855. <h3>dns.resolve(domain, rrtype = 'A', callback)</h3>
  1856. <p>Resolves a domain (e.g. <code>'google.com'</code>) into an array of the record types
  1857. specified by rrtype. Valid rrtypes are <code>A</code> (IPV4 addresses), <code>AAAA</code> (IPV6
  1858. addresses), <code>MX</code> (mail exchange records), <code>TXT</code> (text records), <code>SRV</code> (SRV
  1859. records), and <code>PTR</code> (used for reverse IP lookups).</p>
  1860. <p>The callback has arguments <code>(err, addresses)</code>. The type of each item
  1861. in <code>addresses</code> is determined by the record type, and described in the
  1862. documentation for the corresponding lookup methods below.</p>
  1863. <p>On error, <code>err</code> would be an instanceof <code>Error</code> object, where <code>err.errno</code> is
  1864. one of the error codes listed below and <code>err.message</code> is a string describing
  1865. the error in English.</p>
  1866. <h3>dns.resolve4(domain, callback)</h3>
  1867. <p>The same as <code>dns.resolve()</code>, but only for IPv4 queries (<code>A</code> records).
  1868. <code>addresses</code> is an array of IPv4 addresses (e.g.<br />
  1869. <code>['74.125.79.104', '74.125.79.105', '74.125.79.106']</code>).</p>
  1870. <h3>dns.resolve6(domain, callback)</h3>
  1871. <p>The same as <code>dns.resolve4()</code> except for IPv6 queries (an <code>AAAA</code> query).</p>
  1872. <h3>dns.resolveMx(domain, callback)</h3>
  1873. <p>The same as <code>dns.resolve()</code>, but only for mail exchange queries (<code>MX</code> records).</p>
  1874. <p><code>addresses</code> is an array of MX records, each with a priority and an exchange
  1875. attribute (e.g. <code>[{'priority': 10, 'exchange': 'mx.example.com'},...]</code>).</p>
  1876. <h3>dns.resolveTxt(domain, callback)</h3>
  1877. <p>The same as <code>dns.resolve()</code>, but only for text queries (<code>TXT</code> records).
  1878. <code>addresses</code> is an array of the text records available for <code>domain</code> (e.g.,
  1879. <code>['v=spf1 ip4:0.0.0.0 ~all']</code>).</p>
  1880. <h3>dns.resolveSrv(domain, callback)</h3>
  1881. <p>The same as <code>dns.resolve()</code>, but only for service records (<code>SRV</code> records).
  1882. <code>addresses</code> is an array of the SRV records available for <code>domain</code>. Properties
  1883. of SRV records are priority, weight, port, and name (e.g.,
  1884. <code>[{'priority': 10, {'weight': 5, 'port': 21223, 'name': 'service.example.com'}, ...]</code>).</p>
  1885. <h3>dns.reverse(ip, callback)</h3>
  1886. <p>Reverse resolves an ip address to an array of domain names.</p>
  1887. <p>The callback has arguments <code>(err, domains)</code>.</p>
  1888. <p>If there an an error, <code>err</code> will be non-null and an instanceof the Error
  1889. object.</p>
  1890. <p>Each DNS query can return an error code.</p>
  1891. <ul>
  1892. <li><code>dns.TEMPFAIL</code>: timeout, SERVFAIL or similar.</li>
  1893. <li><code>dns.PROTOCOL</code>: got garbled reply.</li>
  1894. <li><code>dns.NXDOMAIN</code>: domain does not exists.</li>
  1895. <li><code>dns.NODATA</code>: domain exists but no data of reqd type.</li>
  1896. <li><code>dns.NOMEM</code>: out of memory while processing.</li>
  1897. <li><code>dns.BADQUERY</code>: the query is malformed.</li>
  1898. </ul>
  1899. <h2 id="Assert">Assert</h2>
  1900. <p>This module is used for writing unit tests for your applications, you can
  1901. access it with <code>require('assert')</code>.</p>
  1902. <h3>assert.fail(actual, expected, message, operator)</h3>
  1903. <p>Tests if <code>actual</code> is equal to <code>expected</code> using the operator provided.</p>
  1904. <h3>assert.ok(value, message)</h3>
  1905. <p>Tests if value is a <code>true</code> value, it is equivalent to <code>assert.equal(true, value, message);</code></p>
  1906. <h3>assert.equal(actual, expected, message)</h3>
  1907. <p>Tests shallow, coercive equality with the equal comparison operator ( <code>==</code> ).</p>
  1908. <h3>assert.notEqual(actual, expected, message)</h3>
  1909. <p>Tests shallow, coercive non-equality with the not equal comparison operator ( <code>!=</code> ).</p>
  1910. <h3>assert.deepEqual(actual, expected, message)</h3>
  1911. <p>Tests for deep equality.</p>
  1912. <h3>assert.notDeepEqual(actual, expected, message)</h3>
  1913. <p>Tests for any deep inequality.</p>
  1914. <h3>assert.strictEqual(actual, expected, message)</h3>
  1915. <p>Tests strict equality, as determined by the strict equality operator ( <code>===</code> )</p>
  1916. <h3>assert.notStrictEqual(actual, expected, message)</h3>
  1917. <p>Tests strict non-equality, as determined by the strict not equal operator ( <code>!==</code> )</p>
  1918. <h3>assert.throws(block, error, message)</h3>
  1919. <p>Expects <code>block</code> to throw an error.</p>
  1920. <h3>assert.doesNotThrow(block, error, message)</h3>
  1921. <p>Expects <code>block</code> not to throw an error.</p>
  1922. <h3>assert.ifError(value)</h3>
  1923. <p>Tests if value is not a false value, throws if it is a true value. Useful when testing the first argument, <code>error</code> in callbacks.</p>
  1924. <h2 id="Path">Path</h2>
  1925. <p>This module contains utilities for dealing with file paths. Use
  1926. <code>require('path')</code> to use it. It provides the following methods:</p>
  1927. <h3>path.join(/<em> path1, path2, ... </em>/)</h3>
  1928. <p>Join all arguments together and resolve the resulting path. Example:</p>
  1929. <pre><code>node&gt; require('path').join(
  1930. ... '/foo', 'bar', 'baz/asdf', 'quux', '..')
  1931. '/foo/bar/baz/asdf'
  1932. </code></pre>
  1933. <h3>path.normalizeArray(arr)</h3>
  1934. <p>Normalize an array of path parts, taking care of <code>'..'</code> and <code>'.'</code> parts. Example:</p>
  1935. <pre><code>path.normalizeArray(['',
  1936. 'foo', 'bar', 'baz', 'asdf', 'quux', '..'])
  1937. // returns
  1938. [ '', 'foo', 'bar', 'baz', 'asdf' ]
  1939. </code></pre>
  1940. <h3>path.normalize(p)</h3>
  1941. <p>Normalize a string path, taking care of <code>'..'</code> and <code>'.'</code> parts. Example:</p>
  1942. <pre><code>path.normalize('/foo/bar/baz/asdf/quux/..')
  1943. // returns
  1944. '/foo/bar/baz/asdf'
  1945. </code></pre>
  1946. <h3>path.dirname(p)</h3>
  1947. <p>Return the directory name of a path. Similar to the Unix <code>dirname</code> command. Example:</p>
  1948. <pre><code>path.dirname('/foo/bar/baz/asdf/quux')
  1949. // returns
  1950. '/foo/bar/baz/asdf'
  1951. </code></pre>
  1952. <h3>path.basename(p, ext)</h3>
  1953. <p>Return the last portion of a path. Similar to the Unix <code>basename</code> command. Example:</p>
  1954. <pre><code>path.basename('/foo/bar/baz/asdf/quux.html')
  1955. // returns
  1956. 'quux.html'
  1957. path.basename('/foo/bar/baz/asdf/quux.html', '.html')
  1958. // returns
  1959. 'quux'
  1960. </code></pre>
  1961. <h3>path.extname(p)</h3>
  1962. <p>Return the extension of the path. Everything after the last '.' in the last portion
  1963. of the path. If there is no '.' in the last portion of the path or the only '.' is
  1964. the first character, then it returns an empty string. Examples:</p>
  1965. <pre><code>path.extname('index.html')
  1966. // returns
  1967. '.html'
  1968. path.extname('index')
  1969. // returns
  1970. ''
  1971. </code></pre>
  1972. <h3>path.exists(p, callback)</h3>
  1973. <p>Test whether or not the given path exists. Then, call the <code>callback</code> argument with either true or false. Example:</p>
  1974. <pre><code>path.exists('/etc/passwd', function (exists) {
  1975. sys.debug(exists ? "it's there" : "no passwd!");
  1976. });
  1977. </code></pre>
  1978. <h2 id="URL">URL</h2>
  1979. <p>This module has utilities for URL resolution and parsing.
  1980. Call <code>require('url')</code> to use it.</p>
  1981. <p>Parsed URL objects have some or all of the following fields, depending on
  1982. whether or not they exist in the URL string. Any parts that are not in the URL
  1983. string will not be in the parsed object. Examples are shown for the URL</p>
  1984. <p><code>'http://user:pass@host.com:8080/p/a/t/h?query=string#hash'</code></p>
  1985. <ul>
  1986. <li><p><code>href</code></p>
  1987. <p>The full URL that was originally parsed. Example:
  1988. <code>'http://user:pass@host.com:8080/p/a/t/h?query=string#hash'</code></p></li>
  1989. <li><p><code>protocol</code></p>
  1990. <p>The request protocol. Example: <code>'http:'</code></p></li>
  1991. <li><p><code>host</code></p>
  1992. <p>The full host portion of the URL, including port and authentication information. Example:
  1993. <code>'user:pass@host.com:8080'</code></p></li>
  1994. <li><p><code>auth</code></p>
  1995. <p>The authentication information portion of a URL. Example: <code>'user:pass'</code></p></li>
  1996. <li><p><code>hostname</code></p>
  1997. <p>Just the hostname portion of the host. Example: <code>'host.com'</code></p></li>
  1998. <li><p><code>port</code></p>
  1999. <p>The port number portion of the host. Example: <code>'8080'</code></p></li>
  2000. <li><p><code>pathname</code></p>
  2001. <p>The path section of the URL, that comes after the host and before the query, including the initial slash if present. Example: <code>'/p/a/t/h'</code></p></li>
  2002. <li><p><code>search</code></p>
  2003. <p>The 'query string' portion of the URL, including the leading question mark. Example: <code>'?query=string'</code></p></li>
  2004. <li><p><code>query</code></p>
  2005. <p>Either the 'params' portion of the query string, or a querystring-parsed object. Example:
  2006. <code>'query=string'</code> or <code>{'query':'string'}</code></p></li>
  2007. <li><p><code>hash</code></p>
  2008. <p>The 'fragment' portion of the URL including the pound-sign. Example: <code>'#hash'</code></p></li>
  2009. </ul>
  2010. <p>The following methods are provided by the URL module:</p>
  2011. <h3>url.parse(urlStr, parseQueryString=false)</h3>
  2012. <p>Take a URL string, and return an object. Pass <code>true</code> as the second argument to also parse
  2013. the query string using the <code>querystring</code> module.</p>
  2014. <h3>url.format(urlObj)</h3>
  2015. <p>Take a parsed URL object, and return a formatted URL string.</p>
  2016. <h3>url.resolve(from, to)</h3>
  2017. <p>Take a base URL, and a href URL, and resolve them as a browser would for an anchor tag.</p>
  2018. <h2 id="Query String">Query String</h2>
  2019. <p>This module provides utilities for dealing with query strings. It provides the following methods:</p>
  2020. <h3>querystring.stringify(obj, sep='&amp;', eq='=', munge=true)</h3>
  2021. <p>Serialize an object to a query string. Optionally override the default separator and assignment characters.
  2022. Example:</p>
  2023. <pre><code>querystring.stringify({foo: 'bar'})
  2024. // returns
  2025. 'foo=bar'
  2026. querystring.stringify({foo: 'bar', baz: 'bob'}, ';', ':')
  2027. // returns
  2028. 'foo:bar;baz:bob'
  2029. </code></pre>
  2030. <p>By default, this function will perform PHP/Rails-style parameter mungeing for arrays and objects used as
  2031. values within <code>obj</code>.
  2032. Example:</p>
  2033. <pre><code>querystring.stringify({foo: 'bar', foo: 'baz', foo: 'boz'})
  2034. // returns
  2035. 'foo[]=bar&amp;foo[]=baz&amp;foo[]=boz'
  2036. querystring.stringify({foo: {bar: 'baz'}})
  2037. // returns
  2038. 'foo[bar]=baz'
  2039. </code></pre>
  2040. <p>If you wish to disable the array mungeing (e.g. when generating parameters for a Java servlet), you
  2041. can set the <code>munge</code> argument to <code>false</code>.
  2042. Example:</p>
  2043. <pre><code>querystring.stringify({foo: 'bar', foo: 'baz', foo: 'boz'}, '&amp;', '=', false)
  2044. // returns
  2045. 'foo=bar&amp;foo=baz&amp;foo=boz'
  2046. </code></pre>
  2047. <p>Note that when <code>munge</code> is <code>false</code>, parameter names with object values will still be munged.</p>
  2048. <h3>querystring.parse(str, sep='&amp;', eq='=')</h3>
  2049. <p>Deserialize a query string to an object. Optionally override the default separator and assignment characters.</p>
  2050. <pre><code>querystring.parse('a=b&amp;b=c')
  2051. // returns
  2052. { 'a': 'b'
  2053. , 'b': 'c'
  2054. }
  2055. </code></pre>
  2056. <p>This function can parse both munged and unmunged query strings (see <code>stringify</code> for details).</p>
  2057. <h3>querystring.escape</h3>
  2058. <p>The escape function used by <code>querystring.stringify</code>, provided so that it could be overridden if necessary.</p>
  2059. <h3>querystring.unescape</h3>
  2060. <p>The unescape function used by <code>querystring.parse</code>, provided so that it could be overridden if necessary.</p>
  2061. <h2 id="REPL">REPL</h2>
  2062. <p>A Read-Eval-Print-Loop (REPL) is available both as a standalone program and easily
  2063. includable in other programs. REPL provides a way to interactively run
  2064. JavaScript and see the results. It can be used for debugging, testing, or
  2065. just trying things out.</p>
  2066. <p>By executing <code>node</code> without any arguments from the command-line you will be
  2067. dropped into the REPL. It has simplistic emacs line-editting.</p>
  2068. <pre><code>mjr:~$ node
  2069. Type '.help' for options.
  2070. node&gt; a = [ 1, 2, 3];
  2071. [ 1, 2, 3 ]
  2072. node&gt; a.forEach(function (v) {
  2073. ... sys.puts(v);
  2074. ... });
  2075. 1
  2076. 2
  2077. 3
  2078. </code></pre>
  2079. <p>For advanced line-editors, start node with the environmental variable <code>NODE_NO_READLINE=1</code>.
  2080. This will start the REPL in canonical terminal settings which will allow you to use with <code>rlwrap</code>.</p>
  2081. <p>For example, you could add this to your bashrc file:</p>
  2082. <pre><code>alias node="env NODE_NO_READLINE=1 rlwrap node"
  2083. </code></pre>
  2084. <h3>repl.start(prompt, stream)</h3>
  2085. <p>Starts a REPL with <code>prompt</code> as the prompt and <code>stream</code> for all I/O. <code>prompt</code>
  2086. is optional and defaults to <code>node&gt;</code>. <code>stream</code> is optional and defaults to
  2087. <code>process.openStdin()</code>.</p>
  2088. <p>Multiple REPLs may be started against the same running instance of node. Each
  2089. will share the same global object but will have unique I/O.</p>
  2090. <p>Here is an example that starts a REPL on stdin, a Unix socket, and a TCP socket:</p>
  2091. <pre><code>var sys = require("sys"),
  2092. net = require("net"),
  2093. repl = require("repl");
  2094. connections = 0;
  2095. repl.start("node via stdin&gt; ");
  2096. net.createServer(function (socket) {
  2097. connections += 1;
  2098. repl.start("node via Unix socket&gt; ", socket);
  2099. }).listen("/tmp/node-repl-sock");
  2100. net.createServer(function (socket) {
  2101. connections += 1;
  2102. repl.start("node via TCP socket&gt; ", socket);
  2103. }).listen(5001);
  2104. </code></pre>
  2105. <p>Running this program from the command line will start a REPL on stdin. Other
  2106. REPL clients may connect through the Unix socket or TCP socket. <code>telnet</code> is useful
  2107. for connecting to TCP sockets, and <code>socat</code> can be used to connect to both Unix and
  2108. TCP sockets.</p>
  2109. <p>By starting a REPL from a Unix socket-based server instead of stdin, you can
  2110. connect to a long-running node process without restarting it.</p>
  2111. <h3>REPL Features</h3>
  2112. <p>Inside the REPL, Control+D will exit. Multi-line expressions can be input.</p>
  2113. <p>The special variable <code>_</code> (underscore) contains the result of the last expression.</p>
  2114. <pre><code>node&gt; [ "a", "b", "c" ]
  2115. [ 'a', 'b', 'c' ]
  2116. node&gt; _.length
  2117. 3
  2118. node&gt; _ += 1
  2119. 4
  2120. </code></pre>
  2121. <p>The REPL provides access to any variables in the global scope. You can expose a variable
  2122. to the REPL explicitly by assigning it to the <code>scope</code> object associated with each
  2123. <code>REPLServer</code>. For example:</p>
  2124. <pre><code>// repl_test.js
  2125. var repl = require("repl"),
  2126. msg = "message";
  2127. repl.start().scope.m = msg;
  2128. </code></pre>
  2129. <p>Things in the <code>scope</code> object appear as local within the REPL:</p>
  2130. <pre><code>mjr:~$ node repl_test.js
  2131. node&gt; m
  2132. 'message'
  2133. </code></pre>
  2134. <p>There are a few special REPL commands:</p>
  2135. <ul>
  2136. <li><p><code>.break</code> - While inputting a multi-line expression, sometimes you get lost or just don't care
  2137. about completing it. <code>.break</code> will start over.</p></li>
  2138. <li><p><code>.clear</code> - Resets the <code>scope</code> object to an empty object and clears any multi-line expression.</p></li>
  2139. <li><p><code>.exit</code> - Close the I/O stream, which will cause the REPL to exit.</p></li>
  2140. <li><p><code>.help</code> - Show this list of special commands.</p></li>
  2141. </ul>
  2142. <h2 id="Modules">Modules</h2>
  2143. <p>Node uses the CommonJS module system.</p>
  2144. <p>Node has a simple module loading system. In Node, files and modules are in
  2145. one-to-one correspondence. As an example, <code>foo.js</code> loads the module
  2146. <code>circle.js</code> in the same directory.</p>
  2147. <p>The contents of <code>foo.js</code>:</p>
  2148. <pre><code>var circle = require('./circle'),
  2149. sys = require('sys');
  2150. sys.puts( 'The area of a circle of radius 4 is '
  2151. + circle.area(4));
  2152. </code></pre>
  2153. <p>The contents of <code>circle.js</code>:</p>
  2154. <pre><code>var PI = 3.14;
  2155. exports.area = function (r) {
  2156. return PI * r * r;
  2157. };
  2158. exports.circumference = function (r) {
  2159. return 2 * PI * r;
  2160. };
  2161. </code></pre>
  2162. <p>The module <code>circle.js</code> has exported the functions <code>area()</code> and
  2163. <code>circumference()</code>. To export an object, add to the special <code>exports</code>
  2164. object. (Alternatively, one can use <code>this</code> instead of <code>exports</code>.) Variables
  2165. local to the module will be private. In this example the variable <code>PI</code> is
  2166. private to <code>circle.js</code>. The function <code>puts()</code> comes from the module <code>'sys'</code>,
  2167. which is a built-in module. Modules which are not prefixed by <code>'./'</code> are
  2168. built-in module--more about this later.</p>
  2169. <p>A module prefixed with <code>'./'</code> is relative to the file calling <code>require()</code>.
  2170. That is, <code>circle.js</code> must be in the same directory as <code>foo.js</code> for
  2171. <code>require('./circle')</code> to find it.</p>
  2172. <p>Without the leading <code>'./'</code>, like <code>require('assert')</code> the module is searched
  2173. for in the <code>require.paths</code> array. <code>require.paths</code> on my system looks like
  2174. this:</p>
  2175. <p><code>[ '/home/ryan/.node_libraries' ]</code></p>
  2176. <p>That is, when <code>require('assert')</code> is called Node looks for:</p>
  2177. <ul>
  2178. <li>1: <code>/home/ryan/.node_libraries/assert.js</code></li>
  2179. <li>2: <code>/home/ryan/.node_libraries/assert.node</code></li>
  2180. <li>3: <code>/home/ryan/.node_libraries/assert/index.js</code></li>
  2181. <li>4: <code>/home/ryan/.node_libraries/assert/index.node</code></li>
  2182. </ul>
  2183. <p>interrupting once a file is found. Files ending in <code>'.node'</code> are binary Addon
  2184. Modules; see 'Addons' below. <code>'index.js'</code> allows one to package a module as
  2185. a directory.</p>
  2186. <p><code>require.paths</code> can be modified at runtime by simply unshifting new
  2187. paths onto it, or at startup with the <code>NODE_PATH</code> environmental
  2188. variable (which should be a list of paths, colon separated).</p>
  2189. <h2 id="Addons">Addons</h2>
  2190. <p>Addons are dynamically linked shared objects. They can provide glue to C and
  2191. C++ libraries. The API (at the moment) is rather complex, involving
  2192. knowledge of several libraries:</p>
  2193. <ul>
  2194. <li><p>V8 JavaScript, a C++ library. Used for interfacing with JavaScript:
  2195. creating objects, calling functions, etc. Documented mostly in the
  2196. <code>v8.h</code> header file (<code>deps/v8/include/v8.h</code> in the Node source tree).</p></li>
  2197. <li><p>libev, C event loop library. Anytime one needs to wait for a file
  2198. descriptor to become readable, wait for a timer, or wait for a signal to
  2199. received one will need to interface with libev. That is, if you perform
  2200. any I/O, libev will need to be used. Node uses the <code>EV_DEFAULT</code> event
  2201. loop. Documentation can be found http:/cvs.schmorp.de/libev/ev.html[here].</p></li>
  2202. <li><p>libeio, C thread pool library. Used to execute blocking POSIX system
  2203. calls asynchronously. Mostly wrappers already exist for such calls, in
  2204. <code>src/file.cc</code> so you will probably not need to use it. If you do need it,
  2205. look at the header file <code>deps/libeio/eio.h</code>.</p></li>
  2206. <li><p>Internal Node libraries. Most importantly is the <code>node::ObjectWrap</code>
  2207. class which you will likely want to derive from.</p></li>
  2208. <li><p>Others. Look in <code>deps/</code> for what else is available.</p></li>
  2209. </ul>
  2210. <p>Node statically compiles all its dependencies into the executable. When
  2211. compiling your module, you don't need to worry about linking to any of these
  2212. libraries.</p>
  2213. <p>To get started let's make a small Addon which does the following except in
  2214. C++:</p>
  2215. <pre><code>exports.hello = 'world';
  2216. </code></pre>
  2217. <p>To get started we create a file <code>hello.cc</code>:</p>
  2218. <pre><code>#include &lt;v8.h&gt;
  2219. using namespace v8;
  2220. extern 'C' void
  2221. init (Handle&lt;Object> target)
  2222. {
  2223. HandleScope scope;
  2224. target-&gt;Set(String::New("hello"), String::New("World"));
  2225. }
  2226. </code></pre>
  2227. <p>This source code needs to be built into <code>hello.node</code>, the binary Addon. To
  2228. do this we create a file called <code>wscript</code> which is python code and looks
  2229. like this:</p>
  2230. <pre><code>srcdir = '.'
  2231. blddir = 'build'
  2232. VERSION = '0.0.1'
  2233. def set_options(opt):
  2234. opt.tool_options('compiler_cxx')
  2235. def configure(conf):
  2236. conf.check_tool('compiler_cxx')
  2237. conf.check_tool('node_addon')
  2238. def build(bld):
  2239. obj = bld.new_task_gen('cxx', 'shlib', 'node_addon')
  2240. obj.target = 'hello'
  2241. obj.source = 'hello.cc'
  2242. </code></pre>
  2243. <p>Running <code>node-waf configure build</code> will create a file
  2244. <code>build/default/hello.node</code> which is our Addon.</p>
  2245. <p><code>node-waf</code> is just http://code.google.com/p/waf/[WAF], the python-based build system. <code>node-waf</code> is
  2246. provided for the ease of users.</p>
  2247. <p>All Node addons must export a function called <code>init</code> with this signature:</p>
  2248. <pre><code>extern 'C' void init (Handle&lt;Object> target)
  2249. </code></pre>
  2250. <p>For the moment, that is all the documentation on addons. Please see
  2251. <a href="http://github.com/ry/node_postgres">http://github.com/ry/node_postgres</a> for a real example.</p>
  2252. </div>
  2253. </div>
  2254. <script type="text/javascript" src="./jquery.js"></script>
  2255. <script type="text/javascript" src="./sh_main.js"></script>
  2256. <script type="text/javascript" src="./sh_javascript.min.js"></script>
  2257. <script type="text/javascript" src="./doc.js"></script>
  2258. </body>
  2259. </html>