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