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