5 The `process` object is a global object and can be accessed from anywhere.
6 It is an instance of [EventEmitter][].
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. The callback takes one argument, the code the
15 process is exiting with.
17 Example of listening for `exit`:
19 process.on('exit', function(code) {
20 setTimeout(function() {
21 console.log('This will not run');
23 console.log('About to exit with code:', code);
26 ## Event: 'uncaughtException'
28 Emitted when an exception bubbles all the way back to the event loop. If a
29 listener is added for this exception, the default action (which is to print
30 a stack trace and exit) will not occur.
32 Example of listening for `uncaughtException`:
34 process.on('uncaughtException', function(err) {
35 console.log('Caught exception: ' + err);
38 setTimeout(function() {
39 console.log('This will still run.');
42 // Intentionally cause an exception, but don't catch it.
44 console.log('This will not run.');
46 Note that `uncaughtException` is a very crude mechanism for exception
47 handling and may be removed in the future.
49 Don't use it, use [domains](domain.html) instead. If you do use it, restart
50 your application after every unhandled exception!
52 Do *not* use it as the node.js equivalent of `On Error Resume Next`. An
53 unhandled exception means your application - and by extension node.js itself -
54 is in an undefined state. Blindly resuming means *anything* could happen.
56 Think of resuming as pulling the power cord when you are upgrading your system.
57 Nine out of ten times nothing happens - but the 10th time, your system is bust.
64 <!--name=SIGINT, SIGHUP, etc.-->
66 Emitted when the processes receives a signal. See sigaction(2) for a list of
67 standard POSIX signal names such as SIGINT, SIGHUP, etc.
69 Example of listening for `SIGINT`:
71 // Start reading from stdin so we don't exit.
72 process.stdin.resume();
74 process.on('SIGINT', function() {
75 console.log('Got SIGINT. Press Control-D to exit.');
78 An easy way to send the `SIGINT` signal is with `Control-C` in most terminal
83 - `SIGUSR1` is reserved by node.js to start the debugger. It's possible to
84 install a listener but that won't stop the debugger from starting.
85 - `SIGTERM` and `SIGINT` have default handlers on non-Windows platforms that resets
86 the terminal mode before exiting with code `128 + signal number`. If one of
87 these signals has a listener installed, its default behaviour will be removed
88 (node will no longer exit).
89 - `SIGPIPE` is ignored by default, it can have a listener installed.
90 - `SIGHUP` is generated on Windows when the console window is closed, and on other
91 platforms under various similar conditions, see signal(7). It can have a
92 listener installed, however node will be unconditionally terminated by Windows
93 about 10 seconds later. On non-Windows platforms, the default behaviour of
94 `SIGHUP` is to terminate node, but once a listener has been installed its
95 default behaviour will be removed.
96 - `SIGTERM` is not supported on Windows, it can be listened on.
97 - `SIGINT` is supported on all platforms, and can usually be generated with
98 `CTRL+C` (though this may be configurable). It is not generated when terminal
100 - `SIGBREAK` is delivered on Windows when `CTRL+BREAK` is pressed, on non-Windows
101 platforms it can be listened on, but there is no way to send or generate it.
102 - `SIGWINCH` is delivered when the console has been resized. On Windows, this will
103 only happen on write to the console when the cursor is being moved, or when a
104 readable tty is used in raw mode.
105 - `SIGKILL` cannot have a listener installed, it will unconditionally terminate
106 node on all platforms.
107 - `SIGSTOP` cannot have a listener installed.
111 A `Writable Stream` to `stdout`.
113 Example: the definition of `console.log`
115 console.log = function(d) {
116 process.stdout.write(d + '\n');
119 `process.stderr` and `process.stdout` are unlike other streams in Node in
120 that writes to them are usually blocking. They are blocking in the case
121 that they refer to regular files or TTY file descriptors. In the case they
122 refer to pipes, they are non-blocking like other streams.
124 To check if Node is being run in a TTY context, read the `isTTY` property
125 on `process.stderr`, `process.stdout`, or `process.stdin`:
127 $ node -p "Boolean(process.stdin.isTTY)"
129 $ echo "foo" | node -p "Boolean(process.stdin.isTTY)"
132 $ node -p "Boolean(process.stdout.isTTY)"
134 $ node -p "Boolean(process.stdout.isTTY)" | cat
137 See [the tty docs](tty.html#tty_tty) for more information.
141 A writable stream to stderr.
143 `process.stderr` and `process.stdout` are unlike other streams in Node in
144 that writes to them are usually blocking. They are blocking in the case
145 that they refer to regular files or TTY file descriptors. In the case they
146 refer to pipes, they are non-blocking like other streams.
151 A `Readable Stream` for stdin. The stdin stream is paused by default, so one
152 must call `process.stdin.resume()` to read from it.
154 Example of opening standard input and listening for both events:
156 process.stdin.resume();
157 process.stdin.setEncoding('utf8');
159 process.stdin.on('data', function(chunk) {
160 process.stdout.write('data: ' + chunk);
163 process.stdin.on('end', function() {
164 process.stdout.write('end');
170 An array containing the command line arguments. The first element will be
171 'node', the second element will be the name of the JavaScript file. The
172 next elements will be any additional command line arguments.
174 // print process.argv
175 process.argv.forEach(function(val, index, array) {
176 console.log(index + ': ' + val);
181 $ node process-2.js one two=three four
183 1: /Users/mjr/work/node/process-2.js
191 This is the absolute pathname of the executable that started the process.
200 This is the set of node-specific command line options from the
201 executable that started the process. These options do not show up in
202 `process.argv`, and do not include the node executable, the name of
203 the script, or any options following the script name. These options
204 are useful in order to spawn child processes with the same execution
205 environment as the parent.
209 $ node --harmony script.js --version
211 results in process.execArgv:
217 ['/usr/local/bin/node', 'script.js', '--version']
222 This causes node to emit an abort. This will cause node to exit and
223 generate a core file.
225 ## process.chdir(directory)
227 Changes the current working directory of the process or throws an exception if that fails.
229 console.log('Starting directory: ' + process.cwd());
231 process.chdir('/tmp');
232 console.log('New directory: ' + process.cwd());
235 console.log('chdir: ' + err);
242 Returns the current working directory of the process.
244 console.log('Current directory: ' + process.cwd());
249 An object containing the user environment. See environ(7).
252 ## process.exit([code])
254 Ends the process with the specified `code`. If omitted, exit uses the
257 To exit with a 'failure' code:
261 The shell that executed node should see the exit code as 1.
266 Note: this function is only available on POSIX platforms (i.e. not Windows)
268 Gets the group identity of the process. (See getgid(2).)
269 This is the numerical group id, not the group name.
271 if (process.getgid) {
272 console.log('Current gid: ' + process.getgid());
276 ## process.setgid(id)
278 Note: this function is only available on POSIX platforms (i.e. not Windows)
280 Sets the group identity of the process. (See setgid(2).) This accepts either
281 a numerical ID or a groupname string. If a groupname is specified, this method
282 blocks while resolving it to a numerical ID.
284 if (process.getgid && process.setgid) {
285 console.log('Current gid: ' + process.getgid());
288 console.log('New gid: ' + process.getgid());
291 console.log('Failed to set gid: ' + err);
298 Note: this function is only available on POSIX platforms (i.e. not Windows)
300 Gets the user identity of the process. (See getuid(2).)
301 This is the numerical userid, not the username.
303 if (process.getuid) {
304 console.log('Current uid: ' + process.getuid());
308 ## process.setuid(id)
310 Note: this function is only available on POSIX platforms (i.e. not Windows)
312 Sets the user identity of the process. (See setuid(2).) This accepts either
313 a numerical ID or a username string. If a username is specified, this method
314 blocks while resolving it to a numerical ID.
316 if (process.getuid && process.setuid) {
317 console.log('Current uid: ' + process.getuid());
320 console.log('New uid: ' + process.getuid());
323 console.log('Failed to set uid: ' + err);
328 ## process.getgroups()
330 Note: this function is only available on POSIX platforms (i.e. not Windows)
332 Returns an array with the supplementary group IDs. POSIX leaves it unspecified
333 if the effective group ID is included but node.js ensures it always is.
336 ## process.setgroups(groups)
338 Note: this function is only available on POSIX platforms (i.e. not Windows)
340 Sets the supplementary group IDs. This is a privileged operation, meaning you
341 need to be root or have the CAP_SETGID capability.
343 The list can contain group IDs, group names or both.
346 ## process.initgroups(user, extra_group)
348 Note: this function is only available on POSIX platforms (i.e. not Windows)
350 Reads /etc/group and initializes the group access list, using all groups of
351 which the user is a member. This is a privileged operation, meaning you need
352 to be root or have the CAP_SETGID capability.
354 `user` is a user name or user ID. `extra_group` is a group name or group ID.
356 Some care needs to be taken when dropping privileges. Example:
358 console.log(process.getgroups()); // [ 0 ]
359 process.initgroups('bnoordhuis', 1000); // switch user
360 console.log(process.getgroups()); // [ 27, 30, 46, 1000, 0 ]
361 process.setgid(1000); // drop root gid
362 console.log(process.getgroups()); // [ 27, 30, 46, 1000 ]
367 A compiled-in property that exposes `NODE_VERSION`.
369 console.log('Version: ' + process.version);
373 A property exposing version strings of node and its dependencies.
375 console.log(process.versions);
377 Will print something like:
379 { http_parser: '1.0',
390 An Object containing the JavaScript representation of the configure options
391 that were used to compile the current node executable. This is the same as
392 the "config.gypi" file that was produced when running the `./configure` script.
394 An example of the possible output looks like:
398 default_configuration: 'Release',
404 node_install_npm: 'true',
406 node_shared_cares: 'false',
407 node_shared_http_parser: 'false',
408 node_shared_libuv: 'false',
409 node_shared_v8: 'false',
410 node_shared_zlib: 'false',
411 node_use_dtrace: 'false',
412 node_use_openssl: 'true',
413 node_shared_openssl: 'false',
414 strict_aliasing: 'true',
416 v8_use_snapshot: 'true' } }
418 ## process.kill(pid, [signal])
420 Send a signal to a process. `pid` is the process id and `signal` is the
421 string describing the signal to send. Signal names are strings like
422 'SIGINT' or 'SIGHUP'. If omitted, the signal will be 'SIGTERM'.
423 See kill(2) for more information.
425 Will throw an error if target does not exist, and as a special case, a signal of
426 `0` can be used to test for the existence of a process.
428 Note that just because the name of this function is `process.kill`, it is
429 really just a signal sender, like the `kill` system call. The signal sent
430 may do something other than kill the target process.
432 Example of sending a signal to yourself:
434 process.on('SIGHUP', function() {
435 console.log('Got SIGHUP signal.');
438 setTimeout(function() {
439 console.log('Exiting.');
443 process.kill(process.pid, 'SIGHUP');
445 Note: When SIGUSR1 is received by Node.js it starts the debugger, see
446 [Signal Events](#process_signal_events).
450 The PID of the process.
452 console.log('This process is pid ' + process.pid);
457 Getter/setter to set what is displayed in 'ps'.
459 When used as a setter, the maximum length is platform-specific and probably
462 On Linux and OS X, it's limited to the size of the binary name plus the
463 length of the command line arguments because it overwrites the argv memory.
465 v0.8 allowed for longer process title strings by also overwriting the environ
466 memory but that was potentially insecure/confusing in some (rather obscure)
472 What processor architecture you're running on: `'arm'`, `'ia32'`, or `'x64'`.
474 console.log('This processor architecture is ' + process.arch);
479 What platform you're running on:
480 `'darwin'`, `'freebsd'`, `'linux'`, `'sunos'` or `'win32'`
482 console.log('This platform is ' + process.platform);
485 ## process.memoryUsage()
487 Returns an object describing the memory usage of the Node process
490 var util = require('util');
492 console.log(util.inspect(process.memoryUsage()));
500 `heapTotal` and `heapUsed` refer to V8's memory usage.
503 ## process.nextTick(callback)
505 On the next loop around the event loop call this callback.
506 This is *not* a simple alias to `setTimeout(fn, 0)`, it's much more
507 efficient. It typically runs before any other I/O events fire, but there
508 are some exceptions. See `process.maxTickDepth` below.
510 process.nextTick(function() {
511 console.log('nextTick callback');
514 This is important in developing APIs where you want to give the user the
515 chance to assign event handlers after an object has been constructed,
516 but before any I/O has occurred.
518 function MyThing(options) {
519 this.setupOptions(options);
521 process.nextTick(function() {
522 this.startDoingStuff();
526 var thing = new MyThing();
527 thing.getReadyForStuff();
529 // thing.startDoingStuff() gets called now, not before.
531 It is very important for APIs to be either 100% synchronous or 100%
532 asynchronous. Consider this example:
534 // WARNING! DO NOT USE! BAD UNSAFE HAZARD!
535 function maybeSync(arg, cb) {
544 This API is hazardous. If you do this:
546 maybeSync(true, function() {
551 then it's not clear whether `foo()` or `bar()` will be called first.
553 This approach is much better:
555 function definitelyAsync(arg, cb) {
557 process.nextTick(cb);
564 ## process.maxTickDepth
566 * {Number} Default = 1000
568 Callbacks passed to `process.nextTick` will *usually* be called at the
569 end of the current flow of execution, and are thus approximately as fast
570 as calling a function synchronously. Left unchecked, this would starve
571 the event loop, preventing any I/O from occurring.
575 process.nextTick(function foo() {
576 process.nextTick(foo);
579 In order to avoid the situation where Node is blocked by an infinite
580 loop of recursive series of nextTick calls, it defers to allow some I/O
581 to be done every so often.
583 The `process.maxTickDepth` value is the maximum depth of
584 nextTick-calling nextTick-callbacks that will be evaluated before
585 allowing other forms of I/O to occur.
587 ## process.umask([mask])
589 Sets or reads the process's file mode creation mask. Child processes inherit
590 the mask from the parent process. Returns the old mask if `mask` argument is
591 given, otherwise returns the current mask.
593 var oldmask, newmask = 0644;
595 oldmask = process.umask(newmask);
596 console.log('Changed umask from: ' + oldmask.toString(8) +
597 ' to ' + newmask.toString(8));
602 Number of seconds Node has been running.
607 Returns the current high-resolution real time in a `[seconds, nanoseconds]`
608 tuple Array. It is relative to an arbitrary time in the past. It is not
609 related to the time of day and therefore not subject to clock drift. The
610 primary use is for measuring performance between intervals.
612 You may pass in the result of a previous call to `process.hrtime()` to get
613 a diff reading, useful for benchmarks and measuring intervals:
615 var time = process.hrtime();
618 setTimeout(function() {
619 var diff = process.hrtime(time);
622 console.log('benchmark took %d nanoseconds', diff[0] * 1e9 + diff[1]);
623 // benchmark took 1000000527 nanoseconds
626 [EventEmitter]: events.html#events_class_events_eventemitter