-
-
Notifications
You must be signed in to change notification settings - Fork 35.5k
Expand file tree
/
Copy pathprocess.md
More file actions
2578 lines (2047 loc) Β· 78.5 KB
/
process.md
File metadata and controls
2578 lines (2047 loc) Β· 78.5 KB
Edit and raw actions
OlderNewer
Β
1
# Process
2
3
<!-- introduced_in=v0.10.0 -->
4
<!-- type=global -->
5
6
The `process` object is a `global` that provides information about, and control
7
over, the current Node.js process. As a global, it is always available to
8
Node.js applications without using `require()`. It can also be explicitly
9
accessed using `require()`:
10
11
```js
12
const process = require('process');
13
```
14
15
## Process Events
16
17
The `process` object is an instance of [`EventEmitter`][].
18
19
### Event: `'beforeExit'`
20
<!-- YAML
21
added: v0.11.12
22
-->
23
24
The `'beforeExit'` event is emitted when Node.js empties its event loop and has
25
no additional work to schedule. Normally, the Node.js process will exit when
26
there is no work scheduled, but a listener registered on the `'beforeExit'`
27
event can make asynchronous calls, and thereby cause the Node.js process to
28
continue.
29
30
The listener callback function is invoked with the value of
31
[`process.exitCode`][] passed as the only argument.
32
33
The `'beforeExit'` event is *not* emitted for conditions causing explicit
34
termination, such as calling [`process.exit()`][] or uncaught exceptions.
35
36
The `'beforeExit'` should *not* be used as an alternative to the `'exit'` event
37
unless the intention is to schedule additional work.
38
39
```js
40
process.on('beforeExit', (code) => {
41
console.log('Process beforeExit event with code: ', code);
42
});
43
44
process.on('exit', (code) => {
45
console.log('Process exit event with code: ', code);
46
});
47
48
console.log('This message is displayed first.');
49
50
// Prints:
51
// This message is displayed first.
52
// Process beforeExit event with code: 0
53
// Process exit event with code: 0
54
```
55
56
### Event: `'disconnect'`
57
<!-- YAML
58
added: v0.7.7
59
-->
60
61
If the Node.js process is spawned with an IPC channel (see the [Child Process][]
62
and [Cluster][] documentation), the `'disconnect'` event will be emitted when
63
the IPC channel is closed.
64
65
### Event: `'exit'`
66
<!-- YAML
67
added: v0.1.7
68
-->
69
70
* `code` {integer}
71
72
The `'exit'` event is emitted when the Node.js process is about to exit as a
73
result of either:
74
75
* The `process.exit()` method being called explicitly;
76
* The Node.js event loop no longer having any additional work to perform.
77
78
There is no way to prevent the exiting of the event loop at this point, and once
79
all `'exit'` listeners have finished running the Node.js process will terminate.
80
81
The listener callback function is invoked with the exit code specified either
82
by the [`process.exitCode`][] property, or the `exitCode` argument passed to the
83
[`process.exit()`][] method.
84
85
```js
86
process.on('exit', (code) => {
87
console.log(`About to exit with code: ${code}`);
88
});
89
```
90
91
Listener functions **must** only perform **synchronous** operations. The Node.js
92
process will exit immediately after calling the `'exit'` event listeners
93
causing any additional work still queued in the event loop to be abandoned.
94
In the following example, for instance, the timeout will never occur:
95
96
```js
97
process.on('exit', (code) => {
98
setTimeout(() => {
99
console.log('This will not run');
100
}, 0);
101
});
102
```
103
104
### Event: `'message'`
105
<!-- YAML
106
added: v0.5.10
107
-->
108
109
* `message` { Object | boolean | number | string | null } a parsed JSON object
110
or a serializable primitive value.
111
* `sendHandle` {net.Server|net.Socket} a [`net.Server`][] or [`net.Socket`][]
112
object, or undefined.
113
114
If the Node.js process is spawned with an IPC channel (see the [Child Process][]
115
and [Cluster][] documentation), the `'message'` event is emitted whenever a
116
message sent by a parent process using [`childprocess.send()`][] is received by
117
the child process.
118
119
The message goes through serialization and parsing. The resulting message might
120
not be the same as what is originally sent.
121
122
If the `serialization` option was set to `advanced` used when spawning the
123
process, the `message` argument can contain data that JSON is not able
124
to represent.
125
See [Advanced Serialization for `child_process`][] for more details.
126
127
### Event: `'multipleResolves'`
128
<!-- YAML
129
added: v10.12.0
130
-->
131
132
* `type` {string} The resolution type. One of `'resolve'` or `'reject'`.
133
* `promise` {Promise} The promise that resolved or rejected more than once.
134
* `value` {any} The value with which the promise was either resolved or
135
rejected after the original resolve.
136
137
The `'multipleResolves'` event is emitted whenever a `Promise` has been either:
138
139
* Resolved more than once.
140
* Rejected more than once.
141
* Rejected after resolve.
142
* Resolved after reject.
143
144
This is useful for tracking potential errors in an application while using the
145
`Promise` constructor, as multiple resolutions are silently swallowed. However,
146
the occurrence of this event does not necessarily indicate an error. For
147
example, [`Promise.race()`][] can trigger a `'multipleResolves'` event.
148
149
```js
150
process.on('multipleResolves', (type, promise, reason) => {
151
console.error(type, promise, reason);
152
setImmediate(() => process.exit(1));
153
});
154
155
async function main() {
156
try {
157
return await new Promise((resolve, reject) => {
158
resolve('First call');
159
resolve('Swallowed resolve');
160
reject(new Error('Swallowed reject'));
161
});
162
} catch {
163
throw new Error('Failed');
164
}
165
}
166
167
main().then(console.log);
168
// resolve: Promise { 'First call' } 'Swallowed resolve'
169
// reject: Promise { 'First call' } Error: Swallowed reject
170
// at Promise (*)
171
// at new Promise (<anonymous>)
172
// at main (*)
173
// First call
174
```
175
176
### Event: `'rejectionHandled'`
177
<!-- YAML
178
added: v1.4.1
179
-->
180
181
* `promise` {Promise} The late handled promise.
182
183
The `'rejectionHandled'` event is emitted whenever a `Promise` has been rejected
184
and an error handler was attached to it (using [`promise.catch()`][], for
185
example) later than one turn of the Node.js event loop.
186
187
The `Promise` object would have previously been emitted in an
188
`'unhandledRejection'` event, but during the course of processing gained a
189
rejection handler.
190
191
There is no notion of a top level for a `Promise` chain at which rejections can
192
always be handled. Being inherently asynchronous in nature, a `Promise`
193
rejection can be handled at a future point in time β possibly much later than
194
the event loop turn it takes for the `'unhandledRejection'` event to be emitted.
195
196
Another way of stating this is that, unlike in synchronous code where there is
197
an ever-growing list of unhandled exceptions, with Promises there can be a
198
growing-and-shrinking list of unhandled rejections.
199
200
In synchronous code, the `'uncaughtException'` event is emitted when the list of
201
unhandled exceptions grows.
202
203
In asynchronous code, the `'unhandledRejection'` event is emitted when the list
204
of unhandled rejections grows, and the `'rejectionHandled'` event is emitted
205
when the list of unhandled rejections shrinks.
206
207
```js
208
const unhandledRejections = new Map();
209
process.on('unhandledRejection', (reason, promise) => {
210
unhandledRejections.set(promise, reason);
211
});
212
process.on('rejectionHandled', (promise) => {
213
unhandledRejections.delete(promise);
214
});
215
```
216
217
In this example, the `unhandledRejections` `Map` will grow and shrink over time,
218
reflecting rejections that start unhandled and then become handled. It is
219
possible to record such errors in an error log, either periodically (which is
220
likely best for long-running application) or upon process exit (which is likely
221
most convenient for scripts).
222
223
### Event: `'uncaughtException'`
224
<!-- YAML
225
added: v0.1.18
226
changes:
227
- version: v12.0.0
228
pr-url: https://github.com/nodejs/node/pull/26599
229
description: Added the `origin` argument.
230
-->
231
232
* `err` {Error} The uncaught exception.
233
* `origin` {string} Indicates if the exception originates from an unhandled
234
rejection or from synchronous errors. Can either be `'uncaughtException'` or
235
`'unhandledRejection'`.
236
237
The `'uncaughtException'` event is emitted when an uncaught JavaScript
238
exception bubbles all the way back to the event loop. By default, Node.js
239
handles such exceptions by printing the stack trace to `stderr` and exiting
240
with code 1, overriding any previously set [`process.exitCode`][].
241
Adding a handler for the `'uncaughtException'` event overrides this default
242
behavior. Alternatively, change the [`process.exitCode`][] in the
243
`'uncaughtException'` handler which will result in the process exiting with the
244
provided exit code. Otherwise, in the presence of such handler the process will
245
exit with 0.
246
247
```js
248
process.on('uncaughtException', (err, origin) => {
249
fs.writeSync(
250
process.stderr.fd,
251
`Caught exception: ${err}\n` +
252
`Exception origin: ${origin}`
253
);
254
});
255
256
setTimeout(() => {
257
console.log('This will still run.');
258
}, 500);
259
260
// Intentionally cause an exception, but don't catch it.
261
nonexistentFunc();
262
console.log('This will not run.');
263
```
264
265
It is possible to monitor `'uncaughtException'` events without overriding the
266
default behavior to exit the process by installing a
267
`'uncaughtExceptionMonitor'` listener.
268
269
#### Warning: Using `'uncaughtException'` correctly
270
271
`'uncaughtException'` is a crude mechanism for exception handling
272
intended to be used only as a last resort. The event *should not* be used as
273
an equivalent to `On Error Resume Next`. Unhandled exceptions inherently mean
274
that an application is in an undefined state. Attempting to resume application
275
code without properly recovering from the exception can cause additional
276
unforeseen and unpredictable issues.
277
278
Exceptions thrown from within the event handler will not be caught. Instead the
279
process will exit with a non-zero exit code and the stack trace will be printed.
280
This is to avoid infinite recursion.
281
282
Attempting to resume normally after an uncaught exception can be similar to
283
pulling out the power cord when upgrading a computer. Nine out of ten
284
times, nothing happens. But the tenth time, the system becomes corrupted.
285
286
The correct use of `'uncaughtException'` is to perform synchronous cleanup
287
of allocated resources (e.g. file descriptors, handles, etc) before shutting
288
down the process. **It is not safe to resume normal operation after
289
`'uncaughtException'`.**
290
291
To restart a crashed application in a more reliable way, whether
292
`'uncaughtException'` is emitted or not, an external monitor should be employed
293
in a separate process to detect application failures and recover or restart as
294
needed.
295
296
### Event: `'uncaughtExceptionMonitor'`
297
<!-- YAML
298
added: v13.7.0
299
-->
300
301
* `err` {Error} The uncaught exception.
302
* `origin` {string} Indicates if the exception originates from an unhandled
303
rejection or from synchronous errors. Can either be `'uncaughtException'` or
304
`'unhandledRejection'`.
305
306
The `'uncaughtExceptionMonitor'` event is emitted before an
307
`'uncaughtException'` event is emitted or a hook installed via
308
[`process.setUncaughtExceptionCaptureCallback()`][] is called.
309
310
Installing an `'uncaughtExceptionMonitor'` listener does not change the behavior
311
once an `'uncaughtException'` event is emitted. The process will
312
still crash if no `'uncaughtException'` listener is installed.
313
314
```js
315
process.on('uncaughtExceptionMonitor', (err, origin) => {
316
MyMonitoringTool.logSync(err, origin);
317
});
318
319
// Intentionally cause an exception, but don't catch it.
320
nonexistentFunc();
321
// Still crashes Node.js
322
```
323
324
### Event: `'unhandledRejection'`
325
<!-- YAML
326
added: v1.4.1
327
changes:
328
- version: v7.0.0
329
pr-url: https://github.com/nodejs/node/pull/8217
330
description: Not handling `Promise` rejections is deprecated.
331
- version: v6.6.0
332
pr-url: https://github.com/nodejs/node/pull/8223
333
description: Unhandled `Promise` rejections will now emit
334
a process warning.
335
-->
336
337
* `reason` {Error|any} The object with which the promise was rejected
338
(typically an [`Error`][] object).
339
* `promise` {Promise} The rejected promise.
340
341
The `'unhandledRejection'` event is emitted whenever a `Promise` is rejected and
342
no error handler is attached to the promise within a turn of the event loop.
343
When programming with Promises, exceptions are encapsulated as "rejected
344
promises". Rejections can be caught and handled using [`promise.catch()`][] and
345
are propagated through a `Promise` chain. The `'unhandledRejection'` event is
346
useful for detecting and keeping track of promises that were rejected whose
347
rejections have not yet been handled.
348
349
```js
350
process.on('unhandledRejection', (reason, promise) => {
351
console.log('Unhandled Rejection at:', promise, 'reason:', reason);
352
// Application specific logging, throwing an error, or other logic here
353
});
354
355
somePromise.then((res) => {
356
return reportToUser(JSON.pasre(res)); // Note the typo (`pasre`)
357
}); // No `.catch()` or `.then()`
358
```
359
360
The following will also trigger the `'unhandledRejection'` event to be
361
emitted:
362
363
```js
364
function SomeResource() {
365
// Initially set the loaded status to a rejected promise
366
this.loaded = Promise.reject(new Error('Resource not yet loaded!'));
367
}
368
369
const resource = new SomeResource();
370
// no .catch or .then on resource.loaded for at least a turn
371
```
372
373
In this example case, it is possible to track the rejection as a developer error
374
as would typically be the case for other `'unhandledRejection'` events. To
375
address such failures, a non-operational
376
[`.catch(() => { })`][`promise.catch()`] handler may be attached to
377
`resource.loaded`, which would prevent the `'unhandledRejection'` event from
378
being emitted.
379
380
### Event: `'warning'`
381
<!-- YAML
382
added: v6.0.0
383
-->
384
385
* `warning` {Error} Key properties of the warning are:
386
* `name` {string} The name of the warning. **Default:** `'Warning'`.
387
* `message` {string} A system-provided description of the warning.
388
* `stack` {string} A stack trace to the location in the code where the warning
389
was issued.
390
391
The `'warning'` event is emitted whenever Node.js emits a process warning.
392
393
A process warning is similar to an error in that it describes exceptional
394
conditions that are being brought to the user's attention. However, warnings
395
are not part of the normal Node.js and JavaScript error handling flow.
396
Node.js can emit warnings whenever it detects bad coding practices that could
397
lead to sub-optimal application performance, bugs, or security vulnerabilities.
398
399
```js
400
process.on('warning', (warning) => {
401
console.warn(warning.name); // Print the warning name
402
console.warn(warning.message); // Print the warning message
403
console.warn(warning.stack); // Print the stack trace
404
});
405
```
406
407
By default, Node.js will print process warnings to `stderr`. The `--no-warnings`
408
command-line option can be used to suppress the default console output but the
409
`'warning'` event will still be emitted by the `process` object.
410
411
The following example illustrates the warning that is printed to `stderr` when
412
too many listeners have been added to an event:
413
414
```console
415
$ node
416
> events.defaultMaxListeners = 1;
417
> process.on('foo', () => {});
418
> process.on('foo', () => {});
419
> (node:38638) MaxListenersExceededWarning: Possible EventEmitter memory leak
420
detected. 2 foo listeners added. Use emitter.setMaxListeners() to increase limit
421
```
422
423
In contrast, the following example turns off the default warning output and
424
adds a custom handler to the `'warning'` event:
425
426
```console
427
$ node --no-warnings
428
> const p = process.on('warning', (warning) => console.warn('Do not do that!'));
429
> events.defaultMaxListeners = 1;
430
> process.on('foo', () => {});
431
> process.on('foo', () => {});
432
> Do not do that!
433
```
434
435
The `--trace-warnings` command-line option can be used to have the default
436
console output for warnings include the full stack trace of the warning.
437
438
Launching Node.js using the `--throw-deprecation` command line flag will
439
cause custom deprecation warnings to be thrown as exceptions.
440
441
Using the `--trace-deprecation` command line flag will cause the custom
442
deprecation to be printed to `stderr` along with the stack trace.
443
444
Using the `--no-deprecation` command line flag will suppress all reporting
445
of the custom deprecation.
446
447
The `*-deprecation` command line flags only affect warnings that use the name
448
`'DeprecationWarning'`.
449
450
#### Emitting custom warnings
451
452
See the [`process.emitWarning()`][process_emit_warning] method for issuing
453
custom or application-specific warnings.
454
455
### Signal Events
456
457
<!--type=event-->
458
<!--name=SIGINT, SIGHUP, etc.-->
459
460
Signal events will be emitted when the Node.js process receives a signal. Please
461
refer to signal(7) for a listing of standard POSIX signal names such as
462
`'SIGINT'`, `'SIGHUP'`, etc.
463
464
Signals are not available on [`Worker`][] threads.
465
466
The signal handler will receive the signal's name (`'SIGINT'`,
467
`'SIGTERM'`, etc.) as the first argument.
468
469
The name of each event will be the uppercase common name for the signal (e.g.
470
`'SIGINT'` for `SIGINT` signals).
471
472
```js
473
// Begin reading from stdin so the process does not exit.
474
process.stdin.resume();
475
476
process.on('SIGINT', () => {
477
console.log('Received SIGINT. Press Control-D to exit.');
478
});
479
480
// Using a single function to handle multiple signals
481
function handle(signal) {
482
console.log(`Received ${signal}`);
483
}
484
485
process.on('SIGINT', handle);
486
process.on('SIGTERM', handle);
487
```
488
489
* `'SIGUSR1'` is reserved by Node.js to start the [debugger][]. It's possible to
490
install a listener but doing so might interfere with the debugger.
491
* `'SIGTERM'` and `'SIGINT'` have default handlers on non-Windows platforms that
492
reset the terminal mode before exiting with code `128 + signal number`. If one
493
of these signals has a listener installed, its default behavior will be
494
removed (Node.js will no longer exit).
495
* `'SIGPIPE'` is ignored by default. It can have a listener installed.
496
* `'SIGHUP'` is generated on Windows when the console window is closed, and on
497
other platforms under various similar conditions. See signal(7). It can have a
498
listener installed, however Node.js will be unconditionally terminated by
499
Windows about 10 seconds later. On non-Windows platforms, the default
500
behavior of `SIGHUP` is to terminate Node.js, but once a listener has been
501
installed its default behavior will be removed.
502
* `'SIGTERM'` is not supported on Windows, it can be listened on.
503
* `'SIGINT'` from the terminal is supported on all platforms, and can usually be
504
generated with `<Ctrl>+C` (though this may be configurable). It is not
505
generated when terminal raw mode is enabled.
506
* `'SIGBREAK'` is delivered on Windows when `<Ctrl>+<Break>` is pressed, on
507
non-Windows platforms it can be listened on, but there is no way to send or
508
generate it.
509
* `'SIGWINCH'` is delivered when the console has been resized. On Windows, this
510
will only happen on write to the console when the cursor is being moved, or
511
when a readable tty is used in raw mode.
512
* `'SIGKILL'` cannot have a listener installed, it will unconditionally
513
terminate Node.js on all platforms.
514
* `'SIGSTOP'` cannot have a listener installed.
515
* `'SIGBUS'`, `'SIGFPE'`, `'SIGSEGV'` and `'SIGILL'`, when not raised
516
artificially using kill(2), inherently leave the process in a state from
517
which it is not safe to attempt to call JS listeners. Doing so might lead to
518
the process hanging in an endless loop, since listeners attached using
519
`process.on()` are called asynchronously and therefore unable to correct the
520
underlying problem.
521
522
Windows does not support sending signals, but Node.js offers some emulation
523
with [`process.kill()`][], and [`subprocess.kill()`][]. Sending signal `0` can
524
be used to test for the existence of a process. Sending `SIGINT`, `SIGTERM`,
525
and `SIGKILL` cause the unconditional termination of the target process.
526
527
## `process.abort()`
528
<!-- YAML
529
added: v0.7.0
530
-->
531
532
The `process.abort()` method causes the Node.js process to exit immediately and
533
generate a core file.
534
535
This feature is not available in [`Worker`][] threads.
536
537
## `process.allowedNodeEnvironmentFlags`
538
<!-- YAML
539
added: v10.10.0
540
-->
541
542
* {Set}
543
544
The `process.allowedNodeEnvironmentFlags` property is a special,
545
read-only `Set` of flags allowable within the [`NODE_OPTIONS`][]
546
environment variable.
547
548
`process.allowedNodeEnvironmentFlags` extends `Set`, but overrides
549
`Set.prototype.has` to recognize several different possible flag
550
representations. `process.allowedNodeEnvironmentFlags.has()` will
551
return `true` in the following cases:
552
553
* Flags may omit leading single (`-`) or double (`--`) dashes; e.g.,
554
`inspect-brk` for `--inspect-brk`, or `r` for `-r`.
555
* Flags passed through to V8 (as listed in `--v8-options`) may replace
556
one or more *non-leading* dashes for an underscore, or vice-versa;
557
e.g., `--perf_basic_prof`, `--perf-basic-prof`, `--perf_basic-prof`,
558
etc.
559
* Flags may contain one or more equals (`=`) characters; all
560
characters after and including the first equals will be ignored;
561
e.g., `--stack-trace-limit=100`.
562
* Flags *must* be allowable within [`NODE_OPTIONS`][].
563
564
When iterating over `process.allowedNodeEnvironmentFlags`, flags will
565
appear only *once*; each will begin with one or more dashes. Flags
566
passed through to V8 will contain underscores instead of non-leading
567
dashes:
568
569
```js
570
process.allowedNodeEnvironmentFlags.forEach((flag) => {
571
// -r
572
// --inspect-brk
573
// --abort_on_uncaught_exception
574
// ...
575
});
576
```
577
578
The methods `add()`, `clear()`, and `delete()` of
579
`process.allowedNodeEnvironmentFlags` do nothing, and will fail
580
silently.
581
582
If Node.js was compiled *without* [`NODE_OPTIONS`][] support (shown in
583
[`process.config`][]), `process.allowedNodeEnvironmentFlags` will
584
contain what *would have* been allowable.
585
586
## `process.arch`
587
<!-- YAML
588
added: v0.5.0
589
-->
590
591
* {string}
592
593
The operating system CPU architecture for which the Node.js binary was compiled.
594
Possible values are: `'arm'`, `'arm64'`, `'ia32'`, `'mips'`,`'mipsel'`, `'ppc'`,
595
`'ppc64'`, `'s390'`, `'s390x'`, `'x32'`, and `'x64'`.
596
597
```js
598
console.log(`This processor architecture is ${process.arch}`);
599
```
600
601
## `process.argv`
602
<!-- YAML
603
added: v0.1.27
604
-->
605
606
* {string[]}
607
608
The `process.argv` property returns an array containing the command line
609
arguments passed when the Node.js process was launched. The first element will
610
be [`process.execPath`][]. See `process.argv0` if access to the original value
611
of `argv[0]` is needed. The second element will be the path to the JavaScript
612
file being executed. The remaining elements will be any additional command line
613
arguments.
614
615
For example, assuming the following script for `process-args.js`:
616
617
```js
618
// print process.argv
619
process.argv.forEach((val, index) => {
620
console.log(`${index}: ${val}`);
621
});
622
```
623
624
Launching the Node.js process as:
625
626
```console
627
$ node process-args.js one two=three four
628
```
629
630
Would generate the output:
631
632
```text
633
0: /usr/local/bin/node
634
1: /Users/mjr/work/node/process-args.js
635
2: one
636
3: two=three
637
4: four
638
```
639
640
## `process.argv0`
641
<!-- YAML
642
added: v6.4.0
643
-->
644
645
* {string}
646
647
The `process.argv0` property stores a read-only copy of the original value of
648
`argv[0]` passed when Node.js starts.
649
650
```console
651
$ bash -c 'exec -a customArgv0 ./node'
652
> process.argv[0]
653
'/Volumes/code/external/node/out/Release/node'
654
> process.argv0
655
'customArgv0'
656
```
657
658
## `process.channel`
659
<!-- YAML
660
added: v7.1.0
661
changes:
662
- version: REPLACEME
663
pr-url: https://github.com/nodejs/node/pull/30165
664
description: The object no longer accidentally exposes native C++ bindings.
665
-->
666
667
* {Object}
668
669
If the Node.js process was spawned with an IPC channel (see the
670
[Child Process][] documentation), the `process.channel`
671
property is a reference to the IPC channel. If no IPC channel exists, this
672
property is `undefined`.
673
674
### `process.channel.ref()`
675
<!-- YAML
676
added: v7.1.0
677
-->
678
679
This method makes the IPC channel keep the event loop of the process
680
running if `.unref()` has been called before.
681
682
Typically, this is managed through the number of `'disconnect'` and `'message'`
683
listeners on the `process` object. However, this method can be used to
684
explicitly request a specific behavior.
685
686
### `process.channel.unref()`
687
<!-- YAML
688
added: v7.1.0
689
-->
690
691
This method makes the IPC channel not keep the event loop of the process
692
running, and lets it finish even while the channel is open.
693
694
Typically, this is managed through the number of `'disconnect'` and `'message'`
695
listeners on the `process` object. However, this method can be used to
696
explicitly request a specific behavior.
697
698
## `process.chdir(directory)`
699
<!-- YAML
700
added: v0.1.17
701
-->
702
703
* `directory` {string}
704
705
The `process.chdir()` method changes the current working directory of the
706
Node.js process or throws an exception if doing so fails (for instance, if
707
the specified `directory` does not exist).
708
709
```js
710
console.log(`Starting directory: ${process.cwd()}`);
711
try {
712
process.chdir('/tmp');
713
console.log(`New directory: ${process.cwd()}`);
714
} catch (err) {
715
console.error(`chdir: ${err}`);
716
}
717
```
718
719
This feature is not available in [`Worker`][] threads.
720
721
## `process.config`
722
<!-- YAML
723
added: v0.7.7
724
-->
725
726
* {Object}
727
728
The `process.config` property returns an `Object` containing the JavaScript
729
representation of the configure options used to compile the current Node.js
730
executable. This is the same as the `config.gypi` file that was produced when
731
running the `./configure` script.
732
733
An example of the possible output looks like:
734
735
<!-- eslint-skip -->
736
```js
737
{
738
target_defaults:
739
{ cflags: [],
740
default_configuration: 'Release',
741
defines: [],
742
include_dirs: [],
743
libraries: [] },
744
variables:
745
{
746
host_arch: 'x64',
747
napi_build_version: 5,
748
node_install_npm: 'true',
749
node_prefix: '',
750
node_shared_cares: 'false',
751
node_shared_http_parser: 'false',
752
node_shared_libuv: 'false',
753
node_shared_zlib: 'false',
754
node_use_dtrace: 'false',
755
node_use_openssl: 'true',
756
node_shared_openssl: 'false',
757
strict_aliasing: 'true',
758
target_arch: 'x64',
759
v8_use_snapshot: 1
760
}
761
}
762
```
763
764
The `process.config` property is **not** read-only and there are existing
765
modules in the ecosystem that are known to extend, modify, or entirely replace
766
the value of `process.config`.
767
768
## `process.connected`
769
<!-- YAML
770
added: v0.7.2
771
-->
772
773
* {boolean}
774
775
If the Node.js process is spawned with an IPC channel (see the [Child Process][]
776
and [Cluster][] documentation), the `process.connected` property will return
777
`true` so long as the IPC channel is connected and will return `false` after
778
`process.disconnect()` is called.
779
780
Once `process.connected` is `false`, it is no longer possible to send messages
781
over the IPC channel using `process.send()`.
782
783
## `process.cpuUsage([previousValue])`
784
<!-- YAML
785
added: v6.1.0
786
-->
787
788
* `previousValue` {Object} A previous return value from calling
789
`process.cpuUsage()`
790
* Returns: {Object}
791
* `user` {integer}
792
* `system` {integer}
793
794
The `process.cpuUsage()` method returns the user and system CPU time usage of
795
the current process, in an object with properties `user` and `system`, whose
796
values are microsecond values (millionth of a second). These values measure time
797
spent in user and system code respectively, and may end up being greater than
798
actual elapsed time if multiple CPU cores are performing work for this process.
799
800
The result of a previous call to `process.cpuUsage()` can be passed as the
801
argument to the function, to get a diff reading.
802
803
```js
804
const startUsage = process.cpuUsage();
805
// { user: 38579, system: 6986 }
806
807
// spin the CPU for 500 milliseconds
808
const now = Date.now();
809
while (Date.now() - now < 500);
810
811
console.log(process.cpuUsage(startUsage));
812
// { user: 514883, system: 11226 }
813
```
814
815
## `process.cwd()`
816
<!-- YAML
817
added: v0.1.8
818
-->
819
820
* Returns: {string}
821
822
The `process.cwd()` method returns the current working directory of the Node.js
823
process.
824
825
```js
826
console.log(`Current directory: ${process.cwd()}`);
827
```
828
829
## `process.debugPort`
830
<!-- YAML
831
added: v0.7.2
832
-->
833
834
* {number}
835
836
The port used by the Node.js debugger when enabled.
837
838
```js
839
process.debugPort = 5858;
840
```
841
842
## `process.disconnect()`
843
<!-- YAML
844
added: v0.7.2
845
-->
846
847
If the Node.js process is spawned with an IPC channel (see the [Child Process][]
848
and [Cluster][] documentation), the `process.disconnect()` method will close the
849
IPC channel to the parent process, allowing the child process to exit gracefully
850
once there are no other connections keeping it alive.
851
852
The effect of calling `process.disconnect()` is the same as calling
853
[`ChildProcess.disconnect()`][] from the parent process.
854
855
If the Node.js process was not spawned with an IPC channel,
856
`process.disconnect()` will be `undefined`.
857
858
## `process.dlopen(module, filename[, flags])`
859
<!-- YAML
860
added: v0.1.16
861
changes:
862
- version: v9.0.0
863
pr-url: https://github.com/nodejs/node/pull/12794
864
description: Added support for the `flags` argument.
865
-->
866
867
* `module` {Object}
868
* `filename` {string}
869
* `flags` {os.constants.dlopen} **Default:** `os.constants.dlopen.RTLD_LAZY`
870
871
The `process.dlopen()` method allows to dynamically load shared
872
objects. It is primarily used by `require()` to load
873
C++ Addons, and should not be used directly, except in special
874
cases. In other words, [`require()`][] should be preferred over
875
`process.dlopen()`, unless there are specific reasons.
876
877
The `flags` argument is an integer that allows to specify dlopen
878
behavior. See the [`os.constants.dlopen`][] documentation for details.
879
880
If there are specific reasons to use `process.dlopen()` (for instance,
881
to specify dlopen flags), it's often useful to use [`require.resolve()`][]
882
to look up the module's path.
883
884
An important drawback when calling `process.dlopen()` is that the `module`
885
instance must be passed. Functions exported by the C++ Addon will be accessible
886
via `module.exports`.
887
888
The example below shows how to load a C++ Addon, named as `binding`,
889
that exports a `foo` function. All the symbols will be loaded before
890
the call returns, by passing the `RTLD_NOW` constant. In this example
891
the constant is assumed to be available.
892
893
```js
894
const os = require('os');
895
process.dlopen(module, require.resolve('binding'),
896
os.constants.dlopen.RTLD_NOW);
897
module.exports.foo();
898
```
899
900
## `process.emitWarning(warning[, options])`
901
<!-- YAML
902
added: v8.0.0
903
-->
904
905
* `warning` {string|Error} The warning to emit.
906
* `options` {Object}
907
* `type` {string} When `warning` is a `String`, `type` is the name to use
908
for the *type* of warning being emitted. **Default:** `'Warning'`.
909
* `code` {string} A unique identifier for the warning instance being emitted.
910
* `ctor` {Function} When `warning` is a `String`, `ctor` is an optional
911
function used to limit the generated stack trace. **Default:**
912
`process.emitWarning`.
913
* `detail` {string} Additional text to include with the error.
914
915
The `process.emitWarning()` method can be used to emit custom or application
916
specific process warnings. These can be listened for by adding a handler to the
917
[`'warning'`][process_warning] event.
918
919
```js
920
// Emit a warning with a code and additional detail.
921
process.emitWarning('Something happened!', {
922
code: 'MY_WARNING',
923
detail: 'This is some additional information'
924
});
925
// Emits:
926
// (node:56338) [MY_WARNING] Warning: Something happened!
927
// This is some additional information
928
```
929
930
In this example, an `Error` object is generated internally by
931
`process.emitWarning()` and passed through to the
932
[`'warning'`][process_warning] handler.
933
934
```js
935
process.on('warning', (warning) => {
936
console.warn(warning.name); // 'Warning'
937
console.warn(warning.message); // 'Something happened!'
938
console.warn(warning.code); // 'MY_WARNING'
939
console.warn(warning.stack); // Stack trace
940
console.warn(warning.detail); // 'This is some additional information'
941
});
942
```
943
944
If `warning` is passed as an `Error` object, the `options` argument is ignored.
945
946
## `process.emitWarning(warning[, type[, code]][, ctor])`
947
<!-- YAML
948
added: v6.0.0
949
-->
950
951
* `warning` {string|Error} The warning to emit.
952
* `type` {string} When `warning` is a `String`, `type` is the name to use
953
for the *type* of warning being emitted. **Default:** `'Warning'`.
954
* `code` {string} A unique identifier for the warning instance being emitted.
955
* `ctor` {Function} When `warning` is a `String`, `ctor` is an optional
956
function used to limit the generated stack trace. **Default:**
957
`process.emitWarning`.
958
959
The `process.emitWarning()` method can be used to emit custom or application
960
specific process warnings. These can be listened for by adding a handler to the
961
[`'warning'`][process_warning] event.
962
963
```js
964
// Emit a warning using a string.
965
process.emitWarning('Something happened!');
966
// Emits: (node: 56338) Warning: Something happened!
967
```
968
969
```js
970
// Emit a warning using a string and a type.
971
process.emitWarning('Something Happened!', 'CustomWarning');
972
// Emits: (node:56338) CustomWarning: Something Happened!
973
```
974
975
```js
976
process.emitWarning('Something happened!', 'CustomWarning', 'WARN001');
977
// Emits: (node:56338) [WARN001] CustomWarning: Something happened!
978
```
979
980
In each of the previous examples, an `Error` object is generated internally by
981
`process.emitWarning()` and passed through to the [`'warning'`][process_warning]
982
handler.
983
984
```js
985
process.on('warning', (warning) => {
986
console.warn(warning.name);
987
console.warn(warning.message);
988
console.warn(warning.code);
989
console.warn(warning.stack);
990
});
991
```
992
993
If `warning` is passed as an `Error` object, it will be passed through to the
994
`'warning'` event handler unmodified (and the optional `type`,
995
`code` and `ctor` arguments will be ignored):
996
997
```js
998
// Emit a warning using an Error object.
999
const myWarning = new Error('Something happened!');
1000
// Use the Error name property to specify the type name