Detailed explanation of Node. JS module process

  • 2021-08-09 07:07:15
  • OfStack

The process module is a tool provided by nodejs for developers to interact with current processes, and it provides many practical API. Starting from the document, take a glimpse of the leopard, and take one step to understand and learn the process module:

How do I handle command parameters? What do I do with my working directory? How to handle exceptions? How to handle process exit? Standard Stream Objects for process Deep understanding of process. nextTick

How do I handle command parameters?

Command line arguments refer to two aspects:

Parameters passed to node. For example node --harmony script.js --version In, --harmony Is the parameter passed to node Parameters passed to the process. For example node script.js --version --help In, --version --help Is the parameter passed to the process

They pass through each other process.argv And process.execArgv To get.

What do I do with my working directory?

Pass process.cwd() You can get the current working directory.

process. chdir (directory) allows you to switch the current working directory and throw an exception if it fails. The practice is as follows:


function safeChdir(dir) {
 try {
  process.chdir(dir);
  return true;
 } catch (error) {
  return false;
 }
}

How to handle exceptions?

uncaughtException event

Nodejs can catch exceptions via try-catch. If the exception is not caught, it bubbles straight from the bottom to the event loop. If the exception bubbling into the event loop is not handled, it will cause the current process to exit abnormally.

According to the documentation, you can handle uncaught exceptions by listening for uncaughtException events on process:


process.on("uncaughtException", (err, origin) => {
 console.log(err.message);
});

const a = 1 / b;
console.log("abc"); //  Will not be executed 

With the above code, the output from the console is: b is not defined. An error message was captured and the process exited with 0. Developers can clear 1 of the allocated resources (file descriptors, handles, etc.) in the uncaughtException event, and it is not recommended to restart the process in it.

unhandledRejection event

If the exception of an Promise callback is not .catch() Capture, the unhandledRejection event of process is triggered:


process.on("unhandledRejection", (err, promise) => {
 console.log(err.message);
});

Promise.reject(new Error(" Error message ")); //  Not by catch Caught exception, handed over to unhandledRejection Event handling 

warning Event

Alarms are not a formal part of the Node. js and Javascript error handling process. 1 Node. js alerts once relevant code practices are detected that may cause application performance problems, defects, or security risks.

For example, in the previous code, if there is an exception of an uncaught promise callback, the warning event will be triggered.

How to handle process exit?

process.exit() vs process.exitCode

1 nodejs process, you can through process. exit () to specify the exit code, exit directly. The direct use of process. exit () is not recommended, which causes tasks in the event loop to go unprocessed and can lead to truncation and loss of data (such as writing to stdout).


setTimeout(() => {
 console.log(" I won't execute ");
});

process.exit(0);

The correct and safe treatment is to set process. exitCode and allow the process to exit naturally.


setTimeout(() => {
 console.log(" I won't execute ");
});

process.exitCode = 1;

beforeExit Event

Events used to handle process exit are: beforeExit event and exit event.

The beforeExit event is triggered when Node. js empties its event loop and there is nothing else to schedule. For example, if you need 1 asynchronous operation before exiting, you can write it in the beforeExit event:


let hasSend = false;
process.on("beforeExit", () => {
 if (hasSend) return; //  Avoid an infinite loop 

 setTimeout(() => {
  console.log("mock send data to serve");
  hasSend = true;
 }, 500);
});

console.log(".......");
//  Output: 
// .......
// mock send data to serve

Note: If the task is asynchronous in the beforeExit event, it will be added to the task queue again. At this point, after the task queue completes all tasks, the beforeExit event is triggered again. Therefore, if it is not processed, an infinite loop may occur. If exit () is called explicitly, this event will not be triggered.

exit Event

In exit events, only synchronous operations can be performed. After the 'exit' event listener is called, the Node. js process exits immediately, causing any other work that is still queued in the event loop to be abandoned.

Standard Stream Objects for process

process provides three standard streams. It should be noted that some of them are synchronously blocked at some time (see documentation).

process. stderr: WriteStream type, underlying implementation of console. error, default corresponding screen process. stdout: WriteStream type, underlying implementation of console. log, default corresponding screen process. stdin: ReadStream type, corresponding to keyboard input by default

The following is the code based on the "producer-consumer model" to read the console input and output it in time:


process.stdin.setEncoding("utf8");

process.stdin.on("readable", () => {
 let chunk;
 while ((chunk = process.stdin.read()) !== null) {
  process.stdout.write(`>>> ${chunk}`);
 }
});

process.stdin.on("end", () => {
 process.stdout.write(" End ");
});

For the meaning of events, please refer to the documentation of stream.

In-depth understanding of process. nextTick

When I first saw process. nextTick, I was rather confused. Looking at the document, I can know that its purpose is to put the callback function as a micro-task and put it into the task queue of the event loop. But what is the point of doing so?

Because nodejs is not suitable for compute-intensive applications, one process has one thread, and at the current point in time, one event is executing. Then, if our event takes up a lot of cpu time, the subsequent events will have to wait for a long time. Therefore, a programming principle of nodejs is to shorten the execution event of every event as much as possible. This is what process. nextTick does, breaking down a large task into smaller ones. The sample code is as follows:


//  Be split into 2 Function execution 
function BigThing() {
 doPartThing();

 process.nextTick(() => finishThing());
}

When is the nextTick registered task performed in the event loop? Look at the following code:


setTimeout(function() {
 console.log(" No. 1 1 A 1 Seconds ");
 process.nextTick(function() {
  console.log(" No. 1 1 A 1 Seconds: nextTick");
 });
}, 1000);

setTimeout(function() {
 console.log(" No. 1 2 A 1 Seconds ");
}, 1000);

console.log(" I want to export 1");

process.nextTick(function() {
 console.log("nextTick");
});

console.log(" I want to export 2");

The output is as follows: nextTick is earlier than setTimeout:

I want to output 1
I want to output 2
nextTick
The first one second
The first one second: nextTick
The second one second

On the browser side, nextTick degenerates into setTimeout(callback, 0) . But in nodejs, use nextTick instead of setTimeout, the former is more efficient, and strictly speaking, the events created by the two are not in the same order in the task queue (see the previous code).

The above is the detailed explanation of Node. JS module process. For more information about Node. JS module process, please pay attention to other related articles on this site!


Related articles: