-
Notifications
You must be signed in to change notification settings - Fork 4
/
Copy pathapi.html
3282 lines (2156 loc) · 115 KB
/
api.html
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
<h1>node(1) -- evented I/O for V8 JavaScript</h1>
<h2>Sinopsis</h2>
<p>Un ejemplo de un web server escrito con Node el cual responde con 'Hola Mundo':</p>
<pre><code>var http = require('http');
http.createServer(function (request, response) {
response.writeHead(200, {'Content-Type': 'text/plain'});
response.end('Hola mundo\n');
}).listen(8124);
console.log('Server corriendo en http://127.0.0.1:8124/');
</code></pre>
<p>Para correr el server, copie el código dentro de un archivo llamado <code>ejemplo.js</code> y ejecútelo con el programa node</p>
<pre><code>> node ejemplo.js
Server corriendo en http://127.0.0.1:8124/
</code></pre>
<p>Todos los ejemplos en esta documentación puede ser corridos en forma similar.</p>
<h2>Módulos Estándar</h2>
<p>Node viene con un número de módulos que se compilan en el proceso, mayoría de los cuales se documentan a continuación.
La manera más común para usar estos módulos es con <code>require('name')</code> y luego asignar el valor devuelto a una variable local con el mismo nombre que el módulo.</p>
<p>Ejemplo:
var sys = require('sys');</p>
<p>Es posible extender node con otros módulos. Ver <code>'Modulos'</code></p>
<h2>Buffers</h2>
<p>Javascript es un Unicode amigable pero no es agradable para datos binarios. Cuando
se trata de streams TCP o de un sistema de archivos es necesario manejar bytes.
Node tiene muchas estrategias para manipular, crear y consumir bytes.</p>
<p>Los datos en bruto se almacenan en instancias de la clase <code>Buffer</code>.
Un <code>Buffer</code> es similar a un array de enteros pero se corresponde a una asignación de memoria en bruto fuera de la pila de V8.
Un <code>Buffer</code> no pude ser redimensionado.</p>
<p>NdT: octect streams ~= streams de octetos ~= bytes</p>
<p>El <code>Buffer</code> es un objeto global.</p>
<p>La conversión entre Buffers y objetos string de javascript requiere un método explícito de codificación.
Aquí están las diferentes codificaciones de strings;</p>
<ul>
<li><p><code>'ascii'</code> - sólo para 7 bit de datos ASCII. Este método de codificación es muy rápido y se desechará el bit más alto si es seteado.</p></li>
<li><p><code>'utf8'</code> - caracteres Unicode. Muchas páginas webs y otros formatos de documentos utilizan UTF-8.</p></li>
<li><p><code>'base64'</code> - codificacion de cadena en Base64.</p></li>
<li><p><code>'binary'</code> - Una manera de codificar un dato binario en bruto dentro de strings es utilizando sólo los primeros 8 bits de cada caracter.
Este método de codificación es despreciado y debería ser evitado a favor de los objectos <code>Buffer</code> cuando sea posible.
Esta codificación será removida en futuras versiones de Node.</p></li>
</ul>
<h3>new Buffer(size)</h3>
<p>Asigna un nuevo buffer de tamaño <code>size</code> de octetos/bytes.</p>
<h3>new Buffer(array)</h3>
<p>Asigna un nuevo buffer utilizando un <code>array</code> de octetos/bytes.</p>
<h3>new Buffer(str, encoding='utf8')</h3>
<p>Asigna un nuevo buffer asignando el <code>str</code> dado.</p>
<h3>buffer.write(string, offset=0, encoding='utf8')</h3>
<p>Escribe un <code>string</code> en el buffer con <code>offset</code> utilizando la codificación dada.
Retorna el número de bytes escritos. Si <code>buffer</code> no contiene espacio suficiente para que entre el string completo escribirá una cantidad parcial del string.
En el caso de codificación <code>utf8</code>, el método escribirña caracteres parciales.</p>
<p>Ejemplo: escribe una cadena utf8 dentro de un bufer, luego lo imprime</p>
<pre><code>buf = new Buffer(256);
len = buf.write('\u00bd + \u00bc = \u00be', 0);
console.log(len + " bytes: " + buf.toString('utf8', 0, len));
// 12 bytes: ½ + ¼ = ¾
</code></pre>
<h3>buffer.toString(encoding, start=0, end=buffer.length)</h3>
<p>Decodifica y retorna un string desde los datos del buffer codificando con <code>encoding</code> comenzando en <code>start</code> y finalizando en <code>end</code>.</p>
<p>Ver arriba el ejemplo <code>buffer.write()</code>.</p>
<h3>buffer[index]</h3>
<p>Toma y setea el byte en <code>index</code>. Los valores se refieren a los bytes individuales, por lo que el rango permitido es entre <code>0x00</code> y <code>0xFF</code> en hexa o <code>0</code> y <code>255</code>.</p>
<p>Ejemplo: copia un string ASCII dentro del buffer, un byte a la vez.</p>
<pre><code>str = "node.js";
buf = new Buffer(str.length);
for (var i = 0; i < str.length ; i++) {
buf[i] = str.charCodeAt(i);
}
console.log(buf);
// node.js
</code></pre>
<h3>Buffer.byteLength(string, encoding='utf8')</h3>
<p>Da la real longitud del byte de un string.
No es lo mismo que <code>String.prototype.length</code> ya que retorna el número de <em>caracteres</em> en un string.</p>
<p>Ejemplo:</p>
<pre><code>str = '\u00bd + \u00bc = \u00be';
console.log(str + ": " + str.length + " characters, " +
Buffer.byteLength(str, 'utf8') + " bytes");
// ½ + ¼ = ¾: 9 characters, 12 bytes
</code></pre>
<h3>buffer.length</h3>
<p>El tamaño del buffer en bytes. Note que esto no es necesariemente el tamaño del contenido.
<code>length</code> se refiere a la cantidad de memoria asignada para el objeto buffer.
Este no cambia cuando el contenido del buffer cambia.</p>
<p>Ejemplo:</p>
<pre><code>buf = new Buffer(1234);
console.log(buf.length);
buf.write("some string", "ascii", 0);
console.log(buf.length);
// 1234
// 1234
</code></pre>
<h3>buffer.copy(targetBuffer, targetStart, sourceStart, sourceEnd=buffer.length)</h3>
<p>Realiza un memcpy() entre buffers.</p>
<p>Ejemplo: crear dos Buffers, luego copiar <code>buf1</code> desde el byte 16 a hasta el byte 19 dentro de <code>buf2</code>, comenzando en el octavo byte en <code>buf2</code>.</p>
<pre><code>buf1 = new Buffer(26);
buf2 = new Buffer(26);
for (var i = 0 ; i < 26 ; i++) {
buf1[i] = i + 97; // 97 is ASCII a
buf2[i] = 33; // ASCII !
}
buf1.copy(buf2, 8, 16, 20);
console.log(buf2.toString('ascii', 0, 25));
// !!!!!!!!qrst!!!!!!!!!!!!!
</code></pre>
<h3>buffer.slice(start, end)</h3>
<p>Retorna un nuevo buffer el cual referencia la misma memoria que el original, pero desplaza y copia a través de los índices <code>start</code> y <code>end</code>.</p>
<p><strong>Modificando el slice del nuevo buffer modificará la memoria en el buffer original !</strong>
Ejemplo: crear un Buffer con el alfabeto en ASCII, hacer un slice, luego modificar un byte desde el Buffer original.</p>
<pre><code>var buf1 = new Buffer(26);
for (var i = 0 ; i < 26 ; i++) {
buf1[i] = i + 97; // 97 es 'a' en ASCII
}
var buf2 = buf1.slice(0, 3);
console.log(buf2.toString('ascii', 0, buf2.length));
buf1[0] = 33;
console.log(buf2.toString('ascii', 0, buf2.length));
// abc
// !bc
</code></pre>
<h2>EventEmitter</h2>
<p>Muchos objetos en Node emiten eventos: un servidor TCP emite un evento
cada vez que hay un stream, un proceso hijo emite un evento al salir.
Todos los objetos que emiten eventos son instancias de <code>events.EventEmitter</code>.</p>
<p>Los eventos se representan mediante una cadena con estilo camel case. Algunos
ejemplos podrían ser:
<code>'stream'</code>, <code>'data'</code>, <code>'messageBegin'</code>.</p>
<p>De esta manera, podemos agregar funciones a los objetos, para ser ejecutadas
cuando un evento es emitido. Estas funciones son llamadas <em>listeners</em>.</p>
<p><code>require('events').EventEmitter</code> para acceder a la clase <code>EventEmitter</code>.</p>
<p>Todos los emisores de eventos (EventEmitters) emiten el evento <code>'newListener'</code>
al ser agregadas nuevas funciones listeners.</p>
<p>Cuando un <code>EventEmitter</code> encuentra un error, la acción usual a tomar es emitir
un evento <code>'error'</code>. Los eventos de error son especiales--si no hay un handler
para ellos, mostrarán un stack trace y detendrán el programa.</p>
<h3>Evento: 'newListener'</h3>
<p><code>function (event, listener) { }</code></p>
<p>Este evento se emite al ser agregado un nuevo listener.</p>
<h3>Evento: 'error'</h3>
<p><code>function (exception) { }</code></p>
<p>Este evento es emitido al ser encontrado un error. Este evento es
especial - cuando no existen funciones listeners que reciban el error,
Node terminará la ejecución y presentará el stack trace de las
excepciones.</p>
<h3>emitter.on(event, listener)</h3>
<p>Agrega una función listener al final del arreglo de funciones listeners
para el evento especificado.</p>
<pre><code>server.on('stream', function (stream) {
console.log('someone connected!');
});
</code></pre>
<h3>emitter.removeListener(event, listener)</h3>
<p>Elimina una función listener del arreglo de funciones listeners para
el evento especificado.
<strong>Precaucíón</strong>: esto modifica los índices del array en el arreglo de
listeners detrás del listener. </p>
<pre><code>var callback = function(stream) {
console.log('someone connected!');
};
server.on('stream', callback);
// ...
server.removeListener('stream', callback);
</code></pre>
<h3>emitter.removeAllListeners(event)</h3>
<p>Elimina todos los listeners del arreglo de listeners para el evento
especificado.</p>
<h3>emitter.listeners(event)</h3>
<p>Devuelve un arreglo de listeners para el evento especificado. Este arreglo
puede ser modificado. Ej.: para eliminar listeners. </p>
<pre><code>server.on('stream', function (stream) {
console.log('someone connected!');
});
console.log(sys.inspect(server.listeners('stream'));
// [ [Function] ]
</code></pre>
<h3>emitter.emit(event, [arg1], [arg2], [...])</h3>
<p>Ejecuta cada uno de los listeners de acuerdo al orden de los argumentos.</p>
<h2>Streams</h2>
<p>Un stream es una interface abstracta implementada por varios objetos en Node.
Por ejemplo, una solicitud a un servidor HTTP es un stream, como lo es stdout.
Los streams son de escritura, lectura o ambos. Todos los streams son instancias
de <code>EventEmitter</code>.</p>
<h2>Stream de lectura</h2>
<p>Un <code>Stream de lectura</code> tiene los siguientes métodos, miembros y eventos.</p>
<h3>Evento: 'data'</h3>
<p><code>function (data) { }</code></p>
<p>El evento <code>'data'</code> emite un <code>Buffer</code> (predeterminado) o una cadena si fue utilizado
<code>setEncoding()</code>.</p>
<h3>Evento: 'end'</h3>
<p><code>function () { }</code></p>
<p>Es emitido cuando el stream ha recibido un EOF (FIN en terminología TCP).
Indica que no habrán más eventos <code>'data'</code>. En caso que el stream sea de escritura,
se podrá continuar escribiendo.</p>
<h3>Evento: 'error'</h3>
<p><code>function (exception) { }</code></p>
<p>Es emitido si hubo un error al recibir datos. </p>
<h3>Evento: 'close'</h3>
<p><code>function () { }</code>
Es emitido cuando el descriptor de archivos subyacente debe ser cerrado. No
todos los streams lo emitirán. Por ejemplo, una solicitud HTTP no emitirá
<code>'close'</code>.</p>
<h3>Evento: 'fd'</h3>
<p><code>function (fd) { }</code></p>
<p>Es emitido cuando el archivo descriptor es recibido en el stream. Solo streams
de Unix soportan esta funcionalidad; los demás, simplemente nunca emitirán este
evento.</p>
<h3>stream.readable</h3>
<p>A boolean that is <code>true</code> by default, but turns <code>false</code> after an <code>'error'</code>
occured, the stream came to an <code>'end'</code>, or <code>destroy()</code> was called.</p>
<h3>stream.setEncoding(encoding)</h3>
<p>Makes the data event emit a string instead of a <code>Buffer</code>. <code>encoding</code> can be
<code>'utf8'</code>, <code>'ascii'</code>, or <code>'base64'</code>.</p>
<h3>stream.pause()</h3>
<p>Pauses the incoming <code>'data'</code> events.</p>
<h3>stream.resume()</h3>
<p>Resumes the incoming <code>'data'</code> events after a <code>pause()</code>.</p>
<h3>stream.destroy()</h3>
<p>Closes the underlying file descriptor. Stream will not emit any more events.</p>
<h2>Writable Stream</h2>
<p>A <code>Writable Stream</code> has the following methods, members, and events.</p>
<h3>Event: 'drain'</h3>
<p><code>function () { }</code></p>
<p>Emitted after a <code>write()</code> method was called that returned <code>false</code> to
indicate that it is safe to write again.</p>
<h3>Event: 'error'</h3>
<p><code>function (exception) { }</code></p>
<p>Emitted on error with the exception <code>exception</code>.</p>
<h3>Event: 'close'</h3>
<p><code>function () { }</code></p>
<p>Emitted when the underlying file descriptor has been closed.</p>
<h3>stream.writeable</h3>
<p>A boolean that is <code>true</code> by default, but turns <code>false</code> after an <code>'error'</code>
occurred or <code>end()</code> / <code>destroy()</code> was called.</p>
<h3>stream.write(string, encoding='utf8', [fd])</h3>
<p>Writes <code>string</code> with the given <code>encoding</code> to the stream. Returns <code>true</code> if
the string has been flushed to the kernel buffer. Returns <code>false</code> to
indicate that the kernel buffer is full, and the data will be sent out in
the future. The <code>'drain'</code> event will indicate when the kernel buffer is
empty again. The <code>encoding</code> defaults to <code>'utf8'</code>.</p>
<p>If the optional <code>fd</code> parameter is specified, it is interpreted as an integral
file descriptor to be sent over the stream. This is only supported for UNIX
streams, and is silently ignored otherwise. When writing a file descriptor in
this manner, closing the descriptor before the stream drains risks sending an
invalid (closed) FD.</p>
<h3>stream.write(buffer)</h3>
<p>Same as the above except with a raw buffer.</p>
<h3>stream.end()</h3>
<p>Terminates the stream with EOF or FIN.</p>
<h3>stream.end(string, encoding)</h3>
<p>Sends <code>string</code> with the given <code>encoding</code> and terminates the stream with EOF
or FIN. This is useful to reduce the number of packets sent.</p>
<h3>stream.end(buffer)</h3>
<p>Same as above but with a <code>buffer</code>.</p>
<h3>stream.destroy()</h3>
<p>Closes the underlying file descriptor. Stream will not emit any more events.</p>
<h2>Global Objects</h2>
<p>These object are available in the global scope and can be accessed from anywhere.</p>
<h3>global</h3>
<p>The global namespace object.</p>
<h3>process</h3>
<p>The process object. See the <code>'process object'</code> section.</p>
<h3>require()</h3>
<p>To require modules. See the <code>'Modules'</code> section.</p>
<h3>require.paths</h3>
<p>An array of search paths for <code>require()</code>. This array can be modified to add custom paths.</p>
<p>Example: add a new path to the beginning of the search list</p>
<pre><code>require.paths.unshift('/usr/local/node');
console.log(require.paths);
// /usr/local/node,/Users/mjr/.node_libraries
</code></pre>
<h3>__filename</h3>
<p>The filename of the script being executed. This is the absolute path, and not necessarily
the same filename passed in as a command line argument.</p>
<p>Example: running <code>node example.js</code> from <code>/Users/mjr</code></p>
<pre><code>console.log(__filename);
// /Users/mjr/example.js
</code></pre>
<h3>__dirname</h3>
<p>The dirname of the script being executed.</p>
<p>Example: running <code>node example.js</code> from <code>/Users/mjr</code></p>
<pre><code>console.log(__dirname);
// /Users/mjr
</code></pre>
<h3>module</h3>
<p>A reference to the current module (of type <code>process.Module</code>). In particular
<code>module.exports</code> is the same as the <code>exports</code> object. See <code>src/process.js</code>
for more information.</p>
<h2>process</h2>
<p>The <code>process</code> object is a global object and can be accessed from anywhere.
It is an instance of <code>EventEmitter</code>.</p>
<h3>Event: 'exit'</h3>
<p><code>function () {}</code></p>
<p>Emitted when the process is about to exit. This is a good hook to perform
constant time checks of the module's state (like for unit tests). The main
event loop will no longer be run after the 'exit' callback finishes, so
timers may not be scheduled.</p>
<p>Example of listening for <code>exit</code>:</p>
<pre><code>process.on('exit', function () {
process.nextTick(function () {
console.log('This will not run');
});
console.log('About to exit.');
});
</code></pre>
<h3>Event: 'uncaughtException'</h3>
<p><code>function (err) { }</code></p>
<p>Emitted when an exception bubbles all the way back to the event loop. If a
listener is added for this exception, the default action (which is to print
a stack trace and exit) will not occur.</p>
<p>Example of listening for <code>uncaughtException</code>:</p>
<pre><code>process.on('uncaughtException', function (err) {
console.log('Caught exception: ' + err);
});
setTimeout(function () {
console.log('This will still run.');
}, 500);
// Intentionally cause an exception, but don't catch it.
nonexistentFunc();
console.log('This will not run.');
</code></pre>
<p>Note that <code>uncaughtException</code> is a very crude mechanism for exception
handling. Using try / catch in your program will give you more control over
your program's flow. Especially for server programs that are designed to
stay running forever, <code>uncaughtException</code> can be a useful safety mechanism.</p>
<h3>Signal Events</h3>
<p><code>function () {}</code></p>
<p>Emitted when the processes receives a signal. See sigaction(2) for a list of
standard POSIX signal names such as SIGINT, SIGUSR1, etc.</p>
<p>Example of listening for <code>SIGINT</code>:</p>
<pre><code>var stdin = process.openStdin();
process.on('SIGINT', function () {
console.log('Got SIGINT. Press Control-D to exit.');
});
</code></pre>
<p>An easy way to send the <code>SIGINT</code> signal is with <code>Control-C</code> in most terminal
programs.</p>
<h3>process.stdout</h3>
<p>A <code>Writable Stream</code> to <code>stdout</code>.</p>
<p>Example: the definition of <code>console.log</code></p>
<pre><code>console.log = function (d) {
process.stdout.write(d + '\n');
};
</code></pre>
<h3>process.openStdin()</h3>
<p>Opens the standard input stream, returns a <code>Readable Stream</code>.</p>
<p>Example of opening standard input and listening for both events:</p>
<pre><code>var stdin = process.openStdin();
stdin.setEncoding('utf8');
stdin.on('data', function (chunk) {
process.stdout.write('data: ' + chunk);
});
stdin.on('end', function () {
process.stdout.write('end');
});
</code></pre>
<h3>process.argv</h3>
<p>An array containing the command line arguments. The first element will be
'node', the second element will be the name of the JavaScript file. The
next elements will be any additional command line arguments.</p>
<pre><code>// print process.argv
process.argv.forEach(function (val, index, array) {
console.log(index + ': ' + val);
});
</code></pre>
<p>This will generate:</p>
<pre><code>$ node process-2.js one two=three four
0: node
1: /Users/mjr/work/node/process-2.js
2: one
3: two=three
4: four
</code></pre>
<h3>process.execPath</h3>
<p>This is the absolute pathname of the executable that started the process.</p>
<p>Example:</p>
<pre><code>/usr/local/bin/node
</code></pre>
<h3>process.chdir(directory)</h3>
<p>Changes the current working directory of the process or throws an exception if that fails.</p>
<pre><code>console.log('Starting directory: ' + process.cwd());
try {
process.chdir('/tmp');
console.log('New directory: ' + process.cwd());
}
catch (err) {
console.log('chdir: ' + err);
}
</code></pre>
<h3>process.compile(code, filename)</h3>
<p>Similar to <code>eval</code> except that you can specify a <code>filename</code> for better
error reporting and the <code>code</code> cannot see the local scope. The value of <code>filename</code>
will be used as a filename if a stack trace is generated by the compiled code.</p>
<p>Example of using <code>process.compile</code> and <code>eval</code> to run the same code:</p>
<pre><code>var localVar = 123,
compiled, evaled;
compiled = process.compile('localVar = 1;', 'myfile.js');
console.log('localVar: ' + localVar + ', compiled: ' + compiled);
evaled = eval('localVar = 1;');
console.log('localVar: ' + localVar + ', evaled: ' + evaled);
// localVar: 123, compiled: 1
// localVar: 1, evaled: 1
</code></pre>
<p><code>process.compile</code> does not have access to the local scope, so <code>localVar</code> is unchanged.
<code>eval</code> does have access to the local scope, so <code>localVar</code> is changed.</p>
<p>In case of syntax error in <code>code</code>, <code>process.compile</code> exits node.</p>
<p>See also: <code>Script</code></p>
<h3>process.cwd()</h3>
<p>Returns the current working directory of the process.</p>
<pre><code>console.log('Current directory: ' + process.cwd());
</code></pre>
<h3>process.env</h3>
<p>An object containing the user environment. See environ(7).</p>
<h3>process.exit(code=0)</h3>
<p>Ends the process with the specified <code>code</code>. If omitted, exit uses the
'success' code <code>0</code>.</p>
<p>To exit with a 'failure' code:</p>
<pre><code>process.exit(1);
</code></pre>
<p>The shell that executed node should see the exit code as 1.</p>
<h3>process.getgid()</h3>
<p>Gets the group identity of the process. (See getgid(2).) This is the numerical group id, not the group name.</p>
<pre><code>console.log('Current gid: ' + process.getgid());
</code></pre>
<h3>process.setgid(id)</h3>
<p>Sets the group identity of the process. (See setgid(2).) This accepts either a numerical ID or a groupname string. If a groupname is specified, this method blocks while resolving it to a numerical ID.</p>
<pre><code>console.log('Current gid: ' + process.getgid());
try {
process.setgid(501);
console.log('New gid: ' + process.getgid());
}
catch (err) {
console.log('Failed to set gid: ' + err);
}
</code></pre>
<h3>process.getuid()</h3>
<p>Gets the user identity of the process. (See getuid(2).) This is the numerical userid, not the username.</p>
<pre><code>console.log('Current uid: ' + process.getuid());
</code></pre>
<h3>process.setuid(id)</h3>
<p>Sets the user identity of the process. (See setuid(2).) This accepts either a numerical ID or a username string. If a username is specified, this method blocks while resolving it to a numerical ID.</p>
<pre><code>console.log('Current uid: ' + process.getuid());
try {
process.setuid(501);
console.log('New uid: ' + process.getuid());
}
catch (err) {
console.log('Failed to set uid: ' + err);
}
</code></pre>
<h3>process.version</h3>
<p>A compiled-in property that exposes <code>NODE_VERSION</code>.</p>
<pre><code>console.log('Version: ' + process.version);
</code></pre>
<h3>process.installPrefix</h3>
<p>A compiled-in property that exposes <code>NODE_PREFIX</code>.</p>
<pre><code>console.log('Prefix: ' + process.installPrefix);
</code></pre>
<h3>process.kill(pid, signal='SIGINT')</h3>
<p>Send a signal to a process. <code>pid</code> is the process id and <code>signal</code> is the
string describing the signal to send. Signal names are strings like
'SIGINT' or 'SIGUSR1'. If omitted, the signal will be 'SIGINT'.
See kill(2) for more information.</p>
<p>Note that just because the name of this function is <code>process.kill</code>, it is
really just a signal sender, like the <code>kill</code> system call. The signal sent
may do something other than kill the target process.</p>
<p>Example of sending a signal to yourself:</p>
<pre><code>process.on('SIGHUP', function () {
console.log('Got SIGHUP signal.');
});
setTimeout(function () {
console.log('Exiting.');
process.exit(0);
}, 100);
process.kill(process.pid, 'SIGHUP');
</code></pre>
<h3>process.pid</h3>
<p>The PID of the process.</p>
<pre><code>console.log('This process is pid ' + process.pid);
</code></pre>
<h3>process.title</h3>
<p>Getter/setter to set what is displayed in 'ps'.</p>
<h3>process.platform</h3>
<p>What platform you're running on. <code>'linux2'</code>, <code>'darwin'</code>, etc.</p>
<pre><code>console.log('This platform is ' + process.platform);
</code></pre>
<h3>process.memoryUsage()</h3>
<p>Returns an object describing the memory usage of the Node process.</p>
<pre><code>var sys = require('sys');
console.log(sys.inspect(process.memoryUsage()));
</code></pre>
<p>This will generate:</p>
<pre><code>{ rss: 4935680
, vsize: 41893888
, heapTotal: 1826816
, heapUsed: 650472
}
</code></pre>
<p><code>heapTotal</code> and <code>heapUsed</code> refer to V8's memory usage.</p>
<h3>process.nextTick(callback)</h3>
<p>On the next loop around the event loop call this callback.
This is <em>not</em> a simple alias to <code>setTimeout(fn, 0)</code>, it's much more
efficient.</p>
<pre><code>process.nextTick(function () {
console.log('nextTick callback');
});
</code></pre>
<h3>process.umask([mask])</h3>
<p>Sets or reads the process's file mode creation mask. Child processes inherit
the mask from the parent process. Returns the old mask if <code>mask</code> argument is
given, otherwise returns the current mask.</p>
<pre><code>var oldmask, newmask = 0644;
oldmask = process.umask(newmask);
console.log('Changed umask from: ' + oldmask.toString(8) +
' to ' + newmask.toString(8));
</code></pre>
<h2>sys</h2>
<p>These functions are in the module <code>'sys'</code>. Use <code>require('sys')</code> to access
them.</p>
<h3>sys.print(string)</h3>
<p>Like <code>console.log()</code> but without the trailing newline.</p>
<pre><code>require('sys').print('String with no newline');
</code></pre>
<h3>sys.debug(string)</h3>
<p>A synchronous output function. Will block the process and
output <code>string</code> immediately to <code>stderr</code>.</p>
<pre><code>require('sys').debug('message on stderr');
</code></pre>
<h3>sys.log(string)</h3>
<p>Output with timestamp on <code>stdout</code>.</p>
<pre><code>require('sys').log('Timestmaped message.');
</code></pre>
<h3>sys.inspect(object, showHidden=false, depth=2)</h3>
<p>Return a string representation of <code>object</code>, which is useful for debugging.</p>
<p>If <code>showHidden</code> is <code>true</code>, then the object's non-enumerable properties will be
shown too.</p>
<p>If <code>depth</code> is provided, it tells <code>inspect</code> how many times to recurse while
formatting the object. This is useful for inspecting large complicated objects.</p>
<p>The default is to only recurse twice. To make it recurse indefinitely, pass
in <code>null</code> for <code>depth</code>.</p>
<p>Example of inspecting all properties of the <code>sys</code> object:</p>
<pre><code>var sys = require('sys');
console.log(sys.inspect(sys, true, null));
</code></pre>
<h3>sys.pump(readableStream, writeableStream, [callback])</h3>
<p>Experimental</p>
<p>Read the data from <code>readableStream</code> and send it to the <code>writableStream</code>.
When <code>writeableStream.write(data)</code> returns <code>false</code> <code>readableStream</code> will be
paused until the <code>drain</code> event occurs on the <code>writableStream</code>. <code>callback</code> gets
an error as its only argument and is called when <code>writableStream</code> is closed or
when an error occurs.</p>
<h2>Timers</h2>
<h3>setTimeout(callback, delay, [arg], [...])</h3>
<p>To schedule execution of <code>callback</code> after <code>delay</code> milliseconds. Returns a
<code>timeoutId</code> for possible use with <code>clearTimeout()</code>. Optionally, you can
also pass arguments to the callback.</p>
<h3>clearTimeout(timeoutId)</h3>
<p>Prevents a timeout from triggering.</p>
<h3>setInterval(callback, delay, [arg], [...])</h3>
<p>To schedule the repeated execution of <code>callback</code> every <code>delay</code> milliseconds.
Returns a <code>intervalId</code> for possible use with <code>clearInterval()</code>. Optionally,
you can also pass arguments to the callback.</p>
<h3>clearInterval(intervalId)</h3>
<p>Stops a interval from triggering.</p>
<h2>Child Processes</h2>
<p>Node provides a tri-directional <code>popen(3)</code> facility through the <code>ChildProcess</code>
class.</p>
<p>It is possible to stream data through the child's <code>stdin</code>, <code>stdout</code>, and
<code>stderr</code> in a fully non-blocking way.</p>
<p>To create a child process use <code>require('child_process').spawn()</code>.</p>
<p>Child processes always have three streams associated with them. <code>child.stdin</code>,
<code>child.stdout</code>, and <code>child.stderr</code>.</p>
<p><code>ChildProcess</code> is an <code>EventEmitter</code>.</p>
<h3>Event: 'exit'</h3>
<p><code>function (code, signal) {}</code></p>
<p>This event is emitted after the child process ends. If the process terminated
normally, <code>code</code> is the final exit code of the process, otherwise <code>null</code>. If
the process terminated due to receipt of a signal, <code>signal</code> is the string name
of the signal, otherwise <code>null</code>.</p>
<p>After this event is emitted, the <code>'output'</code> and <code>'error'</code> callbacks will no
longer be made.</p>
<p>See <code>waitpid(2)</code>.</p>
<h3>child.stdin</h3>
<p>A <code>Writable Stream</code> that represents the child process's <code>stdin</code>.
Closing this stream via <code>end()</code> often causes the child process to terminate.</p>
<h3>child.stdout</h3>
<p>A <code>Readable Stream</code> that represents the child process's <code>stdout</code>.</p>
<h3>child.stderr</h3>
<p>A <code>Readable Stream</code> that represents the child process's <code>stderr</code>.</p>
<h3>child.pid</h3>
<p>The PID of the child process.</p>
<p>Example:</p>
<pre><code>var spawn = require('child_process').spawn,
grep = spawn('grep', ['ssh']);
console.log('Spawned child pid: ' + grep.pid);
grep.stdin.end();
</code></pre>
<h3>child_process.spawn(command, args=[], [options])</h3>
<p>Launches a new process with the given <code>command</code>, with command line arguments in <code>args</code>.
If omitted, <code>args</code> defaults to an empty Array.</p>
<p>The third argument is used to specify additional options, which defaults to:</p>
<pre><code>{ cwd: undefined
, env: process.env,
, customFds: [-1, -1, -1]
}
</code></pre>
<p><code>cwd</code> allows you to specify the working directory from which the process is spawned.
Use <code>env</code> to specify environment variables that will be visible to the new process.
With <code>customFds</code> it is possible to hook up the new process' [stdin, stout, stderr] to
existing streams; <code>-1</code> means that a new stream should be created.</p>
<p>Example of running <code>ls -lh /usr</code>, capturing <code>stdout</code>, <code>stderr</code>, and the exit code:</p>
<pre><code>var sys = require('sys'),
spawn = require('child_process').spawn,
ls = spawn('ls', ['-lh', '/usr']);
ls.stdout.on('data', function (data) {
sys.print('stdout: ' + data);
});
ls.stderr.on('data', function (data) {
sys.print('stderr: ' + data);
});
ls.on('exit', function (code) {
console.log('child process exited with code ' + code);
});
</code></pre>
<p>Example: A very elaborate way to run 'ps ax | grep ssh'</p>
<pre><code>var sys = require('sys'),
spawn = require('child_process').spawn,
ps = spawn('ps', ['ax']),
grep = spawn('grep', ['ssh']);
ps.stdout.on('data', function (data) {
grep.stdin.write(data);
});
ps.stderr.on('data', function (data) {
sys.print('ps stderr: ' + data);
});
ps.on('exit', function (code) {
if (code !== 0) {
console.log('ps process exited with code ' + code);
}
grep.stdin.end();
});
grep.stdout.on('data', function (data) {
sys.print(data);
});
grep.stderr.on('data', function (data) {
sys.print('grep stderr: ' + data);
});
grep.on('exit', function (code) {
if (code !== 0) {
console.log('grep process exited with code ' + code);
}
});