Home  >  Article  >  Web Front-end  >  Detailed explanation of the use of Node.js notes process module

Detailed explanation of the use of Node.js notes process module

php中世界最好的语言
php中世界最好的语言Original
2018-06-01 09:46:001521browse

This time I will bring you a detailed explanation of the use of the Node.js note process module. What are the precautions when using the Node.js note process module. The following is a practical case, let's take a look.

process exists on the global object and can be used without using require() to load it. The process module mainly does two things

  1. Read: Get process information (resource usage, operating environment, operating status)

  2. Write: Perform process operations (listen to events, schedule tasks, issue warnings) Resource usage

Resource usage

refers to the machine resources consumed by running this process. For example, the composition of memory and cpu

memory

process.memoryUsage())
{ rss: 21848064,
 heapTotal: 7159808,
 heapUsed: 4431688,
 external: 8224 
 }

rss (resident memory) is shown in the figure below

The code segment corresponds to the currently running code

external corresponds to the memory occupied by the C object (bound to the JS object managed by V8), such as the use of Buffer

Buffer.allocUnsafe(1024 * 1024 * 1000);
console.log(process.memoryUsage());
{ rss: 22052864,
 heapTotal: 6635520,
 heapUsed: 4161376,
 external: 1048584224 }

cpu

const startUsage = process.cpuUsage();
console.log(startUsage);
const now = Date.now();
while (Date.now() - now < 500);
console.log(process.cpuUsage());
console.log(process.cpuUsage(startUsage)); //相对时间
// { user: 59459, system: 18966 }
// { user: 558135, system: 22312 }
// { user: 498432, system: 3333 }

user corresponds to the user time, system represents the system time

Running environment

The running environment refers to the running of this process The host environment includes the running directory, node environment, CPU architecture, user environment, and system platform

Running directory

const startUsage = process.cpuUsage();
console.log(startUsage);
const now = Date.now();
while (Date.now() - now < 500);
console.log(process.cpuUsage());
console.log(process.cpuUsage(startUsage)); //相对时间
// { user: 59459, system: 18966 }
// { user: 558135, system: 22312 }
// { user: 498432, system: 3333 }

node environment

console.log(process.version)
// v9.1.0

If you not only want to get the node version information, but also want v8, zlib, libuv version and other information, you need to use process.versions

console.log(process.versions);
{ http_parser: '2.7.0',
 node: '9.1.0',
 v8: '6.2.414.32-node.8',
 uv: '1.15.0',
 zlib: '1.2.11',
 ares: '1.13.0',
 modules: '59',
 nghttp2: '1.25.0',
 openssl: '1.0.2m',
 icu: '59.1',
 unicode: '9.0',
 cldr: '31.0.1',
 tz: '2017b' }

cpu architecture

console.log(`This processor architecture is ${process.arch}`);
// This processor architecture is x64

Supported values ​​include: 'arm', 'arm64', 'ia32', 'mips', 'mipsel', 'ppc', 'ppc64', 's390', 's390x', 'x32' 'x64'

User environment

console.log(process.env.NODE_ENV); // dev
NODE_ENV=dev node b.js

In addition to custom information at startup, process.env can also obtain other User environment information (such as PATH, SHELL, HOME, etc.), if you are interested, you can print it yourself and try it

System platform

console.log(`This platform is ${process.platform}`);
This platform is darwin

Supported system platforms include:'aix' 'darwin' 'freebsd' 'linux' 'openbsd' 'sunos' 'win32'

android is still in the experimental stage

Running status

The running status refers to the information related to the running of the current process, including startup Parameters, execution directory, main file, PID information, running time

Startup parameters

There are three ways to obtain startup parameters. execArgv obtains the command line options of Node.js ( See official website documentation)

argv gets the information of non-command line options, argv0 gets the value of argv[0] (slightly different)

console.log(process.argv)
console.log(process.argv0)
console.log(process.execArgv)
node --harmony b.js foo=bar --version
// 输出结果
[ '/Users/xiji/.nvm/versions/node/v9.1.0/bin/node',
 '/Users/xiji/workspace/learn/node-basic/process/b.js',
 'foo=bar',
 '--version' ]
node
[ '--harmony' ]

Execution directory

console.log(process.execPath);
// /Users/xxxx/.nvm/versions/node/v9.1.0/bin/node

Run Time

var date = new Date();
while(new Date() - date < 500) {}
console.log(process.uptime()); // 0.569

Main file

In addition to require.main, you can also use process.mainModule to determine whether a module is the main file

//a.js
console.log(`module A: ${process.mainModule === module}`);
//b.js
require('./a');
console.log(`module B: ${process.mainModule === module}`);
node b.js
// 输出
module A: false
module B: true

PID information

console.log(`This process is pid ${process.pid}`); //This process is pid 12554

Listening events

Commonly used events include beforeExit, exit, uncaughtException, message

beforeExit and exit There are two differences:

  1. beforeExit can execute asynchronous code, exit can only be synchronous code

  2. code manually calls process.exit() Or triggering uncaptException and causing the process to exit will not trigger the beforeExit event, but the exit event will be triggered.

So the following code console will not be executed

process.on('beforeExit', function(code) {
 console.log('before exit: '+ code);
});
process.on('exit', function(code) {
 setTimeout(function() {
  console.log('exit: ' + code);
 }, 0);
});
a.b();

当异常一直没有被捕获处理的话,最后就会触发'uncaughtException'事件。默认情况下,Node.js会打印堆栈信息到stderr然后退出进程。不要试图阻止uncaughtException退出进程,因此此时程序的状态可能已经不稳定了,建议的方式是及时捕获处理代码中的错误,uncaughtException里面只做一些清理工作(可以执行异步代码)。

注意:node的9.3版本增加了process.setUncaughtExceptionCaptureCallback方法

当process.setUncaughtExceptionCaptureCallback(fn)指定了监听函数的时候,uncaughtException事件将会不再被触发。

process.on('uncaughtException', function() {
 console.log('uncaught listener');
});
process.setUncaughtExceptionCaptureCallback(function() {
 console.log('uncaught fn');
});
a.b();
// uncaught fn

message适用于父子进程之间发送消息,关于如何创建父子进程会放在child_process模块中进行。

调度任务

process.nextTick(fn)

通过process.nextTick调度的任务是异步任务,EventLoop是分阶段的,每个阶段执行特定的任务,而nextTick的任务在阶段切换的时候就会执行,因此nextTick会比setTimeout(fn, 0)更快的执行,关于EventLoop见下图,后面会做进一步详细的讲解

发出警告

process.emitWarning('Something warning happened!', {
 code: 'MY_WARNING',
 type: 'XXXX'
});
// (node:14771) [MY_WARNING] XXXX: Something warning happened!

当type为DeprecationWarning时,可以通过命令行选项施加影响

  1. --throw-deprecation抛出异常

  2. --no-deprecation 不输出DeprecationWarning

  3. --trace-deprecation 打印详细堆栈信息

process.emitWarning('Something warning happened!', {
 type: 'DeprecationWarning'
});
console.log(4);
node --throw-deprecation index.js
node --no-deprecation index.js
node --trace-deprecation index.js

相信看了本文案例你已经掌握了方法,更多精彩请关注php中文网其它相关文章!

推荐阅读:

怎么使用webpack3.0配置webpack-dev-server

JS反射与依赖注入使用案例分析

The above is the detailed content of Detailed explanation of the use of Node.js notes process module. For more information, please follow other related articles on the PHP Chinese website!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn