1# Process 2 3<!-- introduced_in=v0.10.0 --> 4<!-- type=global --> 5 6<!-- source_link=lib/process.js --> 7 8The `process` object is a `global` that provides information about, and control 9over, the current Node.js process. As a global, it is always available to 10Node.js applications without using `require()`. It can also be explicitly 11accessed using `require()`: 12 13```js 14const process = require('process'); 15``` 16 17## Process events 18 19The `process` object is an instance of [`EventEmitter`][]. 20 21### Event: `'beforeExit'` 22<!-- YAML 23added: v0.11.12 24--> 25 26The `'beforeExit'` event is emitted when Node.js empties its event loop and has 27no additional work to schedule. Normally, the Node.js process will exit when 28there is no work scheduled, but a listener registered on the `'beforeExit'` 29event can make asynchronous calls, and thereby cause the Node.js process to 30continue. 31 32The listener callback function is invoked with the value of 33[`process.exitCode`][] passed as the only argument. 34 35The `'beforeExit'` event is *not* emitted for conditions causing explicit 36termination, such as calling [`process.exit()`][] or uncaught exceptions. 37 38The `'beforeExit'` should *not* be used as an alternative to the `'exit'` event 39unless the intention is to schedule additional work. 40 41```js 42process.on('beforeExit', (code) => { 43 console.log('Process beforeExit event with code: ', code); 44}); 45 46process.on('exit', (code) => { 47 console.log('Process exit event with code: ', code); 48}); 49 50console.log('This message is displayed first.'); 51 52// Prints: 53// This message is displayed first. 54// Process beforeExit event with code: 0 55// Process exit event with code: 0 56``` 57 58### Event: `'disconnect'` 59<!-- YAML 60added: v0.7.7 61--> 62 63If the Node.js process is spawned with an IPC channel (see the [Child Process][] 64and [Cluster][] documentation), the `'disconnect'` event will be emitted when 65the IPC channel is closed. 66 67### Event: `'exit'` 68<!-- YAML 69added: v0.1.7 70--> 71 72* `code` {integer} 73 74The `'exit'` event is emitted when the Node.js process is about to exit as a 75result of either: 76 77* The `process.exit()` method being called explicitly; 78* The Node.js event loop no longer having any additional work to perform. 79 80There is no way to prevent the exiting of the event loop at this point, and once 81all `'exit'` listeners have finished running the Node.js process will terminate. 82 83The listener callback function is invoked with the exit code specified either 84by the [`process.exitCode`][] property, or the `exitCode` argument passed to the 85[`process.exit()`][] method. 86 87```js 88process.on('exit', (code) => { 89 console.log(`About to exit with code: ${code}`); 90}); 91``` 92 93Listener functions **must** only perform **synchronous** operations. The Node.js 94process will exit immediately after calling the `'exit'` event listeners 95causing any additional work still queued in the event loop to be abandoned. 96In the following example, for instance, the timeout will never occur: 97 98```js 99process.on('exit', (code) => { 100 setTimeout(() => { 101 console.log('This will not run'); 102 }, 0); 103}); 104``` 105 106### Event: `'message'` 107<!-- YAML 108added: v0.5.10 109--> 110 111* `message` { Object | boolean | number | string | null } a parsed JSON object 112 or a serializable primitive value. 113* `sendHandle` {net.Server|net.Socket} a [`net.Server`][] or [`net.Socket`][] 114 object, or undefined. 115 116If the Node.js process is spawned with an IPC channel (see the [Child Process][] 117and [Cluster][] documentation), the `'message'` event is emitted whenever a 118message sent by a parent process using [`childprocess.send()`][] is received by 119the child process. 120 121The message goes through serialization and parsing. The resulting message might 122not be the same as what is originally sent. 123 124If the `serialization` option was set to `advanced` used when spawning the 125process, the `message` argument can contain data that JSON is not able 126to represent. 127See [Advanced serialization for `child_process`][] for more details. 128 129### Event: `'multipleResolves'` 130<!-- YAML 131added: v10.12.0 132--> 133 134* `type` {string} The resolution type. One of `'resolve'` or `'reject'`. 135* `promise` {Promise} The promise that resolved or rejected more than once. 136* `value` {any} The value with which the promise was either resolved or 137 rejected after the original resolve. 138 139The `'multipleResolves'` event is emitted whenever a `Promise` has been either: 140 141* Resolved more than once. 142* Rejected more than once. 143* Rejected after resolve. 144* Resolved after reject. 145 146This is useful for tracking potential errors in an application while using the 147`Promise` constructor, as multiple resolutions are silently swallowed. However, 148the occurrence of this event does not necessarily indicate an error. For 149example, [`Promise.race()`][] can trigger a `'multipleResolves'` event. 150 151```js 152process.on('multipleResolves', (type, promise, reason) => { 153 console.error(type, promise, reason); 154 setImmediate(() => process.exit(1)); 155}); 156 157async function main() { 158 try { 159 return await new Promise((resolve, reject) => { 160 resolve('First call'); 161 resolve('Swallowed resolve'); 162 reject(new Error('Swallowed reject')); 163 }); 164 } catch { 165 throw new Error('Failed'); 166 } 167} 168 169main().then(console.log); 170// resolve: Promise { 'First call' } 'Swallowed resolve' 171// reject: Promise { 'First call' } Error: Swallowed reject 172// at Promise (*) 173// at new Promise (<anonymous>) 174// at main (*) 175// First call 176``` 177 178### Event: `'rejectionHandled'` 179<!-- YAML 180added: v1.4.1 181--> 182 183* `promise` {Promise} The late handled promise. 184 185The `'rejectionHandled'` event is emitted whenever a `Promise` has been rejected 186and an error handler was attached to it (using [`promise.catch()`][], for 187example) later than one turn of the Node.js event loop. 188 189The `Promise` object would have previously been emitted in an 190`'unhandledRejection'` event, but during the course of processing gained a 191rejection handler. 192 193There is no notion of a top level for a `Promise` chain at which rejections can 194always be handled. Being inherently asynchronous in nature, a `Promise` 195rejection can be handled at a future point in time, possibly much later than 196the event loop turn it takes for the `'unhandledRejection'` event to be emitted. 197 198Another way of stating this is that, unlike in synchronous code where there is 199an ever-growing list of unhandled exceptions, with Promises there can be a 200growing-and-shrinking list of unhandled rejections. 201 202In synchronous code, the `'uncaughtException'` event is emitted when the list of 203unhandled exceptions grows. 204 205In asynchronous code, the `'unhandledRejection'` event is emitted when the list 206of unhandled rejections grows, and the `'rejectionHandled'` event is emitted 207when the list of unhandled rejections shrinks. 208 209```js 210const unhandledRejections = new Map(); 211process.on('unhandledRejection', (reason, promise) => { 212 unhandledRejections.set(promise, reason); 213}); 214process.on('rejectionHandled', (promise) => { 215 unhandledRejections.delete(promise); 216}); 217``` 218 219In this example, the `unhandledRejections` `Map` will grow and shrink over time, 220reflecting rejections that start unhandled and then become handled. It is 221possible to record such errors in an error log, either periodically (which is 222likely best for long-running application) or upon process exit (which is likely 223most convenient for scripts). 224 225### Event: `'uncaughtException'` 226<!-- YAML 227added: v0.1.18 228changes: 229 - version: v12.0.0 230 pr-url: https://github.com/nodejs/node/pull/26599 231 description: Added the `origin` argument. 232--> 233 234* `err` {Error} The uncaught exception. 235* `origin` {string} Indicates if the exception originates from an unhandled 236 rejection or from an synchronous error. Can either be `'uncaughtException'` or 237 `'unhandledRejection'`. The latter is only used in conjunction with the 238 [`--unhandled-rejections`][] flag set to `strict` and an unhandled rejection. 239 240The `'uncaughtException'` event is emitted when an uncaught JavaScript 241exception bubbles all the way back to the event loop. By default, Node.js 242handles such exceptions by printing the stack trace to `stderr` and exiting 243with code 1, overriding any previously set [`process.exitCode`][]. 244Adding a handler for the `'uncaughtException'` event overrides this default 245behavior. Alternatively, change the [`process.exitCode`][] in the 246`'uncaughtException'` handler which will result in the process exiting with the 247provided exit code. Otherwise, in the presence of such handler the process will 248exit with 0. 249 250```js 251process.on('uncaughtException', (err, origin) => { 252 fs.writeSync( 253 process.stderr.fd, 254 `Caught exception: ${err}\n` + 255 `Exception origin: ${origin}` 256 ); 257}); 258 259setTimeout(() => { 260 console.log('This will still run.'); 261}, 500); 262 263// Intentionally cause an exception, but don't catch it. 264nonexistentFunc(); 265console.log('This will not run.'); 266``` 267 268It is possible to monitor `'uncaughtException'` events without overriding the 269default behavior to exit the process by installing a 270`'uncaughtExceptionMonitor'` listener. 271 272#### Warning: Using `'uncaughtException'` correctly 273 274`'uncaughtException'` is a crude mechanism for exception handling 275intended to be used only as a last resort. The event *should not* be used as 276an equivalent to `On Error Resume Next`. Unhandled exceptions inherently mean 277that an application is in an undefined state. Attempting to resume application 278code without properly recovering from the exception can cause additional 279unforeseen and unpredictable issues. 280 281Exceptions thrown from within the event handler will not be caught. Instead the 282process will exit with a non-zero exit code and the stack trace will be printed. 283This is to avoid infinite recursion. 284 285Attempting to resume normally after an uncaught exception can be similar to 286pulling out the power cord when upgrading a computer. Nine out of ten 287times, nothing happens. But the tenth time, the system becomes corrupted. 288 289The correct use of `'uncaughtException'` is to perform synchronous cleanup 290of allocated resources (e.g. file descriptors, handles, etc) before shutting 291down the process. **It is not safe to resume normal operation after 292`'uncaughtException'`.** 293 294To restart a crashed application in a more reliable way, whether 295`'uncaughtException'` is emitted or not, an external monitor should be employed 296in a separate process to detect application failures and recover or restart as 297needed. 298 299### Event: `'uncaughtExceptionMonitor'` 300<!-- YAML 301added: v12.17.0 302--> 303 304* `err` {Error} The uncaught exception. 305* `origin` {string} Indicates if the exception originates from an unhandled 306 rejection or from synchronous errors. Can either be `'uncaughtException'` or 307 `'unhandledRejection'`. 308 309The `'uncaughtExceptionMonitor'` event is emitted before an 310`'uncaughtException'` event is emitted or a hook installed via 311[`process.setUncaughtExceptionCaptureCallback()`][] is called. 312 313Installing an `'uncaughtExceptionMonitor'` listener does not change the behavior 314once an `'uncaughtException'` event is emitted. The process will 315still crash if no `'uncaughtException'` listener is installed. 316 317```js 318process.on('uncaughtExceptionMonitor', (err, origin) => { 319 MyMonitoringTool.logSync(err, origin); 320}); 321 322// Intentionally cause an exception, but don't catch it. 323nonexistentFunc(); 324// Still crashes Node.js 325``` 326 327### Event: `'unhandledRejection'` 328<!-- YAML 329added: v1.4.1 330changes: 331 - version: v7.0.0 332 pr-url: https://github.com/nodejs/node/pull/8217 333 description: Not handling `Promise` rejections is deprecated. 334 - version: v6.6.0 335 pr-url: https://github.com/nodejs/node/pull/8223 336 description: Unhandled `Promise` rejections will now emit 337 a process warning. 338--> 339 340* `reason` {Error|any} The object with which the promise was rejected 341 (typically an [`Error`][] object). 342* `promise` {Promise} The rejected promise. 343 344The `'unhandledRejection'` event is emitted whenever a `Promise` is rejected and 345no error handler is attached to the promise within a turn of the event loop. 346When programming with Promises, exceptions are encapsulated as "rejected 347promises". Rejections can be caught and handled using [`promise.catch()`][] and 348are propagated through a `Promise` chain. The `'unhandledRejection'` event is 349useful for detecting and keeping track of promises that were rejected whose 350rejections have not yet been handled. 351 352```js 353process.on('unhandledRejection', (reason, promise) => { 354 console.log('Unhandled Rejection at:', promise, 'reason:', reason); 355 // Application specific logging, throwing an error, or other logic here 356}); 357 358somePromise.then((res) => { 359 return reportToUser(JSON.pasre(res)); // Note the typo (`pasre`) 360}); // No `.catch()` or `.then()` 361``` 362 363The following will also trigger the `'unhandledRejection'` event to be 364emitted: 365 366```js 367function SomeResource() { 368 // Initially set the loaded status to a rejected promise 369 this.loaded = Promise.reject(new Error('Resource not yet loaded!')); 370} 371 372const resource = new SomeResource(); 373// no .catch or .then on resource.loaded for at least a turn 374``` 375 376In this example case, it is possible to track the rejection as a developer error 377as would typically be the case for other `'unhandledRejection'` events. To 378address such failures, a non-operational 379[`.catch(() => { })`][`promise.catch()`] handler may be attached to 380`resource.loaded`, which would prevent the `'unhandledRejection'` event from 381being emitted. 382 383### Event: `'warning'` 384<!-- YAML 385added: v6.0.0 386--> 387 388* `warning` {Error} Key properties of the warning are: 389 * `name` {string} The name of the warning. **Default:** `'Warning'`. 390 * `message` {string} A system-provided description of the warning. 391 * `stack` {string} A stack trace to the location in the code where the warning 392 was issued. 393 394The `'warning'` event is emitted whenever Node.js emits a process warning. 395 396A process warning is similar to an error in that it describes exceptional 397conditions that are being brought to the user's attention. However, warnings 398are not part of the normal Node.js and JavaScript error handling flow. 399Node.js can emit warnings whenever it detects bad coding practices that could 400lead to sub-optimal application performance, bugs, or security vulnerabilities. 401 402```js 403process.on('warning', (warning) => { 404 console.warn(warning.name); // Print the warning name 405 console.warn(warning.message); // Print the warning message 406 console.warn(warning.stack); // Print the stack trace 407}); 408``` 409 410By default, Node.js will print process warnings to `stderr`. The `--no-warnings` 411command-line option can be used to suppress the default console output but the 412`'warning'` event will still be emitted by the `process` object. 413 414The following example illustrates the warning that is printed to `stderr` when 415too many listeners have been added to an event: 416 417```console 418$ node 419> events.defaultMaxListeners = 1; 420> process.on('foo', () => {}); 421> process.on('foo', () => {}); 422> (node:38638) MaxListenersExceededWarning: Possible EventEmitter memory leak 423detected. 2 foo listeners added. Use emitter.setMaxListeners() to increase limit 424``` 425 426In contrast, the following example turns off the default warning output and 427adds a custom handler to the `'warning'` event: 428 429```console 430$ node --no-warnings 431> const p = process.on('warning', (warning) => console.warn('Do not do that!')); 432> events.defaultMaxListeners = 1; 433> process.on('foo', () => {}); 434> process.on('foo', () => {}); 435> Do not do that! 436``` 437 438The `--trace-warnings` command-line option can be used to have the default 439console output for warnings include the full stack trace of the warning. 440 441Launching Node.js using the `--throw-deprecation` command line flag will 442cause custom deprecation warnings to be thrown as exceptions. 443 444Using the `--trace-deprecation` command line flag will cause the custom 445deprecation to be printed to `stderr` along with the stack trace. 446 447Using the `--no-deprecation` command line flag will suppress all reporting 448of the custom deprecation. 449 450The `*-deprecation` command line flags only affect warnings that use the name 451`'DeprecationWarning'`. 452 453#### Emitting custom warnings 454 455See the [`process.emitWarning()`][process_emit_warning] method for issuing 456custom or application-specific warnings. 457 458### Signal events 459 460<!--type=event--> 461<!--name=SIGINT, SIGHUP, etc.--> 462 463Signal events will be emitted when the Node.js process receives a signal. Please 464refer to signal(7) for a listing of standard POSIX signal names such as 465`'SIGINT'`, `'SIGHUP'`, etc. 466 467Signals are not available on [`Worker`][] threads. 468 469The signal handler will receive the signal's name (`'SIGINT'`, 470 `'SIGTERM'`, etc.) as the first argument. 471 472The name of each event will be the uppercase common name for the signal (e.g. 473`'SIGINT'` for `SIGINT` signals). 474 475```js 476// Begin reading from stdin so the process does not exit. 477process.stdin.resume(); 478 479process.on('SIGINT', () => { 480 console.log('Received SIGINT. Press Control-D to exit.'); 481}); 482 483// Using a single function to handle multiple signals 484function handle(signal) { 485 console.log(`Received ${signal}`); 486} 487 488process.on('SIGINT', handle); 489process.on('SIGTERM', handle); 490``` 491 492* `'SIGUSR1'` is reserved by Node.js to start the [debugger][]. It's possible to 493 install a listener but doing so might interfere with the debugger. 494* `'SIGTERM'` and `'SIGINT'` have default handlers on non-Windows platforms that 495 reset the terminal mode before exiting with code `128 + signal number`. If one 496 of these signals has a listener installed, its default behavior will be 497 removed (Node.js will no longer exit). 498* `'SIGPIPE'` is ignored by default. It can have a listener installed. 499* `'SIGHUP'` is generated on Windows when the console window is closed, and on 500 other platforms under various similar conditions. See signal(7). It can have a 501 listener installed, however Node.js will be unconditionally terminated by 502 Windows about 10 seconds later. On non-Windows platforms, the default 503 behavior of `SIGHUP` is to terminate Node.js, but once a listener has been 504 installed its default behavior will be removed. 505* `'SIGTERM'` is not supported on Windows, it can be listened on. 506* `'SIGINT'` from the terminal is supported on all platforms, and can usually be 507 generated with <kbd>Ctrl</kbd>+<kbd>C</kbd> (though this may be configurable). 508 It is not generated when [terminal raw mode][] is enabled and 509 <kbd>Ctrl</kbd>+<kbd>C</kbd> is used. 510* `'SIGBREAK'` is delivered on Windows when <kbd>Ctrl</kbd>+<kbd>Break</kbd> is 511 pressed. On non-Windows platforms, it can be listened on, but there is no way 512 to send or generate it. 513* `'SIGWINCH'` is delivered when the console has been resized. On Windows, this 514 will only happen on write to the console when the cursor is being moved, or 515 when a readable tty is used in raw mode. 516* `'SIGKILL'` cannot have a listener installed, it will unconditionally 517 terminate Node.js on all platforms. 518* `'SIGSTOP'` cannot have a listener installed. 519* `'SIGBUS'`, `'SIGFPE'`, `'SIGSEGV'` and `'SIGILL'`, when not raised 520 artificially using kill(2), inherently leave the process in a state from 521 which it is not safe to attempt to call JS listeners. Doing so might lead to 522 the process hanging in an endless loop, since listeners attached using 523 `process.on()` are called asynchronously and therefore unable to correct the 524 underlying problem. 525* `0` can be sent to test for the existence of a process, it has no effect if 526 the process exists, but will throw an error if the process does not exist. 527 528Windows does not support signals so has no equivalent to termination by signal, 529but Node.js offers some emulation with [`process.kill()`][], and 530[`subprocess.kill()`][]: 531* Sending `SIGINT`, `SIGTERM`, and `SIGKILL` will cause the unconditional 532 termination of the target process, and afterwards, subprocess will report that 533 the process was terminated by signal. 534* Sending signal `0` can be used as a platform independent way to test for the 535 existence of a process. 536 537## `process.abort()` 538<!-- YAML 539added: v0.7.0 540--> 541 542The `process.abort()` method causes the Node.js process to exit immediately and 543generate a core file. 544 545This feature is not available in [`Worker`][] threads. 546 547## `process.allowedNodeEnvironmentFlags` 548<!-- YAML 549added: v10.10.0 550--> 551 552* {Set} 553 554The `process.allowedNodeEnvironmentFlags` property is a special, 555read-only `Set` of flags allowable within the [`NODE_OPTIONS`][] 556environment variable. 557 558`process.allowedNodeEnvironmentFlags` extends `Set`, but overrides 559`Set.prototype.has` to recognize several different possible flag 560representations. `process.allowedNodeEnvironmentFlags.has()` will 561return `true` in the following cases: 562 563* Flags may omit leading single (`-`) or double (`--`) dashes; e.g., 564 `inspect-brk` for `--inspect-brk`, or `r` for `-r`. 565* Flags passed through to V8 (as listed in `--v8-options`) may replace 566 one or more *non-leading* dashes for an underscore, or vice-versa; 567 e.g., `--perf_basic_prof`, `--perf-basic-prof`, `--perf_basic-prof`, 568 etc. 569* Flags may contain one or more equals (`=`) characters; all 570 characters after and including the first equals will be ignored; 571 e.g., `--stack-trace-limit=100`. 572* Flags *must* be allowable within [`NODE_OPTIONS`][]. 573 574When iterating over `process.allowedNodeEnvironmentFlags`, flags will 575appear only *once*; each will begin with one or more dashes. Flags 576passed through to V8 will contain underscores instead of non-leading 577dashes: 578 579```js 580process.allowedNodeEnvironmentFlags.forEach((flag) => { 581 // -r 582 // --inspect-brk 583 // --abort_on_uncaught_exception 584 // ... 585}); 586``` 587 588The methods `add()`, `clear()`, and `delete()` of 589`process.allowedNodeEnvironmentFlags` do nothing, and will fail 590silently. 591 592If Node.js was compiled *without* [`NODE_OPTIONS`][] support (shown in 593[`process.config`][]), `process.allowedNodeEnvironmentFlags` will 594contain what *would have* been allowable. 595 596## `process.arch` 597<!-- YAML 598added: v0.5.0 599--> 600 601* {string} 602 603The operating system CPU architecture for which the Node.js binary was compiled. 604Possible values are: `'arm'`, `'arm64'`, `'ia32'`, `'mips'`,`'mipsel'`, `'ppc'`, 605`'ppc64'`, `'s390'`, `'s390x'`, `'x32'`, and `'x64'`. 606 607```js 608console.log(`This processor architecture is ${process.arch}`); 609``` 610 611## `process.argv` 612<!-- YAML 613added: v0.1.27 614--> 615 616* {string[]} 617 618The `process.argv` property returns an array containing the command line 619arguments passed when the Node.js process was launched. The first element will 620be [`process.execPath`][]. See `process.argv0` if access to the original value 621of `argv[0]` is needed. The second element will be the path to the JavaScript 622file being executed. The remaining elements will be any additional command line 623arguments. 624 625For example, assuming the following script for `process-args.js`: 626 627```js 628// print process.argv 629process.argv.forEach((val, index) => { 630 console.log(`${index}: ${val}`); 631}); 632``` 633 634Launching the Node.js process as: 635 636```console 637$ node process-args.js one two=three four 638``` 639 640Would generate the output: 641 642```text 6430: /usr/local/bin/node 6441: /Users/mjr/work/node/process-args.js 6452: one 6463: two=three 6474: four 648``` 649 650## `process.argv0` 651<!-- YAML 652added: v6.4.0 653--> 654 655* {string} 656 657The `process.argv0` property stores a read-only copy of the original value of 658`argv[0]` passed when Node.js starts. 659 660```console 661$ bash -c 'exec -a customArgv0 ./node' 662> process.argv[0] 663'/Volumes/code/external/node/out/Release/node' 664> process.argv0 665'customArgv0' 666``` 667 668## `process.channel` 669<!-- YAML 670added: v7.1.0 671--> 672 673* {Object} 674 675If the Node.js process was spawned with an IPC channel (see the 676[Child Process][] documentation), the `process.channel` 677property is a reference to the IPC channel. If no IPC channel exists, this 678property is `undefined`. 679 680## `process.chdir(directory)` 681<!-- YAML 682added: v0.1.17 683--> 684 685* `directory` {string} 686 687The `process.chdir()` method changes the current working directory of the 688Node.js process or throws an exception if doing so fails (for instance, if 689the specified `directory` does not exist). 690 691```js 692console.log(`Starting directory: ${process.cwd()}`); 693try { 694 process.chdir('/tmp'); 695 console.log(`New directory: ${process.cwd()}`); 696} catch (err) { 697 console.error(`chdir: ${err}`); 698} 699``` 700 701This feature is not available in [`Worker`][] threads. 702 703## `process.config` 704<!-- YAML 705added: v0.7.7 706--> 707 708* {Object} 709 710The `process.config` property returns an `Object` containing the JavaScript 711representation of the configure options used to compile the current Node.js 712executable. This is the same as the `config.gypi` file that was produced when 713running the `./configure` script. 714 715An example of the possible output looks like: 716 717<!-- eslint-skip --> 718```js 719{ 720 target_defaults: 721 { cflags: [], 722 default_configuration: 'Release', 723 defines: [], 724 include_dirs: [], 725 libraries: [] }, 726 variables: 727 { 728 host_arch: 'x64', 729 napi_build_version: 5, 730 node_install_npm: 'true', 731 node_prefix: '', 732 node_shared_cares: 'false', 733 node_shared_http_parser: 'false', 734 node_shared_libuv: 'false', 735 node_shared_zlib: 'false', 736 node_use_dtrace: 'false', 737 node_use_openssl: 'true', 738 node_shared_openssl: 'false', 739 strict_aliasing: 'true', 740 target_arch: 'x64', 741 v8_use_snapshot: 1 742 } 743} 744``` 745 746The `process.config` property is **not** read-only and there are existing 747modules in the ecosystem that are known to extend, modify, or entirely replace 748the value of `process.config`. 749 750## `process.connected` 751<!-- YAML 752added: v0.7.2 753--> 754 755* {boolean} 756 757If the Node.js process is spawned with an IPC channel (see the [Child Process][] 758and [Cluster][] documentation), the `process.connected` property will return 759`true` so long as the IPC channel is connected and will return `false` after 760`process.disconnect()` is called. 761 762Once `process.connected` is `false`, it is no longer possible to send messages 763over the IPC channel using `process.send()`. 764 765## `process.cpuUsage([previousValue])` 766<!-- YAML 767added: v6.1.0 768--> 769 770* `previousValue` {Object} A previous return value from calling 771 `process.cpuUsage()` 772* Returns: {Object} 773 * `user` {integer} 774 * `system` {integer} 775 776The `process.cpuUsage()` method returns the user and system CPU time usage of 777the current process, in an object with properties `user` and `system`, whose 778values are microsecond values (millionth of a second). These values measure time 779spent in user and system code respectively, and may end up being greater than 780actual elapsed time if multiple CPU cores are performing work for this process. 781 782The result of a previous call to `process.cpuUsage()` can be passed as the 783argument to the function, to get a diff reading. 784 785```js 786const startUsage = process.cpuUsage(); 787// { user: 38579, system: 6986 } 788 789// spin the CPU for 500 milliseconds 790const now = Date.now(); 791while (Date.now() - now < 500); 792 793console.log(process.cpuUsage(startUsage)); 794// { user: 514883, system: 11226 } 795``` 796 797## `process.cwd()` 798<!-- YAML 799added: v0.1.8 800--> 801 802* Returns: {string} 803 804The `process.cwd()` method returns the current working directory of the Node.js 805process. 806 807```js 808console.log(`Current directory: ${process.cwd()}`); 809``` 810 811## `process.debugPort` 812<!-- YAML 813added: v0.7.2 814--> 815 816* {number} 817 818The port used by the Node.js debugger when enabled. 819 820```js 821process.debugPort = 5858; 822``` 823 824## `process.disconnect()` 825<!-- YAML 826added: v0.7.2 827--> 828 829If the Node.js process is spawned with an IPC channel (see the [Child Process][] 830and [Cluster][] documentation), the `process.disconnect()` method will close the 831IPC channel to the parent process, allowing the child process to exit gracefully 832once there are no other connections keeping it alive. 833 834The effect of calling `process.disconnect()` is the same as calling 835[`ChildProcess.disconnect()`][] from the parent process. 836 837If the Node.js process was not spawned with an IPC channel, 838`process.disconnect()` will be `undefined`. 839 840## `process.dlopen(module, filename[, flags])` 841<!-- YAML 842added: v0.1.16 843changes: 844 - version: v9.0.0 845 pr-url: https://github.com/nodejs/node/pull/12794 846 description: Added support for the `flags` argument. 847--> 848 849* `module` {Object} 850* `filename` {string} 851* `flags` {os.constants.dlopen} **Default:** `os.constants.dlopen.RTLD_LAZY` 852 853The `process.dlopen()` method allows to dynamically load shared 854objects. It is primarily used by `require()` to load 855C++ Addons, and should not be used directly, except in special 856cases. In other words, [`require()`][] should be preferred over 857`process.dlopen()`, unless there are specific reasons. 858 859The `flags` argument is an integer that allows to specify dlopen 860behavior. See the [`os.constants.dlopen`][] documentation for details. 861 862If there are specific reasons to use `process.dlopen()` (for instance, 863to specify dlopen flags), it's often useful to use [`require.resolve()`][] 864to look up the module's path. 865 866An important drawback when calling `process.dlopen()` is that the `module` 867instance must be passed. Functions exported by the C++ Addon will be accessible 868via `module.exports`. 869 870The example below shows how to load a C++ Addon, named as `binding`, 871that exports a `foo` function. All the symbols will be loaded before 872the call returns, by passing the `RTLD_NOW` constant. In this example 873the constant is assumed to be available. 874 875```js 876const os = require('os'); 877process.dlopen(module, require.resolve('binding'), 878 os.constants.dlopen.RTLD_NOW); 879module.exports.foo(); 880``` 881 882## `process.emitWarning(warning[, options])` 883<!-- YAML 884added: v8.0.0 885--> 886 887* `warning` {string|Error} The warning to emit. 888* `options` {Object} 889 * `type` {string} When `warning` is a `String`, `type` is the name to use 890 for the *type* of warning being emitted. **Default:** `'Warning'`. 891 * `code` {string} A unique identifier for the warning instance being emitted. 892 * `ctor` {Function} When `warning` is a `String`, `ctor` is an optional 893 function used to limit the generated stack trace. **Default:** 894 `process.emitWarning`. 895 * `detail` {string} Additional text to include with the error. 896 897The `process.emitWarning()` method can be used to emit custom or application 898specific process warnings. These can be listened for by adding a handler to the 899[`'warning'`][process_warning] event. 900 901```js 902// Emit a warning with a code and additional detail. 903process.emitWarning('Something happened!', { 904 code: 'MY_WARNING', 905 detail: 'This is some additional information' 906}); 907// Emits: 908// (node:56338) [MY_WARNING] Warning: Something happened! 909// This is some additional information 910``` 911 912In this example, an `Error` object is generated internally by 913`process.emitWarning()` and passed through to the 914[`'warning'`][process_warning] handler. 915 916```js 917process.on('warning', (warning) => { 918 console.warn(warning.name); // 'Warning' 919 console.warn(warning.message); // 'Something happened!' 920 console.warn(warning.code); // 'MY_WARNING' 921 console.warn(warning.stack); // Stack trace 922 console.warn(warning.detail); // 'This is some additional information' 923}); 924``` 925 926If `warning` is passed as an `Error` object, the `options` argument is ignored. 927 928## `process.emitWarning(warning[, type[, code]][, ctor])` 929<!-- YAML 930added: v6.0.0 931--> 932 933* `warning` {string|Error} The warning to emit. 934* `type` {string} When `warning` is a `String`, `type` is the name to use 935 for the *type* of warning being emitted. **Default:** `'Warning'`. 936* `code` {string} A unique identifier for the warning instance being emitted. 937* `ctor` {Function} When `warning` is a `String`, `ctor` is an optional 938 function used to limit the generated stack trace. **Default:** 939 `process.emitWarning`. 940 941The `process.emitWarning()` method can be used to emit custom or application 942specific process warnings. These can be listened for by adding a handler to the 943[`'warning'`][process_warning] event. 944 945```js 946// Emit a warning using a string. 947process.emitWarning('Something happened!'); 948// Emits: (node: 56338) Warning: Something happened! 949``` 950 951```js 952// Emit a warning using a string and a type. 953process.emitWarning('Something Happened!', 'CustomWarning'); 954// Emits: (node:56338) CustomWarning: Something Happened! 955``` 956 957```js 958process.emitWarning('Something happened!', 'CustomWarning', 'WARN001'); 959// Emits: (node:56338) [WARN001] CustomWarning: Something happened! 960``` 961 962In each of the previous examples, an `Error` object is generated internally by 963`process.emitWarning()` and passed through to the [`'warning'`][process_warning] 964handler. 965 966```js 967process.on('warning', (warning) => { 968 console.warn(warning.name); 969 console.warn(warning.message); 970 console.warn(warning.code); 971 console.warn(warning.stack); 972}); 973``` 974 975If `warning` is passed as an `Error` object, it will be passed through to the 976`'warning'` event handler unmodified (and the optional `type`, 977`code` and `ctor` arguments will be ignored): 978 979```js 980// Emit a warning using an Error object. 981const myWarning = new Error('Something happened!'); 982// Use the Error name property to specify the type name 983myWarning.name = 'CustomWarning'; 984myWarning.code = 'WARN001'; 985 986process.emitWarning(myWarning); 987// Emits: (node:56338) [WARN001] CustomWarning: Something happened! 988``` 989 990A `TypeError` is thrown if `warning` is anything other than a string or `Error` 991object. 992 993While process warnings use `Error` objects, the process warning 994mechanism is **not** a replacement for normal error handling mechanisms. 995 996The following additional handling is implemented if the warning `type` is 997`'DeprecationWarning'`: 998 999* If the `--throw-deprecation` command-line flag is used, the deprecation 1000 warning is thrown as an exception rather than being emitted as an event. 1001* If the `--no-deprecation` command-line flag is used, the deprecation 1002 warning is suppressed. 1003* If the `--trace-deprecation` command-line flag is used, the deprecation 1004 warning is printed to `stderr` along with the full stack trace. 1005 1006### Avoiding duplicate warnings 1007 1008As a best practice, warnings should be emitted only once per process. To do 1009so, it is recommended to place the `emitWarning()` behind a simple boolean 1010flag as illustrated in the example below: 1011 1012```js 1013function emitMyWarning() { 1014 if (!emitMyWarning.warned) { 1015 emitMyWarning.warned = true; 1016 process.emitWarning('Only warn once!'); 1017 } 1018} 1019emitMyWarning(); 1020// Emits: (node: 56339) Warning: Only warn once! 1021emitMyWarning(); 1022// Emits nothing 1023``` 1024 1025## `process.env` 1026<!-- YAML 1027added: v0.1.27 1028changes: 1029 - version: v11.14.0 1030 pr-url: https://github.com/nodejs/node/pull/26544 1031 description: Worker threads will now use a copy of the parent thread’s 1032 `process.env` by default, configurable through the `env` 1033 option of the `Worker` constructor. 1034 - version: v10.0.0 1035 pr-url: https://github.com/nodejs/node/pull/18990 1036 description: Implicit conversion of variable value to string is deprecated. 1037--> 1038 1039* {Object} 1040 1041The `process.env` property returns an object containing the user environment. 1042See environ(7). 1043 1044An example of this object looks like: 1045 1046<!-- eslint-skip --> 1047```js 1048{ 1049 TERM: 'xterm-256color', 1050 SHELL: '/usr/local/bin/bash', 1051 USER: 'maciej', 1052 PATH: '~/.bin/:/usr/bin:/bin:/usr/sbin:/sbin:/usr/local/bin', 1053 PWD: '/Users/maciej', 1054 EDITOR: 'vim', 1055 SHLVL: '1', 1056 HOME: '/Users/maciej', 1057 LOGNAME: 'maciej', 1058 _: '/usr/local/bin/node' 1059} 1060``` 1061 1062It is possible to modify this object, but such modifications will not be 1063reflected outside the Node.js process, or (unless explicitly requested) 1064to other [`Worker`][] threads. 1065In other words, the following example would not work: 1066 1067```console 1068$ node -e 'process.env.foo = "bar"' && echo $foo 1069``` 1070 1071While the following will: 1072 1073```js 1074process.env.foo = 'bar'; 1075console.log(process.env.foo); 1076``` 1077 1078Assigning a property on `process.env` will implicitly convert the value 1079to a string. **This behavior is deprecated.** Future versions of Node.js may 1080throw an error when the value is not a string, number, or boolean. 1081 1082```js 1083process.env.test = null; 1084console.log(process.env.test); 1085// => 'null' 1086process.env.test = undefined; 1087console.log(process.env.test); 1088// => 'undefined' 1089``` 1090 1091Use `delete` to delete a property from `process.env`. 1092 1093```js 1094process.env.TEST = 1; 1095delete process.env.TEST; 1096console.log(process.env.TEST); 1097// => undefined 1098``` 1099 1100On Windows operating systems, environment variables are case-insensitive. 1101 1102```js 1103process.env.TEST = 1; 1104console.log(process.env.test); 1105// => 1 1106``` 1107 1108Unless explicitly specified when creating a [`Worker`][] instance, 1109each [`Worker`][] thread has its own copy of `process.env`, based on its 1110parent thread’s `process.env`, or whatever was specified as the `env` option 1111to the [`Worker`][] constructor. Changes to `process.env` will not be visible 1112across [`Worker`][] threads, and only the main thread can make changes that 1113are visible to the operating system or to native add-ons. 1114 1115## `process.execArgv` 1116<!-- YAML 1117added: v0.7.7 1118--> 1119 1120* {string[]} 1121 1122The `process.execArgv` property returns the set of Node.js-specific command-line 1123options passed when the Node.js process was launched. These options do not 1124appear in the array returned by the [`process.argv`][] property, and do not 1125include the Node.js executable, the name of the script, or any options following 1126the script name. These options are useful in order to spawn child processes with 1127the same execution environment as the parent. 1128 1129```console 1130$ node --harmony script.js --version 1131``` 1132 1133Results in `process.execArgv`: 1134 1135<!-- eslint-disable semi --> 1136```js 1137['--harmony'] 1138``` 1139 1140And `process.argv`: 1141 1142<!-- eslint-disable semi --> 1143```js 1144['/usr/local/bin/node', 'script.js', '--version'] 1145``` 1146 1147## `process.execPath` 1148<!-- YAML 1149added: v0.1.100 1150--> 1151 1152* {string} 1153 1154The `process.execPath` property returns the absolute pathname of the executable 1155that started the Node.js process. Symbolic links, if any, are resolved. 1156 1157<!-- eslint-disable semi --> 1158```js 1159'/usr/local/bin/node' 1160``` 1161 1162## `process.exit([code])` 1163<!-- YAML 1164added: v0.1.13 1165--> 1166 1167* `code` {integer} The exit code. **Default:** `0`. 1168 1169The `process.exit()` method instructs Node.js to terminate the process 1170synchronously with an exit status of `code`. If `code` is omitted, exit uses 1171either the 'success' code `0` or the value of `process.exitCode` if it has been 1172set. Node.js will not terminate until all the [`'exit'`][] event listeners are 1173called. 1174 1175To exit with a 'failure' code: 1176 1177```js 1178process.exit(1); 1179``` 1180 1181The shell that executed Node.js should see the exit code as `1`. 1182 1183Calling `process.exit()` will force the process to exit as quickly as possible 1184even if there are still asynchronous operations pending that have not yet 1185completed fully, including I/O operations to `process.stdout` and 1186`process.stderr`. 1187 1188In most situations, it is not actually necessary to call `process.exit()` 1189explicitly. The Node.js process will exit on its own *if there is no additional 1190work pending* in the event loop. The `process.exitCode` property can be set to 1191tell the process which exit code to use when the process exits gracefully. 1192 1193For instance, the following example illustrates a *misuse* of the 1194`process.exit()` method that could lead to data printed to stdout being 1195truncated and lost: 1196 1197```js 1198// This is an example of what *not* to do: 1199if (someConditionNotMet()) { 1200 printUsageToStdout(); 1201 process.exit(1); 1202} 1203``` 1204 1205The reason this is problematic is because writes to `process.stdout` in Node.js 1206are sometimes *asynchronous* and may occur over multiple ticks of the Node.js 1207event loop. Calling `process.exit()`, however, forces the process to exit 1208*before* those additional writes to `stdout` can be performed. 1209 1210Rather than calling `process.exit()` directly, the code *should* set the 1211`process.exitCode` and allow the process to exit naturally by avoiding 1212scheduling any additional work for the event loop: 1213 1214```js 1215// How to properly set the exit code while letting 1216// the process exit gracefully. 1217if (someConditionNotMet()) { 1218 printUsageToStdout(); 1219 process.exitCode = 1; 1220} 1221``` 1222 1223If it is necessary to terminate the Node.js process due to an error condition, 1224throwing an *uncaught* error and allowing the process to terminate accordingly 1225is safer than calling `process.exit()`. 1226 1227In [`Worker`][] threads, this function stops the current thread rather 1228than the current process. 1229 1230## `process.exitCode` 1231<!-- YAML 1232added: v0.11.8 1233--> 1234 1235* {integer} 1236 1237A number which will be the process exit code, when the process either 1238exits gracefully, or is exited via [`process.exit()`][] without specifying 1239a code. 1240 1241Specifying a code to [`process.exit(code)`][`process.exit()`] will override any 1242previous setting of `process.exitCode`. 1243 1244## `process.getegid()` 1245<!-- YAML 1246added: v2.0.0 1247--> 1248 1249The `process.getegid()` method returns the numerical effective group identity 1250of the Node.js process. (See getegid(2).) 1251 1252```js 1253if (process.getegid) { 1254 console.log(`Current gid: ${process.getegid()}`); 1255} 1256``` 1257 1258This function is only available on POSIX platforms (i.e. not Windows or 1259Android). 1260 1261## `process.geteuid()` 1262<!-- YAML 1263added: v2.0.0 1264--> 1265 1266* Returns: {Object} 1267 1268The `process.geteuid()` method returns the numerical effective user identity of 1269the process. (See geteuid(2).) 1270 1271```js 1272if (process.geteuid) { 1273 console.log(`Current uid: ${process.geteuid()}`); 1274} 1275``` 1276 1277This function is only available on POSIX platforms (i.e. not Windows or 1278Android). 1279 1280## `process.getgid()` 1281<!-- YAML 1282added: v0.1.31 1283--> 1284 1285* Returns: {Object} 1286 1287The `process.getgid()` method returns the numerical group identity of the 1288process. (See getgid(2).) 1289 1290```js 1291if (process.getgid) { 1292 console.log(`Current gid: ${process.getgid()}`); 1293} 1294``` 1295 1296This function is only available on POSIX platforms (i.e. not Windows or 1297Android). 1298 1299## `process.getgroups()` 1300<!-- YAML 1301added: v0.9.4 1302--> 1303 1304* Returns: {integer[]} 1305 1306The `process.getgroups()` method returns an array with the supplementary group 1307IDs. POSIX leaves it unspecified if the effective group ID is included but 1308Node.js ensures it always is. 1309 1310This function is only available on POSIX platforms (i.e. not Windows or 1311Android). 1312 1313## `process.getuid()` 1314<!-- YAML 1315added: v0.1.28 1316--> 1317 1318* Returns: {integer} 1319 1320The `process.getuid()` method returns the numeric user identity of the process. 1321(See getuid(2).) 1322 1323```js 1324if (process.getuid) { 1325 console.log(`Current uid: ${process.getuid()}`); 1326} 1327``` 1328 1329This function is only available on POSIX platforms (i.e. not Windows or 1330Android). 1331 1332## `process.hasUncaughtExceptionCaptureCallback()` 1333<!-- YAML 1334added: v9.3.0 1335--> 1336 1337* Returns: {boolean} 1338 1339Indicates whether a callback has been set using 1340[`process.setUncaughtExceptionCaptureCallback()`][]. 1341 1342## `process.hrtime([time])` 1343<!-- YAML 1344added: v0.7.6 1345--> 1346 1347* `time` {integer[]} The result of a previous call to `process.hrtime()` 1348* Returns: {integer[]} 1349 1350This is the legacy version of [`process.hrtime.bigint()`][] 1351before `bigint` was introduced in JavaScript. 1352 1353The `process.hrtime()` method returns the current high-resolution real time 1354in a `[seconds, nanoseconds]` tuple `Array`, where `nanoseconds` is the 1355remaining part of the real time that can't be represented in second precision. 1356 1357`time` is an optional parameter that must be the result of a previous 1358`process.hrtime()` call to diff with the current time. If the parameter 1359passed in is not a tuple `Array`, a `TypeError` will be thrown. Passing in a 1360user-defined array instead of the result of a previous call to 1361`process.hrtime()` will lead to undefined behavior. 1362 1363These times are relative to an arbitrary time in the 1364past, and not related to the time of day and therefore not subject to clock 1365drift. The primary use is for measuring performance between intervals: 1366 1367```js 1368const NS_PER_SEC = 1e9; 1369const time = process.hrtime(); 1370// [ 1800216, 25 ] 1371 1372setTimeout(() => { 1373 const diff = process.hrtime(time); 1374 // [ 1, 552 ] 1375 1376 console.log(`Benchmark took ${diff[0] * NS_PER_SEC + diff[1]} nanoseconds`); 1377 // Benchmark took 1000000552 nanoseconds 1378}, 1000); 1379``` 1380 1381## `process.hrtime.bigint()` 1382<!-- YAML 1383added: v10.7.0 1384--> 1385 1386* Returns: {bigint} 1387 1388The `bigint` version of the [`process.hrtime()`][] method returning the 1389current high-resolution real time in nanoseconds as a `bigint`. 1390 1391Unlike [`process.hrtime()`][], it does not support an additional `time` 1392argument since the difference can just be computed directly 1393by subtraction of the two `bigint`s. 1394 1395```js 1396const start = process.hrtime.bigint(); 1397// 191051479007711n 1398 1399setTimeout(() => { 1400 const end = process.hrtime.bigint(); 1401 // 191052633396993n 1402 1403 console.log(`Benchmark took ${end - start} nanoseconds`); 1404 // Benchmark took 1154389282 nanoseconds 1405}, 1000); 1406``` 1407 1408## `process.initgroups(user, extraGroup)` 1409<!-- YAML 1410added: v0.9.4 1411--> 1412 1413* `user` {string|number} The user name or numeric identifier. 1414* `extraGroup` {string|number} A group name or numeric identifier. 1415 1416The `process.initgroups()` method reads the `/etc/group` file and initializes 1417the group access list, using all groups of which the user is a member. This is 1418a privileged operation that requires that the Node.js process either have `root` 1419access or the `CAP_SETGID` capability. 1420 1421Use care when dropping privileges: 1422 1423```js 1424console.log(process.getgroups()); // [ 0 ] 1425process.initgroups('nodeuser', 1000); // switch user 1426console.log(process.getgroups()); // [ 27, 30, 46, 1000, 0 ] 1427process.setgid(1000); // drop root gid 1428console.log(process.getgroups()); // [ 27, 30, 46, 1000 ] 1429``` 1430 1431This function is only available on POSIX platforms (i.e. not Windows or 1432Android). 1433This feature is not available in [`Worker`][] threads. 1434 1435## `process.kill(pid[, signal])` 1436<!-- YAML 1437added: v0.0.6 1438--> 1439 1440* `pid` {number} A process ID 1441* `signal` {string|number} The signal to send, either as a string or number. 1442 **Default:** `'SIGTERM'`. 1443 1444The `process.kill()` method sends the `signal` to the process identified by 1445`pid`. 1446 1447Signal names are strings such as `'SIGINT'` or `'SIGHUP'`. See [Signal Events][] 1448and kill(2) for more information. 1449 1450This method will throw an error if the target `pid` does not exist. As a special 1451case, a signal of `0` can be used to test for the existence of a process. 1452Windows platforms will throw an error if the `pid` is used to kill a process 1453group. 1454 1455Even though the name of this function is `process.kill()`, it is really just a 1456signal sender, like the `kill` system call. The signal sent may do something 1457other than kill the target process. 1458 1459```js 1460process.on('SIGHUP', () => { 1461 console.log('Got SIGHUP signal.'); 1462}); 1463 1464setTimeout(() => { 1465 console.log('Exiting.'); 1466 process.exit(0); 1467}, 100); 1468 1469process.kill(process.pid, 'SIGHUP'); 1470``` 1471 1472When `SIGUSR1` is received by a Node.js process, Node.js will start the 1473debugger. See [Signal Events][]. 1474 1475## `process.mainModule` 1476<!-- YAML 1477added: v0.1.17 1478--> 1479 1480* {Object} 1481 1482The `process.mainModule` property provides an alternative way of retrieving 1483[`require.main`][]. The difference is that if the main module changes at 1484runtime, [`require.main`][] may still refer to the original main module in 1485modules that were required before the change occurred. Generally, it's 1486safe to assume that the two refer to the same module. 1487 1488As with [`require.main`][], `process.mainModule` will be `undefined` if there 1489is no entry script. 1490 1491## `process.memoryUsage()` 1492<!-- YAML 1493added: v0.1.16 1494changes: 1495 - version: v12.17.0 1496 pr-url: https://github.com/nodejs/node/pull/31550 1497 description: Added `arrayBuffers` to the returned object. 1498 - version: v7.2.0 1499 pr-url: https://github.com/nodejs/node/pull/9587 1500 description: Added `external` to the returned object. 1501--> 1502 1503* Returns: {Object} 1504 * `rss` {integer} 1505 * `heapTotal` {integer} 1506 * `heapUsed` {integer} 1507 * `external` {integer} 1508 * `arrayBuffers` {integer} 1509 1510The `process.memoryUsage()` method returns an object describing the memory usage 1511of the Node.js process measured in bytes. 1512 1513For example, the code: 1514 1515```js 1516console.log(process.memoryUsage()); 1517``` 1518 1519Will generate: 1520 1521<!-- eslint-skip --> 1522```js 1523{ 1524 rss: 4935680, 1525 heapTotal: 1826816, 1526 heapUsed: 650472, 1527 external: 49879, 1528 arrayBuffers: 9386 1529} 1530``` 1531 1532* `heapTotal` and `heapUsed` refer to V8's memory usage. 1533* `external` refers to the memory usage of C++ objects bound to JavaScript 1534 objects managed by V8. 1535* `rss`, Resident Set Size, is the amount of space occupied in the main 1536 memory device (that is a subset of the total allocated memory) for the 1537 process, including all C++ and JavaScript objects and code. 1538* `arrayBuffers` refers to memory allocated for `ArrayBuffer`s and 1539 `SharedArrayBuffer`s, including all Node.js [`Buffer`][]s. 1540 This is also included in the `external` value. When Node.js is used as an 1541 embedded library, this value may be `0` because allocations for `ArrayBuffer`s 1542 may not be tracked in that case. 1543 1544When using [`Worker`][] threads, `rss` will be a value that is valid for the 1545entire process, while the other fields will only refer to the current thread. 1546 1547## `process.nextTick(callback[, ...args])` 1548<!-- YAML 1549added: v0.1.26 1550changes: 1551 - version: v1.8.1 1552 pr-url: https://github.com/nodejs/node/pull/1077 1553 description: Additional arguments after `callback` are now supported. 1554--> 1555 1556* `callback` {Function} 1557* `...args` {any} Additional arguments to pass when invoking the `callback` 1558 1559`process.nextTick()` adds `callback` to the "next tick queue". This queue is 1560fully drained after the current operation on the JavaScript stack runs to 1561completion and before the event loop is allowed to continue. It's possible to 1562create an infinite loop if one were to recursively call `process.nextTick()`. 1563See the [Event Loop][] guide for more background. 1564 1565```js 1566console.log('start'); 1567process.nextTick(() => { 1568 console.log('nextTick callback'); 1569}); 1570console.log('scheduled'); 1571// Output: 1572// start 1573// scheduled 1574// nextTick callback 1575``` 1576 1577This is important when developing APIs in order to give users the opportunity 1578to assign event handlers *after* an object has been constructed but before any 1579I/O has occurred: 1580 1581```js 1582function MyThing(options) { 1583 this.setupOptions(options); 1584 1585 process.nextTick(() => { 1586 this.startDoingStuff(); 1587 }); 1588} 1589 1590const thing = new MyThing(); 1591thing.getReadyForStuff(); 1592 1593// thing.startDoingStuff() gets called now, not before. 1594``` 1595 1596It is very important for APIs to be either 100% synchronous or 100% 1597asynchronous. Consider this example: 1598 1599```js 1600// WARNING! DO NOT USE! BAD UNSAFE HAZARD! 1601function maybeSync(arg, cb) { 1602 if (arg) { 1603 cb(); 1604 return; 1605 } 1606 1607 fs.stat('file', cb); 1608} 1609``` 1610 1611This API is hazardous because in the following case: 1612 1613```js 1614const maybeTrue = Math.random() > 0.5; 1615 1616maybeSync(maybeTrue, () => { 1617 foo(); 1618}); 1619 1620bar(); 1621``` 1622 1623It is not clear whether `foo()` or `bar()` will be called first. 1624 1625The following approach is much better: 1626 1627```js 1628function definitelyAsync(arg, cb) { 1629 if (arg) { 1630 process.nextTick(cb); 1631 return; 1632 } 1633 1634 fs.stat('file', cb); 1635} 1636``` 1637 1638## `process.noDeprecation` 1639<!-- YAML 1640added: v0.8.0 1641--> 1642 1643* {boolean} 1644 1645The `process.noDeprecation` property indicates whether the `--no-deprecation` 1646flag is set on the current Node.js process. See the documentation for 1647the [`'warning'` event][process_warning] and the 1648[`emitWarning()` method][process_emit_warning] for more information about this 1649flag's behavior. 1650 1651## `process.pid` 1652<!-- YAML 1653added: v0.1.15 1654--> 1655 1656* {integer} 1657 1658The `process.pid` property returns the PID of the process. 1659 1660```js 1661console.log(`This process is pid ${process.pid}`); 1662``` 1663 1664## `process.platform` 1665<!-- YAML 1666added: v0.1.16 1667--> 1668 1669* {string} 1670 1671The `process.platform` property returns a string identifying the operating 1672system platform on which the Node.js process is running. 1673 1674Currently possible values are: 1675 1676* `'aix'` 1677* `'darwin'` 1678* `'freebsd'` 1679* `'linux'` 1680* `'openbsd'` 1681* `'sunos'` 1682* `'win32'` 1683 1684```js 1685console.log(`This platform is ${process.platform}`); 1686``` 1687 1688The value `'android'` may also be returned if the Node.js is built on the 1689Android operating system. However, Android support in Node.js 1690[is experimental][Android building]. 1691 1692## `process.ppid` 1693<!-- YAML 1694added: 1695 - v9.2.0 1696 - v8.10.0 1697 - v6.13.0 1698--> 1699 1700* {integer} 1701 1702The `process.ppid` property returns the PID of the parent of the 1703current process. 1704 1705```js 1706console.log(`The parent process is pid ${process.ppid}`); 1707``` 1708 1709## `process.release` 1710<!-- YAML 1711added: v3.0.0 1712changes: 1713 - version: v4.2.0 1714 pr-url: https://github.com/nodejs/node/pull/3212 1715 description: The `lts` property is now supported. 1716--> 1717 1718* {Object} 1719 1720The `process.release` property returns an `Object` containing metadata related 1721to the current release, including URLs for the source tarball and headers-only 1722tarball. 1723 1724`process.release` contains the following properties: 1725 1726* `name` {string} A value that will always be `'node'` for Node.js. For 1727 legacy io.js releases, this will be `'io.js'`. 1728* `sourceUrl` {string} an absolute URL pointing to a _`.tar.gz`_ file containing 1729 the source code of the current release. 1730* `headersUrl`{string} an absolute URL pointing to a _`.tar.gz`_ file containing 1731 only the source header files for the current release. This file is 1732 significantly smaller than the full source file and can be used for compiling 1733 Node.js native add-ons. 1734* `libUrl` {string} an absolute URL pointing to a _`node.lib`_ file matching the 1735 architecture and version of the current release. This file is used for 1736 compiling Node.js native add-ons. _This property is only present on Windows 1737 builds of Node.js and will be missing on all other platforms._ 1738* `lts` {string} a string label identifying the [LTS][] label for this release. 1739 This property only exists for LTS releases and is `undefined` for all other 1740 release types, including _Current_ releases. 1741 Valid values include the LTS Release Codenames (including those 1742 that are no longer supported). A non-exhaustive example of 1743 these codenames includes: 1744 * `'Dubnium'` for the 10.x LTS line beginning with 10.13.0. 1745 * `'Erbium'` for the 12.x LTS line beginning with 12.13.0. 1746 For other LTS Release Codenames, see [Node.js Changelog Archive](https://github.com/nodejs/node/blob/master/doc/changelogs/CHANGELOG_ARCHIVE.md) 1747 1748<!-- eslint-skip --> 1749```js 1750{ 1751 name: 'node', 1752 lts: 'Erbium', 1753 sourceUrl: 'https://nodejs.org/download/release/v12.18.1/node-v12.18.1.tar.gz', 1754 headersUrl: 'https://nodejs.org/download/release/v12.18.1/node-v12.18.1-headers.tar.gz', 1755 libUrl: 'https://nodejs.org/download/release/v12.18.1/win-x64/node.lib' 1756} 1757``` 1758 1759In custom builds from non-release versions of the source tree, only the 1760`name` property may be present. The additional properties should not be 1761relied upon to exist. 1762 1763## `process.report` 1764<!-- YAML 1765added: v11.8.0 1766changes: 1767 - version: v12.17.0 1768 pr-url: https://github.com/nodejs/node/pull/32242 1769 description: This API is no longer experimental. 1770--> 1771 1772* {Object} 1773 1774`process.report` is an object whose methods are used to generate diagnostic 1775reports for the current process. Additional documentation is available in the 1776[report documentation][]. 1777 1778### `process.report.compact` 1779<!-- YAML 1780added: v12.17.0 1781--> 1782 1783* {boolean} 1784 1785Write reports in a compact format, single-line JSON, more easily consumable 1786by log processing systems than the default multi-line format designed for 1787human consumption. 1788 1789```js 1790console.log(`Reports are compact? ${process.report.compact}`); 1791``` 1792 1793### `process.report.directory` 1794<!-- YAML 1795added: v11.12.0 1796changes: 1797 - version: v12.17.0 1798 pr-url: https://github.com/nodejs/node/pull/32242 1799 description: This API is no longer experimental. 1800--> 1801 1802* {string} 1803 1804Directory where the report is written. The default value is the empty string, 1805indicating that reports are written to the current working directory of the 1806Node.js process. 1807 1808```js 1809console.log(`Report directory is ${process.report.directory}`); 1810``` 1811 1812### `process.report.filename` 1813<!-- YAML 1814added: v11.12.0 1815changes: 1816 - version: v12.17.0 1817 pr-url: https://github.com/nodejs/node/pull/32242 1818 description: This API is no longer experimental. 1819--> 1820 1821* {string} 1822 1823Filename where the report is written. If set to the empty string, the output 1824filename will be comprised of a timestamp, PID, and sequence number. The default 1825value is the empty string. 1826 1827```js 1828console.log(`Report filename is ${process.report.filename}`); 1829``` 1830 1831### `process.report.getReport([err])` 1832<!-- YAML 1833added: v11.8.0 1834changes: 1835 - version: v12.17.0 1836 pr-url: https://github.com/nodejs/node/pull/32242 1837 description: This API is no longer experimental. 1838--> 1839 1840* `err` {Error} A custom error used for reporting the JavaScript stack. 1841* Returns: {Object} 1842 1843Returns a JavaScript Object representation of a diagnostic report for the 1844running process. The report's JavaScript stack trace is taken from `err`, if 1845present. 1846 1847```js 1848const data = process.report.getReport(); 1849console.log(data.header.nodeJsVersion); 1850 1851// Similar to process.report.writeReport() 1852const fs = require('fs'); 1853fs.writeFileSync(util.inspect(data), 'my-report.log', 'utf8'); 1854``` 1855 1856Additional documentation is available in the [report documentation][]. 1857 1858### `process.report.reportOnFatalError` 1859<!-- YAML 1860added: v11.12.0 1861--> 1862 1863> Stability: 1 - Experimental 1864 1865* {boolean} 1866 1867If `true`, a diagnostic report is generated on fatal errors, such as out of 1868memory errors or failed C++ assertions. 1869 1870```js 1871console.log(`Report on fatal error: ${process.report.reportOnFatalError}`); 1872``` 1873 1874### `process.report.reportOnSignal` 1875<!-- YAML 1876added: v11.12.0 1877changes: 1878 - version: v12.17.0 1879 pr-url: https://github.com/nodejs/node/pull/32242 1880 description: This API is no longer experimental. 1881--> 1882 1883* {boolean} 1884 1885If `true`, a diagnostic report is generated when the process receives the 1886signal specified by `process.report.signal`. 1887 1888```js 1889console.log(`Report on signal: ${process.report.reportOnSignal}`); 1890``` 1891 1892### `process.report.reportOnUncaughtException` 1893<!-- YAML 1894added: v11.12.0 1895changes: 1896 - version: v12.17.0 1897 pr-url: https://github.com/nodejs/node/pull/32242 1898 description: This API is no longer experimental. 1899--> 1900 1901* {boolean} 1902 1903If `true`, a diagnostic report is generated on uncaught exception. 1904 1905```js 1906console.log(`Report on exception: ${process.report.reportOnUncaughtException}`); 1907``` 1908 1909### `process.report.signal` 1910<!-- YAML 1911added: v11.12.0 1912changes: 1913 - version: v12.17.0 1914 pr-url: https://github.com/nodejs/node/pull/32242 1915 description: This API is no longer experimental. 1916--> 1917 1918* {string} 1919 1920The signal used to trigger the creation of a diagnostic report. Defaults to 1921`'SIGUSR2'`. 1922 1923```js 1924console.log(`Report signal: ${process.report.signal}`); 1925``` 1926 1927### `process.report.writeReport([filename][, err])` 1928<!-- YAML 1929added: v11.8.0 1930changes: 1931 - version: v12.17.0 1932 pr-url: https://github.com/nodejs/node/pull/32242 1933 description: This API is no longer experimental. 1934--> 1935 1936* `filename` {string} Name of the file where the report is written. This 1937 should be a relative path, that will be appended to the directory specified in 1938 `process.report.directory`, or the current working directory of the Node.js 1939 process, if unspecified. 1940* `err` {Error} A custom error used for reporting the JavaScript stack. 1941 1942* Returns: {string} Returns the filename of the generated report. 1943 1944Writes a diagnostic report to a file. If `filename` is not provided, the default 1945filename includes the date, time, PID, and a sequence number. The report's 1946JavaScript stack trace is taken from `err`, if present. 1947 1948```js 1949process.report.writeReport(); 1950``` 1951 1952Additional documentation is available in the [report documentation][]. 1953 1954## `process.resourceUsage()` 1955<!-- YAML 1956added: v12.6.0 1957--> 1958 1959* Returns: {Object} the resource usage for the current process. All of these 1960 values come from the `uv_getrusage` call which returns 1961 a [`uv_rusage_t` struct][uv_rusage_t]. 1962 * `userCPUTime` {integer} maps to `ru_utime` computed in microseconds. 1963 It is the same value as [`process.cpuUsage().user`][process.cpuUsage]. 1964 * `systemCPUTime` {integer} maps to `ru_stime` computed in microseconds. 1965 It is the same value as [`process.cpuUsage().system`][process.cpuUsage]. 1966 * `maxRSS` {integer} maps to `ru_maxrss` which is the maximum resident set 1967 size used in kilobytes. 1968 * `sharedMemorySize` {integer} maps to `ru_ixrss` but is not supported by 1969 any platform. 1970 * `unsharedDataSize` {integer} maps to `ru_idrss` but is not supported by 1971 any platform. 1972 * `unsharedStackSize` {integer} maps to `ru_isrss` but is not supported by 1973 any platform. 1974 * `minorPageFault` {integer} maps to `ru_minflt` which is the number of 1975 minor page faults for the process, see 1976 [this article for more details][wikipedia_minor_fault]. 1977 * `majorPageFault` {integer} maps to `ru_majflt` which is the number of 1978 major page faults for the process, see 1979 [this article for more details][wikipedia_major_fault]. This field is not 1980 supported on Windows. 1981 * `swappedOut` {integer} maps to `ru_nswap` but is not supported by any 1982 platform. 1983 * `fsRead` {integer} maps to `ru_inblock` which is the number of times the 1984 file system had to perform input. 1985 * `fsWrite` {integer} maps to `ru_oublock` which is the number of times the 1986 file system had to perform output. 1987 * `ipcSent` {integer} maps to `ru_msgsnd` but is not supported by any 1988 platform. 1989 * `ipcReceived` {integer} maps to `ru_msgrcv` but is not supported by any 1990 platform. 1991 * `signalsCount` {integer} maps to `ru_nsignals` but is not supported by any 1992 platform. 1993 * `voluntaryContextSwitches` {integer} maps to `ru_nvcsw` which is the 1994 number of times a CPU context switch resulted due to a process voluntarily 1995 giving up the processor before its time slice was completed (usually to 1996 await availability of a resource). This field is not supported on Windows. 1997 * `involuntaryContextSwitches` {integer} maps to `ru_nivcsw` which is the 1998 number of times a CPU context switch resulted due to a higher priority 1999 process becoming runnable or because the current process exceeded its 2000 time slice. This field is not supported on Windows. 2001 2002```js 2003console.log(process.resourceUsage()); 2004/* 2005 Will output: 2006 { 2007 userCPUTime: 82872, 2008 systemCPUTime: 4143, 2009 maxRSS: 33164, 2010 sharedMemorySize: 0, 2011 unsharedDataSize: 0, 2012 unsharedStackSize: 0, 2013 minorPageFault: 2469, 2014 majorPageFault: 0, 2015 swappedOut: 0, 2016 fsRead: 0, 2017 fsWrite: 8, 2018 ipcSent: 0, 2019 ipcReceived: 0, 2020 signalsCount: 0, 2021 voluntaryContextSwitches: 79, 2022 involuntaryContextSwitches: 1 2023 } 2024*/ 2025``` 2026 2027## `process.send(message[, sendHandle[, options]][, callback])` 2028<!-- YAML 2029added: v0.5.9 2030--> 2031 2032* `message` {Object} 2033* `sendHandle` {net.Server|net.Socket} 2034* `options` {Object} used to parameterize the sending of certain types of 2035 handles.`options` supports the following properties: 2036 * `keepOpen` {boolean} A value that can be used when passing instances of 2037 `net.Socket`. When `true`, the socket is kept open in the sending process. 2038 **Default:** `false`. 2039* `callback` {Function} 2040* Returns: {boolean} 2041 2042If Node.js is spawned with an IPC channel, the `process.send()` method can be 2043used to send messages to the parent process. Messages will be received as a 2044[`'message'`][] event on the parent's [`ChildProcess`][] object. 2045 2046If Node.js was not spawned with an IPC channel, `process.send` will be 2047`undefined`. 2048 2049The message goes through serialization and parsing. The resulting message might 2050not be the same as what is originally sent. 2051 2052## `process.setegid(id)` 2053<!-- YAML 2054added: v2.0.0 2055--> 2056 2057* `id` {string|number} A group name or ID 2058 2059The `process.setegid()` method sets the effective group identity of the process. 2060(See setegid(2).) The `id` can be passed as either a numeric ID or a group 2061name string. If a group name is specified, this method blocks while resolving 2062the associated a numeric ID. 2063 2064```js 2065if (process.getegid && process.setegid) { 2066 console.log(`Current gid: ${process.getegid()}`); 2067 try { 2068 process.setegid(501); 2069 console.log(`New gid: ${process.getegid()}`); 2070 } catch (err) { 2071 console.log(`Failed to set gid: ${err}`); 2072 } 2073} 2074``` 2075 2076This function is only available on POSIX platforms (i.e. not Windows or 2077Android). 2078This feature is not available in [`Worker`][] threads. 2079 2080## `process.seteuid(id)` 2081<!-- YAML 2082added: v2.0.0 2083--> 2084 2085* `id` {string|number} A user name or ID 2086 2087The `process.seteuid()` method sets the effective user identity of the process. 2088(See seteuid(2).) The `id` can be passed as either a numeric ID or a username 2089string. If a username is specified, the method blocks while resolving the 2090associated numeric ID. 2091 2092```js 2093if (process.geteuid && process.seteuid) { 2094 console.log(`Current uid: ${process.geteuid()}`); 2095 try { 2096 process.seteuid(501); 2097 console.log(`New uid: ${process.geteuid()}`); 2098 } catch (err) { 2099 console.log(`Failed to set uid: ${err}`); 2100 } 2101} 2102``` 2103 2104This function is only available on POSIX platforms (i.e. not Windows or 2105Android). 2106This feature is not available in [`Worker`][] threads. 2107 2108## `process.setgid(id)` 2109<!-- YAML 2110added: v0.1.31 2111--> 2112 2113* `id` {string|number} The group name or ID 2114 2115The `process.setgid()` method sets the group identity of the process. (See 2116setgid(2).) The `id` can be passed as either a numeric ID or a group name 2117string. If a group name is specified, this method blocks while resolving the 2118associated numeric ID. 2119 2120```js 2121if (process.getgid && process.setgid) { 2122 console.log(`Current gid: ${process.getgid()}`); 2123 try { 2124 process.setgid(501); 2125 console.log(`New gid: ${process.getgid()}`); 2126 } catch (err) { 2127 console.log(`Failed to set gid: ${err}`); 2128 } 2129} 2130``` 2131 2132This function is only available on POSIX platforms (i.e. not Windows or 2133Android). 2134This feature is not available in [`Worker`][] threads. 2135 2136## `process.setgroups(groups)` 2137<!-- YAML 2138added: v0.9.4 2139--> 2140 2141* `groups` {integer[]} 2142 2143The `process.setgroups()` method sets the supplementary group IDs for the 2144Node.js process. This is a privileged operation that requires the Node.js 2145process to have `root` or the `CAP_SETGID` capability. 2146 2147The `groups` array can contain numeric group IDs, group names or both. 2148 2149This function is only available on POSIX platforms (i.e. not Windows or 2150Android). 2151This feature is not available in [`Worker`][] threads. 2152 2153## `process.setuid(id)` 2154<!-- YAML 2155added: v0.1.28 2156--> 2157 2158* `id` {integer | string} 2159 2160The `process.setuid(id)` method sets the user identity of the process. (See 2161setuid(2).) The `id` can be passed as either a numeric ID or a username string. 2162If a username is specified, the method blocks while resolving the associated 2163numeric ID. 2164 2165```js 2166if (process.getuid && process.setuid) { 2167 console.log(`Current uid: ${process.getuid()}`); 2168 try { 2169 process.setuid(501); 2170 console.log(`New uid: ${process.getuid()}`); 2171 } catch (err) { 2172 console.log(`Failed to set uid: ${err}`); 2173 } 2174} 2175``` 2176 2177This function is only available on POSIX platforms (i.e. not Windows or 2178Android). 2179This feature is not available in [`Worker`][] threads. 2180 2181## `process.setUncaughtExceptionCaptureCallback(fn)` 2182<!-- YAML 2183added: v9.3.0 2184--> 2185 2186* `fn` {Function|null} 2187 2188The `process.setUncaughtExceptionCaptureCallback()` function sets a function 2189that will be invoked when an uncaught exception occurs, which will receive the 2190exception value itself as its first argument. 2191 2192If such a function is set, the [`'uncaughtException'`][] event will 2193not be emitted. If `--abort-on-uncaught-exception` was passed from the 2194command line or set through [`v8.setFlagsFromString()`][], the process will 2195not abort. 2196 2197To unset the capture function, 2198`process.setUncaughtExceptionCaptureCallback(null)` may be used. Calling this 2199method with a non-`null` argument while another capture function is set will 2200throw an error. 2201 2202Using this function is mutually exclusive with using the deprecated 2203[`domain`][] built-in module. 2204 2205## `process.stderr` 2206 2207* {Stream} 2208 2209The `process.stderr` property returns a stream connected to 2210`stderr` (fd `2`). It is a [`net.Socket`][] (which is a [Duplex][] 2211stream) unless fd `2` refers to a file, in which case it is 2212a [Writable][] stream. 2213 2214`process.stderr` differs from other Node.js streams in important ways. See 2215[note on process I/O][] for more information. 2216 2217### `process.stderr.fd` 2218 2219* {number} 2220 2221This property refers to the value of underlying file descriptor of 2222`process.stderr`. The value is fixed at `2`. In [`Worker`][] threads, 2223this field does not exist. 2224 2225## `process.stdin` 2226 2227* {Stream} 2228 2229The `process.stdin` property returns a stream connected to 2230`stdin` (fd `0`). It is a [`net.Socket`][] (which is a [Duplex][] 2231stream) unless fd `0` refers to a file, in which case it is 2232a [Readable][] stream. 2233 2234For details of how to read from `stdin` see [`readable.read()`][]. 2235 2236As a [Duplex][] stream, `process.stdin` can also be used in "old" mode that 2237is compatible with scripts written for Node.js prior to v0.10. 2238For more information see [Stream compatibility][]. 2239 2240In "old" streams mode the `stdin` stream is paused by default, so one 2241must call `process.stdin.resume()` to read from it. Note also that calling 2242`process.stdin.resume()` itself would switch stream to "old" mode. 2243 2244### `process.stdin.fd` 2245 2246* {number} 2247 2248This property refers to the value of underlying file descriptor of 2249`process.stdin`. The value is fixed at `0`. In [`Worker`][] threads, 2250this field does not exist. 2251 2252## `process.stdout` 2253 2254* {Stream} 2255 2256The `process.stdout` property returns a stream connected to 2257`stdout` (fd `1`). It is a [`net.Socket`][] (which is a [Duplex][] 2258stream) unless fd `1` refers to a file, in which case it is 2259a [Writable][] stream. 2260 2261For example, to copy `process.stdin` to `process.stdout`: 2262 2263```js 2264process.stdin.pipe(process.stdout); 2265``` 2266 2267`process.stdout` differs from other Node.js streams in important ways. See 2268[note on process I/O][] for more information. 2269 2270### `process.stdout.fd` 2271 2272* {number} 2273 2274This property refers to the value of underlying file descriptor of 2275`process.stdout`. The value is fixed at `1`. In [`Worker`][] threads, 2276this field does not exist. 2277 2278### A note on process I/O 2279 2280`process.stdout` and `process.stderr` differ from other Node.js streams in 2281important ways: 2282 22831. They are used internally by [`console.log()`][] and [`console.error()`][], 2284 respectively. 22852. Writes may be synchronous depending on what the stream is connected to 2286 and whether the system is Windows or POSIX: 2287 * Files: *synchronous* on Windows and POSIX 2288 * TTYs (Terminals): *asynchronous* on Windows, *synchronous* on POSIX 2289 * Pipes (and sockets): *synchronous* on Windows, *asynchronous* on POSIX 2290 2291These behaviors are partly for historical reasons, as changing them would 2292create backward incompatibility, but they are also expected by some users. 2293 2294Synchronous writes avoid problems such as output written with `console.log()` or 2295`console.error()` being unexpectedly interleaved, or not written at all if 2296`process.exit()` is called before an asynchronous write completes. See 2297[`process.exit()`][] for more information. 2298 2299***Warning***: Synchronous writes block the event loop until the write has 2300completed. This can be near instantaneous in the case of output to a file, but 2301under high system load, pipes that are not being read at the receiving end, or 2302with slow terminals or file systems, its possible for the event loop to be 2303blocked often enough and long enough to have severe negative performance 2304impacts. This may not be a problem when writing to an interactive terminal 2305session, but consider this particularly careful when doing production logging to 2306the process output streams. 2307 2308To check if a stream is connected to a [TTY][] context, check the `isTTY` 2309property. 2310 2311For instance: 2312 2313```console 2314$ node -p "Boolean(process.stdin.isTTY)" 2315true 2316$ echo "foo" | node -p "Boolean(process.stdin.isTTY)" 2317false 2318$ node -p "Boolean(process.stdout.isTTY)" 2319true 2320$ node -p "Boolean(process.stdout.isTTY)" | cat 2321false 2322``` 2323 2324See the [TTY][] documentation for more information. 2325 2326## `process.throwDeprecation` 2327<!-- YAML 2328added: v0.9.12 2329--> 2330 2331* {boolean} 2332 2333The initial value of `process.throwDeprecation` indicates whether the 2334`--throw-deprecation` flag is set on the current Node.js process. 2335`process.throwDeprecation` is mutable, so whether or not deprecation 2336warnings result in errors may be altered at runtime. See the 2337documentation for the [`'warning'` event][process_warning] and the 2338[`emitWarning()` method][process_emit_warning] for more information. 2339 2340```console 2341$ node --throw-deprecation -p "process.throwDeprecation" 2342true 2343$ node -p "process.throwDeprecation" 2344undefined 2345$ node 2346> process.emitWarning('test', 'DeprecationWarning'); 2347undefined 2348> (node:26598) DeprecationWarning: test 2349> process.throwDeprecation = true; 2350true 2351> process.emitWarning('test', 'DeprecationWarning'); 2352Thrown: 2353[DeprecationWarning: test] { name: 'DeprecationWarning' } 2354``` 2355 2356## `process.title` 2357<!-- YAML 2358added: v0.1.104 2359--> 2360 2361* {string} 2362 2363The `process.title` property returns the current process title (i.e. returns 2364the current value of `ps`). Assigning a new value to `process.title` modifies 2365the current value of `ps`. 2366 2367When a new value is assigned, different platforms will impose different maximum 2368length restrictions on the title. Usually such restrictions are quite limited. 2369For instance, on Linux and macOS, `process.title` is limited to the size of the 2370binary name plus the length of the command line arguments because setting the 2371`process.title` overwrites the `argv` memory of the process. Node.js v0.8 2372allowed for longer process title strings by also overwriting the `environ` 2373memory but that was potentially insecure and confusing in some (rather obscure) 2374cases. 2375 2376Assigning a value to `process.title` might not result in an accurate label 2377within process manager applications such as macOS Activity Monitor or Windows 2378Services Manager. 2379 2380## `process.traceDeprecation` 2381<!-- YAML 2382added: v0.8.0 2383--> 2384 2385* {boolean} 2386 2387The `process.traceDeprecation` property indicates whether the 2388`--trace-deprecation` flag is set on the current Node.js process. See the 2389documentation for the [`'warning'` event][process_warning] and the 2390[`emitWarning()` method][process_emit_warning] for more information about this 2391flag's behavior. 2392 2393## `process.umask()` 2394<!-- YAML 2395added: v0.1.19 2396changes: 2397 - version: 2398 - v12.19.0 2399 - v14.0.0 2400 pr-url: https://github.com/nodejs/node/pull/32499 2401 description: Calling `process.umask()` with no arguments is deprecated. 2402 2403--> 2404 2405> Stability: 0 - Deprecated. Calling `process.umask()` with no argument causes 2406> the process-wide umask to be written twice. This introduces a race condition 2407> between threads, and is a potential security vulnerability. There is no safe, 2408> cross-platform alternative API. 2409 2410`process.umask()` returns the Node.js process's file mode creation mask. Child 2411processes inherit the mask from the parent process. 2412 2413## `process.umask(mask)` 2414<!-- YAML 2415added: v0.1.19 2416--> 2417 2418* `mask` {string|integer} 2419 2420`process.umask(mask)` sets the Node.js process's file mode creation mask. Child 2421processes inherit the mask from the parent process. Returns the previous mask. 2422 2423```js 2424const newmask = 0o022; 2425const oldmask = process.umask(newmask); 2426console.log( 2427 `Changed umask from ${oldmask.toString(8)} to ${newmask.toString(8)}` 2428); 2429``` 2430 2431In [`Worker`][] threads, `process.umask(mask)` will throw an exception. 2432 2433## `process.uptime()` 2434<!-- YAML 2435added: v0.5.0 2436--> 2437 2438* Returns: {number} 2439 2440The `process.uptime()` method returns the number of seconds the current Node.js 2441process has been running. 2442 2443The return value includes fractions of a second. Use `Math.floor()` to get whole 2444seconds. 2445 2446## `process.version` 2447<!-- YAML 2448added: v0.1.3 2449--> 2450 2451* {string} 2452 2453The `process.version` property contains the Node.js version string. 2454 2455```js 2456console.log(`Version: ${process.version}`); 2457// Version: v14.8.0 2458``` 2459 2460To get the version string without the prepended _v_, use 2461`process.versions.node`. 2462 2463## `process.versions` 2464<!-- YAML 2465added: v0.2.0 2466changes: 2467 - version: v4.2.0 2468 pr-url: https://github.com/nodejs/node/pull/3102 2469 description: The `icu` property is now supported. 2470 - version: v9.0.0 2471 pr-url: https://github.com/nodejs/node/pull/15785 2472 description: The `v8` property now includes a Node.js specific suffix. 2473--> 2474 2475* {Object} 2476 2477The `process.versions` property returns an object listing the version strings of 2478Node.js and its dependencies. `process.versions.modules` indicates the current 2479ABI version, which is increased whenever a C++ API changes. Node.js will refuse 2480to load modules that were compiled against a different module ABI version. 2481 2482```js 2483console.log(process.versions); 2484``` 2485 2486Will generate an object similar to: 2487 2488```console 2489{ node: '11.13.0', 2490 v8: '7.0.276.38-node.18', 2491 uv: '1.27.0', 2492 zlib: '1.2.11', 2493 brotli: '1.0.7', 2494 ares: '1.15.0', 2495 modules: '67', 2496 nghttp2: '1.34.0', 2497 napi: '4', 2498 llhttp: '1.1.1', 2499 http_parser: '2.8.0', 2500 openssl: '1.1.1b', 2501 cldr: '34.0', 2502 icu: '63.1', 2503 tz: '2018e', 2504 unicode: '11.0' } 2505``` 2506 2507## Exit codes 2508 2509Node.js will normally exit with a `0` status code when no more async 2510operations are pending. The following status codes are used in other 2511cases: 2512 2513* `1` **Uncaught Fatal Exception**: There was an uncaught exception, 2514 and it was not handled by a domain or an [`'uncaughtException'`][] event 2515 handler. 2516* `2`: Unused (reserved by Bash for builtin misuse) 2517* `3` **Internal JavaScript Parse Error**: The JavaScript source code 2518 internal in the Node.js bootstrapping process caused a parse error. This 2519 is extremely rare, and generally can only happen during development 2520 of Node.js itself. 2521* `4` **Internal JavaScript Evaluation Failure**: The JavaScript 2522 source code internal in the Node.js bootstrapping process failed to 2523 return a function value when evaluated. This is extremely rare, and 2524 generally can only happen during development of Node.js itself. 2525* `5` **Fatal Error**: There was a fatal unrecoverable error in V8. 2526 Typically a message will be printed to stderr with the prefix `FATAL 2527 ERROR`. 2528* `6` **Non-function Internal Exception Handler**: There was an 2529 uncaught exception, but the internal fatal exception handler 2530 function was somehow set to a non-function, and could not be called. 2531* `7` **Internal Exception Handler Run-Time Failure**: There was an 2532 uncaught exception, and the internal fatal exception handler 2533 function itself threw an error while attempting to handle it. This 2534 can happen, for example, if an [`'uncaughtException'`][] or 2535 `domain.on('error')` handler throws an error. 2536* `8`: Unused. In previous versions of Node.js, exit code 8 sometimes 2537 indicated an uncaught exception. 2538* `9` **Invalid Argument**: Either an unknown option was specified, 2539 or an option requiring a value was provided without a value. 2540* `10` **Internal JavaScript Run-Time Failure**: The JavaScript 2541 source code internal in the Node.js bootstrapping process threw an error 2542 when the bootstrapping function was called. This is extremely rare, 2543 and generally can only happen during development of Node.js itself. 2544* `12` **Invalid Debug Argument**: The `--inspect` and/or `--inspect-brk` 2545 options were set, but the port number chosen was invalid or unavailable. 2546* `>128` **Signal Exits**: If Node.js receives a fatal signal such as 2547 `SIGKILL` or `SIGHUP`, then its exit code will be `128` plus the 2548 value of the signal code. This is a standard POSIX practice, since 2549 exit codes are defined to be 7-bit integers, and signal exits set 2550 the high-order bit, and then contain the value of the signal code. 2551 For example, signal `SIGABRT` has value `6`, so the expected exit 2552 code will be `128` + `6`, or `134`. 2553 2554[`'exit'`]: #process_event_exit 2555[`'message'`]: child_process.html#child_process_event_message 2556[`'uncaughtException'`]: #process_event_uncaughtexception 2557[`--unhandled-rejections`]: cli.html#cli_unhandled_rejections_mode 2558[`Buffer`]: buffer.html 2559[`ChildProcess.disconnect()`]: child_process.html#child_process_subprocess_disconnect 2560[`ChildProcess.send()`]: child_process.html#child_process_subprocess_send_message_sendhandle_options_callback 2561[`ChildProcess`]: child_process.html#child_process_class_childprocess 2562[`Error`]: errors.html#errors_class_error 2563[`EventEmitter`]: events.html#events_class_eventemitter 2564[`NODE_OPTIONS`]: cli.html#cli_node_options_options 2565[`Worker`]: worker_threads.html#worker_threads_class_worker 2566[`console.error()`]: console.html#console_console_error_data_args 2567[`console.log()`]: console.html#console_console_log_data_args 2568[`domain`]: domain.html 2569[`net.Server`]: net.html#net_class_net_server 2570[`net.Socket`]: net.html#net_class_net_socket 2571[`os.constants.dlopen`]: os.html#os_dlopen_constants 2572[`process.argv`]: #process_process_argv 2573[`process.config`]: #process_process_config 2574[`process.execPath`]: #process_process_execpath 2575[`process.exit()`]: #process_process_exit_code 2576[`process.exitCode`]: #process_process_exitcode 2577[`process.hrtime()`]: #process_process_hrtime_time 2578[`process.hrtime.bigint()`]: #process_process_hrtime_bigint 2579[`process.kill()`]: #process_process_kill_pid_signal 2580[`process.setUncaughtExceptionCaptureCallback()`]: process.html#process_process_setuncaughtexceptioncapturecallback_fn 2581[`promise.catch()`]: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Promise/catch 2582[`Promise.race()`]: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Promise/race 2583[`require()`]: globals.html#globals_require 2584[`require.main`]: modules.html#modules_accessing_the_main_module 2585[`require.resolve()`]: modules.html#modules_require_resolve_request_options 2586[`subprocess.kill()`]: child_process.html#child_process_subprocess_kill_signal 2587[`v8.setFlagsFromString()`]: v8.html#v8_v8_setflagsfromstring_flags 2588[Advanced serialization for `child_process`]: child_process.html#child_process_advanced_serialization 2589[Android building]: https://github.com/nodejs/node/blob/master/BUILDING.md#androidandroid-based-devices-eg-firefox-os 2590[Child Process]: child_process.html 2591[Cluster]: cluster.html 2592[Duplex]: stream.html#stream_duplex_and_transform_streams 2593[Event Loop]: https://nodejs.org/en/docs/guides/event-loop-timers-and-nexttick/#process-nexttick 2594[LTS]: https://github.com/nodejs/Release 2595[Readable]: stream.html#stream_readable_streams 2596[`readable.read()`]: stream.html#stream_readable_read_size 2597[Signal Events]: #process_signal_events 2598[Stream compatibility]: stream.html#stream_compatibility_with_older_node_js_versions 2599[TTY]: tty.html#tty_tty 2600[Writable]: stream.html#stream_writable_streams 2601[debugger]: debugger.html 2602[note on process I/O]: process.html#process_a_note_on_process_i_o 2603[process.cpuUsage]: #process_process_cpuusage_previousvalue 2604[process_emit_warning]: #process_process_emitwarning_warning_type_code_ctor 2605[process_warning]: #process_event_warning 2606[report documentation]: report.html 2607[terminal raw mode]: tty.html#tty_readstream_setrawmode_mode 2608[uv_rusage_t]: https://docs.libuv.org/en/v1.x/misc.html#c.uv_rusage_t 2609[wikipedia_minor_fault]: https://en.wikipedia.org/wiki/Page_fault#Minor 2610[wikipedia_major_fault]: https://en.wikipedia.org/wiki/Page_fault#Major 2611