doc: set logical umask in process.umask example
[platform/upstream/nodejs.git] / doc / api / process.markdown
1 # process
2
3 <!-- type=global -->
4
5 The `process` object is a global object and can be accessed from anywhere.
6 It is an instance of [EventEmitter][].
7
8 ## Exit Codes
9
10 Node will normally exit with a `0` status code when no more async
11 operations are pending.  The following status codes are used in other
12 cases:
13
14 * `1` **Uncaught Fatal Exception** - There was an uncaught exception,
15   and it was not handled by a domain or an `uncaughtException` event
16   handler.
17 * `2` - Unused (reserved by Bash for builtin misuse)
18 * `3` **Internal JavaScript Parse Error** - The JavaScript source code
19   internal in Node's bootstrapping process caused a parse error.  This
20   is extremely rare, and generally can only happen during development
21   of Node itself.
22 * `4` **Internal JavaScript Evaluation Failure** - The JavaScript
23   source code internal in Node's bootstrapping process failed to
24   return a function value when evaluated.  This is extremely rare, and
25   generally can only happen during development of Node itself.
26 * `5` **Fatal Error** - There was a fatal unrecoverable error in V8.
27   Typically a message will be printed to stderr with the prefix `FATAL
28   ERROR`.
29 * `6` **Non-function Internal Exception Handler** - There was an
30   uncaught exception, but the internal fatal exception handler
31   function was somehow set to a non-function, and could not be called.
32 * `7` **Internal Exception Handler Run-Time Failure** - There was an
33   uncaught exception, and the internal fatal exception handler
34   function itself threw an error while attempting to handle it.  This
35   can happen, for example, if a `process.on('uncaughtException')` or
36   `domain.on('error')` handler throws an error.
37 * `8` - Unused.  In previous versions of Node, exit code 8 sometimes
38   indicated an uncaught exception.
39 * `9` - **Invalid Argument** - Either an unknown option was specified,
40   or an option requiring a value was provided without a value.
41 * `10` **Internal JavaScript Run-Time Failure** - The JavaScript
42   source code internal in Node's bootstrapping process threw an error
43   when the bootstrapping function was called.  This is extremely rare,
44   and generally can only happen during development of Node itself.
45 * `12` **Invalid Debug Argument** - The `--debug` and/or `--debug-brk`
46   options were set, but an invalid port number was chosen.
47 * `>128` **Signal Exits** - If Node receives a fatal signal such as
48   `SIGKILL` or `SIGHUP`, then its exit code will be `128` plus the
49   value of the signal code.  This is a standard Unix practice, since
50   exit codes are defined to be 7-bit integers, and signal exits set
51   the high-order bit, and then contain the value of the signal code.
52
53 ## Event: 'exit'
54
55 Emitted when the process is about to exit. There is no way to prevent the
56 exiting of the event loop at this point, and once all `exit` listeners have
57 finished running the process will exit. Therefore you **must** only perform
58 **synchronous** operations in this handler. This is a good hook to perform
59 checks on the module's state (like for unit tests). The callback takes one
60 argument, the code the process is exiting with.
61
62 Example of listening for `exit`:
63
64     process.on('exit', function(code) {
65       // do *NOT* do this
66       setTimeout(function() {
67         console.log('This will not run');
68       }, 0);
69       console.log('About to exit with code:', code);
70     });
71
72
73 ## Event: 'beforeExit'
74
75 This event is emitted when node empties it's event loop and has nothing else to
76 schedule. Normally, node exits when there is no work scheduled, but a listener
77 for 'beforeExit' can make asynchronous calls, and cause node to continue.
78
79 'beforeExit' is not emitted for conditions causing explicit termination, such as
80 `process.exit()` or uncaught exceptions, and should not be used as an
81 alternative to the 'exit' event unless the intention is to schedule more work.
82
83
84 ## Event: 'uncaughtException'
85
86 Emitted when an exception bubbles all the way back to the event loop. If a
87 listener is added for this exception, the default action (which is to print
88 a stack trace and exit) will not occur.
89
90 Example of listening for `uncaughtException`:
91
92     process.on('uncaughtException', function(err) {
93       console.log('Caught exception: ' + err);
94     });
95
96     setTimeout(function() {
97       console.log('This will still run.');
98     }, 500);
99
100     // Intentionally cause an exception, but don't catch it.
101     nonexistentFunc();
102     console.log('This will not run.');
103
104 Note that `uncaughtException` is a very crude mechanism for exception
105 handling.
106
107 Don't use it, use [domains](domain.html) instead. If you do use it, restart
108 your application after every unhandled exception!
109
110 Do *not* use it as the node.js equivalent of `On Error Resume Next`. An
111 unhandled exception means your application - and by extension node.js itself -
112 is in an undefined state. Blindly resuming means *anything* could happen.
113
114 Think of resuming as pulling the power cord when you are upgrading your system.
115 Nine out of ten times nothing happens - but the 10th time, your system is bust.
116
117 You have been warned.
118
119 ## Signal Events
120
121 <!--type=event-->
122 <!--name=SIGINT, SIGHUP, etc.-->
123
124 Emitted when the processes receives a signal. See sigaction(2) for a list of
125 standard POSIX signal names such as SIGINT, SIGHUP, etc.
126
127 Example of listening for `SIGINT`:
128
129     // Start reading from stdin so we don't exit.
130     process.stdin.resume();
131
132     process.on('SIGINT', function() {
133       console.log('Got SIGINT.  Press Control-D to exit.');
134     });
135
136 An easy way to send the `SIGINT` signal is with `Control-C` in most terminal
137 programs.
138
139 Note:
140
141 - `SIGUSR1` is reserved by node.js to start the debugger.  It's possible to
142   install a listener but that won't stop the debugger from starting.
143 - `SIGTERM` and `SIGINT` have default handlers on non-Windows platforms that resets
144   the terminal mode before exiting with code `128 + signal number`. If one of
145   these signals has a listener installed, its default behaviour will be removed
146   (node will no longer exit).
147 - `SIGPIPE` is ignored by default, it can have a listener installed.
148 - `SIGHUP` is generated on Windows when the console window is closed, and on other
149   platforms under various similar conditions, see signal(7). It can have a
150   listener installed, however node will be unconditionally terminated by Windows
151   about 10 seconds later. On non-Windows platforms, the default behaviour of
152   `SIGHUP` is to terminate node, but once a listener has been installed its
153   default behaviour will be removed.
154 - `SIGTERM` is not supported on Windows, it can be listened on.
155 - `SIGINT` from the terminal is supported on all platforms, and can usually be
156   generated with `CTRL+C` (though this may be configurable). It is not generated
157   when terminal raw mode is enabled.
158 - `SIGBREAK` is delivered on Windows when `CTRL+BREAK` is pressed, on non-Windows
159   platforms it can be listened on, but there is no way to send or generate it.
160 - `SIGWINCH` is delivered when the console has been resized. On Windows, this will
161   only happen on write to the console when the cursor is being moved, or when a
162   readable tty is used in raw mode.
163 - `SIGKILL` cannot have a listener installed, it will unconditionally terminate
164   node on all platforms.
165 - `SIGSTOP` cannot have a listener installed.
166
167 Note that Windows does not support sending Signals, but node offers some
168 emulation with `process.kill()`, and `child_process.kill()`:
169 - Sending signal `0` can be used to search for the existence of a process
170 - Sending `SIGINT`, `SIGTERM`, and `SIGKILL` cause the unconditional exit of the
171   target process.
172
173 ## process.stdout
174
175 A `Writable Stream` to `stdout`.
176
177 Example: the definition of `console.log`
178
179     console.log = function(d) {
180       process.stdout.write(d + '\n');
181     };
182
183 `process.stderr` and `process.stdout` are unlike other streams in Node in
184 that they cannot be closed (`end()` will throw), they never emit the `finish`
185 event and that writes are usually blocking.
186
187 - They are blocking in the case that they refer to regular files or TTY file
188   descriptors.
189 - In the case they refer to pipes:
190   - They are blocking in Linux/Unix.
191   - They are non-blocking like other streams in Windows.
192
193 To check if Node is being run in a TTY context, read the `isTTY` property
194 on `process.stderr`, `process.stdout`, or `process.stdin`:
195
196     $ node -p "Boolean(process.stdin.isTTY)"
197     true
198     $ echo "foo" | node -p "Boolean(process.stdin.isTTY)"
199     false
200
201     $ node -p "Boolean(process.stdout.isTTY)"
202     true
203     $ node -p "Boolean(process.stdout.isTTY)" | cat
204     false
205
206 See [the tty docs](tty.html#tty_tty) for more information.
207
208 ## process.stderr
209
210 A writable stream to stderr.
211
212 `process.stderr` and `process.stdout` are unlike other streams in Node in
213 that they cannot be closed (`end()` will throw), they never emit the `finish`
214 event and that writes are usually blocking.
215
216 - They are blocking in the case that they refer to regular files or TTY file
217   descriptors.
218 - In the case they refer to pipes:
219   - They are blocking in Linux/Unix.
220   - They are non-blocking like other streams in Windows.
221
222
223 ## process.stdin
224
225 A `Readable Stream` for stdin. 
226
227 Example of opening standard input and listening for both events:
228
229     process.stdin.setEncoding('utf8');
230
231     process.stdin.on('readable', function() {
232       var chunk = process.stdin.read();
233       if (chunk !== null) {
234         process.stdout.write('data: ' + chunk);
235       }
236     });
237
238     process.stdin.on('end', function() {
239       process.stdout.write('end');
240     });
241
242 As a Stream, `process.stdin` can also be used in "old" mode that is compatible
243 with scripts written for node prior v0.10.
244 For more information see
245 [Stream compatibility](stream.html#stream_compatibility_with_older_node_versions).
246
247 In "old" Streams mode the stdin stream is paused by default, so one
248 must call `process.stdin.resume()` to read from it. Note also that calling
249 `process.stdin.resume()` itself would switch stream to "old" mode.
250
251 If you are starting a new project you should prefer a more recent "new" Streams
252 mode over "old" one.
253
254 ## process.argv
255
256 An array containing the command line arguments.  The first element will be
257 'node', the second element will be the name of the JavaScript file.  The
258 next elements will be any additional command line arguments.
259
260     // print process.argv
261     process.argv.forEach(function(val, index, array) {
262       console.log(index + ': ' + val);
263     });
264
265 This will generate:
266
267     $ node process-2.js one two=three four
268     0: node
269     1: /Users/mjr/work/node/process-2.js
270     2: one
271     3: two=three
272     4: four
273
274
275 ## process.execPath
276
277 This is the absolute pathname of the executable that started the process.
278
279 Example:
280
281     /usr/local/bin/node
282
283
284 ## process.execArgv
285
286 This is the set of node-specific command line options from the
287 executable that started the process.  These options do not show up in
288 `process.argv`, and do not include the node executable, the name of
289 the script, or any options following the script name. These options
290 are useful in order to spawn child processes with the same execution
291 environment as the parent.
292
293 Example:
294
295     $ node --harmony script.js --version
296
297 results in process.execArgv:
298
299     ['--harmony']
300
301 and process.argv:
302
303     ['/usr/local/bin/node', 'script.js', '--version']
304
305
306 ## process.abort()
307
308 This causes node to emit an abort. This will cause node to exit and
309 generate a core file.
310
311 ## process.chdir(directory)
312
313 Changes the current working directory of the process or throws an exception if that fails.
314
315     console.log('Starting directory: ' + process.cwd());
316     try {
317       process.chdir('/tmp');
318       console.log('New directory: ' + process.cwd());
319     }
320     catch (err) {
321       console.log('chdir: ' + err);
322     }
323
324
325
326 ## process.cwd()
327
328 Returns the current working directory of the process.
329
330     console.log('Current directory: ' + process.cwd());
331
332
333 ## process.env
334
335 An object containing the user environment. See environ(7).
336
337 An example of this object looks like:
338
339     { TERM: 'xterm-256color',
340       SHELL: '/usr/local/bin/bash',
341       USER: 'maciej',
342       PATH: '~/.bin/:/usr/bin:/bin:/usr/sbin:/sbin:/usr/local/bin',
343       PWD: '/Users/maciej',
344       EDITOR: 'vim',
345       SHLVL: '1',
346       HOME: '/Users/maciej',
347       LOGNAME: 'maciej',
348       _: '/usr/local/bin/node' }
349
350 You can write to this object, but changes won't be reflected outside of your
351 process. That means that the following won't work:
352
353     node -e 'process.env.foo = "bar"' && echo $foo
354
355 But this will:
356
357     process.env.foo = 'bar';
358     console.log(process.env.foo);
359
360
361 ## process.exit([code])
362
363 Ends the process with the specified `code`.  If omitted, exit uses the
364 'success' code `0`.
365
366 To exit with a 'failure' code:
367
368     process.exit(1);
369
370 The shell that executed node should see the exit code as 1.
371
372
373 ## process.exitCode
374
375 A number which will be the process exit code, when the process either
376 exits gracefully, or is exited via `process.exit()` without specifying
377 a code.
378
379 Specifying a code to `process.exit(code)` will override any previous
380 setting of `process.exitCode`.
381
382
383 ## process.getgid()
384
385 Note: this function is only available on POSIX platforms (i.e. not Windows,
386 Android)
387
388 Gets the group identity of the process. (See getgid(2).)
389 This is the numerical group id, not the group name.
390
391     if (process.getgid) {
392       console.log('Current gid: ' + process.getgid());
393     }
394
395
396 ## process.setgid(id)
397
398 Note: this function is only available on POSIX platforms (i.e. not Windows,
399 Android)
400
401 Sets the group identity of the process. (See setgid(2).)  This accepts either
402 a numerical ID or a groupname string. If a groupname is specified, this method
403 blocks while resolving it to a numerical ID.
404
405     if (process.getgid && process.setgid) {
406       console.log('Current gid: ' + process.getgid());
407       try {
408         process.setgid(501);
409         console.log('New gid: ' + process.getgid());
410       }
411       catch (err) {
412         console.log('Failed to set gid: ' + err);
413       }
414     }
415
416
417 ## process.getuid()
418
419 Note: this function is only available on POSIX platforms (i.e. not Windows,
420 Android)
421
422 Gets the user identity of the process. (See getuid(2).)
423 This is the numerical userid, not the username.
424
425     if (process.getuid) {
426       console.log('Current uid: ' + process.getuid());
427     }
428
429
430 ## process.setuid(id)
431
432 Note: this function is only available on POSIX platforms (i.e. not Windows,
433 Android)
434
435 Sets the user identity of the process. (See setuid(2).)  This accepts either
436 a numerical ID or a username string.  If a username is specified, this method
437 blocks while resolving it to a numerical ID.
438
439     if (process.getuid && process.setuid) {
440       console.log('Current uid: ' + process.getuid());
441       try {
442         process.setuid(501);
443         console.log('New uid: ' + process.getuid());
444       }
445       catch (err) {
446         console.log('Failed to set uid: ' + err);
447       }
448     }
449
450
451 ## process.getgroups()
452
453 Note: this function is only available on POSIX platforms (i.e. not Windows,
454 Android)
455
456 Returns an array with the supplementary group IDs. POSIX leaves it unspecified
457 if the effective group ID is included but node.js ensures it always is.
458
459
460 ## process.setgroups(groups)
461
462 Note: this function is only available on POSIX platforms (i.e. not Windows,
463 Android)
464
465 Sets the supplementary group IDs. This is a privileged operation, meaning you
466 need to be root or have the CAP_SETGID capability.
467
468 The list can contain group IDs, group names or both.
469
470
471 ## process.initgroups(user, extra_group)
472
473 Note: this function is only available on POSIX platforms (i.e. not Windows,
474 Android)
475
476 Reads /etc/group and initializes the group access list, using all groups of
477 which the user is a member. This is a privileged operation, meaning you need
478 to be root or have the CAP_SETGID capability.
479
480 `user` is a user name or user ID. `extra_group` is a group name or group ID.
481
482 Some care needs to be taken when dropping privileges. Example:
483
484     console.log(process.getgroups());         // [ 0 ]
485     process.initgroups('bnoordhuis', 1000);   // switch user
486     console.log(process.getgroups());         // [ 27, 30, 46, 1000, 0 ]
487     process.setgid(1000);                     // drop root gid
488     console.log(process.getgroups());         // [ 27, 30, 46, 1000 ]
489
490
491 ## process.version
492
493 A compiled-in property that exposes `NODE_VERSION`.
494
495     console.log('Version: ' + process.version);
496
497 ## process.versions
498
499 A property exposing version strings of node and its dependencies.
500
501     console.log(process.versions);
502
503 Will print something like:
504
505     { http_parser: '1.0',
506       node: '0.10.4',
507       v8: '3.14.5.8',
508       ares: '1.9.0-DEV',
509       uv: '0.10.3',
510       zlib: '1.2.3',
511       modules: '11',
512       openssl: '1.0.1e' }
513
514 ## process.config
515
516 An Object containing the JavaScript representation of the configure options
517 that were used to compile the current node executable. This is the same as
518 the "config.gypi" file that was produced when running the `./configure` script.
519
520 An example of the possible output looks like:
521
522     { target_defaults:
523        { cflags: [],
524          default_configuration: 'Release',
525          defines: [],
526          include_dirs: [],
527          libraries: [] },
528       variables:
529        { host_arch: 'x64',
530          node_install_npm: 'true',
531          node_prefix: '',
532          node_shared_cares: 'false',
533          node_shared_http_parser: 'false',
534          node_shared_libuv: 'false',
535          node_shared_v8: 'false',
536          node_shared_zlib: 'false',
537          node_use_dtrace: 'false',
538          node_use_openssl: 'true',
539          node_shared_openssl: 'false',
540          strict_aliasing: 'true',
541          target_arch: 'x64',
542          v8_use_snapshot: 'true' } }
543
544 ## process.kill(pid[, signal])
545
546 Send a signal to a process. `pid` is the process id and `signal` is the
547 string describing the signal to send.  Signal names are strings like
548 'SIGINT' or 'SIGHUP'.  If omitted, the signal will be 'SIGTERM'.
549 See [Signal Events](#process_signal_events) and kill(2) for more information.
550
551 Will throw an error if target does not exist, and as a special case, a signal of
552 `0` can be used to test for the existence of a process.
553
554 Note that just because the name of this function is `process.kill`, it is
555 really just a signal sender, like the `kill` system call.  The signal sent
556 may do something other than kill the target process.
557
558 Example of sending a signal to yourself:
559
560     process.on('SIGHUP', function() {
561       console.log('Got SIGHUP signal.');
562     });
563
564     setTimeout(function() {
565       console.log('Exiting.');
566       process.exit(0);
567     }, 100);
568
569     process.kill(process.pid, 'SIGHUP');
570
571 Note: When SIGUSR1 is received by Node.js it starts the debugger, see
572 [Signal Events](#process_signal_events).
573
574 ## process.pid
575
576 The PID of the process.
577
578     console.log('This process is pid ' + process.pid);
579
580
581 ## process.title
582
583 Getter/setter to set what is displayed in 'ps'.
584
585 When used as a setter, the maximum length is platform-specific and probably
586 short.
587
588 On Linux and OS X, it's limited to the size of the binary name plus the
589 length of the command line arguments because it overwrites the argv memory.
590
591 v0.8 allowed for longer process title strings by also overwriting the environ
592 memory but that was potentially insecure/confusing in some (rather obscure)
593 cases.
594
595
596 ## process.arch
597
598 What processor architecture you're running on: `'arm'`, `'ia32'`, or `'x64'`.
599
600     console.log('This processor architecture is ' + process.arch);
601
602
603 ## process.platform
604
605 What platform you're running on:
606 `'darwin'`, `'freebsd'`, `'linux'`, `'sunos'` or `'win32'`
607
608     console.log('This platform is ' + process.platform);
609
610
611 ## process.memoryUsage()
612
613 Returns an object describing the memory usage of the Node process
614 measured in bytes.
615
616     var util = require('util');
617
618     console.log(util.inspect(process.memoryUsage()));
619
620 This will generate:
621
622     { rss: 4935680,
623       heapTotal: 1826816,
624       heapUsed: 650472 }
625
626 `heapTotal` and `heapUsed` refer to V8's memory usage.
627
628
629 ## process.nextTick(callback)
630
631 * `callback` {Function}
632
633 Once the current event loop turn runs to completion, call the callback
634 function.
635
636 This is *not* a simple alias to `setTimeout(fn, 0)`, it's much more
637 efficient.  It runs before any additional I/O events (including
638 timers) fire in subsequent ticks of the event loop.
639
640     console.log('start');
641     process.nextTick(function() {
642       console.log('nextTick callback');
643     });
644     console.log('scheduled');
645     // Output:
646     // start
647     // scheduled
648     // nextTick callback
649
650 This is important in developing APIs where you want to give the user the
651 chance to assign event handlers after an object has been constructed,
652 but before any I/O has occurred.
653
654     function MyThing(options) {
655       this.setupOptions(options);
656
657       process.nextTick(function() {
658         this.startDoingStuff();
659       }.bind(this));
660     }
661
662     var thing = new MyThing();
663     thing.getReadyForStuff();
664
665     // thing.startDoingStuff() gets called now, not before.
666
667 It is very important for APIs to be either 100% synchronous or 100%
668 asynchronous.  Consider this example:
669
670     // WARNING!  DO NOT USE!  BAD UNSAFE HAZARD!
671     function maybeSync(arg, cb) {
672       if (arg) {
673         cb();
674         return;
675       }
676
677       fs.stat('file', cb);
678     }
679
680 This API is hazardous.  If you do this:
681
682     maybeSync(true, function() {
683       foo();
684     });
685     bar();
686
687 then it's not clear whether `foo()` or `bar()` will be called first.
688
689 This approach is much better:
690
691     function definitelyAsync(arg, cb) {
692       if (arg) {
693         process.nextTick(cb);
694         return;
695       }
696
697       fs.stat('file', cb);
698     }
699
700 Note: the nextTick queue is completely drained on each pass of the
701 event loop **before** additional I/O is processed.  As a result,
702 recursively setting nextTick callbacks will block any I/O from
703 happening, just like a `while(true);` loop.
704
705 ## process.umask([mask])
706
707 Sets or reads the process's file mode creation mask. Child processes inherit
708 the mask from the parent process. Returns the old mask if `mask` argument is
709 given, otherwise returns the current mask.
710
711     var oldmask, newmask = 0022;
712
713     oldmask = process.umask(newmask);
714     console.log('Changed umask from: ' + oldmask.toString(8) +
715                 ' to ' + newmask.toString(8));
716
717
718 ## process.uptime()
719
720 Number of seconds Node has been running.
721
722
723 ## process.hrtime()
724
725 Returns the current high-resolution real time in a `[seconds, nanoseconds]`
726 tuple Array. It is relative to an arbitrary time in the past. It is not
727 related to the time of day and therefore not subject to clock drift. The
728 primary use is for measuring performance between intervals.
729
730 You may pass in the result of a previous call to `process.hrtime()` to get
731 a diff reading, useful for benchmarks and measuring intervals:
732
733     var time = process.hrtime();
734     // [ 1800216, 25 ]
735
736     setTimeout(function() {
737       var diff = process.hrtime(time);
738       // [ 1, 552 ]
739
740       console.log('benchmark took %d nanoseconds', diff[0] * 1e9 + diff[1]);
741       // benchmark took 1000000527 nanoseconds
742     }, 1000);
743
744
745 ## process.mainModule
746
747 Alternate way to retrieve
748 [`require.main`](modules.html#modules_accessing_the_main_module).
749 The difference is that if the main module changes at runtime, `require.main`
750 might still refer to the original main module in modules that were required
751 before the change occurred. Generally it's safe to assume that the two refer
752 to the same module.
753
754 As with `require.main`, it will be `undefined` if there was no entry script.
755
756 [EventEmitter]: events.html#events_class_events_eventemitter