docs: process.on('exit') receives exit code
[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
9 ## Event: 'exit'
10
11 Emitted when the process is about to exit.  This is a good hook to perform
12 constant time checks of the module's state (like for unit tests).  The main
13 event loop will no longer be run after the 'exit' callback finishes, so
14 timers may not be scheduled.  The callback takes one argument, the code the
15 process is exiting with.
16
17 Example of listening for `exit`:
18
19     process.on('exit', function(code) {
20       setTimeout(function() {
21         console.log('This will not run');
22       }, 0);
23       console.log('About to exit with code:', code);
24     });
25
26 ## Event: 'uncaughtException'
27
28 Emitted when an exception bubbles all the way back to the event loop. If a
29 listener is added for this exception, the default action (which is to print
30 a stack trace and exit) will not occur.
31
32 Example of listening for `uncaughtException`:
33
34     process.on('uncaughtException', function(err) {
35       console.log('Caught exception: ' + err);
36     });
37
38     setTimeout(function() {
39       console.log('This will still run.');
40     }, 500);
41
42     // Intentionally cause an exception, but don't catch it.
43     nonexistentFunc();
44     console.log('This will not run.');
45
46 Note that `uncaughtException` is a very crude mechanism for exception
47 handling and may be removed in the future.
48
49 Don't use it, use [domains](domain.html) instead. If you do use it, restart
50 your application after every unhandled exception!
51
52 Do *not* use it as the node.js equivalent of `On Error Resume Next`. An
53 unhandled exception means your application - and by extension node.js itself -
54 is in an undefined state. Blindly resuming means *anything* could happen.
55
56 Think of resuming as pulling the power cord when you are upgrading your system.
57 Nine out of ten times nothing happens - but the 10th time, your system is bust.
58
59 You have been warned.
60
61 ## Signal Events
62
63 <!--type=event-->
64 <!--name=SIGINT, SIGHUP, etc.-->
65
66 Emitted when the processes receives a signal. See sigaction(2) for a list of
67 standard POSIX signal names such as SIGINT, SIGHUP, etc.
68
69 Example of listening for `SIGINT`:
70
71     // Start reading from stdin so we don't exit.
72     process.stdin.resume();
73
74     process.on('SIGINT', function() {
75       console.log('Got SIGINT.  Press Control-D to exit.');
76     });
77
78 An easy way to send the `SIGINT` signal is with `Control-C` in most terminal
79 programs.
80
81 Note:
82
83 - `SIGUSR1` is reserved by node.js to start the debugger.  It's possible to
84   install a listener but that won't stop the debugger from starting.
85 - `SIGTERM` and `SIGINT` have default handlers on non-Windows platforms that resets
86   the terminal mode before exiting with code `128 + signal number`. If one of
87   these signals has a listener installed, its default behaviour will be removed
88   (node will no longer exit).
89 - `SIGPIPE` is ignored by default, it can have a listener installed.
90 - `SIGHUP` is generated on Windows when the console window is closed, and on other
91   platforms under various similar conditions, see signal(7). It can have a
92   listener installed, however node will be unconditionally terminated by Windows
93   about 10 seconds later. On non-Windows platforms, the default behaviour of
94   `SIGHUP` is to terminate node, but once a listener has been installed its
95   default behaviour will be removed.
96 - `SIGTERM` is not supported on Windows, it can be listened on.
97 - `SIGINT` is supported on all platforms, and can usually be generated with
98   `CTRL+C` (though this may be configurable). It is not generated when terminal
99   raw mode is enabled.
100 - `SIGBREAK` is delivered on Windows when `CTRL+BREAK` is pressed, on non-Windows
101   platforms it can be listened on, but there is no way to send or generate it.
102 - `SIGWINCH` is delivered when the console has been resized. On Windows, this will
103   only happen on write to the console when the cursor is being moved, or when a
104   readable tty is used in raw mode.
105 - `SIGKILL` cannot have a listener installed, it will unconditionally terminate
106   node on all platforms.
107 - `SIGSTOP` cannot have a listener installed.
108
109 ## process.stdout
110
111 A `Writable Stream` to `stdout`.
112
113 Example: the definition of `console.log`
114
115     console.log = function(d) {
116       process.stdout.write(d + '\n');
117     };
118
119 `process.stderr` and `process.stdout` are unlike other streams in Node in
120 that writes to them are usually blocking.  They are blocking in the case
121 that they refer to regular files or TTY file descriptors. In the case they
122 refer to pipes, they are non-blocking like other streams.
123
124 To check if Node is being run in a TTY context, read the `isTTY` property
125 on `process.stderr`, `process.stdout`, or `process.stdin`:
126
127     $ node -p "Boolean(process.stdin.isTTY)"
128     true
129     $ echo "foo" | node -p "Boolean(process.stdin.isTTY)"
130     false
131
132     $ node -p "Boolean(process.stdout.isTTY)"
133     true
134     $ node -p "Boolean(process.stdout.isTTY)" | cat
135     false
136
137 See [the tty docs](tty.html#tty_tty) for more information.
138
139 ## process.stderr
140
141 A writable stream to stderr.
142
143 `process.stderr` and `process.stdout` are unlike other streams in Node in
144 that writes to them are usually blocking.  They are blocking in the case
145 that they refer to regular files or TTY file descriptors. In the case they
146 refer to pipes, they are non-blocking like other streams.
147
148
149 ## process.stdin
150
151 A `Readable Stream` for stdin. The stdin stream is paused by default, so one
152 must call `process.stdin.resume()` to read from it.
153
154 Example of opening standard input and listening for both events:
155
156     process.stdin.resume();
157     process.stdin.setEncoding('utf8');
158
159     process.stdin.on('data', function(chunk) {
160       process.stdout.write('data: ' + chunk);
161     });
162
163     process.stdin.on('end', function() {
164       process.stdout.write('end');
165     });
166
167
168 ## process.argv
169
170 An array containing the command line arguments.  The first element will be
171 'node', the second element will be the name of the JavaScript file.  The
172 next elements will be any additional command line arguments.
173
174     // print process.argv
175     process.argv.forEach(function(val, index, array) {
176       console.log(index + ': ' + val);
177     });
178
179 This will generate:
180
181     $ node process-2.js one two=three four
182     0: node
183     1: /Users/mjr/work/node/process-2.js
184     2: one
185     3: two=three
186     4: four
187
188
189 ## process.execPath
190
191 This is the absolute pathname of the executable that started the process.
192
193 Example:
194
195     /usr/local/bin/node
196
197
198 ## process.execArgv
199
200 This is the set of node-specific command line options from the
201 executable that started the process.  These options do not show up in
202 `process.argv`, and do not include the node executable, the name of
203 the script, or any options following the script name. These options
204 are useful in order to spawn child processes with the same execution
205 environment as the parent.
206
207 Example:
208
209     $ node --harmony script.js --version
210
211 results in process.execArgv:
212
213     ['--harmony']
214
215 and process.argv:
216
217     ['/usr/local/bin/node', 'script.js', '--version']
218
219
220 ## process.abort()
221
222 This causes node to emit an abort. This will cause node to exit and
223 generate a core file.
224
225 ## process.chdir(directory)
226
227 Changes the current working directory of the process or throws an exception if that fails.
228
229     console.log('Starting directory: ' + process.cwd());
230     try {
231       process.chdir('/tmp');
232       console.log('New directory: ' + process.cwd());
233     }
234     catch (err) {
235       console.log('chdir: ' + err);
236     }
237
238
239
240 ## process.cwd()
241
242 Returns the current working directory of the process.
243
244     console.log('Current directory: ' + process.cwd());
245
246
247 ## process.env
248
249 An object containing the user environment. See environ(7).
250
251
252 ## process.exit([code])
253
254 Ends the process with the specified `code`.  If omitted, exit uses the
255 'success' code `0`.
256
257 To exit with a 'failure' code:
258
259     process.exit(1);
260
261 The shell that executed node should see the exit code as 1.
262
263
264 ## process.getgid()
265
266 Note: this function is only available on POSIX platforms (i.e. not Windows)
267
268 Gets the group identity of the process. (See getgid(2).)
269 This is the numerical group id, not the group name.
270
271     if (process.getgid) {
272       console.log('Current gid: ' + process.getgid());
273     }
274
275
276 ## process.setgid(id)
277
278 Note: this function is only available on POSIX platforms (i.e. not Windows)
279
280 Sets the group identity of the process. (See setgid(2).)  This accepts either
281 a numerical ID or a groupname string. If a groupname is specified, this method
282 blocks while resolving it to a numerical ID.
283
284     if (process.getgid && process.setgid) {
285       console.log('Current gid: ' + process.getgid());
286       try {
287         process.setgid(501);
288         console.log('New gid: ' + process.getgid());
289       }
290       catch (err) {
291         console.log('Failed to set gid: ' + err);
292       }
293     }
294
295
296 ## process.getuid()
297
298 Note: this function is only available on POSIX platforms (i.e. not Windows)
299
300 Gets the user identity of the process. (See getuid(2).)
301 This is the numerical userid, not the username.
302
303     if (process.getuid) {
304       console.log('Current uid: ' + process.getuid());
305     }
306
307
308 ## process.setuid(id)
309
310 Note: this function is only available on POSIX platforms (i.e. not Windows)
311
312 Sets the user identity of the process. (See setuid(2).)  This accepts either
313 a numerical ID or a username string.  If a username is specified, this method
314 blocks while resolving it to a numerical ID.
315
316     if (process.getuid && process.setuid) {
317       console.log('Current uid: ' + process.getuid());
318       try {
319         process.setuid(501);
320         console.log('New uid: ' + process.getuid());
321       }
322       catch (err) {
323         console.log('Failed to set uid: ' + err);
324       }
325     }
326
327
328 ## process.getgroups()
329
330 Note: this function is only available on POSIX platforms (i.e. not Windows)
331
332 Returns an array with the supplementary group IDs. POSIX leaves it unspecified
333 if the effective group ID is included but node.js ensures it always is.
334
335
336 ## process.setgroups(groups)
337
338 Note: this function is only available on POSIX platforms (i.e. not Windows)
339
340 Sets the supplementary group IDs. This is a privileged operation, meaning you
341 need to be root or have the CAP_SETGID capability.
342
343 The list can contain group IDs, group names or both.
344
345
346 ## process.initgroups(user, extra_group)
347
348 Note: this function is only available on POSIX platforms (i.e. not Windows)
349
350 Reads /etc/group and initializes the group access list, using all groups of
351 which the user is a member. This is a privileged operation, meaning you need
352 to be root or have the CAP_SETGID capability.
353
354 `user` is a user name or user ID. `extra_group` is a group name or group ID.
355
356 Some care needs to be taken when dropping privileges. Example:
357
358     console.log(process.getgroups());         // [ 0 ]
359     process.initgroups('bnoordhuis', 1000);   // switch user
360     console.log(process.getgroups());         // [ 27, 30, 46, 1000, 0 ]
361     process.setgid(1000);                     // drop root gid
362     console.log(process.getgroups());         // [ 27, 30, 46, 1000 ]
363
364
365 ## process.version
366
367 A compiled-in property that exposes `NODE_VERSION`.
368
369     console.log('Version: ' + process.version);
370
371 ## process.versions
372
373 A property exposing version strings of node and its dependencies.
374
375     console.log(process.versions);
376
377 Will print something like:
378
379     { http_parser: '1.0',
380       node: '0.10.4',
381       v8: '3.14.5.8',
382       ares: '1.9.0-DEV',
383       uv: '0.10.3',
384       zlib: '1.2.3',
385       modules: '11',
386       openssl: '1.0.1e' }
387
388 ## process.config
389
390 An Object containing the JavaScript representation of the configure options
391 that were used to compile the current node executable. This is the same as
392 the "config.gypi" file that was produced when running the `./configure` script.
393
394 An example of the possible output looks like:
395
396     { target_defaults:
397        { cflags: [],
398          default_configuration: 'Release',
399          defines: [],
400          include_dirs: [],
401          libraries: [] },
402       variables:
403        { host_arch: 'x64',
404          node_install_npm: 'true',
405          node_prefix: '',
406          node_shared_cares: 'false',
407          node_shared_http_parser: 'false',
408          node_shared_libuv: 'false',
409          node_shared_v8: 'false',
410          node_shared_zlib: 'false',
411          node_use_dtrace: 'false',
412          node_use_openssl: 'true',
413          node_shared_openssl: 'false',
414          strict_aliasing: 'true',
415          target_arch: 'x64',
416          v8_use_snapshot: 'true' } }
417
418 ## process.kill(pid, [signal])
419
420 Send a signal to a process. `pid` is the process id and `signal` is the
421 string describing the signal to send.  Signal names are strings like
422 'SIGINT' or 'SIGHUP'.  If omitted, the signal will be 'SIGTERM'.
423 See kill(2) for more information.
424
425 Will throw an error if target does not exist, and as a special case, a signal of
426 `0` can be used to test for the existence of a process.
427
428 Note that just because the name of this function is `process.kill`, it is
429 really just a signal sender, like the `kill` system call.  The signal sent
430 may do something other than kill the target process.
431
432 Example of sending a signal to yourself:
433
434     process.on('SIGHUP', function() {
435       console.log('Got SIGHUP signal.');
436     });
437
438     setTimeout(function() {
439       console.log('Exiting.');
440       process.exit(0);
441     }, 100);
442
443     process.kill(process.pid, 'SIGHUP');
444
445 Note: When SIGUSR1 is received by Node.js it starts the debugger, see
446 [Signal Events](#process_signal_events).
447
448 ## process.pid
449
450 The PID of the process.
451
452     console.log('This process is pid ' + process.pid);
453
454
455 ## process.title
456
457 Getter/setter to set what is displayed in 'ps'.
458
459 When used as a setter, the maximum length is platform-specific and probably
460 short.
461
462 On Linux and OS X, it's limited to the size of the binary name plus the
463 length of the command line arguments because it overwrites the argv memory.
464
465 v0.8 allowed for longer process title strings by also overwriting the environ
466 memory but that was potentially insecure/confusing in some (rather obscure)
467 cases.
468
469
470 ## process.arch
471
472 What processor architecture you're running on: `'arm'`, `'ia32'`, or `'x64'`.
473
474     console.log('This processor architecture is ' + process.arch);
475
476
477 ## process.platform
478
479 What platform you're running on:
480 `'darwin'`, `'freebsd'`, `'linux'`, `'sunos'` or `'win32'`
481
482     console.log('This platform is ' + process.platform);
483
484
485 ## process.memoryUsage()
486
487 Returns an object describing the memory usage of the Node process
488 measured in bytes.
489
490     var util = require('util');
491
492     console.log(util.inspect(process.memoryUsage()));
493
494 This will generate:
495
496     { rss: 4935680,
497       heapTotal: 1826816,
498       heapUsed: 650472 }
499
500 `heapTotal` and `heapUsed` refer to V8's memory usage.
501
502
503 ## process.nextTick(callback)
504
505 On the next loop around the event loop call this callback.
506 This is *not* a simple alias to `setTimeout(fn, 0)`, it's much more
507 efficient.  It typically runs before any other I/O events fire, but there
508 are some exceptions.  See `process.maxTickDepth` below.
509
510     process.nextTick(function() {
511       console.log('nextTick callback');
512     });
513
514 This is important in developing APIs where you want to give the user the
515 chance to assign event handlers after an object has been constructed,
516 but before any I/O has occurred.
517
518     function MyThing(options) {
519       this.setupOptions(options);
520
521       process.nextTick(function() {
522         this.startDoingStuff();
523       }.bind(this));
524     }
525
526     var thing = new MyThing();
527     thing.getReadyForStuff();
528
529     // thing.startDoingStuff() gets called now, not before.
530
531 It is very important for APIs to be either 100% synchronous or 100%
532 asynchronous.  Consider this example:
533
534     // WARNING!  DO NOT USE!  BAD UNSAFE HAZARD!
535     function maybeSync(arg, cb) {
536       if (arg) {
537         cb();
538         return;
539       }
540
541       fs.stat('file', cb);
542     }
543
544 This API is hazardous.  If you do this:
545
546     maybeSync(true, function() {
547       foo();
548     });
549     bar();
550
551 then it's not clear whether `foo()` or `bar()` will be called first.
552
553 This approach is much better:
554
555     function definitelyAsync(arg, cb) {
556       if (arg) {
557         process.nextTick(cb);
558         return;
559       }
560
561       fs.stat('file', cb);
562     }
563
564 ## process.maxTickDepth
565
566 * {Number} Default = 1000
567
568 Callbacks passed to `process.nextTick` will *usually* be called at the
569 end of the current flow of execution, and are thus approximately as fast
570 as calling a function synchronously.  Left unchecked, this would starve
571 the event loop, preventing any I/O from occurring.
572
573 Consider this code:
574
575     process.nextTick(function foo() {
576       process.nextTick(foo);
577     });
578
579 In order to avoid the situation where Node is blocked by an infinite
580 loop of recursive series of nextTick calls, it defers to allow some I/O
581 to be done every so often.
582
583 The `process.maxTickDepth` value is the maximum depth of
584 nextTick-calling nextTick-callbacks that will be evaluated before
585 allowing other forms of I/O to occur.
586
587 ## process.umask([mask])
588
589 Sets or reads the process's file mode creation mask. Child processes inherit
590 the mask from the parent process. Returns the old mask if `mask` argument is
591 given, otherwise returns the current mask.
592
593     var oldmask, newmask = 0644;
594
595     oldmask = process.umask(newmask);
596     console.log('Changed umask from: ' + oldmask.toString(8) +
597                 ' to ' + newmask.toString(8));
598
599
600 ## process.uptime()
601
602 Number of seconds Node has been running.
603
604
605 ## process.hrtime()
606
607 Returns the current high-resolution real time in a `[seconds, nanoseconds]`
608 tuple Array. It is relative to an arbitrary time in the past. It is not
609 related to the time of day and therefore not subject to clock drift. The
610 primary use is for measuring performance between intervals.
611
612 You may pass in the result of a previous call to `process.hrtime()` to get
613 a diff reading, useful for benchmarks and measuring intervals:
614
615     var time = process.hrtime();
616     // [ 1800216, 25 ]
617
618     setTimeout(function() {
619       var diff = process.hrtime(time);
620       // [ 1, 552 ]
621
622       console.log('benchmark took %d nanoseconds', diff[0] * 1e9 + diff[1]);
623       // benchmark took 1000000527 nanoseconds
624     }, 1000);
625
626 [EventEmitter]: events.html#events_class_events_eventemitter