1# Process 2 3<!-- introduced_in=v0.10.0 --> 4 5<!-- type=global --> 6 7<!-- source_link=lib/process.js --> 8 9The `process` object provides information about, and control over, the current 10Node.js process. 11 12```mjs 13import process from 'node:process'; 14``` 15 16```cjs 17const process = require('node:process'); 18``` 19 20## Process events 21 22The `process` object is an instance of [`EventEmitter`][]. 23 24### Event: `'beforeExit'` 25 26<!-- YAML 27added: v0.11.12 28--> 29 30The `'beforeExit'` event is emitted when Node.js empties its event loop and has 31no additional work to schedule. Normally, the Node.js process will exit when 32there is no work scheduled, but a listener registered on the `'beforeExit'` 33event can make asynchronous calls, and thereby cause the Node.js process to 34continue. 35 36The listener callback function is invoked with the value of 37[`process.exitCode`][] passed as the only argument. 38 39The `'beforeExit'` event is _not_ emitted for conditions causing explicit 40termination, such as calling [`process.exit()`][] or uncaught exceptions. 41 42The `'beforeExit'` should _not_ be used as an alternative to the `'exit'` event 43unless the intention is to schedule additional work. 44 45```mjs 46import process from 'node:process'; 47 48process.on('beforeExit', (code) => { 49 console.log('Process beforeExit event with code: ', code); 50}); 51 52process.on('exit', (code) => { 53 console.log('Process exit event with code: ', code); 54}); 55 56console.log('This message is displayed first.'); 57 58// Prints: 59// This message is displayed first. 60// Process beforeExit event with code: 0 61// Process exit event with code: 0 62``` 63 64```cjs 65const process = require('node:process'); 66 67process.on('beforeExit', (code) => { 68 console.log('Process beforeExit event with code: ', code); 69}); 70 71process.on('exit', (code) => { 72 console.log('Process exit event with code: ', code); 73}); 74 75console.log('This message is displayed first.'); 76 77// Prints: 78// This message is displayed first. 79// Process beforeExit event with code: 0 80// Process exit event with code: 0 81``` 82 83### Event: `'disconnect'` 84 85<!-- YAML 86added: v0.7.7 87--> 88 89If the Node.js process is spawned with an IPC channel (see the [Child Process][] 90and [Cluster][] documentation), the `'disconnect'` event will be emitted when 91the IPC channel is closed. 92 93### Event: `'exit'` 94 95<!-- YAML 96added: v0.1.7 97--> 98 99* `code` {integer} 100 101The `'exit'` event is emitted when the Node.js process is about to exit as a 102result of either: 103 104* The `process.exit()` method being called explicitly; 105* The Node.js event loop no longer having any additional work to perform. 106 107There is no way to prevent the exiting of the event loop at this point, and once 108all `'exit'` listeners have finished running the Node.js process will terminate. 109 110The listener callback function is invoked with the exit code specified either 111by the [`process.exitCode`][] property, or the `exitCode` argument passed to the 112[`process.exit()`][] method. 113 114```mjs 115import process from 'node:process'; 116 117process.on('exit', (code) => { 118 console.log(`About to exit with code: ${code}`); 119}); 120``` 121 122```cjs 123const process = require('node:process'); 124 125process.on('exit', (code) => { 126 console.log(`About to exit with code: ${code}`); 127}); 128``` 129 130Listener functions **must** only perform **synchronous** operations. The Node.js 131process will exit immediately after calling the `'exit'` event listeners 132causing any additional work still queued in the event loop to be abandoned. 133In the following example, for instance, the timeout will never occur: 134 135```mjs 136import process from 'node:process'; 137 138process.on('exit', (code) => { 139 setTimeout(() => { 140 console.log('This will not run'); 141 }, 0); 142}); 143``` 144 145```cjs 146const process = require('node:process'); 147 148process.on('exit', (code) => { 149 setTimeout(() => { 150 console.log('This will not run'); 151 }, 0); 152}); 153``` 154 155### Event: `'message'` 156 157<!-- YAML 158added: v0.5.10 159--> 160 161* `message` { Object | boolean | number | string | null } a parsed JSON object 162 or a serializable primitive value. 163* `sendHandle` {net.Server|net.Socket} a [`net.Server`][] or [`net.Socket`][] 164 object, or undefined. 165 166If the Node.js process is spawned with an IPC channel (see the [Child Process][] 167and [Cluster][] documentation), the `'message'` event is emitted whenever a 168message sent by a parent process using [`childprocess.send()`][] is received by 169the child process. 170 171The message goes through serialization and parsing. The resulting message might 172not be the same as what is originally sent. 173 174If the `serialization` option was set to `advanced` used when spawning the 175process, the `message` argument can contain data that JSON is not able 176to represent. 177See [Advanced serialization for `child_process`][] for more details. 178 179### Event: `'multipleResolves'` 180 181<!-- YAML 182added: v10.12.0 183deprecated: v17.6.0 184--> 185 186> Stability: 0 - Deprecated 187 188* `type` {string} The resolution type. One of `'resolve'` or `'reject'`. 189* `promise` {Promise} The promise that resolved or rejected more than once. 190* `value` {any} The value with which the promise was either resolved or 191 rejected after the original resolve. 192 193The `'multipleResolves'` event is emitted whenever a `Promise` has been either: 194 195* Resolved more than once. 196* Rejected more than once. 197* Rejected after resolve. 198* Resolved after reject. 199 200This is useful for tracking potential errors in an application while using the 201`Promise` constructor, as multiple resolutions are silently swallowed. However, 202the occurrence of this event does not necessarily indicate an error. For 203example, [`Promise.race()`][] can trigger a `'multipleResolves'` event. 204 205Because of the unreliability of the event in cases like the 206[`Promise.race()`][] example above it has been deprecated. 207 208```mjs 209import process from 'node:process'; 210 211process.on('multipleResolves', (type, promise, reason) => { 212 console.error(type, promise, reason); 213 setImmediate(() => process.exit(1)); 214}); 215 216async function main() { 217 try { 218 return await new Promise((resolve, reject) => { 219 resolve('First call'); 220 resolve('Swallowed resolve'); 221 reject(new Error('Swallowed reject')); 222 }); 223 } catch { 224 throw new Error('Failed'); 225 } 226} 227 228main().then(console.log); 229// resolve: Promise { 'First call' } 'Swallowed resolve' 230// reject: Promise { 'First call' } Error: Swallowed reject 231// at Promise (*) 232// at new Promise (<anonymous>) 233// at main (*) 234// First call 235``` 236 237```cjs 238const process = require('node:process'); 239 240process.on('multipleResolves', (type, promise, reason) => { 241 console.error(type, promise, reason); 242 setImmediate(() => process.exit(1)); 243}); 244 245async function main() { 246 try { 247 return await new Promise((resolve, reject) => { 248 resolve('First call'); 249 resolve('Swallowed resolve'); 250 reject(new Error('Swallowed reject')); 251 }); 252 } catch { 253 throw new Error('Failed'); 254 } 255} 256 257main().then(console.log); 258// resolve: Promise { 'First call' } 'Swallowed resolve' 259// reject: Promise { 'First call' } Error: Swallowed reject 260// at Promise (*) 261// at new Promise (<anonymous>) 262// at main (*) 263// First call 264``` 265 266### Event: `'rejectionHandled'` 267 268<!-- YAML 269added: v1.4.1 270--> 271 272* `promise` {Promise} The late handled promise. 273 274The `'rejectionHandled'` event is emitted whenever a `Promise` has been rejected 275and an error handler was attached to it (using [`promise.catch()`][], for 276example) later than one turn of the Node.js event loop. 277 278The `Promise` object would have previously been emitted in an 279`'unhandledRejection'` event, but during the course of processing gained a 280rejection handler. 281 282There is no notion of a top level for a `Promise` chain at which rejections can 283always be handled. Being inherently asynchronous in nature, a `Promise` 284rejection can be handled at a future point in time, possibly much later than 285the event loop turn it takes for the `'unhandledRejection'` event to be emitted. 286 287Another way of stating this is that, unlike in synchronous code where there is 288an ever-growing list of unhandled exceptions, with Promises there can be a 289growing-and-shrinking list of unhandled rejections. 290 291In synchronous code, the `'uncaughtException'` event is emitted when the list of 292unhandled exceptions grows. 293 294In asynchronous code, the `'unhandledRejection'` event is emitted when the list 295of unhandled rejections grows, and the `'rejectionHandled'` event is emitted 296when the list of unhandled rejections shrinks. 297 298```mjs 299import process from 'node:process'; 300 301const unhandledRejections = new Map(); 302process.on('unhandledRejection', (reason, promise) => { 303 unhandledRejections.set(promise, reason); 304}); 305process.on('rejectionHandled', (promise) => { 306 unhandledRejections.delete(promise); 307}); 308``` 309 310```cjs 311const process = require('node:process'); 312 313const unhandledRejections = new Map(); 314process.on('unhandledRejection', (reason, promise) => { 315 unhandledRejections.set(promise, reason); 316}); 317process.on('rejectionHandled', (promise) => { 318 unhandledRejections.delete(promise); 319}); 320``` 321 322In this example, the `unhandledRejections` `Map` will grow and shrink over time, 323reflecting rejections that start unhandled and then become handled. It is 324possible to record such errors in an error log, either periodically (which is 325likely best for long-running application) or upon process exit (which is likely 326most convenient for scripts). 327 328### Event: `'uncaughtException'` 329 330<!-- YAML 331added: v0.1.18 332changes: 333 - version: 334 - v12.0.0 335 - v10.17.0 336 pr-url: https://github.com/nodejs/node/pull/26599 337 description: Added the `origin` argument. 338--> 339 340* `err` {Error} The uncaught exception. 341* `origin` {string} Indicates if the exception originates from an unhandled 342 rejection or from a synchronous error. Can either be `'uncaughtException'` or 343 `'unhandledRejection'`. The latter is used when an exception happens in a 344 `Promise` based async context (or if a `Promise` is rejected) and 345 [`--unhandled-rejections`][] flag set to `strict` or `throw` (which is the 346 default) and the rejection is not handled, or when a rejection happens during 347 the command line entry point's ES module static loading phase. 348 349The `'uncaughtException'` event is emitted when an uncaught JavaScript 350exception bubbles all the way back to the event loop. By default, Node.js 351handles such exceptions by printing the stack trace to `stderr` and exiting 352with code 1, overriding any previously set [`process.exitCode`][]. 353Adding a handler for the `'uncaughtException'` event overrides this default 354behavior. Alternatively, change the [`process.exitCode`][] in the 355`'uncaughtException'` handler which will result in the process exiting with the 356provided exit code. Otherwise, in the presence of such handler the process will 357exit with 0. 358 359```mjs 360import process from 'node:process'; 361 362process.on('uncaughtException', (err, origin) => { 363 fs.writeSync( 364 process.stderr.fd, 365 `Caught exception: ${err}\n` + 366 `Exception origin: ${origin}`, 367 ); 368}); 369 370setTimeout(() => { 371 console.log('This will still run.'); 372}, 500); 373 374// Intentionally cause an exception, but don't catch it. 375nonexistentFunc(); 376console.log('This will not run.'); 377``` 378 379```cjs 380const process = require('node:process'); 381 382process.on('uncaughtException', (err, origin) => { 383 fs.writeSync( 384 process.stderr.fd, 385 `Caught exception: ${err}\n` + 386 `Exception origin: ${origin}`, 387 ); 388}); 389 390setTimeout(() => { 391 console.log('This will still run.'); 392}, 500); 393 394// Intentionally cause an exception, but don't catch it. 395nonexistentFunc(); 396console.log('This will not run.'); 397``` 398 399It is possible to monitor `'uncaughtException'` events without overriding the 400default behavior to exit the process by installing a 401`'uncaughtExceptionMonitor'` listener. 402 403#### Warning: Using `'uncaughtException'` correctly 404 405`'uncaughtException'` is a crude mechanism for exception handling 406intended to be used only as a last resort. The event _should not_ be used as 407an equivalent to `On Error Resume Next`. Unhandled exceptions inherently mean 408that an application is in an undefined state. Attempting to resume application 409code without properly recovering from the exception can cause additional 410unforeseen and unpredictable issues. 411 412Exceptions thrown from within the event handler will not be caught. Instead the 413process will exit with a non-zero exit code and the stack trace will be printed. 414This is to avoid infinite recursion. 415 416Attempting to resume normally after an uncaught exception can be similar to 417pulling out the power cord when upgrading a computer. Nine out of ten 418times, nothing happens. But the tenth time, the system becomes corrupted. 419 420The correct use of `'uncaughtException'` is to perform synchronous cleanup 421of allocated resources (e.g. file descriptors, handles, etc) before shutting 422down the process. **It is not safe to resume normal operation after 423`'uncaughtException'`.** 424 425To restart a crashed application in a more reliable way, whether 426`'uncaughtException'` is emitted or not, an external monitor should be employed 427in a separate process to detect application failures and recover or restart as 428needed. 429 430### Event: `'uncaughtExceptionMonitor'` 431 432<!-- YAML 433added: 434 - v13.7.0 435 - v12.17.0 436--> 437 438* `err` {Error} The uncaught exception. 439* `origin` {string} Indicates if the exception originates from an unhandled 440 rejection or from synchronous errors. Can either be `'uncaughtException'` or 441 `'unhandledRejection'`. The latter is used when an exception happens in a 442 `Promise` based async context (or if a `Promise` is rejected) and 443 [`--unhandled-rejections`][] flag set to `strict` or `throw` (which is the 444 default) and the rejection is not handled, or when a rejection happens during 445 the command line entry point's ES module static loading phase. 446 447The `'uncaughtExceptionMonitor'` event is emitted before an 448`'uncaughtException'` event is emitted or a hook installed via 449[`process.setUncaughtExceptionCaptureCallback()`][] is called. 450 451Installing an `'uncaughtExceptionMonitor'` listener does not change the behavior 452once an `'uncaughtException'` event is emitted. The process will 453still crash if no `'uncaughtException'` listener is installed. 454 455```mjs 456import process from 'node:process'; 457 458process.on('uncaughtExceptionMonitor', (err, origin) => { 459 MyMonitoringTool.logSync(err, origin); 460}); 461 462// Intentionally cause an exception, but don't catch it. 463nonexistentFunc(); 464// Still crashes Node.js 465``` 466 467```cjs 468const process = require('node:process'); 469 470process.on('uncaughtExceptionMonitor', (err, origin) => { 471 MyMonitoringTool.logSync(err, origin); 472}); 473 474// Intentionally cause an exception, but don't catch it. 475nonexistentFunc(); 476// Still crashes Node.js 477``` 478 479### Event: `'unhandledRejection'` 480 481<!-- YAML 482added: v1.4.1 483changes: 484 - version: v7.0.0 485 pr-url: https://github.com/nodejs/node/pull/8217 486 description: Not handling `Promise` rejections is deprecated. 487 - version: v6.6.0 488 pr-url: https://github.com/nodejs/node/pull/8223 489 description: Unhandled `Promise` rejections will now emit 490 a process warning. 491--> 492 493* `reason` {Error|any} The object with which the promise was rejected 494 (typically an [`Error`][] object). 495* `promise` {Promise} The rejected promise. 496 497The `'unhandledRejection'` event is emitted whenever a `Promise` is rejected and 498no error handler is attached to the promise within a turn of the event loop. 499When programming with Promises, exceptions are encapsulated as "rejected 500promises". Rejections can be caught and handled using [`promise.catch()`][] and 501are propagated through a `Promise` chain. The `'unhandledRejection'` event is 502useful for detecting and keeping track of promises that were rejected whose 503rejections have not yet been handled. 504 505```mjs 506import process from 'node:process'; 507 508process.on('unhandledRejection', (reason, promise) => { 509 console.log('Unhandled Rejection at:', promise, 'reason:', reason); 510 // Application specific logging, throwing an error, or other logic here 511}); 512 513somePromise.then((res) => { 514 return reportToUser(JSON.pasre(res)); // Note the typo (`pasre`) 515}); // No `.catch()` or `.then()` 516``` 517 518```cjs 519const process = require('node:process'); 520 521process.on('unhandledRejection', (reason, promise) => { 522 console.log('Unhandled Rejection at:', promise, 'reason:', reason); 523 // Application specific logging, throwing an error, or other logic here 524}); 525 526somePromise.then((res) => { 527 return reportToUser(JSON.pasre(res)); // Note the typo (`pasre`) 528}); // No `.catch()` or `.then()` 529``` 530 531The following will also trigger the `'unhandledRejection'` event to be 532emitted: 533 534```mjs 535import process from 'node:process'; 536 537function SomeResource() { 538 // Initially set the loaded status to a rejected promise 539 this.loaded = Promise.reject(new Error('Resource not yet loaded!')); 540} 541 542const resource = new SomeResource(); 543// no .catch or .then on resource.loaded for at least a turn 544``` 545 546```cjs 547const process = require('node:process'); 548 549function SomeResource() { 550 // Initially set the loaded status to a rejected promise 551 this.loaded = Promise.reject(new Error('Resource not yet loaded!')); 552} 553 554const resource = new SomeResource(); 555// no .catch or .then on resource.loaded for at least a turn 556``` 557 558In this example case, it is possible to track the rejection as a developer error 559as would typically be the case for other `'unhandledRejection'` events. To 560address such failures, a non-operational 561[`.catch(() => { })`][`promise.catch()`] handler may be attached to 562`resource.loaded`, which would prevent the `'unhandledRejection'` event from 563being emitted. 564 565### Event: `'warning'` 566 567<!-- YAML 568added: v6.0.0 569--> 570 571* `warning` {Error} Key properties of the warning are: 572 * `name` {string} The name of the warning. **Default:** `'Warning'`. 573 * `message` {string} A system-provided description of the warning. 574 * `stack` {string} A stack trace to the location in the code where the warning 575 was issued. 576 577The `'warning'` event is emitted whenever Node.js emits a process warning. 578 579A process warning is similar to an error in that it describes exceptional 580conditions that are being brought to the user's attention. However, warnings 581are not part of the normal Node.js and JavaScript error handling flow. 582Node.js can emit warnings whenever it detects bad coding practices that could 583lead to sub-optimal application performance, bugs, or security vulnerabilities. 584 585```mjs 586import process from 'node:process'; 587 588process.on('warning', (warning) => { 589 console.warn(warning.name); // Print the warning name 590 console.warn(warning.message); // Print the warning message 591 console.warn(warning.stack); // Print the stack trace 592}); 593``` 594 595```cjs 596const process = require('node:process'); 597 598process.on('warning', (warning) => { 599 console.warn(warning.name); // Print the warning name 600 console.warn(warning.message); // Print the warning message 601 console.warn(warning.stack); // Print the stack trace 602}); 603``` 604 605By default, Node.js will print process warnings to `stderr`. The `--no-warnings` 606command-line option can be used to suppress the default console output but the 607`'warning'` event will still be emitted by the `process` object. 608 609The following example illustrates the warning that is printed to `stderr` when 610too many listeners have been added to an event: 611 612```console 613$ node 614> events.defaultMaxListeners = 1; 615> process.on('foo', () => {}); 616> process.on('foo', () => {}); 617> (node:38638) MaxListenersExceededWarning: Possible EventEmitter memory leak 618detected. 2 foo listeners added. Use emitter.setMaxListeners() to increase limit 619``` 620 621In contrast, the following example turns off the default warning output and 622adds a custom handler to the `'warning'` event: 623 624```console 625$ node --no-warnings 626> const p = process.on('warning', (warning) => console.warn('Do not do that!')); 627> events.defaultMaxListeners = 1; 628> process.on('foo', () => {}); 629> process.on('foo', () => {}); 630> Do not do that! 631``` 632 633The `--trace-warnings` command-line option can be used to have the default 634console output for warnings include the full stack trace of the warning. 635 636Launching Node.js using the `--throw-deprecation` command-line flag will 637cause custom deprecation warnings to be thrown as exceptions. 638 639Using the `--trace-deprecation` command-line flag will cause the custom 640deprecation to be printed to `stderr` along with the stack trace. 641 642Using the `--no-deprecation` command-line flag will suppress all reporting 643of the custom deprecation. 644 645The `*-deprecation` command-line flags only affect warnings that use the name 646`'DeprecationWarning'`. 647 648### Event: `'worker'` 649 650<!-- YAML 651added: 652 - v16.2.0 653 - v14.18.0 654--> 655 656* `worker` {Worker} The {Worker} that was created. 657 658The `'worker'` event is emitted after a new {Worker} thread has been created. 659 660#### Emitting custom warnings 661 662See the [`process.emitWarning()`][process_emit_warning] method for issuing 663custom or application-specific warnings. 664 665#### Node.js warning names 666 667There are no strict guidelines for warning types (as identified by the `name` 668property) emitted by Node.js. New types of warnings can be added at any time. 669A few of the warning types that are most common include: 670 671* `'DeprecationWarning'` - Indicates use of a deprecated Node.js API or feature. 672 Such warnings must include a `'code'` property identifying the 673 [deprecation code][]. 674* `'ExperimentalWarning'` - Indicates use of an experimental Node.js API or 675 feature. Such features must be used with caution as they may change at any 676 time and are not subject to the same strict semantic-versioning and long-term 677 support policies as supported features. 678* `'MaxListenersExceededWarning'` - Indicates that too many listeners for a 679 given event have been registered on either an `EventEmitter` or `EventTarget`. 680 This is often an indication of a memory leak. 681* `'TimeoutOverflowWarning'` - Indicates that a numeric value that cannot fit 682 within a 32-bit signed integer has been provided to either the `setTimeout()` 683 or `setInterval()` functions. 684* `'UnsupportedWarning'` - Indicates use of an unsupported option or feature 685 that will be ignored rather than treated as an error. One example is use of 686 the HTTP response status message when using the HTTP/2 compatibility API. 687 688### Signal events 689 690<!--type=event--> 691 692<!--name=SIGINT, SIGHUP, etc.--> 693 694Signal events will be emitted when the Node.js process receives a signal. Please 695refer to signal(7) for a listing of standard POSIX signal names such as 696`'SIGINT'`, `'SIGHUP'`, etc. 697 698Signals are not available on [`Worker`][] threads. 699 700The signal handler will receive the signal's name (`'SIGINT'`, 701`'SIGTERM'`, etc.) as the first argument. 702 703The name of each event will be the uppercase common name for the signal (e.g. 704`'SIGINT'` for `SIGINT` signals). 705 706```mjs 707import process from 'node:process'; 708 709// Begin reading from stdin so the process does not exit. 710process.stdin.resume(); 711 712process.on('SIGINT', () => { 713 console.log('Received SIGINT. Press Control-D to exit.'); 714}); 715 716// Using a single function to handle multiple signals 717function handle(signal) { 718 console.log(`Received ${signal}`); 719} 720 721process.on('SIGINT', handle); 722process.on('SIGTERM', handle); 723``` 724 725```cjs 726const process = require('node:process'); 727 728// Begin reading from stdin so the process does not exit. 729process.stdin.resume(); 730 731process.on('SIGINT', () => { 732 console.log('Received SIGINT. Press Control-D to exit.'); 733}); 734 735// Using a single function to handle multiple signals 736function handle(signal) { 737 console.log(`Received ${signal}`); 738} 739 740process.on('SIGINT', handle); 741process.on('SIGTERM', handle); 742``` 743 744* `'SIGUSR1'` is reserved by Node.js to start the [debugger][]. It's possible to 745 install a listener but doing so might interfere with the debugger. 746* `'SIGTERM'` and `'SIGINT'` have default handlers on non-Windows platforms that 747 reset the terminal mode before exiting with code `128 + signal number`. If one 748 of these signals has a listener installed, its default behavior will be 749 removed (Node.js will no longer exit). 750* `'SIGPIPE'` is ignored by default. It can have a listener installed. 751* `'SIGHUP'` is generated on Windows when the console window is closed, and on 752 other platforms under various similar conditions. See signal(7). It can have a 753 listener installed, however Node.js will be unconditionally terminated by 754 Windows about 10 seconds later. On non-Windows platforms, the default 755 behavior of `SIGHUP` is to terminate Node.js, but once a listener has been 756 installed its default behavior will be removed. 757* `'SIGTERM'` is not supported on Windows, it can be listened on. 758* `'SIGINT'` from the terminal is supported on all platforms, and can usually be 759 generated with <kbd>Ctrl</kbd>+<kbd>C</kbd> (though this may be configurable). 760 It is not generated when [terminal raw mode][] is enabled 761 and <kbd>Ctrl</kbd>+<kbd>C</kbd> is used. 762* `'SIGBREAK'` is delivered on Windows when <kbd>Ctrl</kbd>+<kbd>Break</kbd> is 763 pressed. On non-Windows platforms, it can be listened on, but there is no way 764 to send or generate it. 765* `'SIGWINCH'` is delivered when the console has been resized. On Windows, this 766 will only happen on write to the console when the cursor is being moved, or 767 when a readable tty is used in raw mode. 768* `'SIGKILL'` cannot have a listener installed, it will unconditionally 769 terminate Node.js on all platforms. 770* `'SIGSTOP'` cannot have a listener installed. 771* `'SIGBUS'`, `'SIGFPE'`, `'SIGSEGV'`, and `'SIGILL'`, when not raised 772 artificially using kill(2), inherently leave the process in a state from 773 which it is not safe to call JS listeners. Doing so might cause the process 774 to stop responding. 775* `0` can be sent to test for the existence of a process, it has no effect if 776 the process exists, but will throw an error if the process does not exist. 777 778Windows does not support signals so has no equivalent to termination by signal, 779but Node.js offers some emulation with [`process.kill()`][], and 780[`subprocess.kill()`][]: 781 782* Sending `SIGINT`, `SIGTERM`, and `SIGKILL` will cause the unconditional 783 termination of the target process, and afterwards, subprocess will report that 784 the process was terminated by signal. 785* Sending signal `0` can be used as a platform independent way to test for the 786 existence of a process. 787 788## `process.abort()` 789 790<!-- YAML 791added: v0.7.0 792--> 793 794The `process.abort()` method causes the Node.js process to exit immediately and 795generate a core file. 796 797This feature is not available in [`Worker`][] threads. 798 799## `process.allowedNodeEnvironmentFlags` 800 801<!-- YAML 802added: v10.10.0 803--> 804 805* {Set} 806 807The `process.allowedNodeEnvironmentFlags` property is a special, 808read-only `Set` of flags allowable within the [`NODE_OPTIONS`][] 809environment variable. 810 811`process.allowedNodeEnvironmentFlags` extends `Set`, but overrides 812`Set.prototype.has` to recognize several different possible flag 813representations. `process.allowedNodeEnvironmentFlags.has()` will 814return `true` in the following cases: 815 816* Flags may omit leading single (`-`) or double (`--`) dashes; e.g., 817 `inspect-brk` for `--inspect-brk`, or `r` for `-r`. 818* Flags passed through to V8 (as listed in `--v8-options`) may replace 819 one or more _non-leading_ dashes for an underscore, or vice-versa; 820 e.g., `--perf_basic_prof`, `--perf-basic-prof`, `--perf_basic-prof`, 821 etc. 822* Flags may contain one or more equals (`=`) characters; all 823 characters after and including the first equals will be ignored; 824 e.g., `--stack-trace-limit=100`. 825* Flags _must_ be allowable within [`NODE_OPTIONS`][]. 826 827When iterating over `process.allowedNodeEnvironmentFlags`, flags will 828appear only _once_; each will begin with one or more dashes. Flags 829passed through to V8 will contain underscores instead of non-leading 830dashes: 831 832```mjs 833import { allowedNodeEnvironmentFlags } from 'node:process'; 834 835allowedNodeEnvironmentFlags.forEach((flag) => { 836 // -r 837 // --inspect-brk 838 // --abort_on_uncaught_exception 839 // ... 840}); 841``` 842 843```cjs 844const { allowedNodeEnvironmentFlags } = require('node:process'); 845 846allowedNodeEnvironmentFlags.forEach((flag) => { 847 // -r 848 // --inspect-brk 849 // --abort_on_uncaught_exception 850 // ... 851}); 852``` 853 854The methods `add()`, `clear()`, and `delete()` of 855`process.allowedNodeEnvironmentFlags` do nothing, and will fail 856silently. 857 858If Node.js was compiled _without_ [`NODE_OPTIONS`][] support (shown in 859[`process.config`][]), `process.allowedNodeEnvironmentFlags` will 860contain what _would have_ been allowable. 861 862## `process.arch` 863 864<!-- YAML 865added: v0.5.0 866--> 867 868* {string} 869 870The operating system CPU architecture for which the Node.js binary was compiled. 871Possible values are: `'arm'`, `'arm64'`, `'ia32'`, `'mips'`,`'mipsel'`, `'ppc'`, 872`'ppc64'`, `'s390'`, `'s390x'`, and `'x64'`. 873 874```mjs 875import { arch } from 'node:process'; 876 877console.log(`This processor architecture is ${arch}`); 878``` 879 880```cjs 881const { arch } = require('node:process'); 882 883console.log(`This processor architecture is ${arch}`); 884``` 885 886## `process.argv` 887 888<!-- YAML 889added: v0.1.27 890--> 891 892* {string\[]} 893 894The `process.argv` property returns an array containing the command-line 895arguments passed when the Node.js process was launched. The first element will 896be [`process.execPath`][]. See `process.argv0` if access to the original value 897of `argv[0]` is needed. The second element will be the path to the JavaScript 898file being executed. The remaining elements will be any additional command-line 899arguments. 900 901For example, assuming the following script for `process-args.js`: 902 903```mjs 904import { argv } from 'node:process'; 905 906// print process.argv 907argv.forEach((val, index) => { 908 console.log(`${index}: ${val}`); 909}); 910``` 911 912```cjs 913const { argv } = require('node:process'); 914 915// print process.argv 916argv.forEach((val, index) => { 917 console.log(`${index}: ${val}`); 918}); 919``` 920 921Launching the Node.js process as: 922 923```console 924$ node process-args.js one two=three four 925``` 926 927Would generate the output: 928 929```text 9300: /usr/local/bin/node 9311: /Users/mjr/work/node/process-args.js 9322: one 9333: two=three 9344: four 935``` 936 937## `process.argv0` 938 939<!-- YAML 940added: v6.4.0 941--> 942 943* {string} 944 945The `process.argv0` property stores a read-only copy of the original value of 946`argv[0]` passed when Node.js starts. 947 948```console 949$ bash -c 'exec -a customArgv0 ./node' 950> process.argv[0] 951'/Volumes/code/external/node/out/Release/node' 952> process.argv0 953'customArgv0' 954``` 955 956## `process.channel` 957 958<!-- YAML 959added: v7.1.0 960changes: 961 - version: v14.0.0 962 pr-url: https://github.com/nodejs/node/pull/30165 963 description: The object no longer accidentally exposes native C++ bindings. 964--> 965 966* {Object} 967 968If the Node.js process was spawned with an IPC channel (see the 969[Child Process][] documentation), the `process.channel` 970property is a reference to the IPC channel. If no IPC channel exists, this 971property is `undefined`. 972 973### `process.channel.ref()` 974 975<!-- YAML 976added: v7.1.0 977--> 978 979This method makes the IPC channel keep the event loop of the process 980running if `.unref()` has been called before. 981 982Typically, this is managed through the number of `'disconnect'` and `'message'` 983listeners on the `process` object. However, this method can be used to 984explicitly request a specific behavior. 985 986### `process.channel.unref()` 987 988<!-- YAML 989added: v7.1.0 990--> 991 992This method makes the IPC channel not keep the event loop of the process 993running, and lets it finish even while the channel is open. 994 995Typically, this is managed through the number of `'disconnect'` and `'message'` 996listeners on the `process` object. However, this method can be used to 997explicitly request a specific behavior. 998 999## `process.chdir(directory)` 1000 1001<!-- YAML 1002added: v0.1.17 1003--> 1004 1005* `directory` {string} 1006 1007The `process.chdir()` method changes the current working directory of the 1008Node.js process or throws an exception if doing so fails (for instance, if 1009the specified `directory` does not exist). 1010 1011```mjs 1012import { chdir, cwd } from 'node:process'; 1013 1014console.log(`Starting directory: ${cwd()}`); 1015try { 1016 chdir('/tmp'); 1017 console.log(`New directory: ${cwd()}`); 1018} catch (err) { 1019 console.error(`chdir: ${err}`); 1020} 1021``` 1022 1023```cjs 1024const { chdir, cwd } = require('node:process'); 1025 1026console.log(`Starting directory: ${cwd()}`); 1027try { 1028 chdir('/tmp'); 1029 console.log(`New directory: ${cwd()}`); 1030} catch (err) { 1031 console.error(`chdir: ${err}`); 1032} 1033``` 1034 1035This feature is not available in [`Worker`][] threads. 1036 1037## `process.config` 1038 1039<!-- YAML 1040added: v0.7.7 1041changes: 1042 - version: v16.0.0 1043 pr-url: https://github.com/nodejs/node/pull/36902 1044 description: Modifying process.config has been deprecated. 1045--> 1046 1047* {Object} 1048 1049The `process.config` property returns an `Object` containing the JavaScript 1050representation of the configure options used to compile the current Node.js 1051executable. This is the same as the `config.gypi` file that was produced when 1052running the `./configure` script. 1053 1054An example of the possible output looks like: 1055 1056<!-- eslint-skip --> 1057 1058```js 1059{ 1060 target_defaults: 1061 { cflags: [], 1062 default_configuration: 'Release', 1063 defines: [], 1064 include_dirs: [], 1065 libraries: [] }, 1066 variables: 1067 { 1068 host_arch: 'x64', 1069 napi_build_version: 5, 1070 node_install_npm: 'true', 1071 node_prefix: '', 1072 node_shared_cares: 'false', 1073 node_shared_http_parser: 'false', 1074 node_shared_libuv: 'false', 1075 node_shared_zlib: 'false', 1076 node_use_dtrace: 'false', 1077 node_use_openssl: 'true', 1078 node_shared_openssl: 'false', 1079 strict_aliasing: 'true', 1080 target_arch: 'x64', 1081 v8_use_snapshot: 1 1082 } 1083} 1084``` 1085 1086The `process.config` property is **not** read-only and there are existing 1087modules in the ecosystem that are known to extend, modify, or entirely replace 1088the value of `process.config`. 1089 1090Modifying the `process.config` property, or any child-property of the 1091`process.config` object has been deprecated. The `process.config` will be made 1092read-only in a future release. 1093 1094## `process.connected` 1095 1096<!-- YAML 1097added: v0.7.2 1098--> 1099 1100* {boolean} 1101 1102If the Node.js process is spawned with an IPC channel (see the [Child Process][] 1103and [Cluster][] documentation), the `process.connected` property will return 1104`true` so long as the IPC channel is connected and will return `false` after 1105`process.disconnect()` is called. 1106 1107Once `process.connected` is `false`, it is no longer possible to send messages 1108over the IPC channel using `process.send()`. 1109 1110## `process.constrainedMemory()` 1111 1112<!-- YAML 1113added: v18.15.0 1114--> 1115 1116> Stability: 1 - Experimental 1117 1118* {number|undefined} 1119 1120Gets the amount of memory available to the process (in bytes) based on 1121limits imposed by the OS. If there is no such constraint, or the constraint 1122is unknown, `undefined` is returned. 1123 1124See [`uv_get_constrained_memory`][uv_get_constrained_memory] for more 1125information. 1126 1127## `process.cpuUsage([previousValue])` 1128 1129<!-- YAML 1130added: v6.1.0 1131--> 1132 1133* `previousValue` {Object} A previous return value from calling 1134 `process.cpuUsage()` 1135* Returns: {Object} 1136 * `user` {integer} 1137 * `system` {integer} 1138 1139The `process.cpuUsage()` method returns the user and system CPU time usage of 1140the current process, in an object with properties `user` and `system`, whose 1141values are microsecond values (millionth of a second). These values measure time 1142spent in user and system code respectively, and may end up being greater than 1143actual elapsed time if multiple CPU cores are performing work for this process. 1144 1145The result of a previous call to `process.cpuUsage()` can be passed as the 1146argument to the function, to get a diff reading. 1147 1148```mjs 1149import { cpuUsage } from 'node:process'; 1150 1151const startUsage = cpuUsage(); 1152// { user: 38579, system: 6986 } 1153 1154// spin the CPU for 500 milliseconds 1155const now = Date.now(); 1156while (Date.now() - now < 500); 1157 1158console.log(cpuUsage(startUsage)); 1159// { user: 514883, system: 11226 } 1160``` 1161 1162```cjs 1163const { cpuUsage } = require('node:process'); 1164 1165const startUsage = cpuUsage(); 1166// { user: 38579, system: 6986 } 1167 1168// spin the CPU for 500 milliseconds 1169const now = Date.now(); 1170while (Date.now() - now < 500); 1171 1172console.log(cpuUsage(startUsage)); 1173// { user: 514883, system: 11226 } 1174``` 1175 1176## `process.cwd()` 1177 1178<!-- YAML 1179added: v0.1.8 1180--> 1181 1182* Returns: {string} 1183 1184The `process.cwd()` method returns the current working directory of the Node.js 1185process. 1186 1187```mjs 1188import { cwd } from 'node:process'; 1189 1190console.log(`Current directory: ${cwd()}`); 1191``` 1192 1193```cjs 1194const { cwd } = require('node:process'); 1195 1196console.log(`Current directory: ${cwd()}`); 1197``` 1198 1199## `process.debugPort` 1200 1201<!-- YAML 1202added: v0.7.2 1203--> 1204 1205* {number} 1206 1207The port used by the Node.js debugger when enabled. 1208 1209```mjs 1210import process from 'node:process'; 1211 1212process.debugPort = 5858; 1213``` 1214 1215```cjs 1216const process = require('node:process'); 1217 1218process.debugPort = 5858; 1219``` 1220 1221## `process.disconnect()` 1222 1223<!-- YAML 1224added: v0.7.2 1225--> 1226 1227If the Node.js process is spawned with an IPC channel (see the [Child Process][] 1228and [Cluster][] documentation), the `process.disconnect()` method will close the 1229IPC channel to the parent process, allowing the child process to exit gracefully 1230once there are no other connections keeping it alive. 1231 1232The effect of calling `process.disconnect()` is the same as calling 1233[`ChildProcess.disconnect()`][] from the parent process. 1234 1235If the Node.js process was not spawned with an IPC channel, 1236`process.disconnect()` will be `undefined`. 1237 1238## `process.dlopen(module, filename[, flags])` 1239 1240<!-- YAML 1241added: v0.1.16 1242changes: 1243 - version: v9.0.0 1244 pr-url: https://github.com/nodejs/node/pull/12794 1245 description: Added support for the `flags` argument. 1246--> 1247 1248* `module` {Object} 1249* `filename` {string} 1250* `flags` {os.constants.dlopen} **Default:** `os.constants.dlopen.RTLD_LAZY` 1251 1252The `process.dlopen()` method allows dynamically loading shared objects. It is 1253primarily used by `require()` to load C++ Addons, and should not be used 1254directly, except in special cases. In other words, [`require()`][] should be 1255preferred over `process.dlopen()` unless there are specific reasons such as 1256custom dlopen flags or loading from ES modules. 1257 1258The `flags` argument is an integer that allows to specify dlopen 1259behavior. See the [`os.constants.dlopen`][] documentation for details. 1260 1261An important requirement when calling `process.dlopen()` is that the `module` 1262instance must be passed. Functions exported by the C++ Addon are then 1263accessible via `module.exports`. 1264 1265The example below shows how to load a C++ Addon, named `local.node`, 1266that exports a `foo` function. All the symbols are loaded before 1267the call returns, by passing the `RTLD_NOW` constant. In this example 1268the constant is assumed to be available. 1269 1270```mjs 1271import { dlopen } from 'node:process'; 1272import { constants } from 'node:os'; 1273import { fileURLToPath } from 'node:url'; 1274 1275const module = { exports: {} }; 1276dlopen(module, fileURLToPath(new URL('local.node', import.meta.url)), 1277 constants.dlopen.RTLD_NOW); 1278module.exports.foo(); 1279``` 1280 1281```cjs 1282const { dlopen } = require('node:process'); 1283const { constants } = require('node:os'); 1284const { join } = require('node:path'); 1285 1286const module = { exports: {} }; 1287dlopen(module, join(__dirname, 'local.node'), constants.dlopen.RTLD_NOW); 1288module.exports.foo(); 1289``` 1290 1291## `process.emitWarning(warning[, options])` 1292 1293<!-- YAML 1294added: v8.0.0 1295--> 1296 1297* `warning` {string|Error} The warning to emit. 1298* `options` {Object} 1299 * `type` {string} When `warning` is a `String`, `type` is the name to use 1300 for the _type_ of warning being emitted. **Default:** `'Warning'`. 1301 * `code` {string} A unique identifier for the warning instance being emitted. 1302 * `ctor` {Function} When `warning` is a `String`, `ctor` is an optional 1303 function used to limit the generated stack trace. **Default:** 1304 `process.emitWarning`. 1305 * `detail` {string} Additional text to include with the error. 1306 1307The `process.emitWarning()` method can be used to emit custom or application 1308specific process warnings. These can be listened for by adding a handler to the 1309[`'warning'`][process_warning] event. 1310 1311```mjs 1312import { emitWarning } from 'node:process'; 1313 1314// Emit a warning with a code and additional detail. 1315emitWarning('Something happened!', { 1316 code: 'MY_WARNING', 1317 detail: 'This is some additional information', 1318}); 1319// Emits: 1320// (node:56338) [MY_WARNING] Warning: Something happened! 1321// This is some additional information 1322``` 1323 1324```cjs 1325const { emitWarning } = require('node:process'); 1326 1327// Emit a warning with a code and additional detail. 1328emitWarning('Something happened!', { 1329 code: 'MY_WARNING', 1330 detail: 'This is some additional information', 1331}); 1332// Emits: 1333// (node:56338) [MY_WARNING] Warning: Something happened! 1334// This is some additional information 1335``` 1336 1337In this example, an `Error` object is generated internally by 1338`process.emitWarning()` and passed through to the 1339[`'warning'`][process_warning] handler. 1340 1341```mjs 1342import process from 'node:process'; 1343 1344process.on('warning', (warning) => { 1345 console.warn(warning.name); // 'Warning' 1346 console.warn(warning.message); // 'Something happened!' 1347 console.warn(warning.code); // 'MY_WARNING' 1348 console.warn(warning.stack); // Stack trace 1349 console.warn(warning.detail); // 'This is some additional information' 1350}); 1351``` 1352 1353```cjs 1354const process = require('node:process'); 1355 1356process.on('warning', (warning) => { 1357 console.warn(warning.name); // 'Warning' 1358 console.warn(warning.message); // 'Something happened!' 1359 console.warn(warning.code); // 'MY_WARNING' 1360 console.warn(warning.stack); // Stack trace 1361 console.warn(warning.detail); // 'This is some additional information' 1362}); 1363``` 1364 1365If `warning` is passed as an `Error` object, the `options` argument is ignored. 1366 1367## `process.emitWarning(warning[, type[, code]][, ctor])` 1368 1369<!-- YAML 1370added: v6.0.0 1371--> 1372 1373* `warning` {string|Error} The warning to emit. 1374* `type` {string} When `warning` is a `String`, `type` is the name to use 1375 for the _type_ of warning being emitted. **Default:** `'Warning'`. 1376* `code` {string} A unique identifier for the warning instance being emitted. 1377* `ctor` {Function} When `warning` is a `String`, `ctor` is an optional 1378 function used to limit the generated stack trace. **Default:** 1379 `process.emitWarning`. 1380 1381The `process.emitWarning()` method can be used to emit custom or application 1382specific process warnings. These can be listened for by adding a handler to the 1383[`'warning'`][process_warning] event. 1384 1385```mjs 1386import { emitWarning } from 'node:process'; 1387 1388// Emit a warning using a string. 1389emitWarning('Something happened!'); 1390// Emits: (node: 56338) Warning: Something happened! 1391``` 1392 1393```cjs 1394const { emitWarning } = require('node:process'); 1395 1396// Emit a warning using a string. 1397emitWarning('Something happened!'); 1398// Emits: (node: 56338) Warning: Something happened! 1399``` 1400 1401```mjs 1402import { emitWarning } from 'node:process'; 1403 1404// Emit a warning using a string and a type. 1405emitWarning('Something Happened!', 'CustomWarning'); 1406// Emits: (node:56338) CustomWarning: Something Happened! 1407``` 1408 1409```cjs 1410const { emitWarning } = require('node:process'); 1411 1412// Emit a warning using a string and a type. 1413emitWarning('Something Happened!', 'CustomWarning'); 1414// Emits: (node:56338) CustomWarning: Something Happened! 1415``` 1416 1417```mjs 1418import { emitWarning } from 'node:process'; 1419 1420emitWarning('Something happened!', 'CustomWarning', 'WARN001'); 1421// Emits: (node:56338) [WARN001] CustomWarning: Something happened! 1422``` 1423 1424```cjs 1425const { emitWarning } = require('node:process'); 1426 1427process.emitWarning('Something happened!', 'CustomWarning', 'WARN001'); 1428// Emits: (node:56338) [WARN001] CustomWarning: Something happened! 1429``` 1430 1431In each of the previous examples, an `Error` object is generated internally by 1432`process.emitWarning()` and passed through to the [`'warning'`][process_warning] 1433handler. 1434 1435```mjs 1436import process from 'node:process'; 1437 1438process.on('warning', (warning) => { 1439 console.warn(warning.name); 1440 console.warn(warning.message); 1441 console.warn(warning.code); 1442 console.warn(warning.stack); 1443}); 1444``` 1445 1446```cjs 1447const process = require('node:process'); 1448 1449process.on('warning', (warning) => { 1450 console.warn(warning.name); 1451 console.warn(warning.message); 1452 console.warn(warning.code); 1453 console.warn(warning.stack); 1454}); 1455``` 1456 1457If `warning` is passed as an `Error` object, it will be passed through to the 1458`'warning'` event handler unmodified (and the optional `type`, 1459`code` and `ctor` arguments will be ignored): 1460 1461```mjs 1462import { emitWarning } from 'node:process'; 1463 1464// Emit a warning using an Error object. 1465const myWarning = new Error('Something happened!'); 1466// Use the Error name property to specify the type name 1467myWarning.name = 'CustomWarning'; 1468myWarning.code = 'WARN001'; 1469 1470emitWarning(myWarning); 1471// Emits: (node:56338) [WARN001] CustomWarning: Something happened! 1472``` 1473 1474```cjs 1475const { emitWarning } = require('node:process'); 1476 1477// Emit a warning using an Error object. 1478const myWarning = new Error('Something happened!'); 1479// Use the Error name property to specify the type name 1480myWarning.name = 'CustomWarning'; 1481myWarning.code = 'WARN001'; 1482 1483emitWarning(myWarning); 1484// Emits: (node:56338) [WARN001] CustomWarning: Something happened! 1485``` 1486 1487A `TypeError` is thrown if `warning` is anything other than a string or `Error` 1488object. 1489 1490While process warnings use `Error` objects, the process warning 1491mechanism is **not** a replacement for normal error handling mechanisms. 1492 1493The following additional handling is implemented if the warning `type` is 1494`'DeprecationWarning'`: 1495 1496* If the `--throw-deprecation` command-line flag is used, the deprecation 1497 warning is thrown as an exception rather than being emitted as an event. 1498* If the `--no-deprecation` command-line flag is used, the deprecation 1499 warning is suppressed. 1500* If the `--trace-deprecation` command-line flag is used, the deprecation 1501 warning is printed to `stderr` along with the full stack trace. 1502 1503### Avoiding duplicate warnings 1504 1505As a best practice, warnings should be emitted only once per process. To do 1506so, place the `emitWarning()` behind a boolean. 1507 1508```mjs 1509import { emitWarning } from 'node:process'; 1510 1511function emitMyWarning() { 1512 if (!emitMyWarning.warned) { 1513 emitMyWarning.warned = true; 1514 emitWarning('Only warn once!'); 1515 } 1516} 1517emitMyWarning(); 1518// Emits: (node: 56339) Warning: Only warn once! 1519emitMyWarning(); 1520// Emits nothing 1521``` 1522 1523```cjs 1524const { emitWarning } = require('node:process'); 1525 1526function emitMyWarning() { 1527 if (!emitMyWarning.warned) { 1528 emitMyWarning.warned = true; 1529 emitWarning('Only warn once!'); 1530 } 1531} 1532emitMyWarning(); 1533// Emits: (node: 56339) Warning: Only warn once! 1534emitMyWarning(); 1535// Emits nothing 1536``` 1537 1538## `process.env` 1539 1540<!-- YAML 1541added: v0.1.27 1542changes: 1543 - version: v11.14.0 1544 pr-url: https://github.com/nodejs/node/pull/26544 1545 description: Worker threads will now use a copy of the parent thread's 1546 `process.env` by default, configurable through the `env` 1547 option of the `Worker` constructor. 1548 - version: v10.0.0 1549 pr-url: https://github.com/nodejs/node/pull/18990 1550 description: Implicit conversion of variable value to string is deprecated. 1551--> 1552 1553* {Object} 1554 1555The `process.env` property returns an object containing the user environment. 1556See environ(7). 1557 1558An example of this object looks like: 1559 1560<!-- eslint-skip --> 1561 1562```js 1563{ 1564 TERM: 'xterm-256color', 1565 SHELL: '/usr/local/bin/bash', 1566 USER: 'maciej', 1567 PATH: '~/.bin/:/usr/bin:/bin:/usr/sbin:/sbin:/usr/local/bin', 1568 PWD: '/Users/maciej', 1569 EDITOR: 'vim', 1570 SHLVL: '1', 1571 HOME: '/Users/maciej', 1572 LOGNAME: 'maciej', 1573 _: '/usr/local/bin/node' 1574} 1575``` 1576 1577It is possible to modify this object, but such modifications will not be 1578reflected outside the Node.js process, or (unless explicitly requested) 1579to other [`Worker`][] threads. 1580In other words, the following example would not work: 1581 1582```console 1583$ node -e 'process.env.foo = "bar"' && echo $foo 1584``` 1585 1586While the following will: 1587 1588```mjs 1589import { env } from 'node:process'; 1590 1591env.foo = 'bar'; 1592console.log(env.foo); 1593``` 1594 1595```cjs 1596const { env } = require('node:process'); 1597 1598env.foo = 'bar'; 1599console.log(env.foo); 1600``` 1601 1602Assigning a property on `process.env` will implicitly convert the value 1603to a string. **This behavior is deprecated.** Future versions of Node.js may 1604throw an error when the value is not a string, number, or boolean. 1605 1606```mjs 1607import { env } from 'node:process'; 1608 1609env.test = null; 1610console.log(env.test); 1611// => 'null' 1612env.test = undefined; 1613console.log(env.test); 1614// => 'undefined' 1615``` 1616 1617```cjs 1618const { env } = require('node:process'); 1619 1620env.test = null; 1621console.log(env.test); 1622// => 'null' 1623env.test = undefined; 1624console.log(env.test); 1625// => 'undefined' 1626``` 1627 1628Use `delete` to delete a property from `process.env`. 1629 1630```mjs 1631import { env } from 'node:process'; 1632 1633env.TEST = 1; 1634delete env.TEST; 1635console.log(env.TEST); 1636// => undefined 1637``` 1638 1639```cjs 1640const { env } = require('node:process'); 1641 1642env.TEST = 1; 1643delete env.TEST; 1644console.log(env.TEST); 1645// => undefined 1646``` 1647 1648On Windows operating systems, environment variables are case-insensitive. 1649 1650```mjs 1651import { env } from 'node:process'; 1652 1653env.TEST = 1; 1654console.log(env.test); 1655// => 1 1656``` 1657 1658```cjs 1659const { env } = require('node:process'); 1660 1661env.TEST = 1; 1662console.log(env.test); 1663// => 1 1664``` 1665 1666Unless explicitly specified when creating a [`Worker`][] instance, 1667each [`Worker`][] thread has its own copy of `process.env`, based on its 1668parent thread's `process.env`, or whatever was specified as the `env` option 1669to the [`Worker`][] constructor. Changes to `process.env` will not be visible 1670across [`Worker`][] threads, and only the main thread can make changes that 1671are visible to the operating system or to native add-ons. On Windows, a copy of 1672`process.env` on a [`Worker`][] instance operates in a case-sensitive manner 1673unlike the main thread. 1674 1675## `process.execArgv` 1676 1677<!-- YAML 1678added: v0.7.7 1679--> 1680 1681* {string\[]} 1682 1683The `process.execArgv` property returns the set of Node.js-specific command-line 1684options passed when the Node.js process was launched. These options do not 1685appear in the array returned by the [`process.argv`][] property, and do not 1686include the Node.js executable, the name of the script, or any options following 1687the script name. These options are useful in order to spawn child processes with 1688the same execution environment as the parent. 1689 1690```console 1691$ node --harmony script.js --version 1692``` 1693 1694Results in `process.execArgv`: 1695 1696<!-- eslint-disable semi --> 1697 1698```js 1699['--harmony'] 1700``` 1701 1702And `process.argv`: 1703 1704<!-- eslint-disable semi --> 1705 1706```js 1707['/usr/local/bin/node', 'script.js', '--version'] 1708``` 1709 1710Refer to [`Worker` constructor][] for the detailed behavior of worker 1711threads with this property. 1712 1713## `process.execPath` 1714 1715<!-- YAML 1716added: v0.1.100 1717--> 1718 1719* {string} 1720 1721The `process.execPath` property returns the absolute pathname of the executable 1722that started the Node.js process. Symbolic links, if any, are resolved. 1723 1724<!-- eslint-disable semi --> 1725 1726```js 1727'/usr/local/bin/node' 1728``` 1729 1730## `process.exit([code])` 1731 1732<!-- YAML 1733added: v0.1.13 1734--> 1735 1736* `code` {integer} The exit code. **Default:** `0`. 1737 1738The `process.exit()` method instructs Node.js to terminate the process 1739synchronously with an exit status of `code`. If `code` is omitted, exit uses 1740either the 'success' code `0` or the value of `process.exitCode` if it has been 1741set. Node.js will not terminate until all the [`'exit'`][] event listeners are 1742called. 1743 1744To exit with a 'failure' code: 1745 1746```mjs 1747import { exit } from 'node:process'; 1748 1749exit(1); 1750``` 1751 1752```cjs 1753const { exit } = require('node:process'); 1754 1755exit(1); 1756``` 1757 1758The shell that executed Node.js should see the exit code as `1`. 1759 1760Calling `process.exit()` will force the process to exit as quickly as possible 1761even if there are still asynchronous operations pending that have not yet 1762completed fully, including I/O operations to `process.stdout` and 1763`process.stderr`. 1764 1765In most situations, it is not actually necessary to call `process.exit()` 1766explicitly. The Node.js process will exit on its own _if there is no additional 1767work pending_ in the event loop. The `process.exitCode` property can be set to 1768tell the process which exit code to use when the process exits gracefully. 1769 1770For instance, the following example illustrates a _misuse_ of the 1771`process.exit()` method that could lead to data printed to stdout being 1772truncated and lost: 1773 1774```mjs 1775import { exit } from 'node:process'; 1776 1777// This is an example of what *not* to do: 1778if (someConditionNotMet()) { 1779 printUsageToStdout(); 1780 exit(1); 1781} 1782``` 1783 1784```cjs 1785const { exit } = require('node:process'); 1786 1787// This is an example of what *not* to do: 1788if (someConditionNotMet()) { 1789 printUsageToStdout(); 1790 exit(1); 1791} 1792``` 1793 1794The reason this is problematic is because writes to `process.stdout` in Node.js 1795are sometimes _asynchronous_ and may occur over multiple ticks of the Node.js 1796event loop. Calling `process.exit()`, however, forces the process to exit 1797_before_ those additional writes to `stdout` can be performed. 1798 1799Rather than calling `process.exit()` directly, the code _should_ set the 1800`process.exitCode` and allow the process to exit naturally by avoiding 1801scheduling any additional work for the event loop: 1802 1803```mjs 1804import process from 'node:process'; 1805 1806// How to properly set the exit code while letting 1807// the process exit gracefully. 1808if (someConditionNotMet()) { 1809 printUsageToStdout(); 1810 process.exitCode = 1; 1811} 1812``` 1813 1814```cjs 1815const process = require('node:process'); 1816 1817// How to properly set the exit code while letting 1818// the process exit gracefully. 1819if (someConditionNotMet()) { 1820 printUsageToStdout(); 1821 process.exitCode = 1; 1822} 1823``` 1824 1825If it is necessary to terminate the Node.js process due to an error condition, 1826throwing an _uncaught_ error and allowing the process to terminate accordingly 1827is safer than calling `process.exit()`. 1828 1829In [`Worker`][] threads, this function stops the current thread rather 1830than the current process. 1831 1832## `process.exitCode` 1833 1834<!-- YAML 1835added: v0.11.8 1836--> 1837 1838* {integer} 1839 1840A number which will be the process exit code, when the process either 1841exits gracefully, or is exited via [`process.exit()`][] without specifying 1842a code. 1843 1844Specifying a code to [`process.exit(code)`][`process.exit()`] will override any 1845previous setting of `process.exitCode`. 1846 1847## `process.getActiveResourcesInfo()` 1848 1849<!-- YAML 1850added: 1851 - v17.3.0 1852 - v16.14.0 1853--> 1854 1855> Stability: 1 - Experimental 1856 1857* Returns: {string\[]} 1858 1859The `process.getActiveResourcesInfo()` method returns an array of strings 1860containing the types of the active resources that are currently keeping the 1861event loop alive. 1862 1863```mjs 1864import { getActiveResourcesInfo } from 'node:process'; 1865import { setTimeout } from 'node:timers'; 1866 1867console.log('Before:', getActiveResourcesInfo()); 1868setTimeout(() => {}, 1000); 1869console.log('After:', getActiveResourcesInfo()); 1870// Prints: 1871// Before: [ 'CloseReq', 'TTYWrap', 'TTYWrap', 'TTYWrap' ] 1872// After: [ 'CloseReq', 'TTYWrap', 'TTYWrap', 'TTYWrap', 'Timeout' ] 1873``` 1874 1875```cjs 1876const { getActiveResourcesInfo } = require('node:process'); 1877const { setTimeout } = require('node:timers'); 1878 1879console.log('Before:', getActiveResourcesInfo()); 1880setTimeout(() => {}, 1000); 1881console.log('After:', getActiveResourcesInfo()); 1882// Prints: 1883// Before: [ 'TTYWrap', 'TTYWrap', 'TTYWrap' ] 1884// After: [ 'TTYWrap', 'TTYWrap', 'TTYWrap', 'Timeout' ] 1885``` 1886 1887## `process.getegid()` 1888 1889<!-- YAML 1890added: v2.0.0 1891--> 1892 1893The `process.getegid()` method returns the numerical effective group identity 1894of the Node.js process. (See getegid(2).) 1895 1896```mjs 1897import process from 'node:process'; 1898 1899if (process.getegid) { 1900 console.log(`Current gid: ${process.getegid()}`); 1901} 1902``` 1903 1904```cjs 1905const process = require('node:process'); 1906 1907if (process.getegid) { 1908 console.log(`Current gid: ${process.getegid()}`); 1909} 1910``` 1911 1912This function is only available on POSIX platforms (i.e. not Windows or 1913Android). 1914 1915## `process.geteuid()` 1916 1917<!-- YAML 1918added: v2.0.0 1919--> 1920 1921* Returns: {Object} 1922 1923The `process.geteuid()` method returns the numerical effective user identity of 1924the process. (See geteuid(2).) 1925 1926```mjs 1927import process from 'node:process'; 1928 1929if (process.geteuid) { 1930 console.log(`Current uid: ${process.geteuid()}`); 1931} 1932``` 1933 1934```cjs 1935const process = require('node:process'); 1936 1937if (process.geteuid) { 1938 console.log(`Current uid: ${process.geteuid()}`); 1939} 1940``` 1941 1942This function is only available on POSIX platforms (i.e. not Windows or 1943Android). 1944 1945## `process.getgid()` 1946 1947<!-- YAML 1948added: v0.1.31 1949--> 1950 1951* Returns: {Object} 1952 1953The `process.getgid()` method returns the numerical group identity of the 1954process. (See getgid(2).) 1955 1956```mjs 1957import process from 'node:process'; 1958 1959if (process.getgid) { 1960 console.log(`Current gid: ${process.getgid()}`); 1961} 1962``` 1963 1964```cjs 1965const process = require('node:process'); 1966 1967if (process.getgid) { 1968 console.log(`Current gid: ${process.getgid()}`); 1969} 1970``` 1971 1972This function is only available on POSIX platforms (i.e. not Windows or 1973Android). 1974 1975## `process.getgroups()` 1976 1977<!-- YAML 1978added: v0.9.4 1979--> 1980 1981* Returns: {integer\[]} 1982 1983The `process.getgroups()` method returns an array with the supplementary group 1984IDs. POSIX leaves it unspecified if the effective group ID is included but 1985Node.js ensures it always is. 1986 1987```mjs 1988import process from 'node:process'; 1989 1990if (process.getgroups) { 1991 console.log(process.getgroups()); // [ 16, 21, 297 ] 1992} 1993``` 1994 1995```cjs 1996const process = require('node:process'); 1997 1998if (process.getgroups) { 1999 console.log(process.getgroups()); // [ 16, 21, 297 ] 2000} 2001``` 2002 2003This function is only available on POSIX platforms (i.e. not Windows or 2004Android). 2005 2006## `process.getuid()` 2007 2008<!-- YAML 2009added: v0.1.28 2010--> 2011 2012* Returns: {integer} 2013 2014The `process.getuid()` method returns the numeric user identity of the process. 2015(See getuid(2).) 2016 2017```mjs 2018import process from 'node:process'; 2019 2020if (process.getuid) { 2021 console.log(`Current uid: ${process.getuid()}`); 2022} 2023``` 2024 2025```cjs 2026const process = require('node:process'); 2027 2028if (process.getuid) { 2029 console.log(`Current uid: ${process.getuid()}`); 2030} 2031``` 2032 2033This function is only available on POSIX platforms (i.e. not Windows or 2034Android). 2035 2036## `process.hasUncaughtExceptionCaptureCallback()` 2037 2038<!-- YAML 2039added: v9.3.0 2040--> 2041 2042* Returns: {boolean} 2043 2044Indicates whether a callback has been set using 2045[`process.setUncaughtExceptionCaptureCallback()`][]. 2046 2047## `process.hrtime([time])` 2048 2049<!-- YAML 2050added: v0.7.6 2051--> 2052 2053> Stability: 3 - Legacy. Use [`process.hrtime.bigint()`][] instead. 2054 2055* `time` {integer\[]} The result of a previous call to `process.hrtime()` 2056* Returns: {integer\[]} 2057 2058This is the legacy version of [`process.hrtime.bigint()`][] 2059before `bigint` was introduced in JavaScript. 2060 2061The `process.hrtime()` method returns the current high-resolution real time 2062in a `[seconds, nanoseconds]` tuple `Array`, where `nanoseconds` is the 2063remaining part of the real time that can't be represented in second precision. 2064 2065`time` is an optional parameter that must be the result of a previous 2066`process.hrtime()` call to diff with the current time. If the parameter 2067passed in is not a tuple `Array`, a `TypeError` will be thrown. Passing in a 2068user-defined array instead of the result of a previous call to 2069`process.hrtime()` will lead to undefined behavior. 2070 2071These times are relative to an arbitrary time in the 2072past, and not related to the time of day and therefore not subject to clock 2073drift. The primary use is for measuring performance between intervals: 2074 2075```mjs 2076import { hrtime } from 'node:process'; 2077 2078const NS_PER_SEC = 1e9; 2079const time = hrtime(); 2080// [ 1800216, 25 ] 2081 2082setTimeout(() => { 2083 const diff = hrtime(time); 2084 // [ 1, 552 ] 2085 2086 console.log(`Benchmark took ${diff[0] * NS_PER_SEC + diff[1]} nanoseconds`); 2087 // Benchmark took 1000000552 nanoseconds 2088}, 1000); 2089``` 2090 2091```cjs 2092const { hrtime } = require('node:process'); 2093 2094const NS_PER_SEC = 1e9; 2095const time = hrtime(); 2096// [ 1800216, 25 ] 2097 2098setTimeout(() => { 2099 const diff = hrtime(time); 2100 // [ 1, 552 ] 2101 2102 console.log(`Benchmark took ${diff[0] * NS_PER_SEC + diff[1]} nanoseconds`); 2103 // Benchmark took 1000000552 nanoseconds 2104}, 1000); 2105``` 2106 2107## `process.hrtime.bigint()` 2108 2109<!-- YAML 2110added: v10.7.0 2111--> 2112 2113* Returns: {bigint} 2114 2115The `bigint` version of the [`process.hrtime()`][] method returning the 2116current high-resolution real time in nanoseconds as a `bigint`. 2117 2118Unlike [`process.hrtime()`][], it does not support an additional `time` 2119argument since the difference can just be computed directly 2120by subtraction of the two `bigint`s. 2121 2122```mjs 2123import { hrtime } from 'node:process'; 2124 2125const start = hrtime.bigint(); 2126// 191051479007711n 2127 2128setTimeout(() => { 2129 const end = hrtime.bigint(); 2130 // 191052633396993n 2131 2132 console.log(`Benchmark took ${end - start} nanoseconds`); 2133 // Benchmark took 1154389282 nanoseconds 2134}, 1000); 2135``` 2136 2137```cjs 2138const { hrtime } = require('node:process'); 2139 2140const start = hrtime.bigint(); 2141// 191051479007711n 2142 2143setTimeout(() => { 2144 const end = hrtime.bigint(); 2145 // 191052633396993n 2146 2147 console.log(`Benchmark took ${end - start} nanoseconds`); 2148 // Benchmark took 1154389282 nanoseconds 2149}, 1000); 2150``` 2151 2152## `process.initgroups(user, extraGroup)` 2153 2154<!-- YAML 2155added: v0.9.4 2156--> 2157 2158* `user` {string|number} The user name or numeric identifier. 2159* `extraGroup` {string|number} A group name or numeric identifier. 2160 2161The `process.initgroups()` method reads the `/etc/group` file and initializes 2162the group access list, using all groups of which the user is a member. This is 2163a privileged operation that requires that the Node.js process either have `root` 2164access or the `CAP_SETGID` capability. 2165 2166Use care when dropping privileges: 2167 2168```mjs 2169import { getgroups, initgroups, setgid } from 'node:process'; 2170 2171console.log(getgroups()); // [ 0 ] 2172initgroups('nodeuser', 1000); // switch user 2173console.log(getgroups()); // [ 27, 30, 46, 1000, 0 ] 2174setgid(1000); // drop root gid 2175console.log(getgroups()); // [ 27, 30, 46, 1000 ] 2176``` 2177 2178```cjs 2179const { getgroups, initgroups, setgid } = require('node:process'); 2180 2181console.log(getgroups()); // [ 0 ] 2182initgroups('nodeuser', 1000); // switch user 2183console.log(getgroups()); // [ 27, 30, 46, 1000, 0 ] 2184setgid(1000); // drop root gid 2185console.log(getgroups()); // [ 27, 30, 46, 1000 ] 2186``` 2187 2188This function is only available on POSIX platforms (i.e. not Windows or 2189Android). 2190This feature is not available in [`Worker`][] threads. 2191 2192## `process.kill(pid[, signal])` 2193 2194<!-- YAML 2195added: v0.0.6 2196--> 2197 2198* `pid` {number} A process ID 2199* `signal` {string|number} The signal to send, either as a string or number. 2200 **Default:** `'SIGTERM'`. 2201 2202The `process.kill()` method sends the `signal` to the process identified by 2203`pid`. 2204 2205Signal names are strings such as `'SIGINT'` or `'SIGHUP'`. See [Signal Events][] 2206and kill(2) for more information. 2207 2208This method will throw an error if the target `pid` does not exist. As a special 2209case, a signal of `0` can be used to test for the existence of a process. 2210Windows platforms will throw an error if the `pid` is used to kill a process 2211group. 2212 2213Even though the name of this function is `process.kill()`, it is really just a 2214signal sender, like the `kill` system call. The signal sent may do something 2215other than kill the target process. 2216 2217```mjs 2218import process, { kill } from 'node:process'; 2219 2220process.on('SIGHUP', () => { 2221 console.log('Got SIGHUP signal.'); 2222}); 2223 2224setTimeout(() => { 2225 console.log('Exiting.'); 2226 process.exit(0); 2227}, 100); 2228 2229kill(process.pid, 'SIGHUP'); 2230``` 2231 2232```cjs 2233const process = require('node:process'); 2234 2235process.on('SIGHUP', () => { 2236 console.log('Got SIGHUP signal.'); 2237}); 2238 2239setTimeout(() => { 2240 console.log('Exiting.'); 2241 process.exit(0); 2242}, 100); 2243 2244process.kill(process.pid, 'SIGHUP'); 2245``` 2246 2247When `SIGUSR1` is received by a Node.js process, Node.js will start the 2248debugger. See [Signal Events][]. 2249 2250## `process.mainModule` 2251 2252<!-- YAML 2253added: v0.1.17 2254deprecated: v14.0.0 2255--> 2256 2257> Stability: 0 - Deprecated: Use [`require.main`][] instead. 2258 2259* {Object} 2260 2261The `process.mainModule` property provides an alternative way of retrieving 2262[`require.main`][]. The difference is that if the main module changes at 2263runtime, [`require.main`][] may still refer to the original main module in 2264modules that were required before the change occurred. Generally, it's 2265safe to assume that the two refer to the same module. 2266 2267As with [`require.main`][], `process.mainModule` will be `undefined` if there 2268is no entry script. 2269 2270## `process.memoryUsage()` 2271 2272<!-- YAML 2273added: v0.1.16 2274changes: 2275 - version: 2276 - v13.9.0 2277 - v12.17.0 2278 pr-url: https://github.com/nodejs/node/pull/31550 2279 description: Added `arrayBuffers` to the returned object. 2280 - version: v7.2.0 2281 pr-url: https://github.com/nodejs/node/pull/9587 2282 description: Added `external` to the returned object. 2283--> 2284 2285* Returns: {Object} 2286 * `rss` {integer} 2287 * `heapTotal` {integer} 2288 * `heapUsed` {integer} 2289 * `external` {integer} 2290 * `arrayBuffers` {integer} 2291 2292Returns an object describing the memory usage of the Node.js process measured in 2293bytes. 2294 2295```mjs 2296import { memoryUsage } from 'node:process'; 2297 2298console.log(memoryUsage()); 2299// Prints: 2300// { 2301// rss: 4935680, 2302// heapTotal: 1826816, 2303// heapUsed: 650472, 2304// external: 49879, 2305// arrayBuffers: 9386 2306// } 2307``` 2308 2309```cjs 2310const { memoryUsage } = require('node:process'); 2311 2312console.log(memoryUsage()); 2313// Prints: 2314// { 2315// rss: 4935680, 2316// heapTotal: 1826816, 2317// heapUsed: 650472, 2318// external: 49879, 2319// arrayBuffers: 9386 2320// } 2321``` 2322 2323* `heapTotal` and `heapUsed` refer to V8's memory usage. 2324* `external` refers to the memory usage of C++ objects bound to JavaScript 2325 objects managed by V8. 2326* `rss`, Resident Set Size, is the amount of space occupied in the main 2327 memory device (that is a subset of the total allocated memory) for the 2328 process, including all C++ and JavaScript objects and code. 2329* `arrayBuffers` refers to memory allocated for `ArrayBuffer`s and 2330 `SharedArrayBuffer`s, including all Node.js [`Buffer`][]s. 2331 This is also included in the `external` value. When Node.js is used as an 2332 embedded library, this value may be `0` because allocations for `ArrayBuffer`s 2333 may not be tracked in that case. 2334 2335When using [`Worker`][] threads, `rss` will be a value that is valid for the 2336entire process, while the other fields will only refer to the current thread. 2337 2338The `process.memoryUsage()` method iterates over each page to gather 2339information about memory usage which might be slow depending on the 2340program memory allocations. 2341 2342## `process.memoryUsage.rss()` 2343 2344<!-- YAML 2345added: 2346 - v15.6.0 2347 - v14.18.0 2348--> 2349 2350* Returns: {integer} 2351 2352The `process.memoryUsage.rss()` method returns an integer representing the 2353Resident Set Size (RSS) in bytes. 2354 2355The Resident Set Size, is the amount of space occupied in the main 2356memory device (that is a subset of the total allocated memory) for the 2357process, including all C++ and JavaScript objects and code. 2358 2359This is the same value as the `rss` property provided by `process.memoryUsage()` 2360but `process.memoryUsage.rss()` is faster. 2361 2362```mjs 2363import { memoryUsage } from 'node:process'; 2364 2365console.log(memoryUsage.rss()); 2366// 35655680 2367``` 2368 2369```cjs 2370const { memoryUsage } = require('node:process'); 2371 2372console.log(memoryUsage.rss()); 2373// 35655680 2374``` 2375 2376## `process.nextTick(callback[, ...args])` 2377 2378<!-- YAML 2379added: v0.1.26 2380changes: 2381 - version: v18.0.0 2382 pr-url: https://github.com/nodejs/node/pull/41678 2383 description: Passing an invalid callback to the `callback` argument 2384 now throws `ERR_INVALID_ARG_TYPE` instead of 2385 `ERR_INVALID_CALLBACK`. 2386 - version: v1.8.1 2387 pr-url: https://github.com/nodejs/node/pull/1077 2388 description: Additional arguments after `callback` are now supported. 2389--> 2390 2391* `callback` {Function} 2392* `...args` {any} Additional arguments to pass when invoking the `callback` 2393 2394`process.nextTick()` adds `callback` to the "next tick queue". This queue is 2395fully drained after the current operation on the JavaScript stack runs to 2396completion and before the event loop is allowed to continue. It's possible to 2397create an infinite loop if one were to recursively call `process.nextTick()`. 2398See the [Event Loop][] guide for more background. 2399 2400```mjs 2401import { nextTick } from 'node:process'; 2402 2403console.log('start'); 2404nextTick(() => { 2405 console.log('nextTick callback'); 2406}); 2407console.log('scheduled'); 2408// Output: 2409// start 2410// scheduled 2411// nextTick callback 2412``` 2413 2414```cjs 2415const { nextTick } = require('node:process'); 2416 2417console.log('start'); 2418nextTick(() => { 2419 console.log('nextTick callback'); 2420}); 2421console.log('scheduled'); 2422// Output: 2423// start 2424// scheduled 2425// nextTick callback 2426``` 2427 2428This is important when developing APIs in order to give users the opportunity 2429to assign event handlers _after_ an object has been constructed but before any 2430I/O has occurred: 2431 2432```mjs 2433import { nextTick } from 'node:process'; 2434 2435function MyThing(options) { 2436 this.setupOptions(options); 2437 2438 nextTick(() => { 2439 this.startDoingStuff(); 2440 }); 2441} 2442 2443const thing = new MyThing(); 2444thing.getReadyForStuff(); 2445 2446// thing.startDoingStuff() gets called now, not before. 2447``` 2448 2449```cjs 2450const { nextTick } = require('node:process'); 2451 2452function MyThing(options) { 2453 this.setupOptions(options); 2454 2455 nextTick(() => { 2456 this.startDoingStuff(); 2457 }); 2458} 2459 2460const thing = new MyThing(); 2461thing.getReadyForStuff(); 2462 2463// thing.startDoingStuff() gets called now, not before. 2464``` 2465 2466It is very important for APIs to be either 100% synchronous or 100% 2467asynchronous. Consider this example: 2468 2469```js 2470// WARNING! DO NOT USE! BAD UNSAFE HAZARD! 2471function maybeSync(arg, cb) { 2472 if (arg) { 2473 cb(); 2474 return; 2475 } 2476 2477 fs.stat('file', cb); 2478} 2479``` 2480 2481This API is hazardous because in the following case: 2482 2483```js 2484const maybeTrue = Math.random() > 0.5; 2485 2486maybeSync(maybeTrue, () => { 2487 foo(); 2488}); 2489 2490bar(); 2491``` 2492 2493It is not clear whether `foo()` or `bar()` will be called first. 2494 2495The following approach is much better: 2496 2497```mjs 2498import { nextTick } from 'node:process'; 2499 2500function definitelyAsync(arg, cb) { 2501 if (arg) { 2502 nextTick(cb); 2503 return; 2504 } 2505 2506 fs.stat('file', cb); 2507} 2508``` 2509 2510```cjs 2511const { nextTick } = require('node:process'); 2512 2513function definitelyAsync(arg, cb) { 2514 if (arg) { 2515 nextTick(cb); 2516 return; 2517 } 2518 2519 fs.stat('file', cb); 2520} 2521``` 2522 2523### When to use `queueMicrotask()` vs. `process.nextTick()` 2524 2525The [`queueMicrotask()`][] API is an alternative to `process.nextTick()` that 2526also defers execution of a function using the same microtask queue used to 2527execute the then, catch, and finally handlers of resolved promises. Within 2528Node.js, every time the "next tick queue" is drained, the microtask queue 2529is drained immediately after. 2530 2531```mjs 2532import { nextTick } from 'node:process'; 2533 2534Promise.resolve().then(() => console.log(2)); 2535queueMicrotask(() => console.log(3)); 2536nextTick(() => console.log(1)); 2537// Output: 2538// 1 2539// 2 2540// 3 2541``` 2542 2543```cjs 2544const { nextTick } = require('node:process'); 2545 2546Promise.resolve().then(() => console.log(2)); 2547queueMicrotask(() => console.log(3)); 2548nextTick(() => console.log(1)); 2549// Output: 2550// 1 2551// 2 2552// 3 2553``` 2554 2555For _most_ userland use cases, the `queueMicrotask()` API provides a portable 2556and reliable mechanism for deferring execution that works across multiple 2557JavaScript platform environments and should be favored over `process.nextTick()`. 2558In simple scenarios, `queueMicrotask()` can be a drop-in replacement for 2559`process.nextTick()`. 2560 2561```js 2562console.log('start'); 2563queueMicrotask(() => { 2564 console.log('microtask callback'); 2565}); 2566console.log('scheduled'); 2567// Output: 2568// start 2569// scheduled 2570// microtask callback 2571``` 2572 2573One note-worthy difference between the two APIs is that `process.nextTick()` 2574allows specifying additional values that will be passed as arguments to the 2575deferred function when it is called. Achieving the same result with 2576`queueMicrotask()` requires using either a closure or a bound function: 2577 2578```js 2579function deferred(a, b) { 2580 console.log('microtask', a + b); 2581} 2582 2583console.log('start'); 2584queueMicrotask(deferred.bind(undefined, 1, 2)); 2585console.log('scheduled'); 2586// Output: 2587// start 2588// scheduled 2589// microtask 3 2590``` 2591 2592There are minor differences in the way errors raised from within the next tick 2593queue and microtask queue are handled. Errors thrown within a queued microtask 2594callback should be handled within the queued callback when possible. If they are 2595not, the `process.on('uncaughtException')` event handler can be used to capture 2596and handle the errors. 2597 2598When in doubt, unless the specific capabilities of `process.nextTick()` are 2599needed, use `queueMicrotask()`. 2600 2601## `process.noDeprecation` 2602 2603<!-- YAML 2604added: v0.8.0 2605--> 2606 2607* {boolean} 2608 2609The `process.noDeprecation` property indicates whether the `--no-deprecation` 2610flag is set on the current Node.js process. See the documentation for 2611the [`'warning'` event][process_warning] and the 2612[`emitWarning()` method][process_emit_warning] for more information about this 2613flag's behavior. 2614 2615## `process.pid` 2616 2617<!-- YAML 2618added: v0.1.15 2619--> 2620 2621* {integer} 2622 2623The `process.pid` property returns the PID of the process. 2624 2625```mjs 2626import { pid } from 'node:process'; 2627 2628console.log(`This process is pid ${pid}`); 2629``` 2630 2631```cjs 2632const { pid } = require('node:process'); 2633 2634console.log(`This process is pid ${pid}`); 2635``` 2636 2637## `process.platform` 2638 2639<!-- YAML 2640added: v0.1.16 2641--> 2642 2643* {string} 2644 2645The `process.platform` property returns a string identifying the operating 2646system platform for which the Node.js binary was compiled. 2647 2648Currently possible values are: 2649 2650* `'aix'` 2651* `'darwin'` 2652* `'freebsd'` 2653* `'linux'` 2654* `'openbsd'` 2655* `'sunos'` 2656* `'win32'` 2657 2658```mjs 2659import { platform } from 'node:process'; 2660 2661console.log(`This platform is ${platform}`); 2662``` 2663 2664```cjs 2665const { platform } = require('node:process'); 2666 2667console.log(`This platform is ${platform}`); 2668``` 2669 2670The value `'android'` may also be returned if the Node.js is built on the 2671Android operating system. However, Android support in Node.js 2672[is experimental][Android building]. 2673 2674## `process.ppid` 2675 2676<!-- YAML 2677added: 2678 - v9.2.0 2679 - v8.10.0 2680 - v6.13.0 2681--> 2682 2683* {integer} 2684 2685The `process.ppid` property returns the PID of the parent of the 2686current process. 2687 2688```mjs 2689import { ppid } from 'node:process'; 2690 2691console.log(`The parent process is pid ${ppid}`); 2692``` 2693 2694```cjs 2695const { ppid } = require('node:process'); 2696 2697console.log(`The parent process is pid ${ppid}`); 2698``` 2699 2700## `process.release` 2701 2702<!-- YAML 2703added: v3.0.0 2704changes: 2705 - version: v4.2.0 2706 pr-url: https://github.com/nodejs/node/pull/3212 2707 description: The `lts` property is now supported. 2708--> 2709 2710* {Object} 2711 2712The `process.release` property returns an `Object` containing metadata related 2713to the current release, including URLs for the source tarball and headers-only 2714tarball. 2715 2716`process.release` contains the following properties: 2717 2718* `name` {string} A value that will always be `'node'`. 2719* `sourceUrl` {string} an absolute URL pointing to a _`.tar.gz`_ file containing 2720 the source code of the current release. 2721* `headersUrl`{string} an absolute URL pointing to a _`.tar.gz`_ file containing 2722 only the source header files for the current release. This file is 2723 significantly smaller than the full source file and can be used for compiling 2724 Node.js native add-ons. 2725* `libUrl` {string|undefined} an absolute URL pointing to a _`node.lib`_ file 2726 matching the architecture and version of the current release. This file is 2727 used for compiling Node.js native add-ons. _This property is only present on 2728 Windows builds of Node.js and will be missing on all other platforms._ 2729* `lts` {string|undefined} a string label identifying the [LTS][] label for this 2730 release. This property only exists for LTS releases and is `undefined` for all 2731 other release types, including _Current_ releases. Valid values include the 2732 LTS Release code names (including those that are no longer supported). 2733 * `'Fermium'` for the 14.x LTS line beginning with 14.15.0. 2734 * `'Gallium'` for the 16.x LTS line beginning with 16.13.0. 2735 * `'Hydrogen'` for the 18.x LTS line beginning with 18.12.0. 2736 For other LTS Release code names, see [Node.js Changelog Archive](https://github.com/nodejs/node/blob/HEAD/doc/changelogs/CHANGELOG_ARCHIVE.md) 2737 2738<!-- eslint-skip --> 2739 2740```js 2741{ 2742 name: 'node', 2743 lts: 'Hydrogen', 2744 sourceUrl: 'https://nodejs.org/download/release/v18.12.0/node-v18.12.0.tar.gz', 2745 headersUrl: 'https://nodejs.org/download/release/v18.12.0/node-v18.12.0-headers.tar.gz', 2746 libUrl: 'https://nodejs.org/download/release/v18.12.0/win-x64/node.lib' 2747} 2748``` 2749 2750In custom builds from non-release versions of the source tree, only the 2751`name` property may be present. The additional properties should not be 2752relied upon to exist. 2753 2754## `process.report` 2755 2756<!-- YAML 2757added: v11.8.0 2758changes: 2759 - version: 2760 - v13.12.0 2761 - v12.17.0 2762 pr-url: https://github.com/nodejs/node/pull/32242 2763 description: This API is no longer experimental. 2764--> 2765 2766* {Object} 2767 2768`process.report` is an object whose methods are used to generate diagnostic 2769reports for the current process. Additional documentation is available in the 2770[report documentation][]. 2771 2772### `process.report.compact` 2773 2774<!-- YAML 2775added: 2776 - v13.12.0 2777 - v12.17.0 2778--> 2779 2780* {boolean} 2781 2782Write reports in a compact format, single-line JSON, more easily consumable 2783by log processing systems than the default multi-line format designed for 2784human consumption. 2785 2786```mjs 2787import { report } from 'node:process'; 2788 2789console.log(`Reports are compact? ${report.compact}`); 2790``` 2791 2792```cjs 2793const { report } = require('node:process'); 2794 2795console.log(`Reports are compact? ${report.compact}`); 2796``` 2797 2798### `process.report.directory` 2799 2800<!-- YAML 2801added: v11.12.0 2802changes: 2803 - version: 2804 - v13.12.0 2805 - v12.17.0 2806 pr-url: https://github.com/nodejs/node/pull/32242 2807 description: This API is no longer experimental. 2808--> 2809 2810* {string} 2811 2812Directory where the report is written. The default value is the empty string, 2813indicating that reports are written to the current working directory of the 2814Node.js process. 2815 2816```mjs 2817import { report } from 'node:process'; 2818 2819console.log(`Report directory is ${report.directory}`); 2820``` 2821 2822```cjs 2823const { report } = require('node:process'); 2824 2825console.log(`Report directory is ${report.directory}`); 2826``` 2827 2828### `process.report.filename` 2829 2830<!-- YAML 2831added: v11.12.0 2832changes: 2833 - version: 2834 - v13.12.0 2835 - v12.17.0 2836 pr-url: https://github.com/nodejs/node/pull/32242 2837 description: This API is no longer experimental. 2838--> 2839 2840* {string} 2841 2842Filename where the report is written. If set to the empty string, the output 2843filename will be comprised of a timestamp, PID, and sequence number. The default 2844value is the empty string. 2845 2846If the value of `process.report.filename` is set to `'stdout'` or `'stderr'`, 2847the report is written to the stdout or stderr of the process respectively. 2848 2849```mjs 2850import { report } from 'node:process'; 2851 2852console.log(`Report filename is ${report.filename}`); 2853``` 2854 2855```cjs 2856const { report } = require('node:process'); 2857 2858console.log(`Report filename is ${report.filename}`); 2859``` 2860 2861### `process.report.getReport([err])` 2862 2863<!-- YAML 2864added: v11.8.0 2865changes: 2866 - version: 2867 - v13.12.0 2868 - v12.17.0 2869 pr-url: https://github.com/nodejs/node/pull/32242 2870 description: This API is no longer experimental. 2871--> 2872 2873* `err` {Error} A custom error used for reporting the JavaScript stack. 2874* Returns: {Object} 2875 2876Returns a JavaScript Object representation of a diagnostic report for the 2877running process. The report's JavaScript stack trace is taken from `err`, if 2878present. 2879 2880```mjs 2881import { report } from 'node:process'; 2882import util from 'node:util'; 2883 2884const data = report.getReport(); 2885console.log(data.header.nodejsVersion); 2886 2887// Similar to process.report.writeReport() 2888import fs from 'node:fs'; 2889fs.writeFileSync('my-report.log', util.inspect(data), 'utf8'); 2890``` 2891 2892```cjs 2893const { report } = require('node:process'); 2894const util = require('node:util'); 2895 2896const data = report.getReport(); 2897console.log(data.header.nodejsVersion); 2898 2899// Similar to process.report.writeReport() 2900const fs = require('node:fs'); 2901fs.writeFileSync('my-report.log', util.inspect(data), 'utf8'); 2902``` 2903 2904Additional documentation is available in the [report documentation][]. 2905 2906### `process.report.reportOnFatalError` 2907 2908<!-- YAML 2909added: v11.12.0 2910changes: 2911 - version: 2912 - v15.0.0 2913 - v14.17.0 2914 pr-url: https://github.com/nodejs/node/pull/35654 2915 description: This API is no longer experimental. 2916--> 2917 2918* {boolean} 2919 2920If `true`, a diagnostic report is generated on fatal errors, such as out of 2921memory errors or failed C++ assertions. 2922 2923```mjs 2924import { report } from 'node:process'; 2925 2926console.log(`Report on fatal error: ${report.reportOnFatalError}`); 2927``` 2928 2929```cjs 2930const { report } = require('node:process'); 2931 2932console.log(`Report on fatal error: ${report.reportOnFatalError}`); 2933``` 2934 2935### `process.report.reportOnSignal` 2936 2937<!-- YAML 2938added: v11.12.0 2939changes: 2940 - version: 2941 - v13.12.0 2942 - v12.17.0 2943 pr-url: https://github.com/nodejs/node/pull/32242 2944 description: This API is no longer experimental. 2945--> 2946 2947* {boolean} 2948 2949If `true`, a diagnostic report is generated when the process receives the 2950signal specified by `process.report.signal`. 2951 2952```mjs 2953import { report } from 'node:process'; 2954 2955console.log(`Report on signal: ${report.reportOnSignal}`); 2956``` 2957 2958```cjs 2959const { report } = require('node:process'); 2960 2961console.log(`Report on signal: ${report.reportOnSignal}`); 2962``` 2963 2964### `process.report.reportOnUncaughtException` 2965 2966<!-- YAML 2967added: v11.12.0 2968changes: 2969 - version: 2970 - v13.12.0 2971 - v12.17.0 2972 pr-url: https://github.com/nodejs/node/pull/32242 2973 description: This API is no longer experimental. 2974--> 2975 2976* {boolean} 2977 2978If `true`, a diagnostic report is generated on uncaught exception. 2979 2980```mjs 2981import { report } from 'node:process'; 2982 2983console.log(`Report on exception: ${report.reportOnUncaughtException}`); 2984``` 2985 2986```cjs 2987const { report } = require('node:process'); 2988 2989console.log(`Report on exception: ${report.reportOnUncaughtException}`); 2990``` 2991 2992### `process.report.signal` 2993 2994<!-- YAML 2995added: v11.12.0 2996changes: 2997 - version: 2998 - v13.12.0 2999 - v12.17.0 3000 pr-url: https://github.com/nodejs/node/pull/32242 3001 description: This API is no longer experimental. 3002--> 3003 3004* {string} 3005 3006The signal used to trigger the creation of a diagnostic report. Defaults to 3007`'SIGUSR2'`. 3008 3009```mjs 3010import { report } from 'node:process'; 3011 3012console.log(`Report signal: ${report.signal}`); 3013``` 3014 3015```cjs 3016const { report } = require('node:process'); 3017 3018console.log(`Report signal: ${report.signal}`); 3019``` 3020 3021### `process.report.writeReport([filename][, err])` 3022 3023<!-- YAML 3024added: v11.8.0 3025changes: 3026 - version: 3027 - v13.12.0 3028 - v12.17.0 3029 pr-url: https://github.com/nodejs/node/pull/32242 3030 description: This API is no longer experimental. 3031--> 3032 3033* `filename` {string} Name of the file where the report is written. This 3034 should be a relative path, that will be appended to the directory specified in 3035 `process.report.directory`, or the current working directory of the Node.js 3036 process, if unspecified. 3037 3038* `err` {Error} A custom error used for reporting the JavaScript stack. 3039 3040* Returns: {string} Returns the filename of the generated report. 3041 3042Writes a diagnostic report to a file. If `filename` is not provided, the default 3043filename includes the date, time, PID, and a sequence number. The report's 3044JavaScript stack trace is taken from `err`, if present. 3045 3046If the value of `filename` is set to `'stdout'` or `'stderr'`, the report is 3047written to the stdout or stderr of the process respectively. 3048 3049```mjs 3050import { report } from 'node:process'; 3051 3052report.writeReport(); 3053``` 3054 3055```cjs 3056const { report } = require('node:process'); 3057 3058report.writeReport(); 3059``` 3060 3061Additional documentation is available in the [report documentation][]. 3062 3063## `process.resourceUsage()` 3064 3065<!-- YAML 3066added: v12.6.0 3067--> 3068 3069* Returns: {Object} the resource usage for the current process. All of these 3070 values come from the `uv_getrusage` call which returns 3071 a [`uv_rusage_t` struct][uv_rusage_t]. 3072 * `userCPUTime` {integer} maps to `ru_utime` computed in microseconds. 3073 It is the same value as [`process.cpuUsage().user`][process.cpuUsage]. 3074 * `systemCPUTime` {integer} maps to `ru_stime` computed in microseconds. 3075 It is the same value as [`process.cpuUsage().system`][process.cpuUsage]. 3076 * `maxRSS` {integer} maps to `ru_maxrss` which is the maximum resident set 3077 size used in kilobytes. 3078 * `sharedMemorySize` {integer} maps to `ru_ixrss` but is not supported by 3079 any platform. 3080 * `unsharedDataSize` {integer} maps to `ru_idrss` but is not supported by 3081 any platform. 3082 * `unsharedStackSize` {integer} maps to `ru_isrss` but is not supported by 3083 any platform. 3084 * `minorPageFault` {integer} maps to `ru_minflt` which is the number of 3085 minor page faults for the process, see 3086 [this article for more details][wikipedia_minor_fault]. 3087 * `majorPageFault` {integer} maps to `ru_majflt` which is the number of 3088 major page faults for the process, see 3089 [this article for more details][wikipedia_major_fault]. This field is not 3090 supported on Windows. 3091 * `swappedOut` {integer} maps to `ru_nswap` but is not supported by any 3092 platform. 3093 * `fsRead` {integer} maps to `ru_inblock` which is the number of times the 3094 file system had to perform input. 3095 * `fsWrite` {integer} maps to `ru_oublock` which is the number of times the 3096 file system had to perform output. 3097 * `ipcSent` {integer} maps to `ru_msgsnd` but is not supported by any 3098 platform. 3099 * `ipcReceived` {integer} maps to `ru_msgrcv` but is not supported by any 3100 platform. 3101 * `signalsCount` {integer} maps to `ru_nsignals` but is not supported by any 3102 platform. 3103 * `voluntaryContextSwitches` {integer} maps to `ru_nvcsw` which is the 3104 number of times a CPU context switch resulted due to a process voluntarily 3105 giving up the processor before its time slice was completed (usually to 3106 await availability of a resource). This field is not supported on Windows. 3107 * `involuntaryContextSwitches` {integer} maps to `ru_nivcsw` which is the 3108 number of times a CPU context switch resulted due to a higher priority 3109 process becoming runnable or because the current process exceeded its 3110 time slice. This field is not supported on Windows. 3111 3112```mjs 3113import { resourceUsage } from 'node:process'; 3114 3115console.log(resourceUsage()); 3116/* 3117 Will output: 3118 { 3119 userCPUTime: 82872, 3120 systemCPUTime: 4143, 3121 maxRSS: 33164, 3122 sharedMemorySize: 0, 3123 unsharedDataSize: 0, 3124 unsharedStackSize: 0, 3125 minorPageFault: 2469, 3126 majorPageFault: 0, 3127 swappedOut: 0, 3128 fsRead: 0, 3129 fsWrite: 8, 3130 ipcSent: 0, 3131 ipcReceived: 0, 3132 signalsCount: 0, 3133 voluntaryContextSwitches: 79, 3134 involuntaryContextSwitches: 1 3135 } 3136*/ 3137``` 3138 3139```cjs 3140const { resourceUsage } = require('node:process'); 3141 3142console.log(resourceUsage()); 3143/* 3144 Will output: 3145 { 3146 userCPUTime: 82872, 3147 systemCPUTime: 4143, 3148 maxRSS: 33164, 3149 sharedMemorySize: 0, 3150 unsharedDataSize: 0, 3151 unsharedStackSize: 0, 3152 minorPageFault: 2469, 3153 majorPageFault: 0, 3154 swappedOut: 0, 3155 fsRead: 0, 3156 fsWrite: 8, 3157 ipcSent: 0, 3158 ipcReceived: 0, 3159 signalsCount: 0, 3160 voluntaryContextSwitches: 79, 3161 involuntaryContextSwitches: 1 3162 } 3163*/ 3164``` 3165 3166## `process.send(message[, sendHandle[, options]][, callback])` 3167 3168<!-- YAML 3169added: v0.5.9 3170--> 3171 3172* `message` {Object} 3173* `sendHandle` {net.Server|net.Socket} 3174* `options` {Object} used to parameterize the sending of certain types of 3175 handles.`options` supports the following properties: 3176 * `keepOpen` {boolean} A value that can be used when passing instances of 3177 `net.Socket`. When `true`, the socket is kept open in the sending process. 3178 **Default:** `false`. 3179* `callback` {Function} 3180* Returns: {boolean} 3181 3182If Node.js is spawned with an IPC channel, the `process.send()` method can be 3183used to send messages to the parent process. Messages will be received as a 3184[`'message'`][] event on the parent's [`ChildProcess`][] object. 3185 3186If Node.js was not spawned with an IPC channel, `process.send` will be 3187`undefined`. 3188 3189The message goes through serialization and parsing. The resulting message might 3190not be the same as what is originally sent. 3191 3192## `process.setegid(id)` 3193 3194<!-- YAML 3195added: v2.0.0 3196--> 3197 3198* `id` {string|number} A group name or ID 3199 3200The `process.setegid()` method sets the effective group identity of the process. 3201(See setegid(2).) The `id` can be passed as either a numeric ID or a group 3202name string. If a group name is specified, this method blocks while resolving 3203the associated a numeric ID. 3204 3205```mjs 3206import process from 'node:process'; 3207 3208if (process.getegid && process.setegid) { 3209 console.log(`Current gid: ${process.getegid()}`); 3210 try { 3211 process.setegid(501); 3212 console.log(`New gid: ${process.getegid()}`); 3213 } catch (err) { 3214 console.error(`Failed to set gid: ${err}`); 3215 } 3216} 3217``` 3218 3219```cjs 3220const process = require('node:process'); 3221 3222if (process.getegid && process.setegid) { 3223 console.log(`Current gid: ${process.getegid()}`); 3224 try { 3225 process.setegid(501); 3226 console.log(`New gid: ${process.getegid()}`); 3227 } catch (err) { 3228 console.error(`Failed to set gid: ${err}`); 3229 } 3230} 3231``` 3232 3233This function is only available on POSIX platforms (i.e. not Windows or 3234Android). 3235This feature is not available in [`Worker`][] threads. 3236 3237## `process.seteuid(id)` 3238 3239<!-- YAML 3240added: v2.0.0 3241--> 3242 3243* `id` {string|number} A user name or ID 3244 3245The `process.seteuid()` method sets the effective user identity of the process. 3246(See seteuid(2).) The `id` can be passed as either a numeric ID or a username 3247string. If a username is specified, the method blocks while resolving the 3248associated numeric ID. 3249 3250```mjs 3251import process from 'node:process'; 3252 3253if (process.geteuid && process.seteuid) { 3254 console.log(`Current uid: ${process.geteuid()}`); 3255 try { 3256 process.seteuid(501); 3257 console.log(`New uid: ${process.geteuid()}`); 3258 } catch (err) { 3259 console.error(`Failed to set uid: ${err}`); 3260 } 3261} 3262``` 3263 3264```cjs 3265const process = require('node:process'); 3266 3267if (process.geteuid && process.seteuid) { 3268 console.log(`Current uid: ${process.geteuid()}`); 3269 try { 3270 process.seteuid(501); 3271 console.log(`New uid: ${process.geteuid()}`); 3272 } catch (err) { 3273 console.error(`Failed to set uid: ${err}`); 3274 } 3275} 3276``` 3277 3278This function is only available on POSIX platforms (i.e. not Windows or 3279Android). 3280This feature is not available in [`Worker`][] threads. 3281 3282## `process.setgid(id)` 3283 3284<!-- YAML 3285added: v0.1.31 3286--> 3287 3288* `id` {string|number} The group name or ID 3289 3290The `process.setgid()` method sets the group identity of the process. (See 3291setgid(2).) The `id` can be passed as either a numeric ID or a group name 3292string. If a group name is specified, this method blocks while resolving the 3293associated numeric ID. 3294 3295```mjs 3296import process from 'node:process'; 3297 3298if (process.getgid && process.setgid) { 3299 console.log(`Current gid: ${process.getgid()}`); 3300 try { 3301 process.setgid(501); 3302 console.log(`New gid: ${process.getgid()}`); 3303 } catch (err) { 3304 console.error(`Failed to set gid: ${err}`); 3305 } 3306} 3307``` 3308 3309```cjs 3310const process = require('node:process'); 3311 3312if (process.getgid && process.setgid) { 3313 console.log(`Current gid: ${process.getgid()}`); 3314 try { 3315 process.setgid(501); 3316 console.log(`New gid: ${process.getgid()}`); 3317 } catch (err) { 3318 console.error(`Failed to set gid: ${err}`); 3319 } 3320} 3321``` 3322 3323This function is only available on POSIX platforms (i.e. not Windows or 3324Android). 3325This feature is not available in [`Worker`][] threads. 3326 3327## `process.setgroups(groups)` 3328 3329<!-- YAML 3330added: v0.9.4 3331--> 3332 3333* `groups` {integer\[]} 3334 3335The `process.setgroups()` method sets the supplementary group IDs for the 3336Node.js process. This is a privileged operation that requires the Node.js 3337process to have `root` or the `CAP_SETGID` capability. 3338 3339The `groups` array can contain numeric group IDs, group names, or both. 3340 3341```mjs 3342import process from 'node:process'; 3343 3344if (process.getgroups && process.setgroups) { 3345 try { 3346 process.setgroups([501]); 3347 console.log(process.getgroups()); // new groups 3348 } catch (err) { 3349 console.error(`Failed to set groups: ${err}`); 3350 } 3351} 3352``` 3353 3354```cjs 3355const process = require('node:process'); 3356 3357if (process.getgroups && process.setgroups) { 3358 try { 3359 process.setgroups([501]); 3360 console.log(process.getgroups()); // new groups 3361 } catch (err) { 3362 console.error(`Failed to set groups: ${err}`); 3363 } 3364} 3365``` 3366 3367This function is only available on POSIX platforms (i.e. not Windows or 3368Android). 3369This feature is not available in [`Worker`][] threads. 3370 3371## `process.setuid(id)` 3372 3373<!-- YAML 3374added: v0.1.28 3375--> 3376 3377* `id` {integer | string} 3378 3379The `process.setuid(id)` method sets the user identity of the process. (See 3380setuid(2).) The `id` can be passed as either a numeric ID or a username string. 3381If a username is specified, the method blocks while resolving the associated 3382numeric ID. 3383 3384```mjs 3385import process from 'node:process'; 3386 3387if (process.getuid && process.setuid) { 3388 console.log(`Current uid: ${process.getuid()}`); 3389 try { 3390 process.setuid(501); 3391 console.log(`New uid: ${process.getuid()}`); 3392 } catch (err) { 3393 console.error(`Failed to set uid: ${err}`); 3394 } 3395} 3396``` 3397 3398```cjs 3399const process = require('node:process'); 3400 3401if (process.getuid && process.setuid) { 3402 console.log(`Current uid: ${process.getuid()}`); 3403 try { 3404 process.setuid(501); 3405 console.log(`New uid: ${process.getuid()}`); 3406 } catch (err) { 3407 console.error(`Failed to set uid: ${err}`); 3408 } 3409} 3410``` 3411 3412This function is only available on POSIX platforms (i.e. not Windows or 3413Android). 3414This feature is not available in [`Worker`][] threads. 3415 3416## `process.setSourceMapsEnabled(val)` 3417 3418<!-- YAML 3419added: 3420 - v16.6.0 3421 - v14.18.0 3422--> 3423 3424> Stability: 1 - Experimental 3425 3426* `val` {boolean} 3427 3428This function enables or disables the [Source Map v3][Source Map] support for 3429stack traces. 3430 3431It provides same features as launching Node.js process with commandline options 3432`--enable-source-maps`. 3433 3434Only source maps in JavaScript files that are loaded after source maps has been 3435enabled will be parsed and loaded. 3436 3437## `process.setUncaughtExceptionCaptureCallback(fn)` 3438 3439<!-- YAML 3440added: v9.3.0 3441--> 3442 3443* `fn` {Function|null} 3444 3445The `process.setUncaughtExceptionCaptureCallback()` function sets a function 3446that will be invoked when an uncaught exception occurs, which will receive the 3447exception value itself as its first argument. 3448 3449If such a function is set, the [`'uncaughtException'`][] event will 3450not be emitted. If `--abort-on-uncaught-exception` was passed from the 3451command line or set through [`v8.setFlagsFromString()`][], the process will 3452not abort. Actions configured to take place on exceptions such as report 3453generations will be affected too 3454 3455To unset the capture function, 3456`process.setUncaughtExceptionCaptureCallback(null)` may be used. Calling this 3457method with a non-`null` argument while another capture function is set will 3458throw an error. 3459 3460Using this function is mutually exclusive with using the deprecated 3461[`domain`][] built-in module. 3462 3463## `process.sourceMapsEnabled` 3464 3465<!-- YAML 3466added: v18.19.0 3467--> 3468 3469> Stability: 1 - Experimental 3470 3471* {boolean} 3472 3473The `process.sourceMapsEnabled` property returns whether the 3474[Source Map v3][Source Map] support for stack traces is enabled. 3475 3476## `process.stderr` 3477 3478* {Stream} 3479 3480The `process.stderr` property returns a stream connected to 3481`stderr` (fd `2`). It is a [`net.Socket`][] (which is a [Duplex][] 3482stream) unless fd `2` refers to a file, in which case it is 3483a [Writable][] stream. 3484 3485`process.stderr` differs from other Node.js streams in important ways. See 3486[note on process I/O][] for more information. 3487 3488### `process.stderr.fd` 3489 3490* {number} 3491 3492This property refers to the value of underlying file descriptor of 3493`process.stderr`. The value is fixed at `2`. In [`Worker`][] threads, 3494this field does not exist. 3495 3496## `process.stdin` 3497 3498* {Stream} 3499 3500The `process.stdin` property returns a stream connected to 3501`stdin` (fd `0`). It is a [`net.Socket`][] (which is a [Duplex][] 3502stream) unless fd `0` refers to a file, in which case it is 3503a [Readable][] stream. 3504 3505For details of how to read from `stdin` see [`readable.read()`][]. 3506 3507As a [Duplex][] stream, `process.stdin` can also be used in "old" mode that 3508is compatible with scripts written for Node.js prior to v0.10. 3509For more information see [Stream compatibility][]. 3510 3511In "old" streams mode the `stdin` stream is paused by default, so one 3512must call `process.stdin.resume()` to read from it. Note also that calling 3513`process.stdin.resume()` itself would switch stream to "old" mode. 3514 3515### `process.stdin.fd` 3516 3517* {number} 3518 3519This property refers to the value of underlying file descriptor of 3520`process.stdin`. The value is fixed at `0`. In [`Worker`][] threads, 3521this field does not exist. 3522 3523## `process.stdout` 3524 3525* {Stream} 3526 3527The `process.stdout` property returns a stream connected to 3528`stdout` (fd `1`). It is a [`net.Socket`][] (which is a [Duplex][] 3529stream) unless fd `1` refers to a file, in which case it is 3530a [Writable][] stream. 3531 3532For example, to copy `process.stdin` to `process.stdout`: 3533 3534```mjs 3535import { stdin, stdout } from 'node:process'; 3536 3537stdin.pipe(stdout); 3538``` 3539 3540```cjs 3541const { stdin, stdout } = require('node:process'); 3542 3543stdin.pipe(stdout); 3544``` 3545 3546`process.stdout` differs from other Node.js streams in important ways. See 3547[note on process I/O][] for more information. 3548 3549### `process.stdout.fd` 3550 3551* {number} 3552 3553This property refers to the value of underlying file descriptor of 3554`process.stdout`. The value is fixed at `1`. In [`Worker`][] threads, 3555this field does not exist. 3556 3557### A note on process I/O 3558 3559`process.stdout` and `process.stderr` differ from other Node.js streams in 3560important ways: 3561 35621. They are used internally by [`console.log()`][] and [`console.error()`][], 3563 respectively. 35642. Writes may be synchronous depending on what the stream is connected to 3565 and whether the system is Windows or POSIX: 3566 * Files: _synchronous_ on Windows and POSIX 3567 * TTYs (Terminals): _asynchronous_ on Windows, _synchronous_ on POSIX 3568 * Pipes (and sockets): _synchronous_ on Windows, _asynchronous_ on POSIX 3569 3570These behaviors are partly for historical reasons, as changing them would 3571create backward incompatibility, but they are also expected by some users. 3572 3573Synchronous writes avoid problems such as output written with `console.log()` or 3574`console.error()` being unexpectedly interleaved, or not written at all if 3575`process.exit()` is called before an asynchronous write completes. See 3576[`process.exit()`][] for more information. 3577 3578_**Warning**_: Synchronous writes block the event loop until the write has 3579completed. This can be near instantaneous in the case of output to a file, but 3580under high system load, pipes that are not being read at the receiving end, or 3581with slow terminals or file systems, it's possible for the event loop to be 3582blocked often enough and long enough to have severe negative performance 3583impacts. This may not be a problem when writing to an interactive terminal 3584session, but consider this particularly careful when doing production logging to 3585the process output streams. 3586 3587To check if a stream is connected to a [TTY][] context, check the `isTTY` 3588property. 3589 3590For instance: 3591 3592```console 3593$ node -p "Boolean(process.stdin.isTTY)" 3594true 3595$ echo "foo" | node -p "Boolean(process.stdin.isTTY)" 3596false 3597$ node -p "Boolean(process.stdout.isTTY)" 3598true 3599$ node -p "Boolean(process.stdout.isTTY)" | cat 3600false 3601``` 3602 3603See the [TTY][] documentation for more information. 3604 3605## `process.throwDeprecation` 3606 3607<!-- YAML 3608added: v0.9.12 3609--> 3610 3611* {boolean} 3612 3613The initial value of `process.throwDeprecation` indicates whether the 3614`--throw-deprecation` flag is set on the current Node.js process. 3615`process.throwDeprecation` is mutable, so whether or not deprecation 3616warnings result in errors may be altered at runtime. See the 3617documentation for the [`'warning'` event][process_warning] and the 3618[`emitWarning()` method][process_emit_warning] for more information. 3619 3620```console 3621$ node --throw-deprecation -p "process.throwDeprecation" 3622true 3623$ node -p "process.throwDeprecation" 3624undefined 3625$ node 3626> process.emitWarning('test', 'DeprecationWarning'); 3627undefined 3628> (node:26598) DeprecationWarning: test 3629> process.throwDeprecation = true; 3630true 3631> process.emitWarning('test', 'DeprecationWarning'); 3632Thrown: 3633[DeprecationWarning: test] { name: 'DeprecationWarning' } 3634``` 3635 3636## `process.title` 3637 3638<!-- YAML 3639added: v0.1.104 3640--> 3641 3642* {string} 3643 3644The `process.title` property returns the current process title (i.e. returns 3645the current value of `ps`). Assigning a new value to `process.title` modifies 3646the current value of `ps`. 3647 3648When a new value is assigned, different platforms will impose different maximum 3649length restrictions on the title. Usually such restrictions are quite limited. 3650For instance, on Linux and macOS, `process.title` is limited to the size of the 3651binary name plus the length of the command-line arguments because setting the 3652`process.title` overwrites the `argv` memory of the process. Node.js v0.8 3653allowed for longer process title strings by also overwriting the `environ` 3654memory but that was potentially insecure and confusing in some (rather obscure) 3655cases. 3656 3657Assigning a value to `process.title` might not result in an accurate label 3658within process manager applications such as macOS Activity Monitor or Windows 3659Services Manager. 3660 3661## `process.traceDeprecation` 3662 3663<!-- YAML 3664added: v0.8.0 3665--> 3666 3667* {boolean} 3668 3669The `process.traceDeprecation` property indicates whether the 3670`--trace-deprecation` flag is set on the current Node.js process. See the 3671documentation for the [`'warning'` event][process_warning] and the 3672[`emitWarning()` method][process_emit_warning] for more information about this 3673flag's behavior. 3674 3675## `process.umask()` 3676 3677<!-- YAML 3678added: v0.1.19 3679changes: 3680 - version: 3681 - v14.0.0 3682 - v12.19.0 3683 pr-url: https://github.com/nodejs/node/pull/32499 3684 description: Calling `process.umask()` with no arguments is deprecated. 3685--> 3686 3687> Stability: 0 - Deprecated. Calling `process.umask()` with no argument causes 3688> the process-wide umask to be written twice. This introduces a race condition 3689> between threads, and is a potential security vulnerability. There is no safe, 3690> cross-platform alternative API. 3691 3692`process.umask()` returns the Node.js process's file mode creation mask. Child 3693processes inherit the mask from the parent process. 3694 3695## `process.umask(mask)` 3696 3697<!-- YAML 3698added: v0.1.19 3699--> 3700 3701* `mask` {string|integer} 3702 3703`process.umask(mask)` sets the Node.js process's file mode creation mask. Child 3704processes inherit the mask from the parent process. Returns the previous mask. 3705 3706```mjs 3707import { umask } from 'node:process'; 3708 3709const newmask = 0o022; 3710const oldmask = umask(newmask); 3711console.log( 3712 `Changed umask from ${oldmask.toString(8)} to ${newmask.toString(8)}`, 3713); 3714``` 3715 3716```cjs 3717const { umask } = require('node:process'); 3718 3719const newmask = 0o022; 3720const oldmask = umask(newmask); 3721console.log( 3722 `Changed umask from ${oldmask.toString(8)} to ${newmask.toString(8)}`, 3723); 3724``` 3725 3726In [`Worker`][] threads, `process.umask(mask)` will throw an exception. 3727 3728## `process.uptime()` 3729 3730<!-- YAML 3731added: v0.5.0 3732--> 3733 3734* Returns: {number} 3735 3736The `process.uptime()` method returns the number of seconds the current Node.js 3737process has been running. 3738 3739The return value includes fractions of a second. Use `Math.floor()` to get whole 3740seconds. 3741 3742## `process.version` 3743 3744<!-- YAML 3745added: v0.1.3 3746--> 3747 3748* {string} 3749 3750The `process.version` property contains the Node.js version string. 3751 3752```mjs 3753import { version } from 'node:process'; 3754 3755console.log(`Version: ${version}`); 3756// Version: v14.8.0 3757``` 3758 3759```cjs 3760const { version } = require('node:process'); 3761 3762console.log(`Version: ${version}`); 3763// Version: v14.8.0 3764``` 3765 3766To get the version string without the prepended _v_, use 3767`process.versions.node`. 3768 3769## `process.versions` 3770 3771<!-- YAML 3772added: v0.2.0 3773changes: 3774 - version: v9.0.0 3775 pr-url: https://github.com/nodejs/node/pull/15785 3776 description: The `v8` property now includes a Node.js specific suffix. 3777 - version: v4.2.0 3778 pr-url: https://github.com/nodejs/node/pull/3102 3779 description: The `icu` property is now supported. 3780--> 3781 3782* {Object} 3783 3784The `process.versions` property returns an object listing the version strings of 3785Node.js and its dependencies. `process.versions.modules` indicates the current 3786ABI version, which is increased whenever a C++ API changes. Node.js will refuse 3787to load modules that were compiled against a different module ABI version. 3788 3789```mjs 3790import { versions } from 'node:process'; 3791 3792console.log(versions); 3793``` 3794 3795```cjs 3796const { versions } = require('node:process'); 3797 3798console.log(versions); 3799``` 3800 3801Will generate an object similar to: 3802 3803```console 3804{ node: '11.13.0', 3805 v8: '7.0.276.38-node.18', 3806 uv: '1.27.0', 3807 zlib: '1.2.11', 3808 brotli: '1.0.7', 3809 ares: '1.15.0', 3810 modules: '67', 3811 nghttp2: '1.34.0', 3812 napi: '4', 3813 llhttp: '1.1.1', 3814 openssl: '1.1.1b', 3815 cldr: '34.0', 3816 icu: '63.1', 3817 tz: '2018e', 3818 unicode: '11.0' } 3819``` 3820 3821## Exit codes 3822 3823Node.js will normally exit with a `0` status code when no more async 3824operations are pending. The following status codes are used in other 3825cases: 3826 3827* `1` **Uncaught Fatal Exception**: There was an uncaught exception, 3828 and it was not handled by a domain or an [`'uncaughtException'`][] event 3829 handler. 3830* `2`: Unused (reserved by Bash for builtin misuse) 3831* `3` **Internal JavaScript Parse Error**: The JavaScript source code 3832 internal in the Node.js bootstrapping process caused a parse error. This 3833 is extremely rare, and generally can only happen during development 3834 of Node.js itself. 3835* `4` **Internal JavaScript Evaluation Failure**: The JavaScript 3836 source code internal in the Node.js bootstrapping process failed to 3837 return a function value when evaluated. This is extremely rare, and 3838 generally can only happen during development of Node.js itself. 3839* `5` **Fatal Error**: There was a fatal unrecoverable error in V8. 3840 Typically a message will be printed to stderr with the prefix `FATAL 3841 ERROR`. 3842* `6` **Non-function Internal Exception Handler**: There was an 3843 uncaught exception, but the internal fatal exception handler 3844 function was somehow set to a non-function, and could not be called. 3845* `7` **Internal Exception Handler Run-Time Failure**: There was an 3846 uncaught exception, and the internal fatal exception handler 3847 function itself threw an error while attempting to handle it. This 3848 can happen, for example, if an [`'uncaughtException'`][] or 3849 `domain.on('error')` handler throws an error. 3850* `8`: Unused. In previous versions of Node.js, exit code 8 sometimes 3851 indicated an uncaught exception. 3852* `9` **Invalid Argument**: Either an unknown option was specified, 3853 or an option requiring a value was provided without a value. 3854* `10` **Internal JavaScript Run-Time Failure**: The JavaScript 3855 source code internal in the Node.js bootstrapping process threw an error 3856 when the bootstrapping function was called. This is extremely rare, 3857 and generally can only happen during development of Node.js itself. 3858* `12` **Invalid Debug Argument**: The `--inspect` and/or `--inspect-brk` 3859 options were set, but the port number chosen was invalid or unavailable. 3860* `13` **Unfinished Top-Level Await**: `await` was used outside of a function 3861 in the top-level code, but the passed `Promise` never resolved. 3862* `14` **Snapshot Failure**: Node.js was started to build a V8 startup 3863 snapshot and it failed because certain requirements of the state of 3864 the application were not met. 3865* `>128` **Signal Exits**: If Node.js receives a fatal signal such as 3866 `SIGKILL` or `SIGHUP`, then its exit code will be `128` plus the 3867 value of the signal code. This is a standard POSIX practice, since 3868 exit codes are defined to be 7-bit integers, and signal exits set 3869 the high-order bit, and then contain the value of the signal code. 3870 For example, signal `SIGABRT` has value `6`, so the expected exit 3871 code will be `128` + `6`, or `134`. 3872 3873[Advanced serialization for `child_process`]: child_process.md#advanced-serialization 3874[Android building]: https://github.com/nodejs/node/blob/HEAD/BUILDING.md#androidandroid-based-devices-eg-firefox-os 3875[Child Process]: child_process.md 3876[Cluster]: cluster.md 3877[Duplex]: stream.md#duplex-and-transform-streams 3878[Event Loop]: https://nodejs.org/en/docs/guides/event-loop-timers-and-nexttick/#process-nexttick 3879[LTS]: https://github.com/nodejs/Release 3880[Readable]: stream.md#readable-streams 3881[Signal Events]: #signal-events 3882[Source Map]: https://sourcemaps.info/spec.html 3883[Stream compatibility]: stream.md#compatibility-with-older-nodejs-versions 3884[TTY]: tty.md#tty 3885[Writable]: stream.md#writable-streams 3886[`'exit'`]: #event-exit 3887[`'message'`]: child_process.md#event-message 3888[`'uncaughtException'`]: #event-uncaughtexception 3889[`--unhandled-rejections`]: cli.md#--unhandled-rejectionsmode 3890[`Buffer`]: buffer.md 3891[`ChildProcess.disconnect()`]: child_process.md#subprocessdisconnect 3892[`ChildProcess.send()`]: child_process.md#subprocesssendmessage-sendhandle-options-callback 3893[`ChildProcess`]: child_process.md#class-childprocess 3894[`Error`]: errors.md#class-error 3895[`EventEmitter`]: events.md#class-eventemitter 3896[`NODE_OPTIONS`]: cli.md#node_optionsoptions 3897[`Promise.race()`]: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Promise/race 3898[`Worker`]: worker_threads.md#class-worker 3899[`Worker` constructor]: worker_threads.md#new-workerfilename-options 3900[`console.error()`]: console.md#consoleerrordata-args 3901[`console.log()`]: console.md#consolelogdata-args 3902[`domain`]: domain.md 3903[`net.Server`]: net.md#class-netserver 3904[`net.Socket`]: net.md#class-netsocket 3905[`os.constants.dlopen`]: os.md#dlopen-constants 3906[`process.argv`]: #processargv 3907[`process.config`]: #processconfig 3908[`process.execPath`]: #processexecpath 3909[`process.exit()`]: #processexitcode 3910[`process.exitCode`]: #processexitcode_1 3911[`process.hrtime()`]: #processhrtimetime 3912[`process.hrtime.bigint()`]: #processhrtimebigint 3913[`process.kill()`]: #processkillpid-signal 3914[`process.setUncaughtExceptionCaptureCallback()`]: #processsetuncaughtexceptioncapturecallbackfn 3915[`promise.catch()`]: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Promise/catch 3916[`queueMicrotask()`]: globals.md#queuemicrotaskcallback 3917[`readable.read()`]: stream.md#readablereadsize 3918[`require()`]: globals.md#require 3919[`require.main`]: modules.md#accessing-the-main-module 3920[`subprocess.kill()`]: child_process.md#subprocesskillsignal 3921[`v8.setFlagsFromString()`]: v8.md#v8setflagsfromstringflags 3922[debugger]: debugger.md 3923[deprecation code]: deprecations.md 3924[note on process I/O]: #a-note-on-process-io 3925[process.cpuUsage]: #processcpuusagepreviousvalue 3926[process_emit_warning]: #processemitwarningwarning-type-code-ctor 3927[process_warning]: #event-warning 3928[report documentation]: report.md 3929[terminal raw mode]: tty.md#readstreamsetrawmodemode 3930[uv_get_constrained_memory]: https://docs.libuv.org/en/v1.x/misc.html#c.uv_get_constrained_memory 3931[uv_rusage_t]: https://docs.libuv.org/en/v1.x/misc.html#c.uv_rusage_t 3932[wikipedia_major_fault]: https://en.wikipedia.org/wiki/Page_fault#Major 3933[wikipedia_minor_fault]: https://en.wikipedia.org/wiki/Page_fault#Minor 3934