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.
122 <!--name=SIGINT, SIGHUP, etc.-->
124 Emitted when the processes receives a signal. See sigaction(2) for a list of
125 standard POSIX signal names such as SIGINT, SIGHUP, etc.
127 Example of listening for `SIGINT`:
129 // Start reading from stdin so we don't exit.
130 process.stdin.resume();
132 process.on('SIGINT', function() {
133 console.log('Got SIGINT. Press Control-D to exit.');
136 An easy way to send the `SIGINT` signal is with `Control-C` in most terminal
141 - `SIGUSR1` is reserved by io.js to start the debugger. It's possible to
142 install a listener but that won't stop the debugger from starting.
143 - `SIGTERM` and `SIGINT` have default handlers on non-Windows platforms that resets
144 the terminal mode before exiting with code `128 + signal number`. If one of
145 these signals has a listener installed, its default behaviour will be removed
146 (io.js will no longer exit).
147 - `SIGPIPE` is ignored by default, it can have a listener installed.
148 - `SIGHUP` is generated on Windows when the console window is closed, and on other
149 platforms under various similar conditions, see signal(7). It can have a
150 listener installed, however io.js will be unconditionally terminated by
151 Windows about 10 seconds later. On non-Windows platforms, the default
152 behaviour of `SIGHUP` is to terminate io.js, but once a listener has been
153 installed its default behaviour will be removed.
154 - `SIGTERM` is not supported on Windows, it can be listened on.
155 - `SIGINT` from the terminal is supported on all platforms, and can usually be
156 generated with `CTRL+C` (though this may be configurable). It is not generated
157 when terminal raw mode is enabled.
158 - `SIGBREAK` is delivered on Windows when `CTRL+BREAK` is pressed, on non-Windows
159 platforms it can be listened on, but there is no way to send or generate it.
160 - `SIGWINCH` is delivered when the console has been resized. On Windows, this will
161 only happen on write to the console when the cursor is being moved, or when a
162 readable tty is used in raw mode.
163 - `SIGKILL` cannot have a listener installed, it will unconditionally terminate
164 io.js on all platforms.
165 - `SIGSTOP` cannot have a listener installed.
167 Note that Windows does not support sending Signals, but io.js offers some
168 emulation with `process.kill()`, and `child_process.kill()`:
169 - Sending signal `0` can be used to search for the existence of a process
170 - Sending `SIGINT`, `SIGTERM`, and `SIGKILL` cause the unconditional exit of the
175 A `Writable Stream` to `stdout` (on fd `1`).
177 Example: the definition of `console.log`
179 console.log = function(d) {
180 process.stdout.write(d + '\n');
183 `process.stderr` and `process.stdout` are unlike other streams in io.js in
184 that they cannot be closed (`end()` will throw), they never emit the `finish`
185 event and that writes are usually blocking.
187 - They are blocking in the case that they refer to regular files or TTY file
189 - In the case they refer to pipes:
190 - They are blocking in Linux/Unix.
191 - They are non-blocking like other streams in Windows.
193 To check if io.js is being run in a TTY context, read the `isTTY` property
194 on `process.stderr`, `process.stdout`, or `process.stdin`:
196 $ iojs -p "Boolean(process.stdin.isTTY)"
198 $ echo "foo" | iojs -p "Boolean(process.stdin.isTTY)"
201 $ iojs -p "Boolean(process.stdout.isTTY)"
203 $ iojs -p "Boolean(process.stdout.isTTY)" | cat
206 See [the tty docs](tty.html#tty_tty) for more information.
210 A writable stream to stderr (on fd `2`).
212 `process.stderr` and `process.stdout` are unlike other streams in io.js in
213 that they cannot be closed (`end()` will throw), they never emit the `finish`
214 event and that writes are usually blocking.
216 - They are blocking in the case that they refer to regular files or TTY file
218 - In the case they refer to pipes:
219 - They are blocking in Linux/Unix.
220 - They are non-blocking like other streams in Windows.
225 A `Readable Stream` for stdin (on fd `0`).
227 Example of opening standard input and listening for both events:
229 process.stdin.setEncoding('utf8');
231 process.stdin.on('readable', function() {
232 var chunk = process.stdin.read();
233 if (chunk !== null) {
234 process.stdout.write('data: ' + chunk);
238 process.stdin.on('end', function() {
239 process.stdout.write('end');
242 As a Stream, `process.stdin` can also be used in "old" mode that is compatible
243 with scripts written for node.js prior to v0.10.
244 For more information see
245 [Stream compatibility](stream.html#stream_compatibility_with_older_node_versions).
247 In "old" Streams mode the stdin stream is paused by default, so one
248 must call `process.stdin.resume()` to read from it. Note also that calling
249 `process.stdin.resume()` itself would switch stream to "old" mode.
251 If you are starting a new project you should prefer a more recent "new" Streams
256 An array containing the command line arguments. The first element will be
257 'iojs', the second element will be the name of the JavaScript file. The
258 next elements will be any additional command line arguments.
260 // print process.argv
261 process.argv.forEach(function(val, index, array) {
262 console.log(index + ': ' + val);
267 $ iojs process-2.js one two=three four
269 1: /Users/mjr/work/iojs/process-2.js
277 This is the absolute pathname of the executable that started the process.
286 This is the set of io.js-specific command line options from the
287 executable that started the process. These options do not show up in
288 `process.argv`, and do not include the io.js executable, the name of
289 the script, or any options following the script name. These options
290 are useful in order to spawn child processes with the same execution
291 environment as the parent.
295 $ iojs --harmony script.js --version
297 results in process.execArgv:
303 ['/usr/local/bin/iojs', 'script.js', '--version']
308 This causes io.js to emit an abort. This will cause io.js to exit and
309 generate a core file.
311 ## process.chdir(directory)
313 Changes the current working directory of the process or throws an exception if that fails.
315 console.log('Starting directory: ' + process.cwd());
317 process.chdir('/tmp');
318 console.log('New directory: ' + process.cwd());
321 console.log('chdir: ' + err);
328 Returns the current working directory of the process.
330 console.log('Current directory: ' + process.cwd());
335 An object containing the user environment. See environ(7).
337 An example of this object looks like:
339 { TERM: 'xterm-256color',
340 SHELL: '/usr/local/bin/bash',
342 PATH: '~/.bin/:/usr/bin:/bin:/usr/sbin:/sbin:/usr/local/bin',
343 PWD: '/Users/maciej',
346 HOME: '/Users/maciej',
348 _: '/usr/local/bin/iojs' }
350 You can write to this object, but changes won't be reflected outside of your
351 process. That means that the following won't work:
353 $ iojs -e 'process.env.foo = "bar"' && echo $foo
357 process.env.foo = 'bar';
358 console.log(process.env.foo);
361 ## process.exit([code])
363 Ends the process with the specified `code`. If omitted, exit uses the
366 To exit with a 'failure' code:
370 The shell that executed io.js should see the exit code as 1.
375 A number which will be the process exit code, when the process either
376 exits gracefully, or is exited via `process.exit()` without specifying
379 Specifying a code to `process.exit(code)` will override any previous
380 setting of `process.exitCode`.
385 Note: this function is only available on POSIX platforms (i.e. not Windows,
388 Gets the group identity of the process. (See getgid(2).)
389 This is the numerical group id, not the group name.
391 if (process.getgid) {
392 console.log('Current gid: ' + process.getgid());
396 ## process.setgid(id)
398 Note: this function is only available on POSIX platforms (i.e. not Windows,
401 Sets the group identity of the process. (See setgid(2).) This accepts either
402 a numerical ID or a groupname string. If a groupname is specified, this method
403 blocks while resolving it to a numerical ID.
405 if (process.getgid && process.setgid) {
406 console.log('Current gid: ' + process.getgid());
409 console.log('New gid: ' + process.getgid());
412 console.log('Failed to set gid: ' + err);
419 Note: this function is only available on POSIX platforms (i.e. not Windows,
422 Gets the user identity of the process. (See getuid(2).)
423 This is the numerical userid, not the username.
425 if (process.getuid) {
426 console.log('Current uid: ' + process.getuid());
430 ## process.setuid(id)
432 Note: this function is only available on POSIX platforms (i.e. not Windows,
435 Sets the user identity of the process. (See setuid(2).) This accepts either
436 a numerical ID or a username string. If a username is specified, this method
437 blocks while resolving it to a numerical ID.
439 if (process.getuid && process.setuid) {
440 console.log('Current uid: ' + process.getuid());
443 console.log('New uid: ' + process.getuid());
446 console.log('Failed to set uid: ' + err);
451 ## process.getgroups()
453 Note: this function is only available on POSIX platforms (i.e. not Windows,
456 Returns an array with the supplementary group IDs. POSIX leaves it unspecified
457 if the effective group ID is included but io.js ensures it always is.
460 ## process.setgroups(groups)
462 Note: this function is only available on POSIX platforms (i.e. not Windows,
465 Sets the supplementary group IDs. This is a privileged operation, meaning you
466 need to be root or have the CAP_SETGID capability.
468 The list can contain group IDs, group names or both.
471 ## process.initgroups(user, extra_group)
473 Note: this function is only available on POSIX platforms (i.e. not Windows,
476 Reads /etc/group and initializes the group access list, using all groups of
477 which the user is a member. This is a privileged operation, meaning you need
478 to be root or have the CAP_SETGID capability.
480 `user` is a user name or user ID. `extra_group` is a group name or group ID.
482 Some care needs to be taken when dropping privileges. Example:
484 console.log(process.getgroups()); // [ 0 ]
485 process.initgroups('bnoordhuis', 1000); // switch user
486 console.log(process.getgroups()); // [ 27, 30, 46, 1000, 0 ]
487 process.setgid(1000); // drop root gid
488 console.log(process.getgroups()); // [ 27, 30, 46, 1000 ]
493 A compiled-in property that exposes `NODE_VERSION`.
495 console.log('Version: ' + process.version);
499 A property exposing version strings of io.js and its dependencies.
501 console.log(process.versions);
503 Will print something like:
505 { http_parser: '2.3.0',
516 An Object containing the JavaScript representation of the configure options
517 that were used to compile the current io.js executable. This is the same as
518 the "config.gypi" file that was produced when running the `./configure` script.
520 An example of the possible output looks like:
524 default_configuration: 'Release',
530 node_install_npm: 'true',
532 node_shared_cares: 'false',
533 node_shared_http_parser: 'false',
534 node_shared_libuv: 'false',
535 node_shared_v8: 'false',
536 node_shared_zlib: 'false',
537 node_use_dtrace: 'false',
538 node_use_openssl: 'true',
539 node_shared_openssl: 'false',
540 strict_aliasing: 'true',
542 v8_use_snapshot: 'true' } }
544 ## process.kill(pid[, signal])
546 Send a signal to a process. `pid` is the process id and `signal` is the
547 string describing the signal to send. Signal names are strings like
548 'SIGINT' or 'SIGHUP'. If omitted, the signal will be 'SIGTERM'.
549 See [Signal Events](#process_signal_events) and kill(2) for more information.
551 Will throw an error if target does not exist, and as a special case, a signal of
552 `0` can be used to test for the existence of a process.
554 Note that just because the name of this function is `process.kill`, it is
555 really just a signal sender, like the `kill` system call. The signal sent
556 may do something other than kill the target process.
558 Example of sending a signal to yourself:
560 process.on('SIGHUP', function() {
561 console.log('Got SIGHUP signal.');
564 setTimeout(function() {
565 console.log('Exiting.');
569 process.kill(process.pid, 'SIGHUP');
571 Note: When SIGUSR1 is received by io.js it starts the debugger, see
572 [Signal Events](#process_signal_events).
576 The PID of the process.
578 console.log('This process is pid ' + process.pid);
583 Getter/setter to set what is displayed in 'ps'.
585 When used as a setter, the maximum length is platform-specific and probably
588 On Linux and OS X, it's limited to the size of the binary name plus the
589 length of the command line arguments because it overwrites the argv memory.
591 v0.8 allowed for longer process title strings by also overwriting the environ
592 memory but that was potentially insecure/confusing in some (rather obscure)
598 What processor architecture you're running on: `'arm'`, `'ia32'`, or `'x64'`.
600 console.log('This processor architecture is ' + process.arch);
605 What platform you're running on:
606 `'darwin'`, `'freebsd'`, `'linux'`, `'sunos'` or `'win32'`
608 console.log('This platform is ' + process.platform);
611 ## process.memoryUsage()
613 Returns an object describing the memory usage of the io.js process
616 var util = require('util');
618 console.log(util.inspect(process.memoryUsage()));
626 `heapTotal` and `heapUsed` refer to V8's memory usage.
629 ## process.nextTick(callback)
631 * `callback` {Function}
633 Once the current event loop turn runs to completion, call the callback
636 This is *not* a simple alias to `setTimeout(fn, 0)`, it's much more
637 efficient. It runs before any additional I/O events (including
638 timers) fire in subsequent ticks of the event loop.
640 console.log('start');
641 process.nextTick(function() {
642 console.log('nextTick callback');
644 console.log('scheduled');
650 This is important in developing APIs where you want to give the user the
651 chance to assign event handlers after an object has been constructed,
652 but before any I/O has occurred.
654 function MyThing(options) {
655 this.setupOptions(options);
657 process.nextTick(function() {
658 this.startDoingStuff();
662 var thing = new MyThing();
663 thing.getReadyForStuff();
665 // thing.startDoingStuff() gets called now, not before.
667 It is very important for APIs to be either 100% synchronous or 100%
668 asynchronous. Consider this example:
670 // WARNING! DO NOT USE! BAD UNSAFE HAZARD!
671 function maybeSync(arg, cb) {
680 This API is hazardous. If you do this:
682 maybeSync(true, function() {
687 then it's not clear whether `foo()` or `bar()` will be called first.
689 This approach is much better:
691 function definitelyAsync(arg, cb) {
693 process.nextTick(cb);
700 Note: the nextTick queue is completely drained on each pass of the
701 event loop **before** additional I/O is processed. As a result,
702 recursively setting nextTick callbacks will block any I/O from
703 happening, just like a `while(true);` loop.
705 ## process.umask([mask])
707 Sets or reads the process's file mode creation mask. Child processes inherit
708 the mask from the parent process. Returns the old mask if `mask` argument is
709 given, otherwise returns the current mask.
711 var oldmask, newmask = 0022;
713 oldmask = process.umask(newmask);
714 console.log('Changed umask from: ' + oldmask.toString(8) +
715 ' to ' + newmask.toString(8));
720 Number of seconds io.js has been running.
725 Returns the current high-resolution real time in a `[seconds, nanoseconds]`
726 tuple Array. It is relative to an arbitrary time in the past. It is not
727 related to the time of day and therefore not subject to clock drift. The
728 primary use is for measuring performance between intervals.
730 You may pass in the result of a previous call to `process.hrtime()` to get
731 a diff reading, useful for benchmarks and measuring intervals:
733 var time = process.hrtime();
736 setTimeout(function() {
737 var diff = process.hrtime(time);
740 console.log('benchmark took %d nanoseconds', diff[0] * 1e9 + diff[1]);
741 // benchmark took 1000000527 nanoseconds
745 ## process.mainModule
747 Alternate way to retrieve
748 [`require.main`](modules.html#modules_accessing_the_main_module).
749 The difference is that if the main module changes at runtime, `require.main`
750 might still refer to the original main module in modules that were required
751 before the change occurred. Generally it's safe to assume that the two refer
754 As with `require.main`, it will be `undefined` if there was no entry script.
756 [EventEmitter]: events.html#events_class_events_eventemitter