May 10, 2021 Node.js
24.. process.setgroups(groups)
25.. process.initgroups(user, extra_group)
29.. process.kill(pid[, signal])
This section describes .js process object that provides information and control about the .js Process process.
process
is a global object that can be accessed anywhere without using require(), an
instance of EventEmitter.
Node normally returns status code 0 when it does not need to handle new asynchronous
0
Here are some status codes that represent other states:
1
Uncaught Fatal Exception - Uncaught Fatal Exception
- has an uncaught exception and is not handled by the domain or
uncaughtException
handler.
2
- Unused (reserved)
3
JavaScript resolution error - Internal JavaScript Parse Error
- The source code for JavaScript causes an parsing error when it starts the Node process. V
ery rare, only when developing Node.
4
JavaScript evaluation failed - Internal JavaScript Evaluation Failure
- JavaScript's source code started the Node process and the return function failed during the evaluation. V
ery rare, only when developing Node.
5
Error - Fatal Error
- Fatal unrec recoverable error in V8.
Typically printed to stderr with the message:
FATAL ERROR
6
Non-function exception handling - Non-function Internal Exception Handler
- No exception was caught, the internal exception handler was somehow set to on-function, and could not be called.
7
Handler Run-Time Failure -
Unaught exception, and throws exception itself while the exception handler is handling it. F
or example,
process.on('uncaughtException')
domain.on('error')
an exception.
8
- Unused Reserved. I
n previous versions of Node, status code 8 sometimes indicated that an exception was not caught.
9
-
Argument Illegal - Invalid Argument
- May have given an unknown argument, or given no value to the argument.
10
Failure - Internal JavaScript Run-Time Failure
- It is rare for JavaScript's source code to throw an error when it starts the Node process, only when developing Node.
12
Invalid Debug Argument
- Set parameter
--debug
--debug-brk
but the wrong port is selected.
>128
Signal Exits -
If Node receives
a fatal signal, such
SIGKILL
or
SIGHUP
the exit code
128
plus the signal code.
This is standard Unix practice, with exit signal codes placed high.
Triggered when the process is ready to exit. T here is no way to prevent roll-out from the event loop at this time. T herefore, you must perform a synchronization operation in the handler. T his is a good time to check the status of a module at a fixed event, such as unit testing. The callback function has an argument that is the exit code for the process.
Examples of
exit
events:
process.on('exit', function(code) {
// do *NOT* do this
setTimeout(function() {
console.log('This will not run');
}, 0);
console.log('About to exit with code:', code);
});
This event is triggered when node emptys the event loop and there is no other schedule. Typically, node exits when there is no process scheduling, but the 'beforeExit' listener can be called asynchronously so that node continues to execute.
'beforeExit' is not an explicit exit condition,
process.exit()
or exception capture is, so don't think of it as an 'exit' event.
Unless you want to arrange more work.
When an exception bubbles back into the event loop, the event is triggered. If a monitor is added to the exception, the default action (printing stack trace information and exiting) will not occur.
Examples
uncaughtException
process.on('uncaughtException', function(err) {
console.log('Caught exception: ' + err);
});
setTimeout(function() {
console.log('This will still run.');
}, 500);
// Intentionally cause an exception, but don't catch it.
nonexistentFunc();
console.log('This will not run.');
Note:
uncaughtException
a very simple exception handling mechanism.
Try not to use it, but instead use domains. If you use it, restart your program each time you don't handle an exception.
Do not use the .js such as
On Error Resume Next
in the database. E
ach unprocessed exception means that your program, and your .js extender, an unknown state.
Blind recovery means that anything can happen
You pulled off the power cord while upgrading the system and recovered it. Maybe 9 out of 10 is no problem, but on the 10th, your system may hang up.
Triggered when a process receives a signal. The list of signals can be found in standard POSIX signal names such as SIGINT, SIGUSR1, etc.
Examples of
SIGINT
// Start reading from stdin so we don't exit.
process.stdin.resume();
process.on('SIGINT', function() {
console.log('Got SIGINT. Press Control-D to exit.');
});
In most terminal programs, the simple
SIGINT
signal is to press the
信号Control-C
Attention:
SIGUSR1
node .js this signal to turn on debugging mode. Y
ou can install a listener without interrupting debugging at first.
SIGTERM
SIGINT
default handlers in non-Windows systems that reset exit mode before exiting (with exit code
128 + 信号码
plus letter number). I
f these signals have monitors, the default behavior will be removed.
SIGPIPE
by default and can be added to the listener.
SIGHUP
generated when the Windowns console is closed, similar conditions for other platforms, see signal (7). Y
ou can add a listener and exit unconditionally after 10 seconds on the Windows platform.
On non-Windows platforms,
SIGHUP
default action is to terminate node, but once a listener is added, the default action is removed.
SIGTERM
Windows does not support it and can be monitored.
SIGINT
are supported and are typically
CTRL+C
(which may require configuration). W
hen terminal original mode is enabled, it is no longer generated.
SIGBREAK
I
n Windows, pressing
CTRL+BREAK
send. N
on-Windows platform, can be monitored, but cannot be sent or generated.
SIGWINCH
- Send when the console is resynched. I
n a Windows system, the cursor moves only when you enter content on the console, or the readable tty is used in the original mode.
SIGKILL
monitors to turn off node unconditionally on all platforms.
SIGSTOP
have a monitor.
Windows does not support sending signals, but node
process.kill()
child_process.kill()
0
the process in operation
SIGINT
SIGTERM
SIGKILL
target process to exit unconditionally.
A
Writable Stream
directed
stdout
(fd
1
).
For example:
console.log
console.log = function(d) {
process.stdout.write(d + '\n');
};
process.stderr
other streams in
process.stdout
and node, will not be
end()
will be thrown, they will
finish
and writes are blocked.
Check if Node is running in the TTY context and read the isTTY property from
process.stderr
process.stdout
or
process.stdin
isTTY
$ node -p "Boolean(process.stdin.isTTY)"
true
$ echo "foo" | node -p "Boolean(process.stdin.isTTY)"
false
$ node -p "Boolean(process.stdout.isTTY)"
true
$ node -p "Boolean(process.stdout.isTTY)" | cat
false
See the tty docs for more information.
A writeable stream pointing to stderr (fd
2
process.stderr
like other streams in
process.stdout
and node, will not be
end()
they will
finish
and write is blocked.
A readable stream pointing to
0
(fd 0).
Here's an example: Open the standard input stream and listen for two events:
process.stdin.setEncoding('utf8');
process.stdin.on('readable', function() {
var chunk = process.stdin.read();
if (chunk !== null) {
process.stdout.write('data: ' + chunk);
}
});
process.stdin.on('end', function() {
process.stdout.write('end');
});
process.stdin
in old mode and is compatible with the node code before v0.10.
For more information, see Streaming .
In the old stream mode, the stdin stream is paused by default and
process.stdin.resume()
read.
You can
process.stdin.resume()
to switch to the old mode.
If you start a new project, it's better to choose a new stream than an old one.
An array that contains command-line parameters. The first element is 'node', the second argument is the name of the JavaScript file, and the third argument is any command line argument.
// print process.argv
process.argv.forEach(function(val, index, array) {
console.log(index + ': ' + val);
});
Will generate:
$ node process-2.js one two=three four
0: node
1: /Users/mjr/work/node/process-2.js
2: one
3: two=three
4: four
The absolute path to the execution file that opens the current process.
Example:
/usr/local/bin/node
The node command line parameters required to start the process. T
hese parameters do not
process.argv
and do not contain the name of the node execution file, or any parameters after the name.
These are used to generate child processes that have the same parameters as the parent process.
Example:
$ node --harmony script.js --version
Parameters of process.execArgv:
['--harmony']
Parameters of process.argv:
['/usr/local/bin/node', 'script.js', '--version']
This causes node to trigger an abort event. Will let node exit and generate a core file.
Change the directory of the current working process and throw an exception if the operation fails.
console.log('Starting directory: ' + process.cwd());
try {
process.chdir('/tmp');
console.log('New directory: ' + process.cwd());
}
catch (err) {
console.log('chdir: ' + err);
}
Returns the working directory of the current process:
console.log('Current directory: ' + process.cwd());
Objects that contain the user environment, see environ (7).
Examples of this object:
{ TERM: 'xterm-256color',
SHELL: '/usr/local/bin/bash',
USER: 'maciej',
PATH: '~/.bin/:/usr/bin:/bin:/usr/sbin:/sbin:/usr/local/bin',
PWD: '/Users/maciej',
EDITOR: 'vim',
SHLVL: '1',
HOME: '/Users/maciej',
LOGNAME: 'maciej',
_: '/usr/local/bin/node' }
You can write to this object, but it does not change the currently running process. The following commands will not succeed:
node -e 'process.env.foo = "bar"' && echo $foo
This will succeed:
process.env.foo = 'bar';
console.log(process.env.foo);
End the process with the specified code.
If ignored, code
0
Exit with failed code:
process.exit(1);
The shell will see an exit code of 1.
The code at the time of the process exit, if the process exits gracefully,
process.exit()
does not need to specify an exit code.
Setting
process.exit(code)
override the
process.exitCode
Note: This function is only available on POSIX platforms (for example, non-Windows and Android).
Gets the group identity of the process (see getgid (2).) Gets the digital Id of the time-to-time group, not the name.
if (process.getgid) {
console.log('Current gid: ' + process.getgid());
}
Note: This function is only available on POSIX platforms (for example, non-Windows and Android).
Set the group identity of the process (see setgid (2).) Y ou can receive a digital ID or group name. If a group name is specified, it blocks the wait to resolve to a digital ID.
if (process.getgid && process.setgid) {
console.log('Current gid: ' + process.getgid());
try {
process.setgid(501);
console.log('New gid: ' + process.getgid());
}
catch (err) {
console.log('Failed to set gid: ' + err);
}
}
Note: This function is only available on POSIX platforms (for example, non-Windows and Android).
Get the user ID of the process (see getuid (2).) This is the digital user ID, not the user name:
if (process.getuid) {
console.log('Current uid: ' + process.getuid());
}
Note: This function is only available on POSIX platforms (for example, non-Windows and Android).
Set the user identity of the process (see setuid (2).) R eceive a numeric ID or string name. If the group name is specified, it blocks the wait to resolve to the digital ID.
if (process.getuid && process.setuid) {
console.log('Current uid: ' + process.getuid());
try {
process.setuid(501);
console.log('New uid: ' + process.getuid());
}
catch (err) {
console.log('Failed to set uid: ' + err);
}
}
Note: This function is only available on POSIX platforms (for example, non-Windows and Android).
Returns the group iD array of the process. PoSIX systems are not guaranteed, but .js is guaranteed.
Note: This function is only available on POSIX platforms (for example, non-Windows and Android).
Set the group ID for the process. This is an authorization operation, all you need to have root permissions, or have CAP_SETGID capabilities.
A list can contain group IDs, group names, or both.
Note: This function is only available on POSIX platforms (for example, non-Windows and Android).
Read/etc/group and initialize the group access list, using all groups in which the members are located. This is an authorization operation, all you need to have root permissions, or have CAP_SETGID capabilities.
user
is the user name or user
extra_group
is the group name or group ID.
You need to be careful when you log out of permissions. Example:
console.log(process.getgroups()); // [ 0 ]
process.initgroups('bnoordhuis', 1000); // switch user
console.log(process.getgroups()); // [ 27, 30, 46, 1000, 0 ]
process.setgid(1000); // drop root gid
console.log(process.getgroups()); // [ 27, 30, 46, 1000 ]
A compilation property that contains
NODE_VERSION
.
console.log('Version: ' + process.version);
A property that contains the version and dependency of node.
console.log(process.versions);
Print it out:
{ http_parser: '1.0',
node: '0.10.4',
v8: '3.14.5.8',
ares: '1.9.0-DEV',
uv: '0.10.3',
zlib: '1.2.3',
modules: '11',
openssl: '1.0.1e' }
An object that contains javascript configuration options for compiling the current node execution file. It is the same as the "config.gypi" file generated by the ./configure script.
One possible output:
{ target_defaults:
{ cflags: [],
default_configuration: 'Release',
defines: [],
include_dirs: [],
libraries: [] },
variables:
{ host_arch: 'x64',
node_install_npm: 'true',
node_prefix: '',
node_shared_cares: 'false',
node_shared_http_parser: 'false',
node_shared_libuv: 'false',
node_shared_v8: 'false',
node_shared_zlib: 'false',
node_use_dtrace: 'false',
node_use_openssl: 'true',
node_shared_openssl: 'false',
strict_aliasing: 'true',
target_arch: 'x64',
v8_use_snapshot: 'true' } }
Send a signal to the process.
pid
the process id, and
signal
a string description of the signal sent. T
he signal name is a string, such as 'SIGINT' or 'SIGHUP'. I
f ignored, the signal will be 'SIGTERM'.
See
Signal Events and
Kill (2) for more information.
If the process does not exit, an error is thrown.
Signal
0
to test the existence of a process.
Note that although this function is
process.kill
it is really just a signal transmitter, just like
kill
system call.
Signaling can do other things, not just kill the target process.
Example, signal yourself:
process.on('SIGHUP', function() {
console.log('Got SIGHUP signal.');
});
setTimeout(function() {
console.log('Exiting.');
process.exit(0);
}, 100);
process.kill(process.pid, 'SIGHUP');
Note: When Node .js receives a SIGUSR1 signal, it turns on debugger debugger debugging mode, see Signal Events .
PID of the current process:
console.log('This process is pid ' + process.pid);
Get/Set (Getter/setter) the name of the process shown in 'ps'.
When you use setter, the length of the string is specified by the system and may be short.
On Linux and OS X, it is limited by the length of the name plus the length of the command line argument because it overrides the parameter memory.
The v0.8 version allows for longer process title strings and also supports overwriting environment memory, but there is potential insecurity and confusion (it's hard to tell).
Current CPU architecture: 'arm', 'ia32' or 'x64'.
console.log('This processor architecture is ' + process.arch);
The platform system on which the
'darwin'
'freebsd'
'linux'
'sunos'
'win32'
console.log('This platform is ' + process.platform);
Returns an object that describes the memory condition used by the Node process in bytes.
var util = require('util');
console.log(util.inspect(process.memoryUsage()));
Will generate:
{ rss: 4935680,
heapTotal: 1826816,
heapUsed: 650472 }
heapTotal
and
heapUsed
to the memory usage of V8.
callback
{Function}
Once the current event loop ends, the call goes back to the function.
This
setTimeout(fn, 0)
which is more efficient.
Any additional I/O event runs before it is triggered in the sub-queue event loop.
console.log('start');
process.nextTick(function() {
console.log('nextTick callback');
});
console.log('scheduled');
// Output:
// start
// scheduled
// nextTick callback
This is useful after object construction, when you want to change additional event handler before I/O events occur.
function MyThing(options) {
this.setupOptions(options);
process.nextTick(function() {
this.startDoingStuff();
}.bind(this));
}
var thing = new MyThing();
thing.getReadyForStuff();
// thing.startDoingStuff() gets called now, not before.
Make sure that your function must be executed 100% synchronously, or 100% asynchronously. Example:
// WARNING! DO NOT USE! BAD UNSAFE HAZARD!
function maybeSync(arg, cb) {
if (arg) {
cb();
return;
}
fs.stat('file', cb);
}
This API is very dangerous. If you do this:
maybeSync(true, function() {
foo();
});
bar();
It is
foo()
bar()
is executed first.
A better way:
function definitelyAsync(arg, cb) {
if (arg) {
process.nextTick(cb);
return;
}
fs.stat('file', cb);
}
Note: NextTick queues call I/O operations only after they have been fully executed. T
herefore, the recursive setting of nextTick's callback is
while(true);
Loops, like this, will prevent any I/O operations from occurring.
Set or read the mask for the process file. T
he child process inherits the mask from the parent process. I
f
mask
parameter is valid, the old mask is returned.
Otherwise, the current mask is returned.
var oldmask, newmask = 0022;
oldmask = process.umask(newmask);
console.log('Changed umask from: ' + oldmask.toString(8) +
' to ' + newmask.toString(8));
Returns the number of seconds that Node has run.
Returns the high-resolution time of the current process in the form of an array of
[seconds, nanoseconds]
I
t is relative to any event in the past. T
his value is date independent and therefore not affected by clock drift.
The primary use is to measure the performance of a program at precise intervals.
You can pass the previous results to
process.hrtime()
which returns the time difference between the two, which is used for benchmarking and measuring time intervals.
var time = process.hrtime();
// [ 1800216, 25 ]
setTimeout(function() {
var diff = process.hrtime(time);
// [ 1, 552 ]
console.log('benchmark took %d nanoseconds', diff[0] * 1e9 + diff[1]);
// benchmark took 1000000527 nanoseconds
}, 1000);
require.main
T
he difference is that if the main module changes at runtime,
require.main
may continue to return to the old module.
It can be argued that the two refer to the same module.
The
process.mainModule
provides an alternative way to retrieve
require.main
T
he difference is that if the main module changes at runtime,
require.main
the original primary module in the required module before the change occurs.
In general, it is safe to assume that the two modules with the same reference are safe.
As
require.main
if there is no entry script,
undefined