{ "source": "doc/api/process.markdown", "globals": [ { "textRaw": "process", "name": "process", "type": "global", "desc": "
The process
object is a global object and can be accessed from anywhere.\nIt is an instance of [EventEmitter][].\n\n
Node will normally exit with a 0
status code when no more async\noperations are pending. The following status codes are used in other\ncases:\n\n
1
Uncaught Fatal Exception - There was an uncaught exception,\nand it was not handled by a domain or an uncaughtException
event\nhandler.2
- Unused (reserved by Bash for builtin misuse)3
Internal JavaScript Parse Error - The JavaScript source code\ninternal in Node's bootstrapping process caused a parse error. This\nis extremely rare, and generally can only happen during development\nof Node itself.4
Internal JavaScript Evaluation Failure - The JavaScript\nsource code internal in Node's bootstrapping process failed to\nreturn a function value when evaluated. This is extremely rare, and\ngenerally can only happen during development of Node itself.5
Fatal Error - There was a fatal unrecoverable error in V8.\nTypically a message will be printed to stderr with the prefix FATAL\nERROR
.6
Non-function Internal Exception Handler - There was an\nuncaught exception, but the internal fatal exception handler\nfunction was somehow set to a non-function, and could not be called.7
Internal Exception Handler Run-Time Failure - There was an\nuncaught exception, and the internal fatal exception handler\nfunction itself threw an error while attempting to handle it. This\ncan happen, for example, if a process.on('uncaughtException')
or\ndomain.on('error')
handler throws an error.8
- Unused. In previous versions of Node, exit code 8 sometimes\nindicated an uncaught exception.9
- Invalid Argument - Either an unknown option was specified,\nor an option requiring a value was provided without a value.10
Internal JavaScript Run-Time Failure - The JavaScript\nsource code internal in Node's bootstrapping process threw an error\nwhen the bootstrapping function was called. This is extremely rare,\nand generally can only happen during development of Node itself.12
Invalid Debug Argument - The --debug
and/or --debug-brk
\noptions were set, but an invalid port number was chosen.>128
Signal Exits - If Node receives a fatal signal such as\nSIGKILL
or SIGHUP
, then its exit code will be 128
plus the\nvalue of the signal code. This is a standard Unix practice, since\nexit codes are defined to be 7-bit integers, and signal exits set\nthe high-order bit, and then contain the value of the signal code.Emitted when the process is about to exit. This is a good hook to perform\nconstant time checks of the module's state (like for unit tests). The main\nevent loop will no longer be run after the 'exit' callback finishes, so\ntimers may not be scheduled.\n\n
\nExample of listening for exit
:\n\n
process.on('exit', function() {\n setTimeout(function() {\n console.log('This will not run');\n }, 0);\n console.log('About to exit.');\n});
\n",
"params": []
},
{
"textRaw": "Event: 'uncaughtException'",
"type": "event",
"name": "uncaughtException",
"desc": "Emitted when an exception bubbles all the way back to the event loop. If a\nlistener is added for this exception, the default action (which is to print\na stack trace and exit) will not occur.\n\n
\nExample of listening for uncaughtException
:\n\n
process.on('uncaughtException', function(err) {\n console.log('Caught exception: ' + err);\n});\n\nsetTimeout(function() {\n console.log('This will still run.');\n}, 500);\n\n// Intentionally cause an exception, but don't catch it.\nnonexistentFunc();\nconsole.log('This will not run.');
\nNote that uncaughtException
is a very crude mechanism for exception\nhandling.\n\n
Don't use it, use domains instead. If you do use it, restart\nyour application after every unhandled exception!\n\n
\nDo not use it as the node.js equivalent of On Error Resume Next
. An\nunhandled exception means your application - and by extension node.js itself -\nis in an undefined state. Blindly resuming means anything could happen.\n\n
Think of resuming as pulling the power cord when you are upgrading your system.\nNine out of ten times nothing happens - but the 10th time, your system is bust.\n\n
\nYou have been warned.\n\n
\n", "params": [] }, { "textRaw": "Signal Events", "name": "SIGINT, SIGHUP, etc.", "type": "event", "desc": "Emitted when the processes receives a signal. See sigaction(2) for a list of\nstandard POSIX signal names such as SIGINT, SIGHUP, etc.\n\n
\nExample of listening for SIGINT
:\n\n
// Start reading from stdin so we don't exit.\nprocess.stdin.resume();\n\nprocess.on('SIGINT', function() {\n console.log('Got SIGINT. Press Control-D to exit.');\n});
\nAn easy way to send the SIGINT
signal is with Control-C
in most terminal\nprograms.\n\n
Note: SIGUSR1 is reserved by node.js to kickstart the debugger. It's possible\nto install a listener but that won't stop the debugger from starting.\n\n
\n", "params": [] } ], "properties": [ { "textRaw": "process.stdout", "name": "stdout", "desc": "A Writable Stream
to stdout
.\n\n
Example: the definition of console.log
\n\n
console.log = function(d) {\n process.stdout.write(d + '\\n');\n};
\nprocess.stderr
and process.stdout
are unlike other streams in Node in\nthat writes to them are usually blocking. They are blocking in the case\nthat they refer to regular files or TTY file descriptors. In the case they\nrefer to pipes, they are non-blocking like other streams.\n\n
To check if Node is being run in a TTY context, read the isTTY
property\non process.stderr
, process.stdout
, or process.stdin
:\n\n
$ node -p "Boolean(process.stdin.isTTY)"\ntrue\n$ echo "foo" | node -p "Boolean(process.stdin.isTTY)"\nfalse\n\n$ node -p "Boolean(process.stdout.isTTY)"\ntrue\n$ node -p "Boolean(process.stdout.isTTY)" | cat\nfalse
\nSee the tty docs for more information.\n\n
\n" }, { "textRaw": "process.stderr", "name": "stderr", "desc": "A writable stream to stderr.\n\n
\nprocess.stderr
and process.stdout
are unlike other streams in Node in\nthat writes to them are usually blocking. They are blocking in the case\nthat they refer to regular files or TTY file descriptors. In the case they\nrefer to pipes, they are non-blocking like other streams.\n\n\n
A Readable Stream
for stdin. The stdin stream is paused by default, so one\nmust call process.stdin.resume()
to read from it.\n\n
Example of opening standard input and listening for both events:\n\n
\nprocess.stdin.resume();\nprocess.stdin.setEncoding('utf8');\n\nprocess.stdin.on('data', function(chunk) {\n process.stdout.write('data: ' + chunk);\n});\n\nprocess.stdin.on('end', function() {\n process.stdout.write('end');\n});
\n"
},
{
"textRaw": "process.argv",
"name": "argv",
"desc": "An array containing the command line arguments. The first element will be\n'node', the second element will be the name of the JavaScript file. The\nnext elements will be any additional command line arguments.\n\n
\n// print process.argv\nprocess.argv.forEach(function(val, index, array) {\n console.log(index + ': ' + val);\n});
\nThis will generate:\n\n
\n$ node process-2.js one two=three four\n0: node\n1: /Users/mjr/work/node/process-2.js\n2: one\n3: two=three\n4: four
\n"
},
{
"textRaw": "process.execPath",
"name": "execPath",
"desc": "This is the absolute pathname of the executable that started the process.\n\n
\nExample:\n\n
\n/usr/local/bin/node
\n"
},
{
"textRaw": "process.execArgv",
"name": "execArgv",
"desc": "This is the set of node-specific command line options from the\nexecutable that started the process. These options do not show up in\nprocess.argv
, and do not include the node executable, the name of\nthe script, or any options following the script name. These options\nare useful in order to spawn child processes with the same execution\nenvironment as the parent.\n\n
Example:\n\n
\n$ node --harmony script.js --version
\nresults in process.execArgv:\n\n
\n['--harmony']
\nand process.argv:\n\n
\n['/usr/local/bin/node', 'script.js', '--version']
\n"
},
{
"textRaw": "process.env",
"name": "env",
"desc": "An object containing the user environment. See environ(7).\n\n\n
\n" }, { "textRaw": "process.exitCode", "name": "exitCode", "desc": "A number which will be the process exit code, when the process either\nexits gracefully, or is exited via process.exit()
without specifying\na code.\n\n
Specifying a code to process.exit(code)
will override any previous\nsetting of process.exitCode
.\n\n\n
A compiled-in property that exposes NODE_VERSION
.\n\n
console.log('Version: ' + process.version);
\n"
},
{
"textRaw": "process.versions",
"name": "versions",
"desc": "A property exposing version strings of node and its dependencies.\n\n
\nconsole.log(process.versions);
\nWill print something like:\n\n
\n{ http_parser: '1.0',\n node: '0.10.4',\n v8: '3.14.5.8',\n ares: '1.9.0-DEV',\n uv: '0.10.3',\n zlib: '1.2.3',\n modules: '11',\n openssl: '1.0.1e' }
\n"
},
{
"textRaw": "process.config",
"name": "config",
"desc": "An Object containing the JavaScript representation of the configure options\nthat were used to compile the current node executable. This is the same as\nthe "config.gypi" file that was produced when running the ./configure
script.\n\n
An example of the possible output looks like:\n\n
\n{ target_defaults:\n { cflags: [],\n default_configuration: 'Release',\n defines: [],\n include_dirs: [],\n libraries: [] },\n variables:\n { host_arch: 'x64',\n node_install_npm: 'true',\n node_prefix: '',\n node_shared_cares: 'false',\n node_shared_http_parser: 'false',\n node_shared_libuv: 'false',\n node_shared_v8: 'false',\n node_shared_zlib: 'false',\n node_use_dtrace: 'false',\n node_use_openssl: 'true',\n node_shared_openssl: 'false',\n strict_aliasing: 'true',\n target_arch: 'x64',\n v8_use_snapshot: 'true' } }
\n"
},
{
"textRaw": "process.pid",
"name": "pid",
"desc": "The PID of the process.\n\n
\nconsole.log('This process is pid ' + process.pid);
\n"
},
{
"textRaw": "process.title",
"name": "title",
"desc": "Getter/setter to set what is displayed in 'ps'.\n\n
\nWhen used as a setter, the maximum length is platform-specific and probably\nshort.\n\n
\nOn Linux and OS X, it's limited to the size of the binary name plus the\nlength of the command line arguments because it overwrites the argv memory.\n\n
\nv0.8 allowed for longer process title strings by also overwriting the environ\nmemory but that was potentially insecure/confusing in some (rather obscure)\ncases.\n\n\n
\n" }, { "textRaw": "process.arch", "name": "arch", "desc": "What processor architecture you're running on: 'arm'
, 'ia32'
, or 'x64'
.\n\n
console.log('This processor architecture is ' + process.arch);
\n"
},
{
"textRaw": "process.platform",
"name": "platform",
"desc": "What platform you're running on:\n'darwin'
, 'freebsd'
, 'linux'
, 'sunos'
or 'win32'
\n\n
console.log('This platform is ' + process.platform);
\n"
}
],
"methods": [
{
"textRaw": "process.abort()",
"type": "method",
"name": "abort",
"desc": "This causes node to emit an abort. This will cause node to exit and\ngenerate a core file.\n\n
\n", "signatures": [ { "params": [] } ] }, { "textRaw": "process.chdir(directory)", "type": "method", "name": "chdir", "desc": "Changes the current working directory of the process or throws an exception if that fails.\n\n
\nconsole.log('Starting directory: ' + process.cwd());\ntry {\n process.chdir('/tmp');\n console.log('New directory: ' + process.cwd());\n}\ncatch (err) {\n console.log('chdir: ' + err);\n}
\n",
"signatures": [
{
"params": [
{
"name": "directory"
}
]
}
]
},
{
"textRaw": "process.cwd()",
"type": "method",
"name": "cwd",
"desc": "Returns the current working directory of the process.\n\n
\nconsole.log('Current directory: ' + process.cwd());
\n",
"signatures": [
{
"params": []
}
]
},
{
"textRaw": "process.exit([code])",
"type": "method",
"name": "exit",
"desc": "Ends the process with the specified code
. If omitted, exit uses the\n'success' code 0
.\n\n
To exit with a 'failure' code:\n\n
\nprocess.exit(1);
\nThe shell that executed node should see the exit code as 1.\n\n\n
\n", "signatures": [ { "params": [ { "name": "code", "optional": true } ] } ] }, { "textRaw": "process.getgid()", "type": "method", "name": "getgid", "desc": "Note: this function is only available on POSIX platforms (i.e. not Windows,\nAndroid)\n\n
\nGets the group identity of the process. (See getgid(2).)\nThis is the numerical group id, not the group name.\n\n
\nif (process.getgid) {\n console.log('Current gid: ' + process.getgid());\n}
\n",
"signatures": [
{
"params": []
}
]
},
{
"textRaw": "process.setgid(id)",
"type": "method",
"name": "setgid",
"desc": "Note: this function is only available on POSIX platforms (i.e. not Windows,\nAndroid)\n\n
\nSets the group identity of the process. (See setgid(2).) This accepts either\na numerical ID or a groupname string. If a groupname is specified, this method\nblocks while resolving it to a numerical ID.\n\n
\nif (process.getgid && process.setgid) {\n console.log('Current gid: ' + process.getgid());\n try {\n process.setgid(501);\n console.log('New gid: ' + process.getgid());\n }\n catch (err) {\n console.log('Failed to set gid: ' + err);\n }\n}
\n",
"signatures": [
{
"params": [
{
"name": "id"
}
]
}
]
},
{
"textRaw": "process.getuid()",
"type": "method",
"name": "getuid",
"desc": "Note: this function is only available on POSIX platforms (i.e. not Windows,\nAndroid)\n\n
\nGets the user identity of the process. (See getuid(2).)\nThis is the numerical userid, not the username.\n\n
\nif (process.getuid) {\n console.log('Current uid: ' + process.getuid());\n}
\n",
"signatures": [
{
"params": []
}
]
},
{
"textRaw": "process.setuid(id)",
"type": "method",
"name": "setuid",
"desc": "Note: this function is only available on POSIX platforms (i.e. not Windows,\nAndroid)\n\n
\nSets the user identity of the process. (See setuid(2).) This accepts either\na numerical ID or a username string. If a username is specified, this method\nblocks while resolving it to a numerical ID.\n\n
\nif (process.getuid && process.setuid) {\n console.log('Current uid: ' + process.getuid());\n try {\n process.setuid(501);\n console.log('New uid: ' + process.getuid());\n }\n catch (err) {\n console.log('Failed to set uid: ' + err);\n }\n}
\n",
"signatures": [
{
"params": [
{
"name": "id"
}
]
}
]
},
{
"textRaw": "process.getgroups()",
"type": "method",
"name": "getgroups",
"desc": "Note: this function is only available on POSIX platforms (i.e. not Windows,\nAndroid)\n\n
\nReturns an array with the supplementary group IDs. POSIX leaves it unspecified\nif the effective group ID is included but node.js ensures it always is.\n\n\n
\n", "signatures": [ { "params": [] } ] }, { "textRaw": "process.setgroups(groups)", "type": "method", "name": "setgroups", "desc": "Note: this function is only available on POSIX platforms (i.e. not Windows,\nAndroid)\n\n
\nSets the supplementary group IDs. This is a privileged operation, meaning you\nneed to be root or have the CAP_SETGID capability.\n\n
\nThe list can contain group IDs, group names or both.\n\n\n
\n", "signatures": [ { "params": [ { "name": "groups" } ] } ] }, { "textRaw": "process.initgroups(user, extra_group)", "type": "method", "name": "initgroups", "desc": "Note: this function is only available on POSIX platforms (i.e. not Windows,\nAndroid)\n\n
\nReads /etc/group and initializes the group access list, using all groups of\nwhich the user is a member. This is a privileged operation, meaning you need\nto be root or have the CAP_SETGID capability.\n\n
\nuser
is a user name or user ID. extra_group
is a group name or group ID.\n\n
Some care needs to be taken when dropping privileges. Example:\n\n
\nconsole.log(process.getgroups()); // [ 0 ]\nprocess.initgroups('bnoordhuis', 1000); // switch user\nconsole.log(process.getgroups()); // [ 27, 30, 46, 1000, 0 ]\nprocess.setgid(1000); // drop root gid\nconsole.log(process.getgroups()); // [ 27, 30, 46, 1000 ]
\n",
"signatures": [
{
"params": [
{
"name": "user"
},
{
"name": "extra_group"
}
]
}
]
},
{
"textRaw": "process.kill(pid, [signal])",
"type": "method",
"name": "kill",
"desc": "Send a signal to a process. pid
is the process id and signal
is the\nstring describing the signal to send. Signal names are strings like\n'SIGINT' or 'SIGHUP'. If omitted, the signal will be 'SIGTERM'.\nSee kill(2) for more information.\n\n
Note that just because the name of this function is process.kill
, it is\nreally just a signal sender, like the kill
system call. The signal sent\nmay do something other than kill the target process.\n\n
Example of sending a signal to yourself:\n\n
\nprocess.on('SIGHUP', function() {\n console.log('Got SIGHUP signal.');\n});\n\nsetTimeout(function() {\n console.log('Exiting.');\n process.exit(0);\n}, 100);\n\nprocess.kill(process.pid, 'SIGHUP');
\nNote: SIGUSR1 is reserved by node.js. It can be used to kickstart the\ndebugger.\n\n
\n", "signatures": [ { "params": [ { "name": "pid" }, { "name": "signal", "optional": true } ] } ] }, { "textRaw": "process.memoryUsage()", "type": "method", "name": "memoryUsage", "desc": "Returns an object describing the memory usage of the Node process\nmeasured in bytes.\n\n
\nvar util = require('util');\n\nconsole.log(util.inspect(process.memoryUsage()));
\nThis will generate:\n\n
\n{ rss: 4935680,\n heapTotal: 1826816,\n heapUsed: 650472 }
\nheapTotal
and heapUsed
refer to V8's memory usage.\n\n\n
Once the current event loop turn runs to completion, call the callback\nfunction.\n\n
\nThis is not a simple alias to setTimeout(fn, 0)
, it's much more\nefficient. It runs before any additional I/O events (including\ntimers) fire in subsequent ticks of the event loop.\n\n
console.log('start');\nprocess.nextTick(function() {\n console.log('nextTick callback');\n});\nconsole.log('scheduled');\n// Output:\n// start\n// scheduled\n// nextTick callback
\nThis is important in developing APIs where you want to give the user the\nchance to assign event handlers after an object has been constructed,\nbut before any I/O has occurred.\n\n
\nfunction MyThing(options) {\n this.setupOptions(options);\n\n process.nextTick(function() {\n this.startDoingStuff();\n }.bind(this));\n}\n\nvar thing = new MyThing();\nthing.getReadyForStuff();\n\n// thing.startDoingStuff() gets called now, not before.
\nIt is very important for APIs to be either 100% synchronous or 100%\nasynchronous. Consider this example:\n\n
\n// WARNING! DO NOT USE! BAD UNSAFE HAZARD!\nfunction maybeSync(arg, cb) {\n if (arg) {\n cb();\n return;\n }\n\n fs.stat('file', cb);\n}
\nThis API is hazardous. If you do this:\n\n
\nmaybeSync(true, function() {\n foo();\n});\nbar();
\nthen it's not clear whether foo()
or bar()
will be called first.\n\n
This approach is much better:\n\n
\nfunction definitelyAsync(arg, cb) {\n if (arg) {\n process.nextTick(cb);\n return;\n }\n\n fs.stat('file', cb);\n}
\nNote: the nextTick queue is completely drained on each pass of the\nevent loop before additional I/O is processed. As a result,\nrecursively setting nextTick callbacks will block any I/O from\nhappening, just like a while(true);
loop.\n\n
Sets or reads the process's file mode creation mask. Child processes inherit\nthe mask from the parent process. Returns the old mask if mask
argument is\ngiven, otherwise returns the current mask.\n\n
var oldmask, newmask = 0644;\n\noldmask = process.umask(newmask);\nconsole.log('Changed umask from: ' + oldmask.toString(8) +\n ' to ' + newmask.toString(8));
\n",
"signatures": [
{
"params": [
{
"name": "mask",
"optional": true
}
]
}
]
},
{
"textRaw": "process.uptime()",
"type": "method",
"name": "uptime",
"desc": "Number of seconds Node has been running.\n\n\n
\n", "signatures": [ { "params": [] } ] }, { "textRaw": "process.hrtime()", "type": "method", "name": "hrtime", "desc": "Returns the current high-resolution real time in a [seconds, nanoseconds]
\ntuple Array. It is relative to an arbitrary time in the past. It is not\nrelated to the time of day and therefore not subject to clock drift. The\nprimary use is for measuring performance between intervals.\n\n
You may pass in the result of a previous call to process.hrtime()
to get\na diff reading, useful for benchmarks and measuring intervals:\n\n
var time = process.hrtime();\n// [ 1800216, 25 ]\n\nsetTimeout(function() {\n var diff = process.hrtime(time);\n // [ 1, 552 ]\n\n console.log('benchmark took %d nanoseconds', diff[0] * 1e9 + diff[1]);\n // benchmark took 1000000527 nanoseconds\n}, 1000);
\n",
"signatures": [
{
"params": []
}
]
}
]
}
]
}