doc: remove mention of maxTickDepth
[platform/upstream/nodejs.git] / doc / api / process.markdown
1 # process
2
3 <!-- type=global -->
4
5 The `process` object is a global object and can be accessed from anywhere.
6 It is an instance of [EventEmitter][].
7
8
9 ## Event: 'exit'
10
11 Emitted when the process is about to exit.  This is a good hook to perform
12 constant time checks of the module's state (like for unit tests).  The main
13 event loop will no longer be run after the 'exit' callback finishes, so
14 timers may not be scheduled.
15
16 Example of listening for `exit`:
17
18     process.on('exit', function() {
19       setTimeout(function() {
20         console.log('This will not run');
21       }, 0);
22       console.log('About to exit.');
23     });
24
25 ## Event: 'uncaughtException'
26
27 Emitted when an exception bubbles all the way back to the event loop. If a
28 listener is added for this exception, the default action (which is to print
29 a stack trace and exit) will not occur.
30
31 Example of listening for `uncaughtException`:
32
33     process.on('uncaughtException', function(err) {
34       console.log('Caught exception: ' + err);
35     });
36
37     setTimeout(function() {
38       console.log('This will still run.');
39     }, 500);
40
41     // Intentionally cause an exception, but don't catch it.
42     nonexistentFunc();
43     console.log('This will not run.');
44
45 Note that `uncaughtException` is a very crude mechanism for exception
46 handling.
47
48 Don't use it, use [domains](domain.html) instead. If you do use it, restart
49 your application after every unhandled exception!
50
51 Do *not* use it as the node.js equivalent of `On Error Resume Next`. An
52 unhandled exception means your application - and by extension node.js itself -
53 is in an undefined state. Blindly resuming means *anything* could happen.
54
55 Think of resuming as pulling the power cord when you are upgrading your system.
56 Nine out of ten times nothing happens - but the 10th time, your system is bust.
57
58 You have been warned.
59
60 ## Signal Events
61
62 <!--type=event-->
63 <!--name=SIGINT, SIGUSR1, etc.-->
64
65 Emitted when the processes receives a signal. See sigaction(2) for a list of
66 standard POSIX signal names such as SIGINT, SIGUSR1, etc.
67
68 Example of listening for `SIGINT`:
69
70     // Start reading from stdin so we don't exit.
71     process.stdin.resume();
72
73     process.on('SIGINT', function() {
74       console.log('Got SIGINT.  Press Control-D to exit.');
75     });
76
77 An easy way to send the `SIGINT` signal is with `Control-C` in most terminal
78 programs.
79
80
81 ## process.stdout
82
83 A `Writable Stream` to `stdout`.
84
85 Example: the definition of `console.log`
86
87     console.log = function(d) {
88       process.stdout.write(d + '\n');
89     };
90
91 `process.stderr` and `process.stdout` are unlike other streams in Node in
92 that writes to them are usually blocking.  They are blocking in the case
93 that they refer to regular files or TTY file descriptors. In the case they
94 refer to pipes, they are non-blocking like other streams.
95
96 To check if Node is being run in a TTY context, read the `isTTY` property
97 on `process.stderr`, `process.stdout`, or `process.stdin`:
98
99     $ node -p "Boolean(process.stdin.isTTY)"
100     true
101     $ echo "foo" | node -p "Boolean(process.stdin.isTTY)"
102     false
103
104     $ node -p "Boolean(process.stdout.isTTY)"
105     true
106     $ node -p "Boolean(process.stdout.isTTY)" | cat
107     false
108
109 See [the tty docs](tty.html#tty_tty) for more information.
110
111 ## process.stderr
112
113 A writable stream to stderr.
114
115 `process.stderr` and `process.stdout` are unlike other streams in Node in
116 that writes to them are usually blocking.  They are blocking in the case
117 that they refer to regular files or TTY file descriptors. In the case they
118 refer to pipes, they are non-blocking like other streams.
119
120
121 ## process.stdin
122
123 A `Readable Stream` for stdin. The stdin stream is paused by default, so one
124 must call `process.stdin.resume()` to read from it.
125
126 Example of opening standard input and listening for both events:
127
128     process.stdin.resume();
129     process.stdin.setEncoding('utf8');
130
131     process.stdin.on('data', function(chunk) {
132       process.stdout.write('data: ' + chunk);
133     });
134
135     process.stdin.on('end', function() {
136       process.stdout.write('end');
137     });
138
139
140 ## process.argv
141
142 An array containing the command line arguments.  The first element will be
143 'node', the second element will be the name of the JavaScript file.  The
144 next elements will be any additional command line arguments.
145
146     // print process.argv
147     process.argv.forEach(function(val, index, array) {
148       console.log(index + ': ' + val);
149     });
150
151 This will generate:
152
153     $ node process-2.js one two=three four
154     0: node
155     1: /Users/mjr/work/node/process-2.js
156     2: one
157     3: two=three
158     4: four
159
160
161 ## process.execPath
162
163 This is the absolute pathname of the executable that started the process.
164
165 Example:
166
167     /usr/local/bin/node
168
169
170 ## process.abort()
171
172 This causes node to emit an abort. This will cause node to exit and
173 generate a core file.
174
175 ## process.chdir(directory)
176
177 Changes the current working directory of the process or throws an exception if that fails.
178
179     console.log('Starting directory: ' + process.cwd());
180     try {
181       process.chdir('/tmp');
182       console.log('New directory: ' + process.cwd());
183     }
184     catch (err) {
185       console.log('chdir: ' + err);
186     }
187
188
189
190 ## process.cwd()
191
192 Returns the current working directory of the process.
193
194     console.log('Current directory: ' + process.cwd());
195
196
197 ## process.env
198
199 An object containing the user environment. See environ(7).
200
201
202 ## process.exit([code])
203
204 Ends the process with the specified `code`.  If omitted, exit uses the
205 'success' code `0`.
206
207 To exit with a 'failure' code:
208
209     process.exit(1);
210
211 The shell that executed node should see the exit code as 1.
212
213
214 ## process.getgid()
215
216 Note: this function is only available on POSIX platforms (i.e. not Windows,
217 Android)
218
219 Gets the group identity of the process. (See getgid(2).)
220 This is the numerical group id, not the group name.
221
222     if (process.getgid) {
223       console.log('Current gid: ' + process.getgid());
224     }
225
226
227 ## process.setgid(id)
228
229 Note: this function is only available on POSIX platforms (i.e. not Windows,
230 Android)
231
232 Sets the group identity of the process. (See setgid(2).)  This accepts either
233 a numerical ID or a groupname string. If a groupname is specified, this method
234 blocks while resolving it to a numerical ID.
235
236     if (process.getgid && process.setgid) {
237       console.log('Current gid: ' + process.getgid());
238       try {
239         process.setgid(501);
240         console.log('New gid: ' + process.getgid());
241       }
242       catch (err) {
243         console.log('Failed to set gid: ' + err);
244       }
245     }
246
247
248 ## process.getuid()
249
250 Note: this function is only available on POSIX platforms (i.e. not Windows,
251 Android)
252
253 Gets the user identity of the process. (See getuid(2).)
254 This is the numerical userid, not the username.
255
256     if (process.getuid) {
257       console.log('Current uid: ' + process.getuid());
258     }
259
260
261 ## process.setuid(id)
262
263 Note: this function is only available on POSIX platforms (i.e. not Windows,
264 Android)
265
266 Sets the user identity of the process. (See setuid(2).)  This accepts either
267 a numerical ID or a username string.  If a username is specified, this method
268 blocks while resolving it to a numerical ID.
269
270     if (process.getuid && process.setuid) {
271       console.log('Current uid: ' + process.getuid());
272       try {
273         process.setuid(501);
274         console.log('New uid: ' + process.getuid());
275       }
276       catch (err) {
277         console.log('Failed to set uid: ' + err);
278       }
279     }
280
281
282 ## process.getgroups()
283
284 Note: this function is only available on POSIX platforms (i.e. not Windows,
285 Android)
286
287 Returns an array with the supplementary group IDs. POSIX leaves it unspecified
288 if the effective group ID is included but node.js ensures it always is.
289
290
291 ## process.setgroups(groups)
292
293 Note: this function is only available on POSIX platforms (i.e. not Windows,
294 Android)
295
296 Sets the supplementary group IDs. This is a privileged operation, meaning you
297 need to be root or have the CAP_SETGID capability.
298
299 The list can contain group IDs, group names or both.
300
301
302 ## process.initgroups(user, extra_group)
303
304 Note: this function is only available on POSIX platforms (i.e. not Windows,
305 Android)
306
307 Reads /etc/group and initializes the group access list, using all groups of
308 which the user is a member. This is a privileged operation, meaning you need
309 to be root or have the CAP_SETGID capability.
310
311 `user` is a user name or user ID. `extra_group` is a group name or group ID.
312
313 Some care needs to be taken when dropping privileges. Example:
314
315     console.log(process.getgroups());         // [ 0 ]
316     process.initgroups('bnoordhuis', 1000);   // switch user
317     console.log(process.getgroups());         // [ 27, 30, 46, 1000, 0 ]
318     process.setgid(1000);                     // drop root gid
319     console.log(process.getgroups());         // [ 27, 30, 46, 1000 ]
320
321
322 ## process.version
323
324 A compiled-in property that exposes `NODE_VERSION`.
325
326     console.log('Version: ' + process.version);
327
328 ## process.versions
329
330 A property exposing version strings of node and its dependencies.
331
332     console.log(process.versions);
333
334 Will print something like:
335
336     { http_parser: '1.0',
337       node: '0.10.4',
338       v8: '3.14.5.8',
339       ares: '1.9.0-DEV',
340       uv: '0.10.3',
341       zlib: '1.2.3',
342       modules: '11',
343       openssl: '1.0.1e' }
344
345 ## process.config
346
347 An Object containing the JavaScript representation of the configure options
348 that were used to compile the current node executable. This is the same as
349 the "config.gypi" file that was produced when running the `./configure` script.
350
351 An example of the possible output looks like:
352
353     { target_defaults:
354        { cflags: [],
355          default_configuration: 'Release',
356          defines: [],
357          include_dirs: [],
358          libraries: [] },
359       variables:
360        { host_arch: 'x64',
361          node_install_npm: 'true',
362          node_prefix: '',
363          node_shared_cares: 'false',
364          node_shared_http_parser: 'false',
365          node_shared_libuv: 'false',
366          node_shared_v8: 'false',
367          node_shared_zlib: 'false',
368          node_use_dtrace: 'false',
369          node_use_openssl: 'true',
370          node_shared_openssl: 'false',
371          strict_aliasing: 'true',
372          target_arch: 'x64',
373          v8_use_snapshot: 'true' } }
374
375 ## process.kill(pid, [signal])
376
377 Send a signal to a process. `pid` is the process id and `signal` is the
378 string describing the signal to send.  Signal names are strings like
379 'SIGINT' or 'SIGUSR1'.  If omitted, the signal will be 'SIGTERM'.
380 See kill(2) for more information.
381
382 Note that just because the name of this function is `process.kill`, it is
383 really just a signal sender, like the `kill` system call.  The signal sent
384 may do something other than kill the target process.
385
386 Example of sending a signal to yourself:
387
388     process.on('SIGHUP', function() {
389       console.log('Got SIGHUP signal.');
390     });
391
392     setTimeout(function() {
393       console.log('Exiting.');
394       process.exit(0);
395     }, 100);
396
397     process.kill(process.pid, 'SIGHUP');
398
399
400 ## process.pid
401
402 The PID of the process.
403
404     console.log('This process is pid ' + process.pid);
405
406
407 ## process.title
408
409 Getter/setter to set what is displayed in 'ps'.
410
411 When used as a setter, the maximum length is platform-specific and probably
412 short.
413
414 On Linux and OS X, it's limited to the size of the binary name plus the
415 length of the command line arguments because it overwrites the argv memory.
416
417 v0.8 allowed for longer process title strings by also overwriting the environ
418 memory but that was potentially insecure/confusing in some (rather obscure)
419 cases.
420
421
422 ## process.arch
423
424 What processor architecture you're running on: `'arm'`, `'ia32'`, or `'x64'`.
425
426     console.log('This processor architecture is ' + process.arch);
427
428
429 ## process.platform
430
431 What platform you're running on:
432 `'darwin'`, `'freebsd'`, `'linux'`, `'sunos'` or `'win32'`
433
434     console.log('This platform is ' + process.platform);
435
436
437 ## process.memoryUsage()
438
439 Returns an object describing the memory usage of the Node process
440 measured in bytes.
441
442     var util = require('util');
443
444     console.log(util.inspect(process.memoryUsage()));
445
446 This will generate:
447
448     { rss: 4935680,
449       heapTotal: 1826816,
450       heapUsed: 650472 }
451
452 `heapTotal` and `heapUsed` refer to V8's memory usage.
453
454
455 ## process.nextTick(callback)
456
457 On the next loop around the event loop call this callback.
458 This is *not* a simple alias to `setTimeout(fn, 0)`, it's much more
459 efficient.  It typically runs before any other I/O events fire, but there
460 are some exceptions.
461
462     process.nextTick(function() {
463       console.log('nextTick callback');
464     });
465
466 This is important in developing APIs where you want to give the user the
467 chance to assign event handlers after an object has been constructed,
468 but before any I/O has occurred.
469
470     function MyThing(options) {
471       this.setupOptions(options);
472
473       process.nextTick(function() {
474         this.startDoingStuff();
475       }.bind(this));
476     }
477
478     var thing = new MyThing();
479     thing.getReadyForStuff();
480
481     // thing.startDoingStuff() gets called now, not before.
482
483 It is very important for APIs to be either 100% synchronous or 100%
484 asynchronous.  Consider this example:
485
486     // WARNING!  DO NOT USE!  BAD UNSAFE HAZARD!
487     function maybeSync(arg, cb) {
488       if (arg) {
489         cb();
490         return;
491       }
492
493       fs.stat('file', cb);
494     }
495
496 This API is hazardous.  If you do this:
497
498     maybeSync(true, function() {
499       foo();
500     });
501     bar();
502
503 then it's not clear whether `foo()` or `bar()` will be called first.
504
505 This approach is much better:
506
507     function definitelyAsync(arg, cb) {
508       if (arg) {
509         process.nextTick(cb);
510         return;
511       }
512
513       fs.stat('file', cb);
514     }
515
516 ## process.umask([mask])
517
518 Sets or reads the process's file mode creation mask. Child processes inherit
519 the mask from the parent process. Returns the old mask if `mask` argument is
520 given, otherwise returns the current mask.
521
522     var oldmask, newmask = 0644;
523
524     oldmask = process.umask(newmask);
525     console.log('Changed umask from: ' + oldmask.toString(8) +
526                 ' to ' + newmask.toString(8));
527
528
529 ## process.uptime()
530
531 Number of seconds Node has been running.
532
533
534 ## process.hrtime()
535
536 Returns the current high-resolution real time in a `[seconds, nanoseconds]`
537 tuple Array. It is relative to an arbitrary time in the past. It is not
538 related to the time of day and therefore not subject to clock drift. The
539 primary use is for measuring performance between intervals.
540
541 You may pass in the result of a previous call to `process.hrtime()` to get
542 a diff reading, useful for benchmarks and measuring intervals:
543
544     var time = process.hrtime();
545     // [ 1800216, 25 ]
546
547     setTimeout(function() {
548       var diff = process.hrtime(time);
549       // [ 1, 552 ]
550
551       console.log('benchmark took %d nanoseconds', diff[0] * 1e9 + diff[1]);
552       // benchmark took 1000000527 nanoseconds
553     }, 1000);
554
555 [EventEmitter]: events.html#events_class_events_eventemitter