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