Merge branch 'v0.10'
[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.  This is a good hook to perform
56 constant time checks of the module's state (like for unit tests).  The main
57 event loop will no longer be run after the 'exit' callback finishes, so
58 timers may not be scheduled.
59
60 Example of listening for `exit`:
61
62     process.on('exit', function() {
63       setTimeout(function() {
64         console.log('This will not run');
65       }, 0);
66       console.log('About to exit.');
67     });
68
69 ## Event: 'uncaughtException'
70
71 Emitted when an exception bubbles all the way back to the event loop. If a
72 listener is added for this exception, the default action (which is to print
73 a stack trace and exit) will not occur.
74
75 Example of listening for `uncaughtException`:
76
77     process.on('uncaughtException', function(err) {
78       console.log('Caught exception: ' + err);
79     });
80
81     setTimeout(function() {
82       console.log('This will still run.');
83     }, 500);
84
85     // Intentionally cause an exception, but don't catch it.
86     nonexistentFunc();
87     console.log('This will not run.');
88
89 Note that `uncaughtException` is a very crude mechanism for exception
90 handling.
91
92 Don't use it, use [domains](domain.html) instead. If you do use it, restart
93 your application after every unhandled exception!
94
95 Do *not* use it as the node.js equivalent of `On Error Resume Next`. An
96 unhandled exception means your application - and by extension node.js itself -
97 is in an undefined state. Blindly resuming means *anything* could happen.
98
99 Think of resuming as pulling the power cord when you are upgrading your system.
100 Nine out of ten times nothing happens - but the 10th time, your system is bust.
101
102 You have been warned.
103
104 ## Signal Events
105
106 <!--type=event-->
107 <!--name=SIGINT, SIGHUP, etc.-->
108
109 Emitted when the processes receives a signal. See sigaction(2) for a list of
110 standard POSIX signal names such as SIGINT, SIGHUP, etc.
111
112 Example of listening for `SIGINT`:
113
114     // Start reading from stdin so we don't exit.
115     process.stdin.resume();
116
117     process.on('SIGINT', function() {
118       console.log('Got SIGINT.  Press Control-D to exit.');
119     });
120
121 An easy way to send the `SIGINT` signal is with `Control-C` in most terminal
122 programs.
123
124 Note:
125
126 - `SIGUSR1` is reserved by node.js to start the debugger.  It's possible to
127   install a listener but that won't stop the debugger from starting.
128 - `SIGTERM` and `SIGINT` have default handlers on non-Windows platforms that resets
129   the terminal mode before exiting with code `128 + signal number`. If one of
130   these signals has a listener installed, its default behaviour will be removed
131   (node will no longer exit).
132 - `SIGPIPE` is ignored by default, it can have a listener installed.
133 - `SIGHUP` is generated on Windows when the console window is closed, and on other
134   platforms under various similar conditions, see signal(7). It can have a
135   listener installed, however node will be unconditionally terminated by Windows
136   about 10 seconds later. On non-Windows platforms, the default behaviour of
137   `SIGHUP` is to terminate node, but once a listener has been installed its
138   default behaviour will be removed.
139 - `SIGTERM` is not supported on Windows, it can be listened on.
140 - `SIGINT` is supported on all platforms, and can usually be generated with
141   `CTRL+C` (though this may be configurable). It is not generated when terminal
142   raw mode is enabled.
143 - `SIGBREAK` is delivered on Windows when `CTRL+BREAK` is pressed, on non-Windows
144   platforms it can be listened on, but there is no way to send or generate it.
145 - `SIGWINCH` is delivered when the console has been resized. On Windows, this will
146   only happen on write to the console when the cursor is being moved, or when a
147   readable tty is used in raw mode.
148 - `SIGKILL` cannot have a listener installed, it will unconditionally terminate
149   node on all platforms.
150 - `SIGSTOP` cannot have a listener installed.
151
152 ## process.stdout
153
154 A `Writable Stream` to `stdout`.
155
156 Example: the definition of `console.log`
157
158     console.log = function(d) {
159       process.stdout.write(d + '\n');
160     };
161
162 `process.stderr` and `process.stdout` are unlike other streams in Node in
163 that writes to them are usually blocking.  They are blocking in the case
164 that they refer to regular files or TTY file descriptors. In the case they
165 refer to pipes, they are non-blocking like other streams.
166
167 To check if Node is being run in a TTY context, read the `isTTY` property
168 on `process.stderr`, `process.stdout`, or `process.stdin`:
169
170     $ node -p "Boolean(process.stdin.isTTY)"
171     true
172     $ echo "foo" | node -p "Boolean(process.stdin.isTTY)"
173     false
174
175     $ node -p "Boolean(process.stdout.isTTY)"
176     true
177     $ node -p "Boolean(process.stdout.isTTY)" | cat
178     false
179
180 See [the tty docs](tty.html#tty_tty) for more information.
181
182 ## process.stderr
183
184 A writable stream to stderr.
185
186 `process.stderr` and `process.stdout` are unlike other streams in Node in
187 that writes to them are usually blocking.  They are blocking in the case
188 that they refer to regular files or TTY file descriptors. In the case they
189 refer to pipes, they are non-blocking like other streams.
190
191
192 ## process.stdin
193
194 A `Readable Stream` for stdin. The stdin stream is paused by default, so one
195 must call `process.stdin.resume()` to read from it.
196
197 Example of opening standard input and listening for both events:
198
199     process.stdin.resume();
200     process.stdin.setEncoding('utf8');
201
202     process.stdin.on('data', function(chunk) {
203       process.stdout.write('data: ' + chunk);
204     });
205
206     process.stdin.on('end', function() {
207       process.stdout.write('end');
208     });
209
210
211 ## process.argv
212
213 An array containing the command line arguments.  The first element will be
214 'node', the second element will be the name of the JavaScript file.  The
215 next elements will be any additional command line arguments.
216
217     // print process.argv
218     process.argv.forEach(function(val, index, array) {
219       console.log(index + ': ' + val);
220     });
221
222 This will generate:
223
224     $ node process-2.js one two=three four
225     0: node
226     1: /Users/mjr/work/node/process-2.js
227     2: one
228     3: two=three
229     4: four
230
231
232 ## process.execPath
233
234 This is the absolute pathname of the executable that started the process.
235
236 Example:
237
238     /usr/local/bin/node
239
240
241 ## process.execArgv
242
243 This is the set of node-specific command line options from the
244 executable that started the process.  These options do not show up in
245 `process.argv`, and do not include the node executable, the name of
246 the script, or any options following the script name. These options
247 are useful in order to spawn child processes with the same execution
248 environment as the parent.
249
250 Example:
251
252     $ node --harmony script.js --version
253
254 results in process.execArgv:
255
256     ['--harmony']
257
258 and process.argv:
259
260     ['/usr/local/bin/node', 'script.js', '--version']
261
262
263 ## process.abort()
264
265 This causes node to emit an abort. This will cause node to exit and
266 generate a core file.
267
268 ## process.chdir(directory)
269
270 Changes the current working directory of the process or throws an exception if that fails.
271
272     console.log('Starting directory: ' + process.cwd());
273     try {
274       process.chdir('/tmp');
275       console.log('New directory: ' + process.cwd());
276     }
277     catch (err) {
278       console.log('chdir: ' + err);
279     }
280
281
282
283 ## process.cwd()
284
285 Returns the current working directory of the process.
286
287     console.log('Current directory: ' + process.cwd());
288
289
290 ## process.env
291
292 An object containing the user environment. See environ(7).
293
294
295 ## process.exit([code])
296
297 Ends the process with the specified `code`.  If omitted, exit uses the
298 'success' code `0`.
299
300 To exit with a 'failure' code:
301
302     process.exit(1);
303
304 The shell that executed node should see the exit code as 1.
305
306
307 ## process.exitCode
308
309 A number which will be the process exit code, when the process either
310 exits gracefully, or is exited via `process.exit()` without specifying
311 a code.
312
313 Specifying a code to `process.exit(code)` will override any previous
314 setting of `process.exitCode`.
315
316
317 ## process.getgid()
318
319 Note: this function is only available on POSIX platforms (i.e. not Windows,
320 Android)
321
322 Gets the group identity of the process. (See getgid(2).)
323 This is the numerical group id, not the group name.
324
325     if (process.getgid) {
326       console.log('Current gid: ' + process.getgid());
327     }
328
329
330 ## process.setgid(id)
331
332 Note: this function is only available on POSIX platforms (i.e. not Windows,
333 Android)
334
335 Sets the group identity of the process. (See setgid(2).)  This accepts either
336 a numerical ID or a groupname string. If a groupname is specified, this method
337 blocks while resolving it to a numerical ID.
338
339     if (process.getgid && process.setgid) {
340       console.log('Current gid: ' + process.getgid());
341       try {
342         process.setgid(501);
343         console.log('New gid: ' + process.getgid());
344       }
345       catch (err) {
346         console.log('Failed to set gid: ' + err);
347       }
348     }
349
350
351 ## process.getuid()
352
353 Note: this function is only available on POSIX platforms (i.e. not Windows,
354 Android)
355
356 Gets the user identity of the process. (See getuid(2).)
357 This is the numerical userid, not the username.
358
359     if (process.getuid) {
360       console.log('Current uid: ' + process.getuid());
361     }
362
363
364 ## process.setuid(id)
365
366 Note: this function is only available on POSIX platforms (i.e. not Windows,
367 Android)
368
369 Sets the user identity of the process. (See setuid(2).)  This accepts either
370 a numerical ID or a username string.  If a username is specified, this method
371 blocks while resolving it to a numerical ID.
372
373     if (process.getuid && process.setuid) {
374       console.log('Current uid: ' + process.getuid());
375       try {
376         process.setuid(501);
377         console.log('New uid: ' + process.getuid());
378       }
379       catch (err) {
380         console.log('Failed to set uid: ' + err);
381       }
382     }
383
384
385 ## process.getgroups()
386
387 Note: this function is only available on POSIX platforms (i.e. not Windows,
388 Android)
389
390 Returns an array with the supplementary group IDs. POSIX leaves it unspecified
391 if the effective group ID is included but node.js ensures it always is.
392
393
394 ## process.setgroups(groups)
395
396 Note: this function is only available on POSIX platforms (i.e. not Windows,
397 Android)
398
399 Sets the supplementary group IDs. This is a privileged operation, meaning you
400 need to be root or have the CAP_SETGID capability.
401
402 The list can contain group IDs, group names or both.
403
404
405 ## process.initgroups(user, extra_group)
406
407 Note: this function is only available on POSIX platforms (i.e. not Windows,
408 Android)
409
410 Reads /etc/group and initializes the group access list, using all groups of
411 which the user is a member. This is a privileged operation, meaning you need
412 to be root or have the CAP_SETGID capability.
413
414 `user` is a user name or user ID. `extra_group` is a group name or group ID.
415
416 Some care needs to be taken when dropping privileges. Example:
417
418     console.log(process.getgroups());         // [ 0 ]
419     process.initgroups('bnoordhuis', 1000);   // switch user
420     console.log(process.getgroups());         // [ 27, 30, 46, 1000, 0 ]
421     process.setgid(1000);                     // drop root gid
422     console.log(process.getgroups());         // [ 27, 30, 46, 1000 ]
423
424
425 ## process.version
426
427 A compiled-in property that exposes `NODE_VERSION`.
428
429     console.log('Version: ' + process.version);
430
431 ## process.versions
432
433 A property exposing version strings of node and its dependencies.
434
435     console.log(process.versions);
436
437 Will print something like:
438
439     { http_parser: '1.0',
440       node: '0.10.4',
441       v8: '3.14.5.8',
442       ares: '1.9.0-DEV',
443       uv: '0.10.3',
444       zlib: '1.2.3',
445       modules: '11',
446       openssl: '1.0.1e' }
447
448 ## process.config
449
450 An Object containing the JavaScript representation of the configure options
451 that were used to compile the current node executable. This is the same as
452 the "config.gypi" file that was produced when running the `./configure` script.
453
454 An example of the possible output looks like:
455
456     { target_defaults:
457        { cflags: [],
458          default_configuration: 'Release',
459          defines: [],
460          include_dirs: [],
461          libraries: [] },
462       variables:
463        { host_arch: 'x64',
464          node_install_npm: 'true',
465          node_prefix: '',
466          node_shared_cares: 'false',
467          node_shared_http_parser: 'false',
468          node_shared_libuv: 'false',
469          node_shared_v8: 'false',
470          node_shared_zlib: 'false',
471          node_use_dtrace: 'false',
472          node_use_openssl: 'true',
473          node_shared_openssl: 'false',
474          strict_aliasing: 'true',
475          target_arch: 'x64',
476          v8_use_snapshot: 'true' } }
477
478 ## process.kill(pid, [signal])
479
480 Send a signal to a process. `pid` is the process id and `signal` is the
481 string describing the signal to send.  Signal names are strings like
482 'SIGINT' or 'SIGHUP'.  If omitted, the signal will be 'SIGTERM'.
483 See kill(2) for more information.
484
485 Will throw an error if target does not exist, and as a special case, a signal of
486 `0` can be used to test for the existence of a process.
487
488 Note that just because the name of this function is `process.kill`, it is
489 really just a signal sender, like the `kill` system call.  The signal sent
490 may do something other than kill the target process.
491
492 Example of sending a signal to yourself:
493
494     process.on('SIGHUP', function() {
495       console.log('Got SIGHUP signal.');
496     });
497
498     setTimeout(function() {
499       console.log('Exiting.');
500       process.exit(0);
501     }, 100);
502
503     process.kill(process.pid, 'SIGHUP');
504
505 Note: When SIGUSR1 is received by Node.js it starts the debugger, see
506 [Signal Events](#process_signal_events).
507
508 ## process.pid
509
510 The PID of the process.
511
512     console.log('This process is pid ' + process.pid);
513
514
515 ## process.title
516
517 Getter/setter to set what is displayed in 'ps'.
518
519 When used as a setter, the maximum length is platform-specific and probably
520 short.
521
522 On Linux and OS X, it's limited to the size of the binary name plus the
523 length of the command line arguments because it overwrites the argv memory.
524
525 v0.8 allowed for longer process title strings by also overwriting the environ
526 memory but that was potentially insecure/confusing in some (rather obscure)
527 cases.
528
529
530 ## process.arch
531
532 What processor architecture you're running on: `'arm'`, `'ia32'`, or `'x64'`.
533
534     console.log('This processor architecture is ' + process.arch);
535
536
537 ## process.platform
538
539 What platform you're running on:
540 `'darwin'`, `'freebsd'`, `'linux'`, `'sunos'` or `'win32'`
541
542     console.log('This platform is ' + process.platform);
543
544
545 ## process.memoryUsage()
546
547 Returns an object describing the memory usage of the Node process
548 measured in bytes.
549
550     var util = require('util');
551
552     console.log(util.inspect(process.memoryUsage()));
553
554 This will generate:
555
556     { rss: 4935680,
557       heapTotal: 1826816,
558       heapUsed: 650472 }
559
560 `heapTotal` and `heapUsed` refer to V8's memory usage.
561
562
563 ## process.nextTick(callback)
564
565 * `callback` {Function}
566
567 Once the current event loop turn runs to completion, call the callback
568 function.
569
570 This is *not* a simple alias to `setTimeout(fn, 0)`, it's much more
571 efficient.  It runs before any additional I/O events (including
572 timers) fire in subsequent ticks of the event loop.
573
574     console.log('start');
575     process.nextTick(function() {
576       console.log('nextTick callback');
577     });
578     console.log('scheduled');
579     // Output:
580     // start
581     // scheduled
582     // nextTick callback
583
584 This is important in developing APIs where you want to give the user the
585 chance to assign event handlers after an object has been constructed,
586 but before any I/O has occurred.
587
588     function MyThing(options) {
589       this.setupOptions(options);
590
591       process.nextTick(function() {
592         this.startDoingStuff();
593       }.bind(this));
594     }
595
596     var thing = new MyThing();
597     thing.getReadyForStuff();
598
599     // thing.startDoingStuff() gets called now, not before.
600
601 It is very important for APIs to be either 100% synchronous or 100%
602 asynchronous.  Consider this example:
603
604     // WARNING!  DO NOT USE!  BAD UNSAFE HAZARD!
605     function maybeSync(arg, cb) {
606       if (arg) {
607         cb();
608         return;
609       }
610
611       fs.stat('file', cb);
612     }
613
614 This API is hazardous.  If you do this:
615
616     maybeSync(true, function() {
617       foo();
618     });
619     bar();
620
621 then it's not clear whether `foo()` or `bar()` will be called first.
622
623 This approach is much better:
624
625     function definitelyAsync(arg, cb) {
626       if (arg) {
627         process.nextTick(cb);
628         return;
629       }
630
631       fs.stat('file', cb);
632     }
633
634 Note: the nextTick queue is completely drained on each pass of the
635 event loop **before** additional I/O is processed.  As a result,
636 recursively setting nextTick callbacks will block any I/O from
637 happening, just like a `while(true);` loop.
638
639 ## process.umask([mask])
640
641 Sets or reads the process's file mode creation mask. Child processes inherit
642 the mask from the parent process. Returns the old mask if `mask` argument is
643 given, otherwise returns the current mask.
644
645     var oldmask, newmask = 0644;
646
647     oldmask = process.umask(newmask);
648     console.log('Changed umask from: ' + oldmask.toString(8) +
649                 ' to ' + newmask.toString(8));
650
651
652 ## process.uptime()
653
654 Number of seconds Node has been running.
655
656
657 ## process.hrtime()
658
659 Returns the current high-resolution real time in a `[seconds, nanoseconds]`
660 tuple Array. It is relative to an arbitrary time in the past. It is not
661 related to the time of day and therefore not subject to clock drift. The
662 primary use is for measuring performance between intervals.
663
664 You may pass in the result of a previous call to `process.hrtime()` to get
665 a diff reading, useful for benchmarks and measuring intervals:
666
667     var time = process.hrtime();
668     // [ 1800216, 25 ]
669
670     setTimeout(function() {
671       var diff = process.hrtime(time);
672       // [ 1, 552 ]
673
674       console.log('benchmark took %d nanoseconds', diff[0] * 1e9 + diff[1]);
675       // benchmark took 1000000527 nanoseconds
676     }, 1000);
677
678
679 ## Async Listeners
680
681 <!-- type=misc -->
682
683     Stability: 1 - Experimental
684
685 The `AsyncListener` API is the JavaScript interface for the `AsyncWrap`
686 class which allows developers to be notified about key events in the
687 lifetime of an asynchronous event. Node performs a lot of asynchronous
688 events internally, and significant use of this API will have a **dramatic
689 performance impact** on your application.
690
691
692 ## process.createAsyncListener(asyncListener[, callbacksObj[, storageValue]])
693
694 * `asyncListener` {Function} callback fired when an asynchronous event is
695 instantiated.
696 * `callbacksObj` {Object} optional callbacks that will fire at specific
697 times in the lifetime of the asynchronous event.
698 * `storageValue` {Value} a value that will be passed as the first argument
699 when the `asyncListener` callback is run, and to all subsequent callback.
700
701 Returns a constructed `AsyncListener` object.
702
703 To begin capturing asynchronous events pass the object to
704 [`process.addAsyncListener()`][]. The same `AsyncListener` instance can
705 only be added once to the active queue, and subsequent attempts to add the
706 instance will be ignored.
707
708 To stop capturing pass the object to [`process.removeAsyncListener()`][].
709 This does _not_ mean the `AsyncListener` previously added will stop
710 triggering callbacks. Once attached to an asynchronous event it will
711 persist with the lifetime of the asynchronous call stack.
712
713 Explanation of function parameters:
714
715 `asyncListener(storageValue)`: A `Function` called when an asynchronous
716 event is instantiated. If a `Value` is returned then it will be attached
717 to the event and overwrite any value that had been passed to
718 `process.createAsyncListener()`'s `storageValue` argument. If an initial
719 `storageValue` was passed when created, then `asyncListener()` will
720 receive that as a function argument.
721
722 `callbacksObj`: An `Object` which may contain three optional fields:
723
724 * `before(context, storageValue)`: A `Function` that is called immediately
725 before the asynchronous callback is about to run. It will be passed both
726 the `context` (i.e. `this`) of the calling function and the `storageValue`
727 either returned from `asyncListener` or passed during construction (if
728 either occurred).
729
730 * `after(context, storageValue)`: A `Function` called immediately after
731 the asynchronous event's callback has run. Note this will not be called
732 if the callback throws and the error is not handled.
733
734 * `error(storageValue, error)`: A `Function` called if the event's
735 callback threw. If `error` returns `true` then Node will assume the error
736 has been properly handled and resume execution normally. When multiple
737 `error()` callbacks have been registered, only **one** of those callbacks
738 needs to return `true` for `AsyncListener` to accept that the error has
739 been handled.
740
741 `storageValue`: A `Value` (i.e. anything) that will be, by default,
742 attached to all new event instances. This will be overwritten if a `Value`
743 is returned by `asyncListener()`.
744
745 Here is an example of overwriting the `storageValue`:
746
747     process.createAsyncListener(function listener(value) {
748       // value === true
749       return false;
750     }, {
751       before: function before(context, value) {
752         // value === false
753       }
754     }, true);
755
756 **Note:** The [EventEmitter][], while used to emit status of an asynchronous
757 event, is not itself asynchronous. So `asyncListener()` will not fire when
758 an event is added, and `before`/`after` will not fire when emitted
759 callbacks are called.
760
761
762 ## process.addAsyncListener(asyncListener[, callbacksObj[, storageValue]])
763 ## process.addAsyncListener(asyncListener)
764
765 Returns a constructed `AsyncListener` object and immediately adds it to
766 the listening queue to begin capturing asynchronous events.
767
768 Function parameters can either be the same as
769 [`process.createAsyncListener()`][], or a constructed `AsyncListener`
770 object.
771
772 Example usage for capturing errors:
773
774     var cntr = 0;
775     var key = process.addAsyncListener(function() {
776       return { uid: cntr++ };
777     }, {
778       before: function onBefore(context, storage) {
779         // Need to remove the listener while logging or will end up
780         // with an infinite call loop.
781         process.removeAsyncListener(key);
782         console.log('uid: %s is about to run', storage.uid);
783         process.addAsyncListener(key);
784       },
785       after: function onAfter(context, storage) {
786         process.removeAsyncListener(key);
787         console.log('uid: %s is about to run', storage.uid);
788         process.addAsyncListener(key);
789       },
790       error: function onError(storage, err) {
791         // Handle known errors
792         if (err.message === 'really, it\'s ok') {
793           process.removeAsyncListener(key);
794           console.log('handled error just threw:');
795           console.log(err.stack);
796           process.addAsyncListener(key);
797           return true;
798         }
799       }
800     });
801
802     process.nextTick(function() {
803       throw new Error('really, it\'s ok');
804     });
805
806     // Output:
807     // uid: 0 is about to run
808     // handled error just threw:
809     // Error: really, it's ok
810     //     at /tmp/test2.js:27:9
811     //     at process._tickCallback (node.js:583:11)
812     //     at Function.Module.runMain (module.js:492:11)
813     //     at startup (node.js:123:16)
814     //     at node.js:1012:3
815
816 ## process.removeAsyncListener(asyncListener)
817
818 Removes the `AsyncListener` from the listening queue.
819
820 Removing the `AsyncListener` from the queue does _not_ mean asynchronous
821 events called during its execution scope will stop firing callbacks. Once
822 attached to an event it will persist for the entire asynchronous call
823 stack. For example:
824
825     var key = process.createAsyncListener(function asyncListener() {
826       // To log we must stop listening or we'll enter infinite recursion.
827       process.removeAsyncListener(key);
828       console.log('You summoned me?');
829       process.addAsyncListener(key);
830     });
831
832     // We want to begin capturing async events some time in the future.
833     setTimeout(function() {
834       process.addAsyncListener(key);
835
836       // Perform a few additional async events.
837       setTimeout(function() {
838         setImmediate(function() {
839           process.nextTick(function() { });
840         });
841       });
842
843       // Removing the listener doesn't mean to stop capturing events that
844       // have already been added.
845       process.removeAsyncListener(key);
846     }, 100);
847
848     // Output:
849     // You summoned me?
850     // You summoned me?
851     // You summoned me?
852     // You summoned me?
853
854 The fact that we logged 4 asynchronous events is an implementation detail
855 of Node's [Timers][].
856
857 To stop capturing from a specific asynchronous event stack
858 `process.removeAsyncListener()` must be called from within the call
859 stack itself. For example:
860
861     var key = process.createAsyncListener(function asyncListener() {
862       // To log we must stop listening or we'll enter infinite recursion.
863       process.removeAsyncListener(key);
864       console.log('You summoned me?');
865       process.addAsyncListener(key);
866     });
867
868     // We want to begin capturing async events some time in the future.
869     setTimeout(function() {
870       process.addAsyncListener(key);
871
872       // Perform a few additional async events.
873       setImmediate(function() {
874         // Stop capturing from this call stack.
875         process.removeAsyncListener(key);
876
877         process.nextTick(function() { });
878       });
879     }, 100);
880
881     // Output:
882     // You summoned me?
883
884 The user must be explicit and always pass the `AsyncListener` they wish
885 to remove. It is not possible to simply remove all listeners at once.
886
887
888 [EventEmitter]: events.html#events_class_events_eventemitter
889 [Timers]: timers.html
890 [`process.createAsyncListener()`]: #process_process_createasynclistener_asynclistener_callbacksobj_storagevalue
891 [`process.addAsyncListener()`]: #process_process_addasynclistener_asynclistener
892 [`process.removeAsyncListener()`]: #process_process_removeasynclistener_asynclistener