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