5 The `process` object is a global object and can be accessed from anywhere.
6 It is an instance of [EventEmitter][].
10 io.js 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 io.js'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 io.js'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 io.js 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 io.js, 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 io.js'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 io.js 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 io.js 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. 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.
62 Example of listening for `exit`:
64 process.on('exit', function(code) {
66 setTimeout(function() {
67 console.log('This will not run');
69 console.log('About to exit with code:', code);
73 ## Event: 'beforeExit'
75 This event is emitted when io.js empties its event loop and has nothing else to
76 schedule. Normally, io.js exits when there is no work scheduled, but a listener
77 for 'beforeExit' can make asynchronous calls, and cause io.js to continue.
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.
84 ## Event: 'uncaughtException'
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.
90 Example of listening for `uncaughtException`:
92 process.on('uncaughtException', function(err) {
93 console.log('Caught exception: ' + err);
96 setTimeout(function() {
97 console.log('This will still run.');
100 // Intentionally cause an exception, but don't catch it.
102 console.log('This will not run.');
104 Note that `uncaughtException` is a very crude mechanism for exception
107 Don't use it, use [domains](domain.html) instead. If you do use it, restart
108 your application after every unhandled exception!
110 Do *not* use it as the io.js equivalent of `On Error Resume Next`. An
111 unhandled exception means your application - and by extension io.js itself -
112 is in an undefined state. Blindly resuming means *anything* could happen.
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.
117 You have been warned.
119 ## Event: 'unhandledRejection'
121 Emitted whenever a `Promise` is rejected and no error handler is attached to
122 the promise within a turn of the event loop. When programming with promises
123 exceptions are encapsulated as rejected promises. Such promises can be caught
124 and handled using `promise.catch(...)` and rejections are propagated through
125 a promise chain. This event is useful for detecting and keeping track of
126 promises that were rejected whose rejections were not handled yet. This event
127 is emitted with the following arguments:
129 - `reason` the object with which the promise was rejected (usually an `Error`
131 - `p` the promise that was rejected.
133 Here is an example that logs every unhandled rejection to the console
135 process.on('unhandledRejection', function(reason, p) {
136 console.log("Unhandled Rejection at: Promise ", p, " reason: ", reason);
137 // application specific logging, throwing an error, or other logic here
140 For example, here is a rejection that will trigger the `'unhandledRejection'`
143 somePromise.then(function(res) {
144 return reportToUser(JSON.pasre(res)); // note the typo
145 }); // no `.catch` or `.then`
147 ## Event: 'rejectionHandled'
149 Emitted whenever a Promise was rejected and an error handler was attached to it
150 (for example with `.catch()`) later than after an event loop turn. This event
151 is emitted with the following arguments:
153 - `p` the promise that was previously emitted in an 'unhandledRejection'
154 event, but which has now gained a rejection handler.
156 There is no notion of a top level for a promise chain at which rejections can
157 always be handled. Being inherently asynchronous in nature, a promise rejection
158 can be be handled at a future point in time — possibly much later than the
159 event loop turn it takes for the 'unhandledRejection' event to be emitted.
161 Another way of stating this is that, unlike in synchronous code where there is
162 an ever-growing list of unhandled exceptions, with promises there is a
163 growing-and-shrinking list of unhandled rejections. In synchronous code, the
164 'uncaughtException' event tells you when the list of unhandled exceptions
165 grows. And in asynchronous code, the 'unhandledRejection' event tells you
166 when the list of unhandled rejections grows, while the 'rejectionHandled'
167 event tells you when the list of unhandled rejections shrinks.
169 For example using the rejection detection hooks in order to keep a list of all
170 the rejected promises at a given time:
172 var unhandledRejections = [];
173 process.on('unhandledRejection', function(reason, p) {
174 unhandledRejections.push(p);
176 process.on('rejectionHandled', function(p) {
177 var index = unhandledRejections.indexOf(p);
178 unhandledRejections.splice(index, 1);
184 <!--name=SIGINT, SIGHUP, etc.-->
186 Emitted when the processes receives a signal. See sigaction(2) for a list of
187 standard POSIX signal names such as SIGINT, SIGHUP, etc.
189 Example of listening for `SIGINT`:
191 // Start reading from stdin so we don't exit.
192 process.stdin.resume();
194 process.on('SIGINT', function() {
195 console.log('Got SIGINT. Press Control-D to exit.');
198 An easy way to send the `SIGINT` signal is with `Control-C` in most terminal
203 - `SIGUSR1` is reserved by io.js to start the debugger. It's possible to
204 install a listener but that won't stop the debugger from starting.
205 - `SIGTERM` and `SIGINT` have default handlers on non-Windows platforms that resets
206 the terminal mode before exiting with code `128 + signal number`. If one of
207 these signals has a listener installed, its default behaviour will be removed
208 (io.js will no longer exit).
209 - `SIGPIPE` is ignored by default, it can have a listener installed.
210 - `SIGHUP` is generated on Windows when the console window is closed, and on other
211 platforms under various similar conditions, see signal(7). It can have a
212 listener installed, however io.js will be unconditionally terminated by
213 Windows about 10 seconds later. On non-Windows platforms, the default
214 behaviour of `SIGHUP` is to terminate io.js, but once a listener has been
215 installed its default behaviour will be removed.
216 - `SIGTERM` is not supported on Windows, it can be listened on.
217 - `SIGINT` from the terminal is supported on all platforms, and can usually be
218 generated with `CTRL+C` (though this may be configurable). It is not generated
219 when terminal raw mode is enabled.
220 - `SIGBREAK` is delivered on Windows when `CTRL+BREAK` is pressed, on non-Windows
221 platforms it can be listened on, but there is no way to send or generate it.
222 - `SIGWINCH` is delivered when the console has been resized. On Windows, this will
223 only happen on write to the console when the cursor is being moved, or when a
224 readable tty is used in raw mode.
225 - `SIGKILL` cannot have a listener installed, it will unconditionally terminate
226 io.js on all platforms.
227 - `SIGSTOP` cannot have a listener installed.
229 Note that Windows does not support sending Signals, but io.js offers some
230 emulation with `process.kill()`, and `child_process.kill()`:
231 - Sending signal `0` can be used to search for the existence of a process
232 - Sending `SIGINT`, `SIGTERM`, and `SIGKILL` cause the unconditional exit of the
237 A `Writable Stream` to `stdout` (on fd `1`).
239 Example: the definition of `console.log`
241 console.log = function(d) {
242 process.stdout.write(d + '\n');
245 `process.stderr` and `process.stdout` are unlike other streams in io.js in
246 that they cannot be closed (`end()` will throw), they never emit the `finish`
247 event and that writes are usually blocking.
249 - They are blocking in the case that they refer to regular files or TTY file
251 - In the case they refer to pipes:
252 - They are blocking in Linux/Unix.
253 - They are non-blocking like other streams in Windows.
255 To check if io.js is being run in a TTY context, read the `isTTY` property
256 on `process.stderr`, `process.stdout`, or `process.stdin`:
258 $ iojs -p "Boolean(process.stdin.isTTY)"
260 $ echo "foo" | iojs -p "Boolean(process.stdin.isTTY)"
263 $ iojs -p "Boolean(process.stdout.isTTY)"
265 $ iojs -p "Boolean(process.stdout.isTTY)" | cat
268 See [the tty docs](tty.html#tty_tty) for more information.
272 A writable stream to stderr (on fd `2`).
274 `process.stderr` and `process.stdout` are unlike other streams in io.js in
275 that they cannot be closed (`end()` will throw), they never emit the `finish`
276 event and that writes are usually blocking.
278 - They are blocking in the case that they refer to regular files or TTY file
280 - In the case they refer to pipes:
281 - They are blocking in Linux/Unix.
282 - They are non-blocking like other streams in Windows.
287 A `Readable Stream` for stdin (on fd `0`).
289 Example of opening standard input and listening for both events:
291 process.stdin.setEncoding('utf8');
293 process.stdin.on('readable', function() {
294 var chunk = process.stdin.read();
295 if (chunk !== null) {
296 process.stdout.write('data: ' + chunk);
300 process.stdin.on('end', function() {
301 process.stdout.write('end');
304 As a Stream, `process.stdin` can also be used in "old" mode that is compatible
305 with scripts written for node.js prior to v0.10.
306 For more information see
307 [Stream compatibility](stream.html#stream_compatibility_with_older_node_versions).
309 In "old" Streams mode the stdin stream is paused by default, so one
310 must call `process.stdin.resume()` to read from it. Note also that calling
311 `process.stdin.resume()` itself would switch stream to "old" mode.
313 If you are starting a new project you should prefer a more recent "new" Streams
318 An array containing the command line arguments. The first element will be
319 'iojs', the second element will be the name of the JavaScript file. The
320 next elements will be any additional command line arguments.
322 // print process.argv
323 process.argv.forEach(function(val, index, array) {
324 console.log(index + ': ' + val);
329 $ iojs process-2.js one two=three four
331 1: /Users/mjr/work/iojs/process-2.js
339 This is the absolute pathname of the executable that started the process.
348 This is the set of io.js-specific command line options from the
349 executable that started the process. These options do not show up in
350 `process.argv`, and do not include the io.js executable, the name of
351 the script, or any options following the script name. These options
352 are useful in order to spawn child processes with the same execution
353 environment as the parent.
357 $ iojs --harmony script.js --version
359 results in process.execArgv:
365 ['/usr/local/bin/iojs', 'script.js', '--version']
370 This causes io.js to emit an abort. This will cause io.js to exit and
371 generate a core file.
373 ## process.chdir(directory)
375 Changes the current working directory of the process or throws an exception if that fails.
377 console.log('Starting directory: ' + process.cwd());
379 process.chdir('/tmp');
380 console.log('New directory: ' + process.cwd());
383 console.log('chdir: ' + err);
390 Returns the current working directory of the process.
392 console.log('Current directory: ' + process.cwd());
397 An object containing the user environment. See environ(7).
399 An example of this object looks like:
401 { TERM: 'xterm-256color',
402 SHELL: '/usr/local/bin/bash',
404 PATH: '~/.bin/:/usr/bin:/bin:/usr/sbin:/sbin:/usr/local/bin',
405 PWD: '/Users/maciej',
408 HOME: '/Users/maciej',
410 _: '/usr/local/bin/iojs' }
412 You can write to this object, but changes won't be reflected outside of your
413 process. That means that the following won't work:
415 $ iojs -e 'process.env.foo = "bar"' && echo $foo
419 process.env.foo = 'bar';
420 console.log(process.env.foo);
423 ## process.exit([code])
425 Ends the process with the specified `code`. If omitted, exit uses the
428 To exit with a 'failure' code:
432 The shell that executed io.js should see the exit code as 1.
437 A number which will be the process exit code, when the process either
438 exits gracefully, or is exited via `process.exit()` without specifying
441 Specifying a code to `process.exit(code)` will override any previous
442 setting of `process.exitCode`.
447 Note: this function is only available on POSIX platforms (i.e. not Windows,
450 Gets the group identity of the process. (See getgid(2).)
451 This is the numerical group id, not the group name.
453 if (process.getgid) {
454 console.log('Current gid: ' + process.getgid());
458 ## process.setgid(id)
460 Note: this function is only available on POSIX platforms (i.e. not Windows,
463 Sets the group identity of the process. (See setgid(2).) This accepts either
464 a numerical ID or a groupname string. If a groupname is specified, this method
465 blocks while resolving it to a numerical ID.
467 if (process.getgid && process.setgid) {
468 console.log('Current gid: ' + process.getgid());
471 console.log('New gid: ' + process.getgid());
474 console.log('Failed to set gid: ' + err);
481 Note: this function is only available on POSIX platforms (i.e. not Windows,
484 Gets the user identity of the process. (See getuid(2).)
485 This is the numerical userid, not the username.
487 if (process.getuid) {
488 console.log('Current uid: ' + process.getuid());
492 ## process.setuid(id)
494 Note: this function is only available on POSIX platforms (i.e. not Windows,
497 Sets the user identity of the process. (See setuid(2).) This accepts either
498 a numerical ID or a username string. If a username is specified, this method
499 blocks while resolving it to a numerical ID.
501 if (process.getuid && process.setuid) {
502 console.log('Current uid: ' + process.getuid());
505 console.log('New uid: ' + process.getuid());
508 console.log('Failed to set uid: ' + err);
513 ## process.getgroups()
515 Note: this function is only available on POSIX platforms (i.e. not Windows,
518 Returns an array with the supplementary group IDs. POSIX leaves it unspecified
519 if the effective group ID is included but io.js ensures it always is.
522 ## process.setgroups(groups)
524 Note: this function is only available on POSIX platforms (i.e. not Windows,
527 Sets the supplementary group IDs. This is a privileged operation, meaning you
528 need to be root or have the CAP_SETGID capability.
530 The list can contain group IDs, group names or both.
533 ## process.initgroups(user, extra_group)
535 Note: this function is only available on POSIX platforms (i.e. not Windows,
538 Reads /etc/group and initializes the group access list, using all groups of
539 which the user is a member. This is a privileged operation, meaning you need
540 to be root or have the CAP_SETGID capability.
542 `user` is a user name or user ID. `extra_group` is a group name or group ID.
544 Some care needs to be taken when dropping privileges. Example:
546 console.log(process.getgroups()); // [ 0 ]
547 process.initgroups('bnoordhuis', 1000); // switch user
548 console.log(process.getgroups()); // [ 27, 30, 46, 1000, 0 ]
549 process.setgid(1000); // drop root gid
550 console.log(process.getgroups()); // [ 27, 30, 46, 1000 ]
555 A compiled-in property that exposes `NODE_VERSION`.
557 console.log('Version: ' + process.version);
561 A property exposing version strings of io.js and its dependencies.
563 console.log(process.versions);
565 Will print something like:
567 { http_parser: '2.3.0',
578 An Object containing the JavaScript representation of the configure options
579 that were used to compile the current io.js executable. This is the same as
580 the "config.gypi" file that was produced when running the `./configure` script.
582 An example of the possible output looks like:
586 default_configuration: 'Release',
592 node_install_npm: 'true',
594 node_shared_cares: 'false',
595 node_shared_http_parser: 'false',
596 node_shared_libuv: 'false',
597 node_shared_v8: 'false',
598 node_shared_zlib: 'false',
599 node_use_dtrace: 'false',
600 node_use_openssl: 'true',
601 node_shared_openssl: 'false',
602 strict_aliasing: 'true',
604 v8_use_snapshot: 'true' } }
606 ## process.kill(pid[, signal])
608 Send a signal to a process. `pid` is the process id and `signal` is the
609 string describing the signal to send. Signal names are strings like
610 'SIGINT' or 'SIGHUP'. If omitted, the signal will be 'SIGTERM'.
611 See [Signal Events](#process_signal_events) and kill(2) for more information.
613 Will throw an error if target does not exist, and as a special case, a signal of
614 `0` can be used to test for the existence of a process.
616 Note that just because the name of this function is `process.kill`, it is
617 really just a signal sender, like the `kill` system call. The signal sent
618 may do something other than kill the target process.
620 Example of sending a signal to yourself:
622 process.on('SIGHUP', function() {
623 console.log('Got SIGHUP signal.');
626 setTimeout(function() {
627 console.log('Exiting.');
631 process.kill(process.pid, 'SIGHUP');
633 Note: When SIGUSR1 is received by io.js it starts the debugger, see
634 [Signal Events](#process_signal_events).
638 The PID of the process.
640 console.log('This process is pid ' + process.pid);
645 Getter/setter to set what is displayed in 'ps'.
647 When used as a setter, the maximum length is platform-specific and probably
650 On Linux and OS X, it's limited to the size of the binary name plus the
651 length of the command line arguments because it overwrites the argv memory.
653 v0.8 allowed for longer process title strings by also overwriting the environ
654 memory but that was potentially insecure/confusing in some (rather obscure)
660 What processor architecture you're running on: `'arm'`, `'ia32'`, or `'x64'`.
662 console.log('This processor architecture is ' + process.arch);
667 What platform you're running on:
668 `'darwin'`, `'freebsd'`, `'linux'`, `'sunos'` or `'win32'`
670 console.log('This platform is ' + process.platform);
673 ## process.memoryUsage()
675 Returns an object describing the memory usage of the io.js process
678 var util = require('util');
680 console.log(util.inspect(process.memoryUsage()));
688 `heapTotal` and `heapUsed` refer to V8's memory usage.
691 ## process.nextTick(callback)
693 * `callback` {Function}
695 Once the current event loop turn runs to completion, call the callback
698 This is *not* a simple alias to `setTimeout(fn, 0)`, it's much more
699 efficient. It runs before any additional I/O events (including
700 timers) fire in subsequent ticks of the event loop.
702 console.log('start');
703 process.nextTick(function() {
704 console.log('nextTick callback');
706 console.log('scheduled');
712 This is important in developing APIs where you want to give the user the
713 chance to assign event handlers after an object has been constructed,
714 but before any I/O has occurred.
716 function MyThing(options) {
717 this.setupOptions(options);
719 process.nextTick(function() {
720 this.startDoingStuff();
724 var thing = new MyThing();
725 thing.getReadyForStuff();
727 // thing.startDoingStuff() gets called now, not before.
729 It is very important for APIs to be either 100% synchronous or 100%
730 asynchronous. Consider this example:
732 // WARNING! DO NOT USE! BAD UNSAFE HAZARD!
733 function maybeSync(arg, cb) {
742 This API is hazardous. If you do this:
744 maybeSync(true, function() {
749 then it's not clear whether `foo()` or `bar()` will be called first.
751 This approach is much better:
753 function definitelyAsync(arg, cb) {
755 process.nextTick(cb);
762 Note: the nextTick queue is completely drained on each pass of the
763 event loop **before** additional I/O is processed. As a result,
764 recursively setting nextTick callbacks will block any I/O from
765 happening, just like a `while(true);` loop.
767 ## process.umask([mask])
769 Sets or reads the process's file mode creation mask. Child processes inherit
770 the mask from the parent process. Returns the old mask if `mask` argument is
771 given, otherwise returns the current mask.
773 var oldmask, newmask = 0022;
775 oldmask = process.umask(newmask);
776 console.log('Changed umask from: ' + oldmask.toString(8) +
777 ' to ' + newmask.toString(8));
782 Number of seconds io.js has been running.
787 Returns the current high-resolution real time in a `[seconds, nanoseconds]`
788 tuple Array. It is relative to an arbitrary time in the past. It is not
789 related to the time of day and therefore not subject to clock drift. The
790 primary use is for measuring performance between intervals.
792 You may pass in the result of a previous call to `process.hrtime()` to get
793 a diff reading, useful for benchmarks and measuring intervals:
795 var time = process.hrtime();
798 setTimeout(function() {
799 var diff = process.hrtime(time);
802 console.log('benchmark took %d nanoseconds', diff[0] * 1e9 + diff[1]);
803 // benchmark took 1000000527 nanoseconds
807 ## process.mainModule
809 Alternate way to retrieve
810 [`require.main`](modules.html#modules_accessing_the_main_module).
811 The difference is that if the main module changes at runtime, `require.main`
812 might still refer to the original main module in modules that were required
813 before the change occurred. Generally it's safe to assume that the two refer
816 As with `require.main`, it will be `undefined` if there was no entry script.
818 [EventEmitter]: events.html#events_class_events_eventemitter