Detailed explanation of process process in nodejs

  • 2021-08-05 08:13:26
  • OfStack

Although node does a lot of abstract work on the operating system, you can still interact directly with it, such as interacting with existing processes in the system and creating working sub-processes. node is a thread for the event loop, but you can create other processes (threads) outside the event loop to participate in the work.

Process module

The process module allows you to obtain or modify the settings of the current node process. No other modules, process is a global process (node main process), and you can access it directly through the process variable.

process implements the EventEmitter interface, and the exit method executes when the process exits. Because the event loop will no longer be executed after the process exits, all code that does not have a callback function will be executed. In the following example, the statement in setTimeout cannot be executed.


process.on('exit', function () {
    setTimeout(function () {
          console.log('This will not run');
    }, 100);
    console.log('Bye.');
});

After you touch node, you will find that exceptions that affect the main event loop will slow down the entire node process. This can be quite a problem, so process provides another useful event uncaughtException to solve this problem, which will crawl the exception for you to handle.


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.');

Let's look at the above example. We registered the uncaughtException event to catch system exceptions. When executing to nonexistentFunc (), an exception is thrown because the function is not defined. Because javascript is an interpretive language, the statements above the nonexistentFunc () method will not be affected and the statements below it will not be executed. So his execution results are as follows:

Caught exception: ReferenceError: nonexistentFunc is not defined

This will still run.

Let's look at another example.


var http = require('http');
var server = http.createServer(function(req,res) {
    res.writeHead(200, {});
    res.end('response');
    badLoggingCall('sent response');
    console.log('sent response');
});
process.on('uncaughtException', function(e) {
    console.log(e);
});
server.listen(8080);

In this example, we created an web server, and when the request is processed, we execute the badLoggingCall () method. Because this method does not exist, an exception will be thrown. However, the uncaughtException event we registered handles the exception so that the server can continue to run without being affected. We log errors on the server side.

[ReferenceError: badLoggingCall is not defined]

Interact with the current process

node provides one of the properties of process, as follows:

process. version: Contains the version number of the current node instance;

process. installPrefix: Contains the installation path;

process. platform: Enumerating the environment of the operating system in which node runs will only display kernel-related information, such as linux2 and darwin, instead of "Redhat ES3", "Windows 7" and "OSX 10.7";

process. uptime (): Contains how long the current process has been running in seconds;

process. getgid (), process. setgid (): Gets or sets group id;

process. getuid (), process. setuid (): Get or design user id;

process. pid: Get process id;

process. title: Sets the process name;

process. execPath: The execution path of the current node process, such as:/usr/local/bin/node;

process. cwd (): Current working directory;

process. memoryUsage (): node process memory usage, rss for ram usage, vsize for total memory usage, including ram and swap;

process. heapTotal, process. heapUsed: Represents the v8 engine memory allocation and the size being used, respectively.

Event Loop and ticker

The process. nextTick () method is provided in node, which allows you to access event loops and delay your work. It is somewhat similar to setTimeout (), it will be executed at the next tick, and it will be executed once every one event. We have an example here:


var http = require('http');
var s = http.createServer(function(req, res) {
    res.writeHead(200, {});
    res.end('foo');
    console.log('http response');
    process.nextTick(function(){console.log('tick')});
});
s.listen(8000);

When the request comes, the logs' http response 'and' tick 'will be recorded. When there is no request, the event loop will be executed every 1 event, and tick will be output.

In addition, the callback functions created by nextTick are isolated, and they do not affect each other.


process.on('uncaughtException', function(e) {
    console.log(e);
});
process.nextTick(function() {
    console.log('tick');
});
process.nextTick(function() {
    iAmAMistake();
    console.log('tock');
});
process.nextTick(function() {
    console.log('tick tock');
});
console.log('End of 1st loop');

In this example, first output 'End of 1st loop', then sequentially output nextTick callback functions, the first will normally output 'tick', the second is a deliberately set exception will output exception information, not 'tock', because of the isolation of nextTick callback functions, the third will still output 'tick tock'. The results are as follows:

End of 1st loop
tick
[ReferenceError: iAmAMistake is not defined]
tick tock

Child process

node provides the child_process module, which allows you to create child processes for the main process so that you can use more server resources and use more cpu, concepts described in the previous section. node provides child_process. spawn () and child_process. exec () for you to implement this 1 function, which is described separately below.

child_process. exec ()

Let's look at a simple example of exec, which creates a child process, the first argument is an shell command, and the second argument is a callback function, which handles the return results.


var cp = require('child_process');
cp.exec('ls -l', function(e, stdout, stderr) {
    if(!e) {
          console.log(stdout);
          console.log(stderr);
    }
});

exec () can also pass the parameters of options:


var options = { 
 encoding: 'utf8',
 timeout: 0,
 maxBuffer: 200 * 1024,
 killSignal: 'SIGTERM',
 setsid: false,
 cwd: null,
 env: null 
};
var cp = require('child_process');
cp.exec('ls -l', options, function(e, stdout, stderr) {
    if(!e) {
          console.log(stdout);
          console.log(stderr);
    }
});

encoding: Encoding format of I/O stream;

timeout: Process timeout;

killSignal: A signal to terminate a process when the time or buffer exceeds the limit;

maxBuffer: The maximum increable value of stdout or stderr;

setsid: Determines whether to create a new session in the process;

cwd: The initial working directory of the process, and when it is null, it means the current working directory using node;

env: The environment variable for the process.

child_process. spawn ()

child_process. spawn () is more powerful and flexible than child_process. exec (), for example:


var cp = require('child_process');
var cat = cp.spawn('cat');
cat.stdout.on('data', function(d) {
    console.log(d.toString());
});
cat.on('exit', function() {
    console.log('kthxbai');
});
cat.stdin.write('meow');
cat.stdin.end();

The above is this site to introduce the nodejs process process, I hope to help you!


Related articles: