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