5 The `process` object is a global object and can be accessed from anywhere.
6 It is an instance of [EventEmitter][].
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
14 * `1` **Uncaught Fatal Exception** - There was an uncaught exception,
15 and it was not handled by a domain or an `uncaughtException` event
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
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
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.
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.
60 Example of listening for `exit`:
62 process.on('exit', function() {
63 setTimeout(function() {
64 console.log('This will not run');
66 console.log('About to exit.');
69 ## Event: 'uncaughtException'
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.
75 Example of listening for `uncaughtException`:
77 process.on('uncaughtException', function(err) {
78 console.log('Caught exception: ' + err);
81 setTimeout(function() {
82 console.log('This will still run.');
85 // Intentionally cause an exception, but don't catch it.
87 console.log('This will not run.');
89 Note that `uncaughtException` is a very crude mechanism for exception
92 Don't use it, use [domains](domain.html) instead. If you do use it, restart
93 your application after every unhandled exception!
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.
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.
102 You have been warned.
107 <!--name=SIGINT, SIGHUP, etc.-->
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.
112 Example of listening for `SIGINT`:
114 // Start reading from stdin so we don't exit.
115 process.stdin.resume();
117 process.on('SIGINT', function() {
118 console.log('Got SIGINT. Press Control-D to exit.');
121 An easy way to send the `SIGINT` signal is with `Control-C` in most terminal
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
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.
154 A `Writable Stream` to `stdout`.
156 Example: the definition of `console.log`
158 console.log = function(d) {
159 process.stdout.write(d + '\n');
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.
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`:
170 $ node -p "Boolean(process.stdin.isTTY)"
172 $ echo "foo" | node -p "Boolean(process.stdin.isTTY)"
175 $ node -p "Boolean(process.stdout.isTTY)"
177 $ node -p "Boolean(process.stdout.isTTY)" | cat
180 See [the tty docs](tty.html#tty_tty) for more information.
184 A writable stream to stderr.
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.
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.
197 Example of opening standard input and listening for both events:
199 process.stdin.resume();
200 process.stdin.setEncoding('utf8');
202 process.stdin.on('data', function(chunk) {
203 process.stdout.write('data: ' + chunk);
206 process.stdin.on('end', function() {
207 process.stdout.write('end');
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.
217 // print process.argv
218 process.argv.forEach(function(val, index, array) {
219 console.log(index + ': ' + val);
224 $ node process-2.js one two=three four
226 1: /Users/mjr/work/node/process-2.js
234 This is the absolute pathname of the executable that started the process.
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.
252 $ node --harmony script.js --version
254 results in process.execArgv:
260 ['/usr/local/bin/node', 'script.js', '--version']
265 This causes node to emit an abort. This will cause node to exit and
266 generate a core file.
268 ## process.chdir(directory)
270 Changes the current working directory of the process or throws an exception if that fails.
272 console.log('Starting directory: ' + process.cwd());
274 process.chdir('/tmp');
275 console.log('New directory: ' + process.cwd());
278 console.log('chdir: ' + err);
285 Returns the current working directory of the process.
287 console.log('Current directory: ' + process.cwd());
292 An object containing the user environment. See environ(7).
295 ## process.exit([code])
297 Ends the process with the specified `code`. If omitted, exit uses the
300 To exit with a 'failure' code:
304 The shell that executed node should see the exit code as 1.
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
313 Specifying a code to `process.exit(code)` will override any previous
314 setting of `process.exitCode`.
319 Note: this function is only available on POSIX platforms (i.e. not Windows,
322 Gets the group identity of the process. (See getgid(2).)
323 This is the numerical group id, not the group name.
325 if (process.getgid) {
326 console.log('Current gid: ' + process.getgid());
330 ## process.setgid(id)
332 Note: this function is only available on POSIX platforms (i.e. not Windows,
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.
339 if (process.getgid && process.setgid) {
340 console.log('Current gid: ' + process.getgid());
343 console.log('New gid: ' + process.getgid());
346 console.log('Failed to set gid: ' + err);
353 Note: this function is only available on POSIX platforms (i.e. not Windows,
356 Gets the user identity of the process. (See getuid(2).)
357 This is the numerical userid, not the username.
359 if (process.getuid) {
360 console.log('Current uid: ' + process.getuid());
364 ## process.setuid(id)
366 Note: this function is only available on POSIX platforms (i.e. not Windows,
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.
373 if (process.getuid && process.setuid) {
374 console.log('Current uid: ' + process.getuid());
377 console.log('New uid: ' + process.getuid());
380 console.log('Failed to set uid: ' + err);
385 ## process.getgroups()
387 Note: this function is only available on POSIX platforms (i.e. not Windows,
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.
394 ## process.setgroups(groups)
396 Note: this function is only available on POSIX platforms (i.e. not Windows,
399 Sets the supplementary group IDs. This is a privileged operation, meaning you
400 need to be root or have the CAP_SETGID capability.
402 The list can contain group IDs, group names or both.
405 ## process.initgroups(user, extra_group)
407 Note: this function is only available on POSIX platforms (i.e. not Windows,
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.
414 `user` is a user name or user ID. `extra_group` is a group name or group ID.
416 Some care needs to be taken when dropping privileges. Example:
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 ]
427 A compiled-in property that exposes `NODE_VERSION`.
429 console.log('Version: ' + process.version);
433 A property exposing version strings of node and its dependencies.
435 console.log(process.versions);
437 Will print something like:
439 { http_parser: '1.0',
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.
454 An example of the possible output looks like:
458 default_configuration: 'Release',
464 node_install_npm: 'true',
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',
476 v8_use_snapshot: 'true' } }
478 ## process.kill(pid, [signal])
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.
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.
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.
492 Example of sending a signal to yourself:
494 process.on('SIGHUP', function() {
495 console.log('Got SIGHUP signal.');
498 setTimeout(function() {
499 console.log('Exiting.');
503 process.kill(process.pid, 'SIGHUP');
505 Note: When SIGUSR1 is received by Node.js it starts the debugger, see
506 [Signal Events](#process_signal_events).
510 The PID of the process.
512 console.log('This process is pid ' + process.pid);
517 Getter/setter to set what is displayed in 'ps'.
519 When used as a setter, the maximum length is platform-specific and probably
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.
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)
532 What processor architecture you're running on: `'arm'`, `'ia32'`, or `'x64'`.
534 console.log('This processor architecture is ' + process.arch);
539 What platform you're running on:
540 `'darwin'`, `'freebsd'`, `'linux'`, `'sunos'` or `'win32'`
542 console.log('This platform is ' + process.platform);
545 ## process.memoryUsage()
547 Returns an object describing the memory usage of the Node process
550 var util = require('util');
552 console.log(util.inspect(process.memoryUsage()));
560 `heapTotal` and `heapUsed` refer to V8's memory usage.
563 ## process.nextTick(callback)
565 * `callback` {Function}
567 Once the current event loop turn runs to completion, call the callback
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.
574 console.log('start');
575 process.nextTick(function() {
576 console.log('nextTick callback');
578 console.log('scheduled');
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.
588 function MyThing(options) {
589 this.setupOptions(options);
591 process.nextTick(function() {
592 this.startDoingStuff();
596 var thing = new MyThing();
597 thing.getReadyForStuff();
599 // thing.startDoingStuff() gets called now, not before.
601 It is very important for APIs to be either 100% synchronous or 100%
602 asynchronous. Consider this example:
604 // WARNING! DO NOT USE! BAD UNSAFE HAZARD!
605 function maybeSync(arg, cb) {
614 This API is hazardous. If you do this:
616 maybeSync(true, function() {
621 then it's not clear whether `foo()` or `bar()` will be called first.
623 This approach is much better:
625 function definitelyAsync(arg, cb) {
627 process.nextTick(cb);
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.
639 ## process.umask([mask])
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.
645 var oldmask, newmask = 0644;
647 oldmask = process.umask(newmask);
648 console.log('Changed umask from: ' + oldmask.toString(8) +
649 ' to ' + newmask.toString(8));
654 Number of seconds Node has been running.
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.
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:
667 var time = process.hrtime();
670 setTimeout(function() {
671 var diff = process.hrtime(time);
674 console.log('benchmark took %d nanoseconds', diff[0] * 1e9 + diff[1]);
675 // benchmark took 1000000527 nanoseconds
683 Stability: 1 - Experimental
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.
692 ## process.createAsyncListener(asyncListener[, callbacksObj[, storageValue]])
694 * `asyncListener` {Function} callback fired when an asynchronous event is
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.
701 Returns a constructed `AsyncListener` object.
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.
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.
713 Explanation of function parameters:
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.
722 `callbacksObj`: An `Object` which may contain three optional fields:
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
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.
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
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()`.
745 Here is an example of overwriting the `storageValue`:
747 process.createAsyncListener(function listener(value) {
751 before: function before(context, value) {
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.
762 ## process.addAsyncListener(asyncListener[, callbacksObj[, storageValue]])
763 ## process.addAsyncListener(asyncListener)
765 Returns a constructed `AsyncListener` object and immediately adds it to
766 the listening queue to begin capturing asynchronous events.
768 Function parameters can either be the same as
769 [`process.createAsyncListener()`][], or a constructed `AsyncListener`
772 Example usage for capturing errors:
775 var key = process.addAsyncListener(function() {
776 return { uid: cntr++ };
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);
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);
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);
802 process.nextTick(function() {
803 throw new Error('really, it\'s ok');
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)
816 ## process.removeAsyncListener(asyncListener)
818 Removes the `AsyncListener` from the listening queue.
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
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);
832 // We want to begin capturing async events some time in the future.
833 setTimeout(function() {
834 process.addAsyncListener(key);
836 // Perform a few additional async events.
837 setTimeout(function() {
838 setImmediate(function() {
839 process.nextTick(function() { });
843 // Removing the listener doesn't mean to stop capturing events that
844 // have already been added.
845 process.removeAsyncListener(key);
854 The fact that we logged 4 asynchronous events is an implementation detail
855 of Node's [Timers][].
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:
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);
868 // We want to begin capturing async events some time in the future.
869 setTimeout(function() {
870 process.addAsyncListener(key);
872 // Perform a few additional async events.
873 setImmediate(function() {
874 // Stop capturing from this call stack.
875 process.removeAsyncListener(key);
877 process.nextTick(function() { });
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.
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