revise installing a license file
[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 ## Event: 'beforeExit'
9
10 This event is emitted when Node.js empties its event loop and has nothing else
11 to schedule. Normally, Node.js exits when there is no work scheduled, but a
12 listener for `'beforeExit'` can make asynchronous calls, and cause Node.js to
13 continue.
14
15 `'beforeExit'` is not emitted for conditions causing explicit termination, such
16 as [`process.exit()`][] or uncaught exceptions, and should not be used as an
17 alternative to the `'exit'` event unless the intention is to schedule more work.
18
19 ## Event: 'exit'
20
21 Emitted when the process is about to exit. There is no way to prevent the
22 exiting of the event loop at this point, and once all `'exit'` listeners have
23 finished running the process will exit. Therefore you **must** only perform
24 **synchronous** operations in this handler. This is a good hook to perform
25 checks on the module's state (like for unit tests). The callback takes one
26 argument, the code the process is exiting with.
27
28 This event is only emitted when Node.js exits explicitly by process.exit() or
29 implicitly by the event loop draining.
30
31 Example of listening for `'exit'`:
32
33 ```js
34 process.on('exit', (code) => {
35   // do *NOT* do this
36   setTimeout(() => {
37     console.log('This will not run');
38   }, 0);
39   console.log('About to exit with code:', code);
40 });
41 ```
42
43 ## Event: 'message'
44
45 * `message` {Object} a parsed JSON object or primitive value
46 * `sendHandle` {Handle object} a [`net.Socket`][] or [`net.Server`][] object, or
47   undefined.
48
49 Messages sent by [`ChildProcess.send()`][] are obtained using the `'message'`
50 event on the child's process object.
51
52 ## Event: 'rejectionHandled'
53
54 Emitted whenever a Promise was rejected and an error handler was attached to it
55 (for example with `.catch()`) later than after an event loop turn. This event
56 is emitted with the following arguments:
57
58  - `p` the promise that was previously emitted in an `'unhandledRejection'`
59  event, but which has now gained a rejection handler.
60
61 There is no notion of a top level for a promise chain at which rejections can
62 always be handled. Being inherently asynchronous in nature, a promise rejection
63 can be handled at a future point in time — possibly much later than the
64 event loop turn it takes for the `'unhandledRejection'` event to be emitted.
65
66 Another way of stating this is that, unlike in synchronous code where there is
67 an ever-growing list of unhandled exceptions, with promises there is a
68 growing-and-shrinking list of unhandled rejections. In synchronous code, the
69 `'uncaughtException'` event tells you when the list of unhandled exceptions
70 grows. And in asynchronous code, the `'unhandledRejection'` event tells you
71 when the list of unhandled rejections grows, while the `'rejectionHandled'`
72 event tells you when the list of unhandled rejections shrinks.
73
74 For example using the rejection detection hooks in order to keep a map of all
75 the rejected promise reasons at a given time:
76
77 ```js
78 const unhandledRejections = new Map();
79 process.on('unhandledRejection', (reason, p) => {
80   unhandledRejections.set(p, reason);
81 });
82 process.on('rejectionHandled', (p) => {
83   unhandledRejections.delete(p);
84 });
85 ```
86
87 This map will grow and shrink over time, reflecting rejections that start
88 unhandled and then become handled. You could record the errors in some error
89 log, either periodically (probably best for long-running programs, allowing
90 you to clear the map, which in the case of a very buggy program could grow
91 indefinitely) or upon process exit (more convenient for scripts).
92
93 ## Event: 'uncaughtException'
94
95 The `'uncaughtException'` event is emitted when an exception bubbles all the
96 way back to the event loop. By default, Node.js handles such exceptions by
97 printing the stack trace to stderr and exiting. Adding a handler for the
98 `'uncaughtException'` event overrides this default behavior.
99
100 For example:
101
102 ```js
103 process.on('uncaughtException', (err) => {
104   console.log(`Caught exception: ${err}`);
105 });
106
107 setTimeout(() => {
108   console.log('This will still run.');
109 }, 500);
110
111 // Intentionally cause an exception, but don't catch it.
112 nonexistentFunc();
113 console.log('This will not run.');
114 ```
115
116 ### Warning: Using `'uncaughtException'` correctly
117
118 Note that `'uncaughtException'` is a crude mechanism for exception handling
119 intended to be used only as a last resort. The event *should not* be used as
120 an equivalent to `On Error Resume Next`. Unhandled exceptions inherently mean
121 that an application is in an undefined state. Attempting to resume application
122 code without properly recovering from the exception can cause additional
123 unforeseen and unpredictable issues.
124
125 Exceptions thrown from within the event handler will not be caught. Instead the
126 process will exit with a non zero exit code and the stack trace will be printed.
127 This is to avoid infinite recursion.
128
129 Attempting to resume normally after an uncaught exception can be similar to
130 pulling out of the power cord when upgrading a computer -- nine out of ten
131 times nothing happens - but the 10th time, the system becomes corrupted.
132
133 The correct use of `'uncaughtException'` is to perform synchronous cleanup
134 of allocated resources (e.g. file descriptors, handles, etc) before shutting
135 down the process. It is not safe to resume normal operation after
136 `'uncaughtException'`.
137
138 ## Event: 'unhandledRejection'
139
140 Emitted whenever a `Promise` is rejected and no error handler is attached to
141 the promise within a turn of the event loop. When programming with promises
142 exceptions are encapsulated as rejected promises. Such promises can be caught
143 and handled using [`promise.catch(...)`][] and rejections are propagated through
144 a promise chain. This event is useful for detecting and keeping track of
145 promises that were rejected whose rejections were not handled yet. This event
146 is emitted with the following arguments:
147
148  - `reason` the object with which the promise was rejected (usually an
149    [`Error`][] instance).
150  - `p` the promise that was rejected.
151
152 Here is an example that logs every unhandled rejection to the console
153
154 ```js
155 process.on('unhandledRejection', (reason, p) => {
156     console.log("Unhandled Rejection at: Promise ", p, " reason: ", reason);
157     // application specific logging, throwing an error, or other logic here
158 });
159 ```
160
161 For example, here is a rejection that will trigger the `'unhandledRejection'`
162 event:
163
164 ```js
165 somePromise.then((res) => {
166   return reportToUser(JSON.pasre(res)); // note the typo (`pasre`)
167 }); // no `.catch` or `.then`
168 ```
169
170 Here is an example of a coding pattern that will also trigger
171 `'unhandledRejection'`:
172
173 ```js
174 function SomeResource() {
175   // Initially set the loaded status to a rejected promise
176   this.loaded = Promise.reject(new Error('Resource not yet loaded!'));
177 }
178
179 var resource = new SomeResource();
180 // no .catch or .then on resource.loaded for at least a turn
181 ```
182
183 In cases like this, you may not want to track the rejection as a developer
184 error like you would for other `'unhandledRejection'` events. To address
185 this, you can either attach a dummy `.catch(() => { })` handler to
186 `resource.loaded`, preventing the `'unhandledRejection'` event from being
187 emitted, or you can use the [`'rejectionHandled'`][] event.
188
189 ## Exit Codes
190
191 Node.js will normally exit with a `0` status code when no more async
192 operations are pending.  The following status codes are used in other
193 cases:
194
195 * `1` **Uncaught Fatal Exception** - There was an uncaught exception,
196   and it was not handled by a domain or an `'uncaughtException'` event
197   handler.
198 * `2` - Unused (reserved by Bash for builtin misuse)
199 * `3` **Internal JavaScript Parse Error** - The JavaScript source code
200   internal in Node.js's bootstrapping process caused a parse error.  This
201   is extremely rare, and generally can only happen during development
202   of Node.js itself.
203 * `4` **Internal JavaScript Evaluation Failure** - The JavaScript
204   source code internal in Node.js's bootstrapping process failed to
205   return a function value when evaluated.  This is extremely rare, and
206   generally can only happen during development of Node.js itself.
207 * `5` **Fatal Error** - There was a fatal unrecoverable error in V8.
208   Typically a message will be printed to stderr with the prefix `FATAL
209   ERROR`.
210 * `6` **Non-function Internal Exception Handler** - There was an
211   uncaught exception, but the internal fatal exception handler
212   function was somehow set to a non-function, and could not be called.
213 * `7` **Internal Exception Handler Run-Time Failure** - There was an
214   uncaught exception, and the internal fatal exception handler
215   function itself threw an error while attempting to handle it.  This
216   can happen, for example, if a `process.on('uncaughtException')` or
217   `domain.on('error')` handler throws an error.
218 * `8` - Unused.  In previous versions of Node.js, exit code 8 sometimes
219   indicated an uncaught exception.
220 * `9` - **Invalid Argument** - Either an unknown option was specified,
221   or an option requiring a value was provided without a value.
222 * `10` **Internal JavaScript Run-Time Failure** - The JavaScript
223   source code internal in Node.js's bootstrapping process threw an error
224   when the bootstrapping function was called.  This is extremely rare,
225   and generally can only happen during development of Node.js itself.
226 * `12` **Invalid Debug Argument** - The `--debug` and/or `--debug-brk`
227   options were set, but an invalid port number was chosen.
228 * `>128` **Signal Exits** - If Node.js receives a fatal signal such as
229   `SIGKILL` or `SIGHUP`, then its exit code will be `128` plus the
230   value of the signal code.  This is a standard Unix practice, since
231   exit codes are defined to be 7-bit integers, and signal exits set
232   the high-order bit, and then contain the value of the signal code.
233
234 ## Signal Events
235
236 <!--type=event-->
237 <!--name=SIGINT, SIGHUP, etc.-->
238
239 Emitted when the processes receives a signal. See sigaction(2) for a list of
240 standard POSIX signal names such as `SIGINT`, `SIGHUP`, etc.
241
242 Example of listening for `SIGINT`:
243
244 ```js
245 // Start reading from stdin so we don't exit.
246 process.stdin.resume();
247
248 process.on('SIGINT', () => {
249   console.log('Got SIGINT.  Press Control-D to exit.');
250 });
251 ```
252
253 An easy way to send the `SIGINT` signal is with `Control-C` in most terminal
254 programs.
255
256 Note:
257
258 - `SIGUSR1` is reserved by Node.js to start the debugger.  It's possible to
259   install a listener but that won't stop the debugger from starting.
260 - `SIGTERM` and `SIGINT` have default handlers on non-Windows platforms that
261   resets the terminal mode before exiting with code `128 + signal number`. If
262   one of these signals has a listener installed, its default behavior will be
263   removed (Node.js will no longer exit).
264 - `SIGPIPE` is ignored by default. It can have a listener installed.
265 - `SIGHUP` is generated on Windows when the console window is closed, and on other
266   platforms under various similar conditions, see signal(7). It can have a
267   listener installed, however Node.js will be unconditionally terminated by
268   Windows about 10 seconds later. On non-Windows platforms, the default
269   behavior of `SIGHUP` is to terminate Node.js, but once a listener has been
270   installed its default behavior will be removed.
271 - `SIGTERM` is not supported on Windows, it can be listened on.
272 - `SIGINT` from the terminal is supported on all platforms, and can usually be
273   generated with `CTRL+C` (though this may be configurable). It is not generated
274   when terminal raw mode is enabled.
275 - `SIGBREAK` is delivered on Windows when `CTRL+BREAK` is pressed, on
276   non-Windows
277   platforms it can be listened on, but there is no way to send or generate it.
278 - `SIGWINCH` is delivered when the console has been resized. On Windows, this
279   will only happen on write to the console when the cursor is being moved, or
280   when a readable tty is used in raw mode.
281 - `SIGKILL` cannot have a listener installed, it will unconditionally terminate
282   Node.js on all platforms.
283 - `SIGSTOP` cannot have a listener installed.
284
285 Note that Windows does not support sending Signals, but Node.js offers some
286 emulation with `process.kill()`, and `child_process.kill()`. Sending signal `0`
287 can be used to test for the existence of a process. Sending `SIGINT`,
288 `SIGTERM`, and `SIGKILL` cause the unconditional termination of the target
289 process.
290
291 ## process.abort()
292
293 This causes Node.js to emit an abort. This will cause Node.js to exit and
294 generate a core file.
295
296 ## process.arch
297
298 What processor architecture you're running on: `'arm'`, `'ia32'`, or `'x64'`.
299
300 ```js
301 console.log('This processor architecture is ' + process.arch);
302 ```
303
304 ## process.argv
305
306 An array containing the command line arguments.  The first element will be
307 'node', the second element will be the name of the JavaScript file.  The
308 next elements will be any additional command line arguments.
309
310 ```js
311 // print process.argv
312 process.argv.forEach((val, index, array) => {
313   console.log(`${index}: ${val}`);
314 });
315 ```
316
317 This will generate:
318
319 ```
320 $ node process-2.js one two=three four
321 0: node
322 1: /Users/mjr/work/node/process-2.js
323 2: one
324 3: two=three
325 4: four
326 ```
327
328 ## process.chdir(directory)
329
330 Changes the current working directory of the process or throws an exception if that fails.
331
332 ```js
333 console.log(`Starting directory: ${process.cwd()}`);
334 try {
335   process.chdir('/tmp');
336   console.log(`New directory: ${process.cwd()}`);
337 }
338 catch (err) {
339   console.log(`chdir: ${err}`);
340 }
341 ```
342
343 ## process.config
344
345 An Object containing the JavaScript representation of the configure options
346 that were used to compile the current Node.js executable. This is the same as
347 the `config.gypi` file that was produced when running the `./configure` script.
348
349 An example of the possible output looks like:
350
351 ```
352 {
353   target_defaults:
354    { cflags: [],
355      default_configuration: 'Release',
356      defines: [],
357      include_dirs: [],
358      libraries: [] },
359   variables:
360    {
361      host_arch: 'x64',
362      node_install_npm: 'true',
363      node_prefix: '',
364      node_shared_cares: 'false',
365      node_shared_http_parser: 'false',
366      node_shared_libuv: 'false',
367      node_shared_zlib: 'false',
368      node_use_dtrace: 'false',
369      node_use_openssl: 'true',
370      node_shared_openssl: 'false',
371      strict_aliasing: 'true',
372      target_arch: 'x64',
373      v8_use_snapshot: 'true'
374    }
375 }
376 ```
377
378 ## process.connected
379
380 * {Boolean} Set to false after `process.disconnect()` is called
381
382 If `process.connected` is false, it is no longer possible to send messages.
383
384 ## process.cwd()
385
386 Returns the current working directory of the process.
387
388 ```js
389 console.log(`Current directory: ${process.cwd()}`);
390 ```
391
392 ## process.disconnect()
393
394 Close the IPC channel to the parent process, allowing this child to exit
395 gracefully once there are no other connections keeping it alive.
396
397 Identical to the parent process's [`ChildProcess.disconnect()`][].
398
399 If Node.js was not spawned with an IPC channel, `process.disconnect()` will be
400 undefined.
401
402 ## process.env
403
404 An object containing the user environment. See environ(7).
405
406 An example of this object looks like:
407
408 ```js
409 { TERM: 'xterm-256color',
410   SHELL: '/usr/local/bin/bash',
411   USER: 'maciej',
412   PATH: '~/.bin/:/usr/bin:/bin:/usr/sbin:/sbin:/usr/local/bin',
413   PWD: '/Users/maciej',
414   EDITOR: 'vim',
415   SHLVL: '1',
416   HOME: '/Users/maciej',
417   LOGNAME: 'maciej',
418   _: '/usr/local/bin/node' }
419 ```
420
421 You can write to this object, but changes won't be reflected outside of your
422 process. That means that the following won't work:
423
424 ```
425 $ node -e 'process.env.foo = "bar"' && echo $foo
426 ```
427
428 But this will:
429
430 ```js
431 process.env.foo = 'bar';
432 console.log(process.env.foo);
433 ```
434
435 Assigning a property on `process.env` will implicitly convert the value
436 to a string.
437
438 Example:
439
440 ```js
441 process.env.test = null;
442 console.log(process.env.test);
443 // => 'null'
444 process.env.test = undefined;
445 console.log(process.env.test);
446 // => 'undefined'
447 ```
448
449 Use `delete` to delete a property from `process.env`.
450
451 Example:
452
453 ```js
454 process.env.TEST = 1;
455 delete process.env.TEST;
456 console.log(process.env.TEST);
457 // => undefined
458 ```
459
460 ## process.execArgv
461
462 This is the set of Node.js-specific command line options from the
463 executable that started the process.  These options do not show up in
464 `process.argv`, and do not include the Node.js executable, the name of
465 the script, or any options following the script name. These options
466 are useful in order to spawn child processes with the same execution
467 environment as the parent.
468
469 Example:
470
471 ```
472 $ node --harmony script.js --version
473 ```
474
475 results in process.execArgv:
476
477 ```js
478 ['--harmony']
479 ```
480
481 and process.argv:
482
483 ```js
484 ['/usr/local/bin/node', 'script.js', '--version']
485 ```
486
487 ## process.execPath
488
489 This is the absolute pathname of the executable that started the process.
490
491 Example:
492
493 ```
494 /usr/local/bin/node
495 ```
496
497
498 ## process.exit([code])
499
500 Ends the process with the specified `code`.  If omitted, exit uses the
501 'success' code `0`.
502
503 To exit with a 'failure' code:
504
505 ```js
506 process.exit(1);
507 ```
508
509 The shell that executed Node.js should see the exit code as 1.
510
511
512 ## process.exitCode
513
514 A number which will be the process exit code, when the process either
515 exits gracefully, or is exited via [`process.exit()`][] without specifying
516 a code.
517
518 Specifying a code to `process.exit(code)` will override any previous
519 setting of `process.exitCode`.
520
521
522 ## process.getegid()
523
524 Note: this function is only available on POSIX platforms (i.e. not Windows,
525 Android)
526
527 Gets the effective group identity of the process. (See getegid(2).)
528 This is the numerical group id, not the group name.
529
530 ```js
531 if (process.getegid) {
532   console.log(`Current gid: ${process.getegid()}`);
533 }
534 ```
535
536
537 ## process.geteuid()
538
539 Note: this function is only available on POSIX platforms (i.e. not Windows,
540 Android)
541
542 Gets the effective user identity of the process. (See geteuid(2).)
543 This is the numerical userid, not the username.
544
545 ```js
546 if (process.geteuid) {
547   console.log(`Current uid: ${process.geteuid()}`);
548 }
549 ```
550
551 ## process.getgid()
552
553 Note: this function is only available on POSIX platforms (i.e. not Windows,
554 Android)
555
556 Gets the group identity of the process. (See getgid(2).)
557 This is the numerical group id, not the group name.
558
559 ```js
560 if (process.getgid) {
561   console.log(`Current gid: ${process.getgid()}`);
562 }
563 ```
564
565 ## process.getgroups()
566
567 Note: this function is only available on POSIX platforms (i.e. not Windows,
568 Android)
569
570 Returns an array with the supplementary group IDs. POSIX leaves it unspecified
571 if the effective group ID is included but Node.js ensures it always is.
572
573 ## process.getuid()
574
575 Note: this function is only available on POSIX platforms (i.e. not Windows,
576 Android)
577
578 Gets the user identity of the process. (See getuid(2).)
579 This is the numerical userid, not the username.
580
581 ```js
582 if (process.getuid) {
583   console.log(`Current uid: ${process.getuid()}`);
584 }
585 ```
586
587 ## process.hrtime()
588
589 Returns the current high-resolution real time in a `[seconds, nanoseconds]`
590 tuple Array. It is relative to an arbitrary time in the past. It is not
591 related to the time of day and therefore not subject to clock drift. The
592 primary use is for measuring performance between intervals.
593
594 You may pass in the result of a previous call to `process.hrtime()` to get
595 a diff reading, useful for benchmarks and measuring intervals:
596
597 ```js
598 var time = process.hrtime();
599 // [ 1800216, 25 ]
600
601 setTimeout(() => {
602   var diff = process.hrtime(time);
603   // [ 1, 552 ]
604
605   console.log('benchmark took %d nanoseconds', diff[0] * 1e9 + diff[1]);
606   // benchmark took 1000000527 nanoseconds
607 }, 1000);
608 ```
609
610
611 ## process.initgroups(user, extra_group)
612
613 Note: this function is only available on POSIX platforms (i.e. not Windows,
614 Android)
615
616 Reads /etc/group and initializes the group access list, using all groups of
617 which the user is a member. This is a privileged operation, meaning you need
618 to be root or have the `CAP_SETGID` capability.
619
620 `user` is a user name or user ID. `extra_group` is a group name or group ID.
621
622 Some care needs to be taken when dropping privileges. Example:
623
624 ```js
625 console.log(process.getgroups());         // [ 0 ]
626 process.initgroups('bnoordhuis', 1000);   // switch user
627 console.log(process.getgroups());         // [ 27, 30, 46, 1000, 0 ]
628 process.setgid(1000);                     // drop root gid
629 console.log(process.getgroups());         // [ 27, 30, 46, 1000 ]
630 ```
631
632 ## process.kill(pid[, signal])
633
634 Send a signal to a process. `pid` is the process id and `signal` is the
635 string describing the signal to send.  Signal names are strings like
636 `SIGINT` or `SIGHUP`.  If omitted, the signal will be `SIGTERM`.
637 See [Signal Events][] and kill(2) for more information.
638
639 Will throw an error if target does not exist, and as a special case, a signal
640 of `0` can be used to test for the existence of a process. Windows platforms
641 will throw an error if the `pid` is used to kill a process group.
642
643 Note that even though the name of this function is `process.kill`, it is really
644 just a signal sender, like the `kill` system call.  The signal sent may do
645 something other than kill the target process.
646
647 Example of sending a signal to yourself:
648
649 ```js
650 process.on('SIGHUP', () => {
651   console.log('Got SIGHUP signal.');
652 });
653
654 setTimeout(() => {
655   console.log('Exiting.');
656   process.exit(0);
657 }, 100);
658
659 process.kill(process.pid, 'SIGHUP');
660 ```
661
662 Note: When SIGUSR1 is received by Node.js it starts the debugger, see
663 [Signal Events][].
664
665 ## process.mainModule
666
667 Alternate way to retrieve [`require.main`][]. The difference is that if the main
668 module changes at runtime, `require.main` might still refer to the original main
669 module in modules that were required before the change occurred. Generally it's
670 safe to assume that the two refer to the same module.
671
672 As with `require.main`, it will be `undefined` if there was no entry script.
673
674 ## process.memoryUsage()
675
676 Returns an object describing the memory usage of the Node.js process
677 measured in bytes.
678
679 ```js
680 const util = require('util');
681
682 console.log(util.inspect(process.memoryUsage()));
683 ```
684
685 This will generate:
686
687 ```js
688 { rss: 4935680,
689   heapTotal: 1826816,
690   heapUsed: 650472 }
691 ```
692
693 `heapTotal` and `heapUsed` refer to V8's memory usage.
694
695
696 ## process.nextTick(callback[, arg][, ...])
697
698 * `callback` {Function}
699
700 Once the current event loop turn runs to completion, call the callback
701 function.
702
703 This is *not* a simple alias to [`setTimeout(fn, 0)`][], it's much more
704 efficient.  It runs before any additional I/O events (including
705 timers) fire in subsequent ticks of the event loop.
706
707 ```js
708 console.log('start');
709 process.nextTick(() => {
710   console.log('nextTick callback');
711 });
712 console.log('scheduled');
713 // Output:
714 // start
715 // scheduled
716 // nextTick callback
717 ```
718
719 This is important in developing APIs where you want to give the user the
720 chance to assign event handlers after an object has been constructed,
721 but before any I/O has occurred.
722
723 ```js
724 function MyThing(options) {
725   this.setupOptions(options);
726
727   process.nextTick(() => {
728     this.startDoingStuff();
729   });
730 }
731 ```
732
733 var thing = new MyThing();
734 thing.getReadyForStuff();
735
736 // thing.startDoingStuff() gets called now, not before.
737 ```
738
739 It is very important for APIs to be either 100% synchronous or 100%
740 asynchronous.  Consider this example:
741
742 ```js
743 // WARNING!  DO NOT USE!  BAD UNSAFE HAZARD!
744 function maybeSync(arg, cb) {
745   if (arg) {
746     cb();
747     return;
748   }
749
750   fs.stat('file', cb);
751 }
752 ```
753
754 This API is hazardous.  If you do this:
755
756 ```js
757 maybeSync(true, () => {
758   foo();
759 });
760 bar();
761 ```
762
763 then it's not clear whether `foo()` or `bar()` will be called first.
764
765 This approach is much better:
766
767 ```js
768 function definitelyAsync(arg, cb) {
769   if (arg) {
770     process.nextTick(cb);
771     return;
772   }
773
774   fs.stat('file', cb);
775 }
776 ```
777
778 Note: the nextTick queue is completely drained on each pass of the
779 event loop **before** additional I/O is processed.  As a result,
780 recursively setting nextTick callbacks will block any I/O from
781 happening, just like a `while(true);` loop.
782
783 ## process.pid
784
785 The PID of the process.
786
787 ```js
788 console.log(`This process is pid ${process.pid}`);
789 ```
790
791 ## process.platform
792
793 What platform you're running on:
794 `'darwin'`, `'freebsd'`, `'linux'`, `'sunos'` or `'win32'`
795
796 ```js
797 console.log(`This platform is ${process.platform}`);
798 ```
799
800 ## process.release
801
802 An Object containing metadata related to the current release, including URLs
803 for the source tarball and headers-only tarball.
804
805 `process.release` contains the following properties:
806
807 * `name`: a string with a value that will always be `'node'` for Node.js. For
808   legacy io.js releases, this will be `'io.js'`.
809 * `sourceUrl`: a complete URL pointing to a _.tar.gz_ file containing the
810   source of the current release.
811 * `headersUrl`: a complete URL pointing to a _.tar.gz_ file containing only
812   the header files for the current release. This file is significantly smaller
813   than the full source file and can be used for compiling add-ons against
814   Node.js.
815 * `libUrl`: a complete URL pointing to an _node.lib_ file matching the
816   architecture and version of the current release. This file is used for
817   compiling add-ons against Node.js. _This property is only present on Windows
818   builds of Node.js and will be missing on all other platforms._
819
820 e.g.
821
822 ```js
823 { name: 'node',
824   sourceUrl: 'https://nodejs.org/download/release/v4.0.0/node-v4.0.0.tar.gz',
825   headersUrl: 'https://nodejs.org/download/release/v4.0.0/node-v4.0.0-headers.tar.gz',
826   libUrl: 'https://nodejs.org/download/release/v4.0.0/win-x64/node.lib' }
827 ```
828
829 In custom builds from non-release versions of the source tree, only the
830 `name` property may be present. The additional properties should not be
831 relied upon to exist.
832
833 ## process.send(message[, sendHandle][, callback])
834
835 * `message` {Object}
836 * `sendHandle` {Handle object}
837 * `callback` {Function}
838 * Return: {Boolean}
839
840 When Node.js is spawned with an IPC channel attached, it can send messages to its
841 parent process using `process.send()`. Each will be received as a
842 [`'message'`][] event on the parent's `ChildProcess` object.
843
844 *Note: this function uses [`JSON.stringify()`][] internally to serialize the `message`.*
845
846 If Node.js was not spawned with an IPC channel, `process.send()` will be undefined.
847
848 ## process.setegid(id)
849
850 Note: this function is only available on POSIX platforms (i.e. not Windows,
851 Android)
852
853 Sets the effective group identity of the process. (See setegid(2).)
854 This accepts either a numerical ID or a groupname string. If a groupname
855 is specified, this method blocks while resolving it to a numerical ID.
856
857 ```js
858 if (process.getegid && process.setegid) {
859   console.log(`Current gid: ${process.getegid()}`);
860   try {
861     process.setegid(501);
862     console.log(`New gid: ${process.getegid()}`);
863   }
864   catch (err) {
865     console.log(`Failed to set gid: ${err}`);
866   }
867 }
868 ```
869
870 ## process.seteuid(id)
871
872 Note: this function is only available on POSIX platforms (i.e. not Windows,
873 Android)
874
875 Sets the effective user identity of the process. (See seteuid(2).)
876 This accepts either a numerical ID or a username string.  If a username
877 is specified, this method blocks while resolving it to a numerical ID.
878
879 ```js
880 if (process.geteuid && process.seteuid) {
881   console.log(`Current uid: ${process.geteuid()}`);
882   try {
883     process.seteuid(501);
884     console.log(`New uid: ${process.geteuid()}`);
885   }
886   catch (err) {
887     console.log(`Failed to set uid: ${err}`);
888   }
889 }
890 ```
891
892 ## process.setgid(id)
893
894 Note: this function is only available on POSIX platforms (i.e. not Windows,
895 Android)
896
897 Sets the group identity of the process. (See setgid(2).)  This accepts either
898 a numerical ID or a groupname string. If a groupname is specified, this method
899 blocks while resolving it to a numerical ID.
900
901 ```js
902 if (process.getgid && process.setgid) {
903   console.log(`Current gid: ${process.getgid()}`);
904   try {
905     process.setgid(501);
906     console.log(`New gid: ${process.getgid()}`);
907   }
908   catch (err) {
909     console.log(`Failed to set gid: ${err}`);
910   }
911 }
912 ```
913
914 ## process.setgroups(groups)
915
916 Note: this function is only available on POSIX platforms (i.e. not Windows,
917 Android)
918
919 Sets the supplementary group IDs. This is a privileged operation, meaning you
920 need to be root or have the `CAP_SETGID` capability.
921
922 The list can contain group IDs, group names or both.
923
924 ## process.setuid(id)
925
926 Note: this function is only available on POSIX platforms (i.e. not Windows,
927 Android)
928
929 Sets the user identity of the process. (See setuid(2).)  This accepts either
930 a numerical ID or a username string.  If a username is specified, this method
931 blocks while resolving it to a numerical ID.
932
933 ```js
934 if (process.getuid && process.setuid) {
935   console.log(`Current uid: ${process.getuid()}`);
936   try {
937     process.setuid(501);
938     console.log(`New uid: ${process.getuid()}`);
939   }
940   catch (err) {
941     console.log(`Failed to set uid: ${err}`);
942   }
943 }
944 ```
945
946 ## process.stderr
947
948 A writable stream to stderr (on fd `2`).
949
950 `process.stderr` and `process.stdout` are unlike other streams in Node.js in
951 that they cannot be closed (`end()` will throw), they never emit the `finish`
952 event and that writes can block when output is redirected to a file (although
953 disks are fast and operating systems normally employ write-back caching so it
954 should be a very rare occurrence indeed.)
955
956 ## process.stdin
957
958 A `Readable Stream` for stdin (on fd `0`).
959
960 Example of opening standard input and listening for both events:
961
962 ```js
963 process.stdin.setEncoding('utf8');
964
965 process.stdin.on('readable', () => {
966   var chunk = process.stdin.read();
967   if (chunk !== null) {
968     process.stdout.write(`data: ${chunk}`);
969   }
970 });
971
972 process.stdin.on('end', () => {
973   process.stdout.write('end');
974 });
975 ```
976
977 As a Stream, `process.stdin` can also be used in "old" mode that is compatible
978 with scripts written for node.js prior to v0.10.
979 For more information see [Stream compatibility][].
980
981 In "old" Streams mode the stdin stream is paused by default, so one
982 must call `process.stdin.resume()` to read from it. Note also that calling
983 `process.stdin.resume()` itself would switch stream to "old" mode.
984
985 If you are starting a new project you should prefer a more recent "new" Streams
986 mode over "old" one.
987
988 ## process.stdout
989
990 A `Writable Stream` to `stdout` (on fd `1`).
991
992 For example, a `console.log` equivalent could look like this:
993
994 ```js
995 console.log = (msg) => {
996   process.stdout.write(`${msg}\n`);
997 };
998 ```
999
1000 `process.stderr` and `process.stdout` are unlike other streams in Node.js in
1001 that they cannot be closed (`end()` will throw), they never emit the `'finish'`
1002 event and that writes can block when output is redirected to a file (although
1003 disks are fast and operating systems normally employ write-back caching so it
1004 should be a very rare occurrence indeed.)
1005
1006 To check if Node.js is being run in a TTY context, read the `isTTY` property
1007 on `process.stderr`, `process.stdout`, or `process.stdin`:
1008
1009 ```
1010 $ node -p "Boolean(process.stdin.isTTY)"
1011 true
1012 $ echo "foo" | node -p "Boolean(process.stdin.isTTY)"
1013 false
1014
1015 $ node -p "Boolean(process.stdout.isTTY)"
1016 true
1017 $ node -p "Boolean(process.stdout.isTTY)" | cat
1018 false
1019 ```
1020
1021 See [the tty docs][] for more information.
1022
1023 ## process.title
1024
1025 Getter/setter to set what is displayed in `ps`.
1026
1027 When used as a setter, the maximum length is platform-specific and probably
1028 short.
1029
1030 On Linux and OS X, it's limited to the size of the binary name plus the
1031 length of the command line arguments because it overwrites the argv memory.
1032
1033 v0.8 allowed for longer process title strings by also overwriting the environ
1034 memory but that was potentially insecure/confusing in some (rather obscure)
1035 cases.
1036
1037 ## process.umask([mask])
1038
1039 Sets or reads the process's file mode creation mask. Child processes inherit
1040 the mask from the parent process. Returns the old mask if `mask` argument is
1041 given, otherwise returns the current mask.
1042
1043 ```js
1044 const newmask = 0o022;
1045 const oldmask = process.umask(newmask);
1046 console.log(
1047   `Changed umask from ${oldmask.toString(8)} to ${newmask.toString(8)}`
1048 );
1049 ```
1050
1051
1052 ## process.uptime()
1053
1054 Number of seconds Node.js has been running.
1055
1056 ## process.version
1057
1058 A compiled-in property that exposes `NODE_VERSION`.
1059
1060 ```js
1061 console.log(`Version: ${process.version}`);
1062 ```
1063
1064 ## process.versions
1065
1066 A property exposing version strings of Node.js and its dependencies.
1067
1068 ```js
1069 console.log(process.versions);
1070 ```
1071
1072 Will print something like:
1073
1074 ```js
1075 { http_parser: '2.3.0',
1076   node: '1.1.1',
1077   v8: '4.1.0.14',
1078   uv: '1.3.0',
1079   zlib: '1.2.8',
1080   ares: '1.10.0-DEV',
1081   modules: '43',
1082   icu: '55.1',
1083   openssl: '1.0.1k' }
1084 ```
1085
1086 [`'message'`]: child_process.html#child_process_event_message
1087 [`ChildProcess.disconnect()`]: child_process.html#child_process_child_disconnect
1088 [`ChildProcess.send()`]: child_process.html#child_process_child_send_message_sendhandle_callback
1089 [`Error`]: errors.html#errors_class_error
1090 [`EventEmitter`]: events.html#events_class_events_eventemitter
1091 [`net.Server`]: net.html#net_class_net_server
1092 [`net.Socket`]: net.html#net_class_net_socket
1093 [`process.exit()`]: #process_process_exit_code
1094 [`promise.catch(...)`]: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Promise/catch
1095 [`'rejectionHandled'`]: #process_event_rejectionhandled
1096 [`require.main`]: modules.html#modules_accessing_the_main_module
1097 [`setTimeout(fn, 0)`]: timers.html#timers_settimeout_callback_delay_arg
1098 [Signal Events]: #process_signal_events
1099 [Stream compatibility]: stream.html#stream_compatibility_with_older_node_js_versions
1100 [the tty docs]: tty.html#tty_tty
1101 [`JSON.stringify()`]: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/JSON/stringify